From 31d66674c2a6e2ae1d2de809ce44d862f12cf794 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sat, 28 Nov 2026 16:14:42 +1100 Subject: [PATCH 01/19] feat(vitaminc-aead): mark the decrypt targets that one scalar builds A sealed leaf holds one scalar or one null. A caller that opens exactly one leaf had only `Decrypt` to bound its target on, and `Decrypt` also covers a sequence, a map and a derived struct. Such a target opened the leaf and was refused afterwards, so a mistake a compiler could catch was found only after the plaintext was decrypted. `ScalarTarget` is the decrypt-side counterpart of `Scalar`. It is implemented for every `FromScalar` type, for an `Option` or a `Protected` of a `ScalarTarget`, and for `OwnedFrame`, which one leaf always builds. A `Vec` of anything but bytes, a map and a derived struct do not implement it. The trait is open, as `Scalar` is. A newtype that derives `Decrypt` over a scalar adds an empty impl, because the derive cannot know that its inner type is a scalar target. Nothing in this crate bounds on the trait, so no existing code changes. --- packages/vitaminc-aead/CHANGELOG.md | 8 + packages/vitaminc-aead/src/frame/owned.rs | 6 +- packages/vitaminc-aead/src/lib.rs | 4 +- packages/vitaminc-aead/src/typed.rs | 92 +++++++ packages/vitaminc-aead/tests/scalar_target.rs | 229 ++++++++++++++++++ .../derived_struct_needs_a_map.rs | 15 ++ .../derived_struct_needs_a_map.stderr | 27 +++ .../tests/ui/scalar_target/map_needs_a_map.rs | 13 + .../ui/scalar_target/map_needs_a_map.stderr | 45 ++++ .../ui/scalar_target/vec_needs_a_sequence.rs | 12 + .../scalar_target/vec_needs_a_sequence.stderr | 17 ++ ...rapped_container_is_not_a_scalar_target.rs | 15 ++ ...ed_container_is_not_a_scalar_target.stderr | 50 ++++ 13 files changed, 531 insertions(+), 2 deletions(-) create mode 100644 packages/vitaminc-aead/tests/scalar_target.rs create mode 100644 packages/vitaminc-aead/tests/ui/scalar_target/derived_struct_needs_a_map.rs create mode 100644 packages/vitaminc-aead/tests/ui/scalar_target/derived_struct_needs_a_map.stderr create mode 100644 packages/vitaminc-aead/tests/ui/scalar_target/map_needs_a_map.rs create mode 100644 packages/vitaminc-aead/tests/ui/scalar_target/map_needs_a_map.stderr create mode 100644 packages/vitaminc-aead/tests/ui/scalar_target/vec_needs_a_sequence.rs create mode 100644 packages/vitaminc-aead/tests/ui/scalar_target/vec_needs_a_sequence.stderr create mode 100644 packages/vitaminc-aead/tests/ui/scalar_target/wrapped_container_is_not_a_scalar_target.rs create mode 100644 packages/vitaminc-aead/tests/ui/scalar_target/wrapped_container_is_not_a_scalar_target.stderr diff --git a/packages/vitaminc-aead/CHANGELOG.md b/packages/vitaminc-aead/CHANGELOG.md index 7549ee1f9..8282e1430 100644 --- a/packages/vitaminc-aead/CHANGELOG.md +++ b/packages/vitaminc-aead/CHANGELOG.md @@ -16,6 +16,14 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ### Added +- `ScalarTarget` (also `typed::ScalarTarget`): a marker for a decrypt target that one scalar builds. + It is the decrypt-side counterpart of `Scalar`. + A caller that opens exactly one leaf bounds its target on it, so a target that needs a sequence or a map does not compile. + It is implemented for every `FromScalar` type, for an `Option` of a `ScalarTarget`, for a `Protected` of a `ScalarTarget` that is `DecryptProtected`, and for `OwnedFrame`. + A `Vec` other than `Vec`, a map and a derived struct with named fields do not implement it. + A derived fieldless enum implements it, because the derive gives it `FromScalar`. + A derived newtype does not: add an empty `impl ScalarTarget` for a newtype of a scalar target. + The trait is open, and nothing in this crate bounds on it, so no existing code changes. - `plaintext::ValueKind`: what a value is, without the value, with the text name a schema spells it with (`"int32"`, `"timestamp"`, `"object"`, `"json"`, …). It covers every scalar, an array, an object and a JSON document. `ValueKind::Uuid` (`"uuid"`) is a UUID: `Logical::Uuid` over sixteen bytes. Its zero is sixteen zero bytes, its null is a typed null as long as a UUID leaf, and it holds only a UUID. diff --git a/packages/vitaminc-aead/src/frame/owned.rs b/packages/vitaminc-aead/src/frame/owned.rs index 384972d67..5efe1d9c8 100644 --- a/packages/vitaminc-aead/src/frame/owned.rs +++ b/packages/vitaminc-aead/src/frame/owned.rs @@ -9,7 +9,7 @@ use crate::plaintext::{ Encrypt, EncryptRef, FixedType, Logical, MapSink, Physical, SeqSink, Sink, SourceError, }; use crate::tags; -use crate::typed::{DecodeError, Decrypt}; +use crate::typed::{DecodeError, Decrypt, ScalarTarget}; /// One value as a transport frame, in a [`Buffer`] of its own: a value /// kept past the call that wrote it, and what a ciphertext opens into. @@ -136,6 +136,10 @@ impl Decrypt for OwnedFrame { } } +/// One leaf always builds a frame: the frame of the one scalar, or of the +/// null, that the leaf holds. +impl ScalarTarget for OwnedFrame {} + /// Wipes the bytes and leaves the plain null, the frame a buffer of no /// value holds: an `OwnedFrame` always holds one frame, so a zeroized one /// reads, walks and seals as a null. diff --git a/packages/vitaminc-aead/src/lib.rs b/packages/vitaminc-aead/src/lib.rs index 88dc2a298..6c25316a4 100644 --- a/packages/vitaminc-aead/src/lib.rs +++ b/packages/vitaminc-aead/src/lib.rs @@ -77,7 +77,9 @@ pub use seal::{AsyncCipher, Cipher, Node, Opened, Pending}; pub use shape::{Refusal, Unencryptable}; // Decryption: typed targets, and sinks of any kind. #[doc(inline)] -pub use typed::{decrypt, decrypt_async, DecodeError, Decrypt, DecryptProtected, FromScalar}; +pub use typed::{ + decrypt, decrypt_async, DecodeError, Decrypt, DecryptProtected, FromScalar, ScalarTarget, +}; #[doc(inline)] pub use walk::{decrypt_into, decrypt_into_async, decrypt_to_frame, walk, DecryptError}; // The frame: a value as transport bytes, and back. diff --git a/packages/vitaminc-aead/src/typed.rs b/packages/vitaminc-aead/src/typed.rs index 600e9792c..ade8eaee1 100644 --- a/packages/vitaminc-aead/src/typed.rs +++ b/packages/vitaminc-aead/src/typed.rs @@ -15,6 +15,11 @@ //! kind, and never reads it as a zero. `HashMap` and `BTreeMap` //! read a map, each value through `T`'s sink. //! +//! [`ScalarTarget`] marks a target that one scalar builds: the scalar +//! targets, an `Option` or a `Protected` of one, and an +//! [`OwnedFrame`](crate::OwnedFrame). A caller that opens exactly one leaf +//! bounds on it, so a target that needs a container does not compile. +//! //! `Protected` is a target for every `T` that implements //! [`DecryptProtected`]: any scalar target that can be wiped, and a //! `Vec` or `Option` of such targets, nested to any depth. A @@ -265,6 +270,84 @@ impl Decrypt for T { } } +/// A target that one scalar builds. +/// +/// The decrypt-side counterpart of [`Scalar`](crate::Scalar). A sealed leaf +/// holds one scalar or one null, and never a sequence or a map. A caller +/// that opens exactly one leaf bounds its target on this trait. A target +/// that only a container builds then fails to compile, where a bound on +/// [`Decrypt`] alone would let it open the leaf and refuse it afterwards. +/// +/// These targets implement it: +/// +/// - Every [`FromScalar`] type: `bool`, the integers (except `u8`), the +/// floats, `String`, `Vec`, `[u8; N]`, this crate's date, timestamp, +/// decimal and UUID values, the jiff, `rust_decimal` and uuid types behind +/// their features, and any type of your own that implements `FromScalar`. +/// - `Option` of a `ScalarTarget`. A null leaf builds `None`. +/// - `Protected` of a `ScalarTarget` that also implements +/// [`DecryptProtected`]. +/// - [`OwnedFrame`](crate::OwnedFrame). One leaf always builds a frame that +/// holds one scalar. +/// +/// These targets do not, because each needs a container: a `Vec` other +/// than `Vec`, a `HashMap` or a `BTreeMap`, and a struct that derives +/// `Decrypt` with named fields. +/// +/// ``` +/// use vitaminc_aead::{Decrypt, OwnedFrame, ScalarTarget}; +/// use vitaminc_protected::Protected; +/// +/// /// Opens exactly one leaf. +/// fn opens_one_leaf() -> T::Sink { +/// T::sink() +/// } +/// +/// let _ = opens_one_leaf::(); +/// let _ = opens_one_leaf::>(); +/// let _ = opens_one_leaf::>(); +/// let _ = opens_one_leaf::>(); +/// let _ = opens_one_leaf::(); +/// ``` +/// +/// A `Vec` needs a sequence, so it does not compile: +/// +/// ```compile_fail,E0277 +/// use vitaminc_aead::ScalarTarget; +/// fn opens_one_leaf() {} +/// opens_one_leaf::>(); +/// ``` +/// +/// The trait is open, as `Scalar` is. A hand-written target whose sink +/// reads a scalar implements it with an empty impl. So does a newtype that +/// derives `Decrypt` over a scalar target: the derive does not implement +/// the marker. +/// +/// ``` +/// use vitaminc_aead::{Decrypt, Encrypt, ScalarTarget}; +/// +/// #[derive(Decrypt, Debug, PartialEq)] +/// struct Email(String); +/// +/// impl ScalarTarget for Email {} +/// +/// fn opens_one_leaf() -> T::Sink { +/// T::sink() +/// } +/// +/// let email = "ada@example.com".visit(opens_one_leaf::())?; +/// assert_eq!(email, Email(String::from("ada@example.com"))); +/// # Ok::<(), vitaminc_aead::DecodeError>(()) +/// ``` +/// +/// Implement it only for a target that a scalar can build. The marker is a +/// promise the compiler does not check: a target that carries it and reads +/// only a container compiles, and then refuses every leaf it is given. +pub trait ScalarTarget: Decrypt {} + +/// Every type that decodes from one scalar is built by one scalar. +impl ScalarTarget for T {} + /// A sink nothing is ever walked into: the element and entry type of a /// container sink that hands out none, such as [`Never`] and the map sink /// of a derived struct with no fields. Uninhabited, so it cannot be built. @@ -1064,6 +1147,10 @@ impl Decrypt for Option { } } +/// A null leaf builds `None`, and any other scalar builds `Some` of what +/// `T` builds. +impl ScalarTarget for Option {} + /// A type that can be decrypted straight into `Protected`: it names /// the sink that builds the wrapped value. /// @@ -1091,6 +1178,11 @@ impl Decrypt for Protected { } } +/// What one scalar builds, it also builds inside the wrapper. A +/// `Protected>` of anything but bytes is not covered, because +/// `Vec` is not a `ScalarTarget`. +impl ScalarTarget for Protected {} + /// Any scalar target that can be wiped, read into `Protected`. A heap /// type (`String`, `Vec`) is copied once, into the wrapper's buffer. /// An inline type (an integer, `[u8; N]`) moves by value, so a move can diff --git a/packages/vitaminc-aead/tests/scalar_target.rs b/packages/vitaminc-aead/tests/scalar_target.rs new file mode 100644 index 000000000..78e819634 --- /dev/null +++ b/packages/vitaminc-aead/tests/scalar_target.rs @@ -0,0 +1,229 @@ +//! `ScalarTarget`, the decrypt-side marker for a target that one scalar +//! builds: the counterpart of `Scalar`. +//! +//! The marker is only worth having if it agrees with the sinks. So for every +//! kind of target that carries it, these tests walk one scalar into the +//! target's sink and check what it builds. The compile-fail half lives in +//! `tests/ui/scalar_target/`: a sequence, a map, a derived struct and a +//! protected sequence do not carry the marker. + +use vitaminc_aead::plaintext::Raw; +use vitaminc_aead::{ + Decrypt, Encrypt, FixedType, FromScalar, Logical, OwnedFrame, Physical, ScalarTarget, + ValueKind, Width, +}; +use vitaminc_protected::{Controlled, Protected}; + +/// What a caller that opens exactly one leaf asks for: the target says one +/// scalar builds it, and the scalar `source` does. +fn built_by_one_scalar(source: impl Encrypt) -> T { + source + .visit(T::sink()) + .expect("one scalar builds a scalar target") +} + +/// A null, as a leaf holds one. +fn null() -> Raw<'static> { + Raw(None, Physical::Null) +} + +#[test] +fn every_built_in_scalar_target_is_built_by_one_scalar() { + assert!(built_by_one_scalar::(true), "bool"); + assert_eq!(built_by_one_scalar::(-8i8), -8, "i8"); + assert_eq!(built_by_one_scalar::(-16i16), -16, "i16"); + assert_eq!(built_by_one_scalar::(-32i32), -32, "i32"); + assert_eq!(built_by_one_scalar::(-64i64), -64, "i64"); + assert_eq!(built_by_one_scalar::(-128i128), -128, "i128"); + assert_eq!(built_by_one_scalar::(16u16), 16, "u16"); + assert_eq!(built_by_one_scalar::(32u32), 32, "u32"); + assert_eq!(built_by_one_scalar::(64u64), 64, "u64"); + assert_eq!(built_by_one_scalar::(128u128), 128, "u128"); + assert_eq!(built_by_one_scalar::(1.5f32), 1.5, "f32"); + assert_eq!(built_by_one_scalar::(2.5f64), 2.5, "f64"); + assert_eq!(built_by_one_scalar::("hi"), "hi", "String"); + assert_eq!( + built_by_one_scalar::>(vec![1u8, 2]), + [1, 2], + "Vec is one byte leaf, not a sequence" + ); + assert_eq!( + built_by_one_scalar::<[u8; 3]>([1u8, 2, 3]), + [1, 2, 3], + "[u8; N]" + ); +} + +#[test] +fn an_option_is_built_by_a_null_or_by_a_scalar() { + assert_eq!( + built_by_one_scalar::>(null()), + None, + "a plain null builds None" + ); + let typed_null = OwnedFrame::typed_null(FixedType::plain(Width::I64).expect("a fixed type")); + assert_eq!( + built_by_one_scalar::>(&typed_null), + None, + "a typed null builds None" + ); + assert_eq!( + built_by_one_scalar::>(34i64), + Some(34), + "a scalar builds Some" + ); + assert_eq!( + built_by_one_scalar::>>("hi"), + Some(Some(String::from("hi"))), + "a nested option" + ); +} + +#[test] +fn a_protected_scalar_target_is_built_by_one_scalar() { + let text = built_by_one_scalar::>("hi"); + assert_eq!(text.risky_ref(), "hi", "Protected"); + let bytes = built_by_one_scalar::>>(vec![9u8, 8]); + assert_eq!(bytes.risky_ref(), &[9, 8], "Protected>"); + let absent = built_by_one_scalar::>>(null()); + assert_eq!( + absent.risky_ref(), + &None, + "Protected> of a null" + ); + let present = built_by_one_scalar::>>(34i64); + assert_eq!( + present.map(|value| *value.risky_ref()), + Some(34), + "Option> of a scalar" + ); +} + +#[test] +fn an_owned_frame_is_built_by_any_scalar_and_by_a_null() { + let text = built_by_one_scalar::("hi"); + assert_eq!( + text.frame().kind(), + Some(ValueKind::String), + "a text scalar" + ); + let date = built_by_one_scalar::(Raw( + Some(Logical::Date), + Physical::Int(vitaminc_aead::Int::I32(19_782)), + )); + assert_eq!(date.frame().kind(), Some(ValueKind::Date), "a date scalar"); + let absent = built_by_one_scalar::(null()); + assert!(absent.frame().is_null(), "a null builds the null frame"); + let present = built_by_one_scalar::>(7u16); + assert_eq!( + present.map(|frame| frame.frame().kind()), + Some(Some(ValueKind::UInt16)), + "Option of a scalar" + ); +} + +/// A scalar target written by hand gets the marker from `FromScalar`. +#[test] +fn a_hand_written_scalar_target_carries_the_marker() { + #[derive(Debug, PartialEq)] + struct Percent(u8); + impl FromScalar for Percent { + const EXPECTED: &'static str = "percentage"; + fn from_scalar(ty: Option, value: Physical<'_>) -> Option { + let n = u32::from_scalar(ty, value)?; + u8::try_from(n).ok().filter(|n| *n <= 100).map(Percent) + } + } + assert_eq!( + built_by_one_scalar::(42u32), + Percent(42), + "a FromScalar type" + ); +} + +/// A derived newtype reads what its inner type reads. The derive does not +/// add the marker, so the newtype's author does. +#[test] +fn a_derived_newtype_takes_the_marker_by_hand() { + #[derive(Decrypt, Debug, PartialEq)] + struct Email(String); + impl ScalarTarget for Email {} + assert_eq!( + built_by_one_scalar::("ada@example.com"), + Email(String::from("ada@example.com")), + "a derived newtype of a scalar target" + ); +} + +/// A derived fieldless enum reads an int leaf through `FromScalar`, so it +/// carries the marker with no impl of its own. +#[test] +fn a_derived_fieldless_enum_carries_the_marker() { + #[derive(Encrypt, Decrypt, Debug, PartialEq, Clone, Copy)] + enum Status { + Active = 1, + Closed = 2, + } + assert_eq!( + built_by_one_scalar::(Status::Closed), + Status::Closed, + "a fieldless enum" + ); + assert_eq!( + built_by_one_scalar::(Status::Active), + Status::Active, + "the other variant" + ); +} + +#[cfg(feature = "jiff")] +#[test] +fn the_date_and_timestamp_targets_are_built_by_one_scalar() { + let date = jiff::civil::Date::constant(2024, 2, 29); + assert_eq!( + built_by_one_scalar::(date), + date, + "jiff date" + ); + let wiped = built_by_one_scalar::(date); + assert_eq!(wiped.to_jiff(), date, "this crate's Date"); + let instant = jiff::Timestamp::new(1_700_000_000, 0).expect("valid"); + assert_eq!( + built_by_one_scalar::(instant), + instant, + "jiff timestamp" + ); + let stamp = built_by_one_scalar::(instant); + assert_eq!(stamp.to_jiff(), instant, "this crate's Timestamp"); +} + +#[cfg(feature = "rust_decimal")] +#[test] +fn the_decimal_targets_are_built_by_one_scalar() { + let value = rust_decimal::Decimal::new(1234, 2); + assert_eq!( + built_by_one_scalar::(value), + value, + "rust_decimal" + ); + let wiped = built_by_one_scalar::(value); + assert_eq!(wiped.to_decimal(), value, "this crate's Decimal"); +} + +#[cfg(feature = "uuid")] +#[test] +fn the_uuid_targets_are_built_by_one_scalar() { + let id = uuid::Uuid::from_bytes([7; 16]); + assert_eq!(built_by_one_scalar::(id), id, "uuid"); + let wiped = built_by_one_scalar::(id); + assert_eq!(wiped.to_uuid(), id, "this crate's Uuid"); +} + +// `trybuild` launches rustc and inspects the filesystem, neither of which can +// run inside Miri's isolated interpreter. +#[cfg(not(miri))] +#[test] +fn containers_are_not_scalar_targets() { + let tests = trybuild::TestCases::new(); + tests.compile_fail("tests/ui/scalar_target/*.rs"); +} diff --git a/packages/vitaminc-aead/tests/ui/scalar_target/derived_struct_needs_a_map.rs b/packages/vitaminc-aead/tests/ui/scalar_target/derived_struct_needs_a_map.rs new file mode 100644 index 000000000..ac9d32892 --- /dev/null +++ b/packages/vitaminc-aead/tests/ui/scalar_target/derived_struct_needs_a_map.rs @@ -0,0 +1,15 @@ +//! A derived struct reads a map, one leaf per field, so one scalar does +//! not build it, even with a single field. + +use vitaminc_aead::{Decrypt, ScalarTarget}; + +#[derive(Decrypt)] +struct Account { + id: u64, +} + +fn opens_one_leaf() {} + +fn main() { + opens_one_leaf::(); +} diff --git a/packages/vitaminc-aead/tests/ui/scalar_target/derived_struct_needs_a_map.stderr b/packages/vitaminc-aead/tests/ui/scalar_target/derived_struct_needs_a_map.stderr new file mode 100644 index 000000000..8a446fa62 --- /dev/null +++ b/packages/vitaminc-aead/tests/ui/scalar_target/derived_struct_needs_a_map.stderr @@ -0,0 +1,27 @@ +error[E0277]: the trait bound `Account: ScalarTarget` is not satisfied + --> tests/ui/scalar_target/derived_struct_needs_a_map.rs:14:22 + | +14 | opens_one_leaf::(); + | ^^^^^^^ unsatisfied trait bound + | +help: the trait `FromScalar` is not implemented for `Account` + --> tests/ui/scalar_target/derived_struct_needs_a_map.rs:7:1 + | + 7 | struct Account { + | ^^^^^^^^^^^^^^ + = help: the following other types implement trait `FromScalar`: + Vec + [u8; N] + bool + f32 + f64 + i128 + i16 + i32 + and $N others + = note: required for `Account` to implement `ScalarTarget` +note: required by a bound in `opens_one_leaf` + --> tests/ui/scalar_target/derived_struct_needs_a_map.rs:11:22 + | +11 | fn opens_one_leaf() {} + | ^^^^^^^^^^^^ required by this bound in `opens_one_leaf` diff --git a/packages/vitaminc-aead/tests/ui/scalar_target/map_needs_a_map.rs b/packages/vitaminc-aead/tests/ui/scalar_target/map_needs_a_map.rs new file mode 100644 index 000000000..38963bdf4 --- /dev/null +++ b/packages/vitaminc-aead/tests/ui/scalar_target/map_needs_a_map.rs @@ -0,0 +1,13 @@ +//! A map target reads a map, one leaf per value, so one scalar does not +//! build it. + +use std::collections::{BTreeMap, HashMap}; + +use vitaminc_aead::ScalarTarget; + +fn opens_one_leaf() {} + +fn main() { + opens_one_leaf::>(); + opens_one_leaf::>(); +} diff --git a/packages/vitaminc-aead/tests/ui/scalar_target/map_needs_a_map.stderr b/packages/vitaminc-aead/tests/ui/scalar_target/map_needs_a_map.stderr new file mode 100644 index 000000000..5a312990d --- /dev/null +++ b/packages/vitaminc-aead/tests/ui/scalar_target/map_needs_a_map.stderr @@ -0,0 +1,45 @@ +error[E0277]: the trait bound `HashMap: ScalarTarget` is not satisfied + --> tests/ui/scalar_target/map_needs_a_map.rs:11:22 + | +11 | opens_one_leaf::>(); + | ^^^^^^^^^^^^^^^^^^^^ the trait `FromScalar` is not implemented for `HashMap` + | + = help: the following other types implement trait `FromScalar`: + Vec + [u8; N] + bool + f32 + f64 + i128 + i16 + i32 + and $N others + = note: required for `HashMap` to implement `ScalarTarget` +note: required by a bound in `opens_one_leaf` + --> tests/ui/scalar_target/map_needs_a_map.rs:8:22 + | + 8 | fn opens_one_leaf() {} + | ^^^^^^^^^^^^ required by this bound in `opens_one_leaf` + +error[E0277]: the trait bound `BTreeMap: ScalarTarget` is not satisfied + --> tests/ui/scalar_target/map_needs_a_map.rs:12:22 + | +12 | opens_one_leaf::>(); + | ^^^^^^^^^^^^^^^^^^^^^ the trait `FromScalar` is not implemented for `BTreeMap` + | + = help: the following other types implement trait `FromScalar`: + Vec + [u8; N] + bool + f32 + f64 + i128 + i16 + i32 + and $N others + = note: required for `BTreeMap` to implement `ScalarTarget` +note: required by a bound in `opens_one_leaf` + --> tests/ui/scalar_target/map_needs_a_map.rs:8:22 + | + 8 | fn opens_one_leaf() {} + | ^^^^^^^^^^^^ required by this bound in `opens_one_leaf` diff --git a/packages/vitaminc-aead/tests/ui/scalar_target/vec_needs_a_sequence.rs b/packages/vitaminc-aead/tests/ui/scalar_target/vec_needs_a_sequence.rs new file mode 100644 index 000000000..fb93438d5 --- /dev/null +++ b/packages/vitaminc-aead/tests/ui/scalar_target/vec_needs_a_sequence.rs @@ -0,0 +1,12 @@ +//! A `Vec` of a scalar target reads a sequence, one leaf per element, +//! so one scalar does not build it. (`Vec` is the byte leaf, and one +//! scalar does build it.) + +use vitaminc_aead::ScalarTarget; + +fn opens_one_leaf() {} + +fn main() { + opens_one_leaf::>(); + opens_one_leaf::>(); +} diff --git a/packages/vitaminc-aead/tests/ui/scalar_target/vec_needs_a_sequence.stderr b/packages/vitaminc-aead/tests/ui/scalar_target/vec_needs_a_sequence.stderr new file mode 100644 index 000000000..e72844bf8 --- /dev/null +++ b/packages/vitaminc-aead/tests/ui/scalar_target/vec_needs_a_sequence.stderr @@ -0,0 +1,17 @@ +error[E0277]: the trait bound `Vec: ScalarTarget` is not satisfied + --> tests/ui/scalar_target/vec_needs_a_sequence.rs:11:22 + | +11 | opens_one_leaf::>(); + | ^^^^^^^^^^^ the trait `FromScalar` is not implemented for `Vec` + | +help: the trait `FromScalar` is implemented for `Vec` + --> src/typed.rs + | + | impl FromScalar for Vec { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ + = note: required for `Vec` to implement `ScalarTarget` +note: required by a bound in `opens_one_leaf` + --> tests/ui/scalar_target/vec_needs_a_sequence.rs:7:22 + | + 7 | fn opens_one_leaf() {} + | ^^^^^^^^^^^^ required by this bound in `opens_one_leaf` diff --git a/packages/vitaminc-aead/tests/ui/scalar_target/wrapped_container_is_not_a_scalar_target.rs b/packages/vitaminc-aead/tests/ui/scalar_target/wrapped_container_is_not_a_scalar_target.rs new file mode 100644 index 000000000..908e97fd7 --- /dev/null +++ b/packages/vitaminc-aead/tests/ui/scalar_target/wrapped_container_is_not_a_scalar_target.rs @@ -0,0 +1,15 @@ +//! `Option` and `Protected` pass the marker through only when what they +//! wrap carries it. A `Vec` reads a sequence, so neither an `Option` +//! of it, a `Protected` of it nor a `Protected` of an `Option` of it is +//! built by one scalar. + +use vitaminc_aead::ScalarTarget; +use vitaminc_protected::Protected; + +fn opens_one_leaf() {} + +fn main() { + opens_one_leaf::>>(); + opens_one_leaf::>>(); + opens_one_leaf::>>>(); +} diff --git a/packages/vitaminc-aead/tests/ui/scalar_target/wrapped_container_is_not_a_scalar_target.stderr b/packages/vitaminc-aead/tests/ui/scalar_target/wrapped_container_is_not_a_scalar_target.stderr new file mode 100644 index 000000000..c10ce0697 --- /dev/null +++ b/packages/vitaminc-aead/tests/ui/scalar_target/wrapped_container_is_not_a_scalar_target.stderr @@ -0,0 +1,50 @@ +error[E0277]: the trait bound `Option>: ScalarTarget` is not satisfied + --> tests/ui/scalar_target/wrapped_container_is_not_a_scalar_target.rs:12:22 + | +12 | opens_one_leaf::>>(); + | ^^^^^^^^^^^^^^^^ the trait `ScalarTarget` is not implemented for `Option>` + | +help: the trait `ScalarTarget` is implemented for `Option` + --> src/typed.rs + | + | impl ScalarTarget for Option {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +note: required by a bound in `opens_one_leaf` + --> tests/ui/scalar_target/wrapped_container_is_not_a_scalar_target.rs:9:22 + | + 9 | fn opens_one_leaf() {} + | ^^^^^^^^^^^^ required by this bound in `opens_one_leaf` + +error[E0277]: the trait bound `Protected>: ScalarTarget` is not satisfied + --> tests/ui/scalar_target/wrapped_container_is_not_a_scalar_target.rs:13:22 + | +13 | opens_one_leaf::>>(); + | ^^^^^^^^^^^^^^^^^^^ the trait `ScalarTarget` is not implemented for `Protected>` + | +help: the trait `ScalarTarget` is implemented for `Protected` + --> src/typed.rs + | + | impl ScalarTarget for Protected {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +note: required by a bound in `opens_one_leaf` + --> tests/ui/scalar_target/wrapped_container_is_not_a_scalar_target.rs:9:22 + | + 9 | fn opens_one_leaf() {} + | ^^^^^^^^^^^^ required by this bound in `opens_one_leaf` + +error[E0277]: the trait bound `Protected>>: ScalarTarget` is not satisfied + --> tests/ui/scalar_target/wrapped_container_is_not_a_scalar_target.rs:14:22 + | +14 | opens_one_leaf::>>>(); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `ScalarTarget` is not implemented for `Protected>>` + | +help: the trait `ScalarTarget` is implemented for `Protected` + --> src/typed.rs + | + | impl ScalarTarget for Protected {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +note: required by a bound in `opens_one_leaf` + --> tests/ui/scalar_target/wrapped_container_is_not_a_scalar_target.rs:9:22 + | + 9 | fn opens_one_leaf() {} + | ^^^^^^^^^^^^ required by this bound in `opens_one_leaf` From 197074ec722eb1ffaf579ef529d70d15e0613615 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sat, 28 Nov 2026 16:14:50 +1100 Subject: [PATCH 02/19] feat(stack-encrypt): encrypt and decrypt one value known only at run time `keyset.encrypt` takes a type whose borrow is a `Scalar`, which is a promise the compiler checks. A language SDK holds a value as a frame and learns its kind only when the code runs, and a frame can hold a list or a map, so it is not a `Scalar`. Each SDK worked around that in its own way: TypeScript wrapped the frame in a type of its own and claimed `Scalar` for it, and Go sealed every value as a record of one field. So the languages did not write the same thing for one value. `dynamic::value` is the engine's own answer. `encrypt` takes a borrowed `Frame` and an optional declared `ValueKind`, and walks the value into the operation `keyset.encrypt` runs. So the ciphertext has the same leaf under the same key request and context, and each language reads what another wrote. `decrypt` opens a ciphertext into an `OwnedFrame` and can check the kind it opens as. Both have a form with a context and a form for many values in one key request. A ciphertext holds one scalar. `encrypt` refuses an array, an object, a passthrough and a null before any key is requested, with a reason that says which was found: `Reason::Array`, `Reason::Object` and `Reason::Null` are new. A null is refused because the typed call has no nullable form either. A declared kind converts a number by the rules a record's typed field uses. The `json` kind takes a document as JSON text and seals it as `JsonPlaintext` is sealed. Decrypt converts nothing, as a record does not, and its refusal names only the kind that was expected. The functions take frames and kinds and return ciphertexts. They add no type that wraps a frame or a value. Two ciphertexts of one value never have the same bytes, because each sealed leaf carries a random AES-GCM nonce. `tests/single_value.rs` holds the two interfaces to every other part: the keyset, the data key's IV and tag, the length, and the plaintext of the leaf. It seals each kind through both, each over a fresh deterministic key source of one seed. The helpers that open a leaf with a kept key move from `tests/value_bytes.rs` to `tests/common/leaves.rs` for that. --- packages/stack-encrypt/CHANGELOG.md | 42 + packages/stack-encrypt/src/dynamic/mod.rs | 12 +- packages/stack-encrypt/src/dynamic/value.rs | 559 +++++++++ packages/stack-encrypt/src/refusal.rs | 14 +- packages/stack-encrypt/tests/common/leaves.rs | 192 +++ packages/stack-encrypt/tests/common/mod.rs | 1 + packages/stack-encrypt/tests/single_value.rs | 1086 +++++++++++++++++ packages/stack-encrypt/tests/value_bytes.rs | 192 +-- 8 files changed, 1919 insertions(+), 179 deletions(-) create mode 100644 packages/stack-encrypt/src/dynamic/value.rs create mode 100644 packages/stack-encrypt/tests/common/leaves.rs create mode 100644 packages/stack-encrypt/tests/single_value.rs diff --git a/packages/stack-encrypt/CHANGELOG.md b/packages/stack-encrypt/CHANGELOG.md index 399b28ef7..28a5f7007 100644 --- a/packages/stack-encrypt/CHANGELOG.md +++ b/packages/stack-encrypt/CHANGELOG.md @@ -9,6 +9,48 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +- **Encrypt and decrypt one value whose type is known only at run time** + (#2009). `dynamic::value` does for a value in a frame what + `keyset.encrypt` and `keyset.decrypt` do for a value of a Rust type. A + language SDK holds a value as a frame, and knows the value's kind only + when the code runs. + - `dynamic::value::encrypt(&keyset, frame, kind)` takes a borrowed + `Frame` and an optional declared `ValueKind`. It returns the + `Ciphertext` that `keyset.encrypt` returns for the same value: the same + leaf, under the same key request and the same context. So + `keyset.decrypt::` opens it, and each language opens what another + wrote. + - `dynamic::value::decrypt(cipher, ciphertext, kind)` opens a ciphertext + into an `OwnedFrame` that holds one scalar. Pass `&keyset` to open only + that keyset's ciphertexts, or `&cipher` to open a ciphertext of any + keyset. + - Each has a form with a context (`encrypt_with_context`, + `decrypt_with_context`) and a form for many values that makes one key + request (`encrypt_all`, `decrypt_all`, and the two `_all_with_context` + forms). + - On encrypt, a declared kind converts a number of another width or kind + when the conversion is exact, by the rules a record's typed field uses. + With no declared kind, the scalar is sealed as it arrived. + - On decrypt, a declared kind is the kind the value must open as. + Nothing is converted. A value of another kind is `Error::OpenedType`, + which names the kind that was expected and never says what the value + opened as. + - The kind `json` takes a document as its JSON text, in a text leaf or a + bytes leaf. The engine checks the text and seals the document as + `JsonPlaintext` is sealed. On decrypt, `json` returns the document's + text in a bytes leaf, as a record's `json` field opens. + - A ciphertext holds one scalar. `encrypt` refuses an array, an object, a + passthrough and a null, plain or typed, before any key is requested. + The refusal is `dynamic::Error::Source` with one of three new reasons, + `Reason::Array`, `Reason::Object` and `Reason::Null`, or with + `Reason::Passthrough`. `undefined` under a declared kind is + `Reason::Undefined`, and a value of another kind is + `Reason::FieldType`. + - Two ciphertexts of one value never have the same bytes, because each + sealed leaf has a random nonce. The two interfaces agree on every + other part: the keyset, the data key, the length, and the plaintext of + the leaf. `tests/single_value.rs` holds them to that for every kind. + - **Encrypt a UUID as a UUID** (#1833). `value::Uuid` is vitaminc's wipeable UUID, built from the uuid crate's `Uuid` with `Uuid::new`. It seals as one leaf, and an `Option`'s `None` seals as a null as long diff --git a/packages/stack-encrypt/src/dynamic/mod.rs b/packages/stack-encrypt/src/dynamic/mod.rs index 98ce8d144..222a32976 100644 --- a/packages/stack-encrypt/src/dynamic/mod.rs +++ b/packages/stack-encrypt/src/dynamic/mod.rs @@ -32,6 +32,10 @@ //! * [`frame::OwnedFrame`] — the engine's plaintext for a value whose type //! is known only at run time: vitaminc's, re-exported with the rest of the //! frame. +//! * [`value`] — one value as one [`Ciphertext`](crate::Ciphertext), and +//! back: what [`KeysetCipher::encrypt`](crate::KeysetCipher::encrypt) and +//! [`KeysetCipher::decrypt`](crate::KeysetCipher::decrypt) do for a value +//! of a Rust type, for a value in a frame. //! * [`term`](term()) — one index term for a value, derived at the one //! scalar it is walked to. //! * [`record`] — a record's declaration as data, *lowered* into the @@ -59,10 +63,11 @@ //! //! # What is not here //! -//! Encrypting a whole value is not: an [`OwnedFrame`](frame::OwnedFrame), -//! like any source, +//! Encrypting a whole value as a tree of leaves is not: an +//! [`OwnedFrame`](frame::OwnedFrame), like any source, //! implements `Encrypt` already, so `keyset.encrypt_tree(value, aad)` is the whole -//! of it and needs nothing from this module. Nor is a second executor: nothing here calls +//! of it and needs nothing from this module. ([`value`] encrypts one scalar +//! as one opaque ciphertext, which is a different stored form.) Nor is a second executor: nothing here calls //! the term functions or the seal path to produce a record. A capability a //! data plan needs and the combinators lack is added to the combinators, //! once. @@ -112,6 +117,7 @@ mod target; mod term; #[cfg(test)] mod test_frame; +pub mod value; /// The document a `json` field's value holds, as [`read_json`] returns it: /// [`crate::json::JsonPlaintext`], named here for a binding that reaches diff --git a/packages/stack-encrypt/src/dynamic/value.rs b/packages/stack-encrypt/src/dynamic/value.rs new file mode 100644 index 000000000..fe9b29ffd --- /dev/null +++ b/packages/stack-encrypt/src/dynamic/value.rs @@ -0,0 +1,559 @@ +//! One value as one ciphertext, for a value whose type is known only at +//! run time. +//! +//! [`KeysetCipher::encrypt`] encrypts one value of a Rust type into one +//! [`Ciphertext`], and [`KeysetCipher::decrypt`] reads it back. A language +//! binding has no Rust type to name. It holds a value as a transport frame +//! ([`Frame`]), and knows the value's kind only when the code runs. This +//! module is the same pair of operations over a frame. +//! +//! - [`encrypt`] seals the one scalar a frame holds. The result is the +//! [`Ciphertext`] that `keyset.encrypt` returns for the same value: the +//! same leaf, under the same key request and the same context. So a value +//! that one language encrypts, every other language decrypts. +//! - [`decrypt`] opens a ciphertext into an [`OwnedFrame`] that holds one +//! scalar. +//! +//! Each has a form that takes a context ([`encrypt_with_context`], +//! [`decrypt_with_context`]) and a form that takes many values and makes +//! one key request ([`encrypt_all`], [`decrypt_all`], and the two +//! `_all_with_context` forms). +//! +//! # The declared kind +//! +//! Each function takes an optional [`ValueKind`]: the kind the caller +//! declares for the value. +//! +//! On encrypt, a declared kind is the kind the value is sealed as. A number +//! of another width or kind is converted when the conversion is exact, by +//! the rules of [`read`](super::read), which a record's typed field uses +//! too. So a JavaScript `34`, which arrives as a float, seals as the +//! integer `34` when the caller declares `uint64`. With no declared kind, +//! the scalar is sealed as it arrived. +//! +//! On decrypt, a declared kind is the kind the value must open as. Nothing +//! is converted: a value of another kind is refused. With no declared +//! kind, the value comes back as it was sealed. +//! +//! # A JSON document +//! +//! The kind [`ValueKind::Json`] is a JSON document. On encrypt, the frame +//! holds the document's JSON text, in a text leaf or a bytes leaf. The +//! engine checks the text by its own JSON rules and seals the document as +//! [`JsonPlaintext`] is sealed, so the +//! ciphertext is the one `keyset.encrypt(JsonPlaintext)` returns. On +//! decrypt, the frame holds the document's JSON text in a bytes leaf, as a +//! record's `json` field opens ([`json_frame`](super::json_frame)). +//! +//! # What is refused +//! +//! A [`Ciphertext`] holds one scalar. So [`encrypt`] refuses an array, an +//! object, a passthrough and a null before any key is requested. The typed +//! call has no form for a null either: `Option` is not an +//! [`OpaqueEncode`](crate::OpaqueEncode) type. Store an absent value as a +//! database `NULL`, or seal it in a record whose field declares how +//! ([`NullMode`](super::NullMode)). +//! +//! A refusal says which kind of value was found, and never the value. +//! +//! [`KeysetCipher::encrypt`]: crate::KeysetCipher::encrypt +//! [`KeysetCipher::decrypt`]: crate::KeysetCipher::decrypt + +use vitaminc_aead::frame::{Frame, OwnedFrame}; +use vitaminc_aead::plaintext::{Logical, Physical}; +use vitaminc_aead::{Encrypt, IntoContext}; + +use super::kind::convert; +use super::term::OneScalar; +use super::{read_json, Error, JsonValueError, Reason, ValueKind}; +use crate::json::inputs::json_reason; +use crate::json::JsonPlaintext; +use crate::target::core::encrypt_opaque; +use crate::target::{CipherRef, Pending, ScalarContext}; +use crate::{Ciphertext, ContextPiece, DecryptFrom, KeysetCipher}; + +/// Encrypt the one scalar `value` holds as one [`Ciphertext`], with the +/// empty context. +/// +/// The result is the ciphertext [`KeysetCipher::encrypt`] returns for the +/// same value: `keyset.decrypt::` opens it, and so does [`decrypt`]. +/// `kind` is the kind the caller declares for the value, or `None` to seal +/// the scalar as it arrived. The [module docs](self) say how a declared +/// kind converts a value, and how a JSON document is sealed. +/// +/// The frame is read here, before this returns. The pending request holds +/// only the value as it will be sealed, in a buffer that is wiped. The +/// frame stays the caller's, to wipe when the caller is done with it. An +/// [`OwnedFrame`] wipes itself when it drops. +/// +/// ``` +/// use stack_encrypt::dynamic::{frame::OwnedFrame, value, ValueKind}; +/// use stack_encrypt::StackCipher; +/// +/// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { +/// // With no `.kms(..)`, the cipher uses ZeroKMS. It reads credentials from +/// // the environment, or from the profile that `npx stash auth login` writes. +/// let cipher = StackCipher::builder() +/// # .kms(stack_encrypt::kms::FakeDataKeySource::new()) +/// .init() +/// .await?; +/// let keyset = cipher.default_keyset(); +/// +/// // A binding holds the value as a frame. A JavaScript number is a float. +/// let age = OwnedFrame::of(34.0f64)?; +/// +/// // The caller declares the kind, so the value is sealed as the integer. +/// let stored = value::encrypt(&keyset, age.frame(), Some(ValueKind::UInt64))?.await?; +/// +/// // The typed call reads it, as it reads a ciphertext it made itself. +/// let typed: u64 = keyset.decrypt(stored.clone()).await?; +/// assert_eq!(typed, 34); +/// +/// // So does the run-time call, into a frame of the declared kind. +/// let opened = value::decrypt(&keyset, stored, Some(ValueKind::UInt64)).await?; +/// assert_eq!(opened.frame(), OwnedFrame::of(34u64)?.frame()); +/// # Ok::<(), Box>(()) +/// # }).unwrap(); +/// ``` +/// +/// # Errors +/// +/// [`Error::Source`], decided here, before any key is requested: +/// +/// - [`Reason::Array`], [`Reason::Object`], [`Reason::Passthrough`] or +/// [`Reason::Null`] for a value that is not one scalar. A typed null is a +/// null. +/// - [`Reason::Undefined`] for JavaScript's `undefined` with a declared +/// kind. With no declared kind, `undefined` is sealed as it arrived. +/// - [`Reason::FieldType`] for a value that is not of the declared kind and +/// does not convert to it exactly. +/// - [`Reason::JsonSyntax`], [`Reason::JsonDuplicateKey`] or +/// [`Reason::JsonIntegerRange`] for text that is not a document, under +/// the kind [`ValueKind::Json`]. +/// +/// The error names no field and holds nothing of the value. A failure of +/// the pending request is the engine's [`Error`](crate::Error), as it is +/// for [`KeysetCipher::encrypt`]. +/// +/// [`KeysetCipher::encrypt`]: crate::KeysetCipher::encrypt +pub fn encrypt<'a, K: 'static>( + keyset: &'a KeysetCipher<'_, K>, + value: Frame<'_>, + kind: Option, +) -> Result, Error> { + seal(keyset, value, kind, ().into_context()) +} + +/// [`encrypt`], authenticating `context`, as +/// [`KeysetCipher::encrypt_with_context`] does. Decrypting needs the same +/// context. +/// +/// ``` +/// use stack_encrypt::dynamic::{frame::OwnedFrame, value}; +/// use stack_encrypt::StackCipher; +/// +/// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { +/// // With no `.kms(..)`, the cipher uses ZeroKMS. It reads credentials from +/// // the environment, or from the profile that `npx stash auth login` writes. +/// let cipher = StackCipher::builder() +/// # .kms(stack_encrypt::kms::FakeDataKeySource::new()) +/// .init() +/// .await?; +/// let keyset = cipher.default_keyset(); +/// +/// let email = OwnedFrame::of("ada@example.com")?; +/// let stored = +/// value::encrypt_with_context(&keyset, email.frame(), None, ("users", "email"))?.await?; +/// +/// let typed: String = keyset +/// .decrypt_with_context(stored, ("users", "email")) +/// .await?; +/// assert_eq!(typed, "ada@example.com"); +/// # Ok::<(), Box>(()) +/// # }).unwrap(); +/// ``` +/// +/// # Errors +/// +/// As [`encrypt`]. A context that cannot be used fails the pending +/// request, as it does for the typed call. +/// +/// [`KeysetCipher::encrypt_with_context`]: crate::KeysetCipher::encrypt_with_context +pub fn encrypt_with_context<'a, 'c, K: 'static>( + keyset: &'a KeysetCipher<'_, K>, + value: Frame<'_>, + kind: Option, + context: impl IntoContext<'c>, +) -> Result, Error> { + seal(keyset, value, kind, context.into_context().into_owned()) +} + +/// Encrypt each of `values` as a [`Ciphertext`] of its own, with the empty +/// context, in one key request. +/// +/// The ciphertexts come back in the order of the values. Each value has +/// its own data key and is authenticated on its own, as the elements of a +/// `Vec` are when the typed call encrypts one into a `Vec`. +/// `kind` is declared for every value. No values make no key request. +/// +/// To encrypt values of different declared kinds in one key request, call +/// [`encrypt`] for each and merge the results with +/// [`Pending::all`](crate::Pending::all). +/// +/// ``` +/// use stack_encrypt::dynamic::{frame::OwnedFrame, value, ValueKind}; +/// use stack_encrypt::StackCipher; +/// +/// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { +/// // With no `.kms(..)`, the cipher uses ZeroKMS. It reads credentials from +/// // the environment, or from the profile that `npx stash auth login` writes. +/// let cipher = StackCipher::builder() +/// # .kms(stack_encrypt::kms::FakeDataKeySource::new()) +/// .init() +/// .await?; +/// let keyset = cipher.default_keyset(); +/// +/// let emails = [OwnedFrame::of("ada@example.com")?, OwnedFrame::of("grace@example.com")?]; +/// let stored = value::encrypt_all( +/// &keyset, +/// emails.iter().map(OwnedFrame::frame), +/// Some(ValueKind::String), +/// )? +/// .await?; +/// assert_eq!(stored.len(), 2); +/// +/// let opened = value::decrypt_all(&keyset, stored, Some(ValueKind::String)).await?; +/// assert_eq!(opened[1].frame(), emails[1].frame()); +/// # Ok::<(), Box>(()) +/// # }).unwrap(); +/// ``` +/// +/// # Errors +/// +/// As [`encrypt`], for the first value that is refused. Nothing is +/// requested for the values before it. +pub fn encrypt_all<'a, 'f, K: 'static>( + keyset: &'a KeysetCipher<'_, K>, + values: impl IntoIterator>, + kind: Option, +) -> Result, K>, Error> { + seal_all(keyset, values, kind, ().into_context()) +} + +/// [`encrypt_all`], authenticating `context` for every value. +/// +/// # Errors +/// +/// As [`encrypt_all`]. A context that cannot be used fails the pending +/// request. +pub fn encrypt_all_with_context<'a, 'f, 'c, K: 'static>( + keyset: &'a KeysetCipher<'_, K>, + values: impl IntoIterator>, + kind: Option, + context: impl IntoContext<'c>, +) -> Result, K>, Error> { + seal_all(keyset, values, kind, context.into_context().into_owned()) +} + +/// Decrypt a [`Ciphertext`] that was sealed with the empty context, into a +/// frame that holds its one scalar. +/// +/// It opens what [`encrypt`] and [`KeysetCipher::encrypt`] seal. `kind` is +/// the kind the value must open as, or `None` to take the value as it was +/// sealed. With [`ValueKind::Json`], the frame holds the document's JSON +/// text in a bytes leaf. +/// +/// Pass `&keyset` to open only a ciphertext of that keyset: a ciphertext +/// of another keyset is refused before any key is retrieved. Pass +/// `&cipher` to open a ciphertext of any keyset the client can use. +/// +/// The frame is plaintext. It wipes its buffer when it drops. +/// +/// With no declared kind, a ciphertext that holds a null opens as the null +/// frame. [`encrypt`] seals no null, but +/// [`KeysetCipher::encrypt_tree`](crate::KeysetCipher::encrypt_tree) does. +/// +/// ``` +/// use stack_encrypt::dynamic::{frame::OwnedFrame, value, ValueKind}; +/// use stack_encrypt::{Error, StackCipher}; +/// +/// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { +/// // With no `.kms(..)`, the cipher uses ZeroKMS. It reads credentials from +/// // the environment, or from the profile that `npx stash auth login` writes. +/// let cipher = StackCipher::builder() +/// # .kms(stack_encrypt::kms::FakeDataKeySource::new()) +/// .init() +/// .await?; +/// let keyset = cipher.default_keyset(); +/// +/// // A ciphertext the typed call made. +/// let stored = keyset.encrypt(String::from("ada@example.com")).await?; +/// +/// // It opens as the kind it was sealed as. +/// let email = value::decrypt(&keyset, stored.clone(), Some(ValueKind::String)).await?; +/// assert_eq!(email.frame(), OwnedFrame::of("ada@example.com")?.frame()); +/// +/// // It does not open as another kind. The error names the kind that was +/// // expected, and nothing about the value. +/// let refused = value::decrypt(&keyset, stored, Some(ValueKind::Int64)).await; +/// assert!(matches!(refused, Err(Error::OpenedType { expected: "int64" }))); +/// # Ok::<(), Box>(()) +/// # }).unwrap(); +/// ``` +/// +/// # Errors +/// +/// The pending request fails with the engine's [`Error`](crate::Error), as +/// [`KeysetCipher::decrypt`] does: +/// [`ForeignKeyset`](crate::Error::ForeignKeyset) before any key is +/// retrieved, a key provider's error, or +/// [`Aead`](crate::Error::Aead) for a wrong context or an altered +/// ciphertext. +/// +/// A value that opens as another kind than `kind` is +/// [`OpenedType`](crate::Error::OpenedType). The error names the kind that +/// was expected. It never says what the value opened as. An array or an +/// object is refused the same way, before any key is retrieved: a +/// ciphertext never holds one. +/// +/// [`KeysetCipher::encrypt`]: crate::KeysetCipher::encrypt +/// [`KeysetCipher::decrypt`]: crate::KeysetCipher::decrypt +pub fn decrypt<'a, K: 'static>( + cipher_ref: impl Into>, + ciphertext: Ciphertext, + kind: Option, +) -> Pending<'a, OwnedFrame, K> { + open(cipher_ref.into(), ciphertext, kind, ().into_context()) +} + +/// [`decrypt`], under the context the value was encrypted with, as +/// [`KeysetCipher::decrypt_with_context`] does. +/// +/// # Errors +/// +/// As [`decrypt`]. Another context than the one the value was sealed with +/// fails the pending request. +/// +/// [`KeysetCipher::decrypt_with_context`]: crate::KeysetCipher::decrypt_with_context +pub fn decrypt_with_context<'a, 'c, K: 'static>( + cipher_ref: impl Into>, + ciphertext: Ciphertext, + kind: Option, + context: impl IntoContext<'c>, +) -> Pending<'a, OwnedFrame, K> { + open( + cipher_ref.into(), + ciphertext, + kind, + context.into_context().into_owned(), + ) +} + +/// Decrypt each of `ciphertexts` that was sealed with the empty context, +/// in one key request for each keyset they were sealed under. +/// +/// The frames come back in the order of the ciphertexts. `kind` is the +/// kind every value must open as. No ciphertexts make no key request. +/// +/// # Errors +/// +/// As [`decrypt`], for the first ciphertext that fails. The values opened +/// before it are wiped. +pub fn decrypt_all<'a, K: 'static>( + cipher_ref: impl Into>, + ciphertexts: Vec, + kind: Option, +) -> Pending<'a, Vec, K> { + open_all(cipher_ref.into(), ciphertexts, kind, ().into_context()) +} + +/// [`decrypt_all`], under the context every value was encrypted with. +/// +/// # Errors +/// +/// As [`decrypt_all`]. +pub fn decrypt_all_with_context<'a, 'c, K: 'static>( + cipher_ref: impl Into>, + ciphertexts: Vec, + kind: Option, + context: impl IntoContext<'c>, +) -> Pending<'a, Vec, K> { + open_all( + cipher_ref.into(), + ciphertexts, + kind, + context.into_context().into_owned(), + ) +} + +/// Check that `value` is one scalar a ciphertext can hold. +/// +/// # Errors +/// +/// [`Error::Source`] with the reason that names what was found: an array, +/// an object, a null or a passthrough. +fn one_scalar(value: Frame<'_>) -> Result<(), Error> { + let found = match value.kind() { + Some(ValueKind::Array) => Reason::Array, + Some(ValueKind::Object) => Reason::Object, + Some(_) => return Ok(()), + // No kind: a null, a passthrough, `undefined`, or a scalar of a + // logical type this build does not know. The last two are scalars. + None if value.is_null() => Reason::Null, + None if value.has_passthrough() => Reason::Passthrough, + None => return Ok(()), + }; + Err(Error::bad_source(found)) +} + +/// Plan the seal of one value under `context`, as the typed call plans it: +/// the value is walked into the same operation, so the leaf is the same. +fn seal<'a, K: 'static>( + keyset: &'a KeysetCipher<'_, K>, + value: Frame<'_>, + kind: Option, + context: ContextPiece<'static>, +) -> Result, Error> { + one_scalar(value)?; + let sealed = match kind { + None => encrypt_opaque(value, keyset, context), + Some(ValueKind::Json) => { + // A document crosses as text or bytes, so this converts nothing. + // It refuses `undefined`, and a value that is neither. + let _ = convert(ValueKind::Json, value)?; + let document = read_json(value).map_err(not_a_document)?; + // The document is sealed through a borrow and wiped when it + // drops here, as the typed call's owned document is. + encrypt_opaque(&document, keyset, context) + } + // The conversion also refuses `undefined`, and a value that is not + // of the declared kind. A converted value is wiped when it drops. + Some(kind) => match convert(kind, value)? { + Some(converted) => encrypt_opaque(converted.frame(), keyset, context), + None => encrypt_opaque(value, keyset, context), + }, + }; + Ok(sealed.try_map(Ciphertext::from_tree)) +} + +/// [`seal`] for each value, merged into one request. +fn seal_all<'a, 'f, K: 'static>( + keyset: &'a KeysetCipher<'_, K>, + values: impl IntoIterator>, + kind: Option, + context: ContextPiece<'static>, +) -> Result, K>, Error> { + // A refused value returns here. The pending requests of the values + // before it are dropped, and each wipes the plaintext it planned. + let sealed = values + .into_iter() + .map(|value| seal(keyset, value, kind, context.clone())) + .collect::, Error>>()?; + Ok(Pending::all(keyset, sealed)) +} + +/// The refusal of a value that is not a document under the `json` kind. +fn not_a_document(error: JsonValueError) -> Error { + Error::bad_source(match error { + JsonValueError::NotText => Reason::FieldType, + JsonValueError::Text(error) => json_reason(error), + }) +} + +/// The refusal of a value that opened as another kind than the one +/// declared. It names the declared kind alone. +fn not_opened_as(kind: ValueKind) -> crate::Error { + crate::Error::OpenedType { + expected: kind.name(), + } +} + +/// Whether a ciphertext can hold a value of `kind`. A ciphertext holds one +/// scalar, so it holds no array and no object. +fn is_scalar_kind(kind: ValueKind) -> bool { + !matches!(kind, ValueKind::Array | ValueKind::Object) +} + +/// Open one ciphertext under `context`, as the typed call opens it into an +/// [`OwnedFrame`], and check the value against `kind`. +fn open<'a, K: 'static>( + cipher_ref: CipherRef<'a, K>, + ciphertext: Ciphertext, + kind: Option, + context: ContextPiece<'static>, +) -> Pending<'a, OwnedFrame, K> { + if let Some(kind) = kind.filter(|kind| !is_scalar_kind(*kind)) { + return Pending::failed(cipher_ref, not_opened_as(kind)); + } + let opened = + OwnedFrame::decrypt_from_with_context(ciphertext, cipher_ref, ScalarContext::from(context)); + match kind { + None => opened, + Some(kind) => opened.try_map(move |value| opened_as(kind, value)), + } +} + +/// [`open`] for each ciphertext, merged into one request. +fn open_all<'a, K: 'static>( + cipher_ref: CipherRef<'a, K>, + ciphertexts: Vec, + kind: Option, + context: ContextPiece<'static>, +) -> Pending<'a, Vec, K> { + if let Some(kind) = kind.filter(|kind| !is_scalar_kind(*kind)) { + return Pending::failed(cipher_ref, not_opened_as(kind)); + } + let opened = Vec::::decrypt_from_with_context( + ciphertexts, + cipher_ref, + ScalarContext::from(context), + ); + match kind { + None => opened, + // A value that fails here drops the frames around it, and each + // frame wipes its buffer when it drops. + Some(kind) => opened.try_map(move |values| { + values + .into_iter() + .map(|value| opened_as(kind, value)) + .collect() + }), + } +} + +/// The opened `value` as a value of `kind`: the value itself, or for a +/// document its JSON text in a bytes leaf. +/// +/// # Errors +/// +/// [`crate::Error::OpenedType`] naming `kind`, for a value of another +/// kind. A frame that is refused is dropped, which wipes it. +fn opened_as(kind: ValueKind, value: OwnedFrame) -> Result { + if kind == ValueKind::Json { + return document_frame(&value); + } + if kind.holds(value.frame().kind()) { + Ok(value) + } else { + Err(not_opened_as(kind)) + } +} + +/// The document a sealed JSON value holds, as a `json` field opens: its +/// JSON text in a bytes leaf. +/// +/// # Errors +/// +/// [`crate::Error::OpenedType`] for a value that is not a text leaf holding +/// a document. The typed call's `JsonPlaintext` refuses the same values. +fn document_frame(value: &OwnedFrame) -> Result { + let document = value + .visit(OneScalar::new( + |ty: Option, value: Physical<'_>| match (ty, value) { + (None, Physical::Text(text)) => JsonPlaintext::parse(text).map_err(|_| None), + _ => Err(None), + }, + )) + .map_err(|_| not_opened_as(ValueKind::Json))?; + super::json_frame(document.value()) +} diff --git a/packages/stack-encrypt/src/refusal.rs b/packages/stack-encrypt/src/refusal.rs index 6250a4130..80add0beb 100644 --- a/packages/stack-encrypt/src/refusal.rs +++ b/packages/stack-encrypt/src/refusal.rs @@ -140,7 +140,10 @@ pub enum Error { /// not carry or carries twice, or a passthrough or a repeated map key /// under a field the plan seals, or a value of another type than its /// field declares that does not convert to it exactly, or `undefined` - /// for a field that declares a type. Also a query its field does not answer: an operator + /// for a field that declares a type. Also one value that a single + /// ciphertext cannot hold ([`value::encrypt`](crate::dynamic::value::encrypt)): + /// an array, an object, a passthrough or a null, or a value that is not + /// of the kind declared for it. Also a query its field does not answer: an operator /// the field's type does not answer, an input that cannot be read as the /// field's type ([`read`](crate::dynamic::read)) or is not the pair a range takes, a page of /// values to verify that holds a value of another type, or statistics @@ -531,6 +534,15 @@ reasons! { /// A passthrough value cannot be stored as a frame: it nests deeper, /// or holds text, bytes or a key longer, than a frame carries. Unframeable => "unframeable", "a passthrough value nests deeper, or holds a longer value, than a frame carries"; + /// An array sits where one value must be: a single ciphertext holds + /// one scalar ([`value::encrypt`](crate::dynamic::value::encrypt)). + Array => "array", "an array where one value must be"; + /// An object sits where one value must be: a single ciphertext + /// holds one scalar. + Object => "object", "an object where one value must be"; + /// A null, plain or typed, sits where one value must be: a single + /// ciphertext holds a value that is present. + Null => "null", "a null where one value must be"; /// A stored field is not a map of outputs. OutputsNotMap => "outputs_not_map", "a stored field is not a map of outputs"; /// A stored sealed field has no `"c"` node. diff --git a/packages/stack-encrypt/tests/common/leaves.rs b/packages/stack-encrypt/tests/common/leaves.rs new file mode 100644 index 000000000..8f005ea25 --- /dev/null +++ b/packages/stack-encrypt/tests/common/leaves.rs @@ -0,0 +1,192 @@ +//! Opening a sealed leaf to the plaintext sealed in it. +//! +//! A sealed leaf carries a random AES-GCM nonce, so two ciphertexts of one +//! value never have the same bytes. What a test can compare is the +//! plaintext each leaf was sealed with. [`kept_cipher`] is a cipher over +//! [`DeterministicSource`] that keeps each data key it generates, and +//! [`reveal`] opens leaves with those keys and the engine's leaf AAD. + +use std::borrow::Cow; +use std::cell::RefCell; +use std::collections::HashMap; +use std::sync::{Arc, Mutex}; + +use stack_encrypt::{CipherText, Ciphertext, SealedValue, StackCipher, StackCipherText}; +use stack_kms::{ + DataKey, DataKeySource, DataKeyWithTag, GenerateKeyPayload, IdentifiedBy, IndexKey, + IndexKeySource, RetrieveKeyPayload, UnverifiedContext, +}; +use uuid::Uuid; +use vitaminc_aead::seal::Cipher; +use vitaminc_aead::{Context, FrameWriter, IntoContext, LocalCipherText, Unspecified}; +use vitaminc_encrypt::{Aes256Cipher, Key as AesKey}; +use vitaminc_protected::{Buffer, Controlled as _, Protected}; + +use super::{hex, DeterministicSource}; + +/// The data keys a [`KeptKeys`] source generated, by IV. +pub type Kept = Mutex, [u8; 32]>>; + +/// [`DeterministicSource`], keeping each data key it generates by its IV, +/// so a test can open the leaves sealed under them without the engine. +pub struct KeptKeys { + inner: DeterministicSource, + keys: Arc, +} + +impl stack_kms::KeySourceKind for KeptKeys { + type Kind = stack_kms::OwnIdentity; +} + +impl DataKeySource for KeptKeys { + async fn generate_keys( + &self, + payloads: Vec>, + keyset_id: Option, + unverified_context: Option>, + ) -> Result, stack_kms::Error> { + let keys = self + .inner + .generate_keys(payloads, keyset_id, unverified_context) + .await?; + let mut kept = self.keys.lock().unwrap(); + for key in &keys { + let _ = kept.insert(key.key.iv.to_vec(), *key.key.key()); + } + Ok(keys) + } + + async fn retrieve_keys( + &self, + payloads: Vec>, + keyset_id: Option, + unverified_context: Option<&UnverifiedContext>, + ) -> Result, stack_kms::Error> { + self.inner + .retrieve_keys(payloads, keyset_id, unverified_context) + .await + } +} + +impl IndexKeySource for KeptKeys { + async fn load_index_key( + &self, + keyset_id: Option, + ) -> Result<(Uuid, IndexKey), stack_kms::Error> { + self.inner.load_index_key(keyset_id).await + } +} + +/// A cipher over the kept keys of `seed`, and the keys. +pub async fn kept_cipher(seed: [u8; 32]) -> (StackCipher, Arc) { + let keys = Arc::default(); + let cipher = StackCipher::builder() + .kms(KeptKeys { + inner: DeterministicSource::new(seed), + keys: Arc::clone(&keys), + }) + .init() + .await + .expect("build cipher"); + (cipher, keys) +} + +/// A vitaminc cipher that opens a stored leaf with its kept key, under the +/// AAD the engine binds a leaf to (`stack-encrypt/leaf`, the format version, +/// the keyset, the AAD of the leaf's place and the key tag, as a PAE), and +/// keeps each plaintext it opened, in walk order. +struct Reveal<'k> { + keys: &'k HashMap, [u8; 32]>, + opened: RefCell>, +} + +impl Cipher for Reveal<'_> { + type Leaf = SealedValue; + type Error = Unspecified; + + fn seal(&self, _: Protected>, _: &Context<'_>) -> Result { + Err(Unspecified) + } + + fn open( + &self, + leaf: SealedValue, + aad: &Context<'_>, + ) -> Result>, Unspecified> { + let (keyset_id, iv, tag, ciphertext) = leaf.into_parts(); + let key = self.keys.get(iv.as_slice()).ok_or(Unspecified)?; + let aad = Context::pae(&[ + b"stack-encrypt/leaf", + &[SealedValue::FORMAT_VERSION], + keyset_id.as_bytes(), + aad.as_bytes(), + &tag, + ]); + let cipher = Aes256Cipher::new(&AesKey::from(*key))?; + let plaintext = cipher.open(LocalCipherText::from(ciphertext), &aad)?; + self.opened.borrow_mut().push(hex(plaintext.risky_ref())); + Ok(plaintext) + } +} + +/// The plaintext of every leaf of `tree`, sealed under `context`, in walk +/// order: a scalar's tagged bytes, a typed null's padded bytes, and an empty +/// container's marker as the empty string. +pub fn reveal<'c>( + keys: &Kept, + tree: StackCipherText, + context: impl IntoContext<'c>, +) -> Vec { + let keys = keys.lock().unwrap(); + let reveal = Reveal { + keys: &keys, + opened: RefCell::default(), + }; + let mut out = Buffer::default(); + vitaminc_aead::decrypt_into( + &reveal, + tree, + context.into_context(), + FrameWriter::new(&mut out), + ) + .unwrap_or_else(|_| { + panic!( + "the leaves open under their kept keys: if every case fails here, \ + the AAD `Reveal` builds no longer mirrors `leaf_aad` in src/cipher.rs" + ) + }); + reveal.opened.into_inner() +} + +/// Everything of a single ciphertext that does not depend on its leaf's +/// nonce. Two ciphertexts of one value, sealed under the same data key and +/// context, have the same parts and different bytes. +#[derive(Debug, PartialEq, Eq)] +pub struct Parts { + /// The ciphertext's bytes before the leaf's AEAD output, in hex: the + /// format version, the keyset, the data key's IV, and its tag with the + /// tag's length. + pub header: String, + /// The length of the whole ciphertext in bytes. + pub len: usize, + /// The plaintext the leaf was sealed with, in hex: its tag and payload. + pub leaf: String, +} + +/// The parts of `ciphertext`, sealed under `context`, opened with the keys +/// `keys` kept. +pub fn parts<'c>(keys: &Kept, ciphertext: Ciphertext, context: impl IntoContext<'c>) -> Parts { + let bytes = ciphertext.to_bytes(); + // The leaf's AEAD output is the last part of the bytes: its nonce, the + // encrypted plaintext and the authentication tag. + let (_, _, _, sealed) = SealedValue::from(ciphertext.clone()).into_parts(); + let header = hex(&bytes[..bytes.len() - sealed.len()]); + let leaf = SealedValue::from(ciphertext); + let mut leaves = reveal(keys, CipherText::Single(leaf), context); + assert_eq!(leaves.len(), 1, "a ciphertext is one leaf"); + Parts { + header, + len: bytes.len(), + leaf: leaves.remove(0), + } +} diff --git a/packages/stack-encrypt/tests/common/mod.rs b/packages/stack-encrypt/tests/common/mod.rs index da2fca6bd..27d931c49 100644 --- a/packages/stack-encrypt/tests/common/mod.rs +++ b/packages/stack-encrypt/tests/common/mod.rs @@ -387,3 +387,4 @@ pub fn unhex(text: &str) -> Vec { } #[cfg(feature = "dynamic")] pub mod conformance; +pub mod leaves; diff --git a/packages/stack-encrypt/tests/single_value.rs b/packages/stack-encrypt/tests/single_value.rs new file mode 100644 index 000000000..138e0f501 --- /dev/null +++ b/packages/stack-encrypt/tests/single_value.rs @@ -0,0 +1,1086 @@ +//! One value as one ciphertext through the run-time interface +//! (`dynamic::value`), held to the typed one (`keyset.encrypt`, +//! `keyset.decrypt`). +//! +//! A sealed leaf carries a random AES-GCM nonce, so two ciphertexts of one +//! value never have the same bytes. What the two interfaces must agree on +//! is everything else: the bytes before the leaf's AEAD output (the format +//! version, the keyset, and the data key's IV and tag), the ciphertext's +//! length, and the plaintext the leaf was sealed with. The tests here seal +//! each value through both interfaces, each over a fresh deterministic key +//! source of one seed, and compare those parts. They also open each +//! interface's ciphertext through the other. +// The typed `Uuid` case needs the `uuid` feature, which `dynamic` does not +// turn on. +#![cfg(all(feature = "dynamic", feature = "uuid"))] + +mod common; + +use std::sync::atomic::Ordering; + +use common::frames::{frame, owned}; +use common::leaves::{kept_cipher, parts, Parts}; +use miette::Diagnostic as _; +use proptest::prelude::*; +use serde_json::json; +use stack_encrypt::dynamic::{self, frame::OwnedFrame, value, Reason, ValueKind}; +use stack_encrypt::json::JsonPlaintext; +use stack_encrypt::kms::IdentifiedBy; +use stack_encrypt::value::{Date, Decimal, Timestamp, Uuid as UuidValue}; +use stack_encrypt::{CipherText, Ciphertext, ContextPiece, Error, IntoContext, OpaqueEncode}; +use vitaminc_aead::frame::PASSTHROUGH; +use vitaminc_aead::plaintext::{FixedType, Int, Logical, Physical, Raw, Width}; + +const SEED: [u8; 32] = *b"stack-encrypt single value v1 "; + +/// A context a test seals under, beside the empty one. +fn column() -> ContextPiece<'static> { + ("users", "value").into_context().into_owned() +} + +/// The empty context, which `keyset.encrypt` and `value::encrypt` use. +fn no_context() -> ContextPiece<'static> { + ().into_context() +} + +/// `value` sealed by the typed call, over a fresh key source of the seed. +async fn typed(value: S, context: &ContextPiece<'static>) -> (Ciphertext, Parts) { + let (cipher, keys) = kept_cipher(SEED).await; + let sealed = cipher + .default_keyset() + .encrypt_with_context(value, context.clone()) + .await + .expect("the typed call seals"); + (sealed.clone(), parts(&keys, sealed, context.clone())) +} + +/// `value` sealed by the run-time call, over a fresh key source of the seed. +async fn run_time( + value: &OwnedFrame, + kind: Option, + context: &ContextPiece<'static>, +) -> (Ciphertext, Parts) { + let (cipher, keys) = kept_cipher(SEED).await; + let sealed = value::encrypt_with_context( + &cipher.default_keyset(), + value.frame(), + kind, + context.clone(), + ) + .expect("the run-time call takes the value") + .await + .expect("the run-time call seals"); + (sealed.clone(), parts(&keys, sealed, context.clone())) +} + +/// The run-time call and the typed call seal the same ciphertext for one +/// value, and each opens the other's. `typed_value` builds the typed value, +/// `frame_of` the frame a binding hands over, and `stored` the frame the +/// value opens as. +async fn assert_same_ciphertext( + name: &str, + typed_value: impl Fn() -> S, + frame_of: &OwnedFrame, + kind: Option, + stored: &OwnedFrame, + read_back: impl Fn(&T) -> OwnedFrame, +) where + S: OpaqueEncode, + T: stack_encrypt::OpaqueDecode, +{ + for context in [no_context(), column()] { + let (typed_ciphertext, typed_parts) = typed(typed_value(), &context).await; + let (run_time_ciphertext, run_time_parts) = run_time(frame_of, kind, &context).await; + assert_eq!( + run_time_parts, typed_parts, + "{name}: the run-time ciphertext differs from the typed one in a part that is not the nonce" + ); + + let (cipher, _) = kept_cipher(SEED).await; + let keyset = cipher.default_keyset(); + let opened: T = keyset + .decrypt_with_context(run_time_ciphertext, context.clone()) + .await + .unwrap_or_else(|error| { + panic!("{name}: the typed call opens the run-time ciphertext: {error}") + }); + assert_eq!( + read_back(&opened).frame(), + stored.frame(), + "{name}: the typed call reads another value from the run-time ciphertext" + ); + let opened = value::decrypt_with_context(&keyset, typed_ciphertext, None, context.clone()) + .await + .unwrap_or_else(|error| { + panic!("{name}: the run-time call opens the typed ciphertext: {error}") + }); + assert_eq!( + opened.frame(), + stored.frame(), + "{name}: the run-time call reads another value from the typed ciphertext" + ); + } +} + +fn int(int: Int) -> OwnedFrame { + frame(Raw(None, Physical::Int(int))) +} + +fn date() -> Date { + Date::new("2024-02-29".parse::().expect("a date")) +} + +fn timestamp() -> Timestamp { + Timestamp::new( + "2026-10-17T01:02:03.123456789Z" + .parse::() + .expect("an instant"), + ) + .expect("in range") +} + +fn decimal() -> Decimal { + Decimal::new( + "-1234.5600" + .parse::() + .expect("a decimal"), + ) +} + +fn uuid_value() -> UuidValue { + UuidValue::new(uuid::Uuid::from_u128( + 0x123e_4567_e89b_12d3_a456_4266_1417_4000, + )) +} + +mod the_run_time_ciphertext_is_the_typed_one { + use super::*; + + /// A value of a Rust type whose frame is of the same kind, with the + /// kind declared and with none. + macro_rules! same { + ($name:literal, $kind:expr, $ty:ty, $value:expr) => {{ + let stored = frame($value); + for declared in [None, Some($kind)] { + assert_same_ciphertext( + $name, + || $value, + &stored, + declared, + &stored, + |opened: &$ty| frame(opened), + ) + .await; + } + }}; + } + + #[tokio::test] + async fn for_every_scalar_kind_a_rust_type_spells() { + same!("bool", ValueKind::Bool, bool, true); + same!("int8", ValueKind::Int8, i8, -8i8); + same!("int16", ValueKind::Int16, i16, -300i16); + same!("int32", ValueKind::Int32, i32, -2i32); + same!("int64", ValueKind::Int64, i64, -9_007_199_254_740_993i64); + same!("int128", ValueKind::Int128, i128, i128::MIN); + same!("uint16", ValueKind::UInt16, u16, 60_000u16); + same!("uint32", ValueKind::UInt32, u32, 4_000_000_000u32); + same!("uint64", ValueKind::UInt64, u64, u64::MAX); + same!("uint128", ValueKind::UInt128, u128, u128::MAX); + same!("float32", ValueKind::Float32, f32, 1.5f32); + same!("float64", ValueKind::Float64, f64, -0.0f64); + same!("string", ValueKind::String, String, String::from("café")); + same!("empty string", ValueKind::String, String, String::new()); + same!("bytes", ValueKind::Bytes, Vec, vec![0u8, 255, 16]); + same!("date", ValueKind::Date, Date, date()); + same!("timestamp", ValueKind::Timestamp, Timestamp, timestamp()); + same!("decimal", ValueKind::Decimal, Decimal, decimal()); + same!("uuid", ValueKind::Uuid, UuidValue, uuid_value()); + } + + /// No Rust type spells a lone `u8`: a `Vec` is a byte string. So + /// the run-time leaf is compared with the leaf the cipher seals for the + /// same scalar walked as a tree. + #[tokio::test] + async fn for_an_unsigned_8_bit_integer() { + let context = column(); + let scalar = || Raw(None, Physical::Int(Int::U8(200))); + let (cipher, keys) = kept_cipher(SEED).await; + let tree = cipher + .default_keyset() + .encrypt_tree(scalar(), context.clone()) + .await + .expect("a scalar seals as a tree of one leaf"); + let CipherText::Single(leaf) = tree else { + panic!("a scalar seals as one leaf"); + }; + let walked = parts(&keys, Ciphertext::from(leaf), context.clone()); + for declared in [None, Some(ValueKind::UInt8)] { + let (_, run_time_parts) = run_time(&frame(scalar()), declared, &context).await; + assert_eq!( + run_time_parts, walked, + "uint8 declared as {declared:?}: the run-time leaf differs from the cipher's own" + ); + } + } + + /// A number of another width or kind seals as the declared kind's + /// value, which is the ciphertext the typed call makes for that value. + #[tokio::test] + async fn for_a_number_converted_to_its_declared_kind() { + assert_same_ciphertext( + "float64 34 as uint64", + || 34u64, + &frame(34.0f64), + Some(ValueKind::UInt64), + &frame(34u64), + |opened: &u64| frame(*opened), + ) + .await; + assert_same_ciphertext( + "int64 -7 as int8", + || -7i8, + &frame(-7i64), + Some(ValueKind::Int8), + &frame(-7i8), + |opened: &i8| frame(*opened), + ) + .await; + assert_same_ciphertext( + "int32 12 as float64", + || 12.0f64, + &frame(12i32), + Some(ValueKind::Float64), + &frame(12.0f64), + |opened: &f64| frame(*opened), + ) + .await; + assert_same_ciphertext( + "int64 5 as decimal", + || Decimal::new(rust_decimal::Decimal::new(5, 0)), + &frame(5i64), + Some(ValueKind::Decimal), + &frame(Decimal::new(rust_decimal::Decimal::new(5, 0))), + |opened: &Decimal| frame(opened), + ) + .await; + } + + /// A document's JSON text, in a text leaf or a bytes leaf, seals as + /// the typed call seals the document: as its compact JSON text. + #[tokio::test] + async fn for_a_json_document() { + let text = r#"{ "b": [1, 2.5, null], "a": "é" }"#; + let document = || JsonPlaintext::parse(text).expect("a document"); + // What a `String` reads back: the text the document was sealed as. + let sealed_text = frame(r#"{"a":"é","b":[1,2.5,null]}"#); + for (name, crossing) in [ + ("json as text", frame(text)), + ("json as bytes", frame(text.as_bytes().to_vec())), + ] { + assert_same_ciphertext( + name, + document, + &crossing, + Some(ValueKind::Json), + &sealed_text, + |opened: &String| frame(opened.as_str()), + ) + .await; + } + } + + proptest! { + #![proptest_config(ProptestConfig::with_cases(48))] + + /// For any scalar, any declared kind that is the scalar's own, and + /// any context, the run-time ciphertext is the typed one. + #[test] + fn for_any_generated_scalar( + scalar in any_scalar(), + declare in any::(), + context in proptest::option::of("[a-z]{1,8}"), + ) { + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .expect("a runtime"); + let context = match &context { + Some(context) => context.as_str().into_context().into_owned(), + None => no_context(), + }; + let (run_time_parts, typed_parts) = runtime.block_on(async { + let declared = declare.then_some(scalar.kind()); + let (_, run_time_parts) = run_time(&scalar.frame(), declared, &context).await; + (run_time_parts, scalar.typed_parts(&context).await) + }); + prop_assert_eq!( + run_time_parts, + typed_parts, + "a {:?} sealed at run time differs from the typed ciphertext", + scalar.kind() + ); + } + } + + /// One generated scalar, of a kind a Rust type spells. + #[derive(Debug, Clone)] + enum Scalar { + Bool(bool), + Int64(i64), + UInt64(u64), + Float64(f64), + Text(String), + Bytes(Vec), + } + + fn any_scalar() -> impl Strategy { + prop_oneof![ + any::().prop_map(Scalar::Bool), + any::().prop_map(Scalar::Int64), + any::().prop_map(Scalar::UInt64), + any::().prop_map(Scalar::Float64), + ".{0,24}".prop_map(Scalar::Text), + proptest::collection::vec(any::(), 0..24).prop_map(Scalar::Bytes), + ] + } + + impl Scalar { + fn kind(&self) -> ValueKind { + match self { + Scalar::Bool(_) => ValueKind::Bool, + Scalar::Int64(_) => ValueKind::Int64, + Scalar::UInt64(_) => ValueKind::UInt64, + Scalar::Float64(_) => ValueKind::Float64, + Scalar::Text(_) => ValueKind::String, + Scalar::Bytes(_) => ValueKind::Bytes, + } + } + + fn frame(&self) -> OwnedFrame { + match self { + Scalar::Bool(value) => frame(*value), + Scalar::Int64(value) => frame(*value), + Scalar::UInt64(value) => frame(*value), + Scalar::Float64(value) => frame(*value), + Scalar::Text(value) => frame(value.as_str()), + Scalar::Bytes(value) => frame(value.clone()), + } + } + + async fn typed_parts(&self, context: &ContextPiece<'static>) -> Parts { + match self { + Scalar::Bool(value) => typed(*value, context).await.1, + Scalar::Int64(value) => typed(*value, context).await.1, + Scalar::UInt64(value) => typed(*value, context).await.1, + Scalar::Float64(value) => typed(*value, context).await.1, + Scalar::Text(value) => typed(value.clone(), context).await.1, + Scalar::Bytes(value) => typed(value.clone(), context).await.1, + } + } + } +} + +/// A frame the hand writes: a passthrough of the text `clear`. +fn passthrough() -> OwnedFrame { + let mut bytes = vec![PASSTHROUGH]; + bytes.extend_from_slice(frame("clear").frame().as_bytes()); + owned(&bytes) +} + +fn typed_null() -> OwnedFrame { + OwnedFrame::typed_null(FixedType::plain(Width::I64).expect("a fixed type")) +} + +fn undefined() -> OwnedFrame { + frame(Raw(Some(Logical::Undefined), Physical::Null)) +} + +/// The refusal `value::encrypt` makes for `value` under `kind`, with a +/// check that it made no key request. +async fn refused(value: &OwnedFrame, kind: Option) -> dynamic::Error { + let (cipher, generates, retrieves) = common::counting_cipher().await; + let keyset = cipher.default_keyset(); + let single = match value::encrypt(&keyset, value.frame(), kind) { + Err(error) => error, + Ok(_) => panic!("a value under {kind:?} was taken where a refusal was expected"), + }; + let with_context = + match value::encrypt_with_context(&keyset, value.frame(), kind, "users/value") { + Err(error) => error, + Ok(_) => panic!("the form with a context took what the form without refused"), + }; + assert_eq!( + with_context.reason(), + single.reason(), + "the form with a context refuses for the same reason" + ); + assert_eq!( + generates.load(Ordering::SeqCst), + 0, + "a refused value requests no data key" + ); + assert_eq!( + retrieves.load(Ordering::SeqCst), + 0, + "a refused value retrieves no data key" + ); + single +} + +fn assert_source_refusal(error: &dynamic::Error, reason: Reason, what: &str) { + assert!( + matches!(error, dynamic::Error::Source { field: None, .. }), + "{what}: expected a source refusal naming no field, got: {error:?}" + ); + assert_eq!(error.reason(), Some(reason), "{what}: the reason"); + assert_eq!( + error.code().map(|code| code.to_string()).as_deref(), + Some("stack_encrypt::dynamic_source"), + "{what}: the diagnostic code" + ); +} + +mod encrypt_refuses_before_any_key_request { + use super::*; + + #[tokio::test] + async fn a_value_that_is_not_one_scalar() { + let cases = [ + ("an array", frame(vec!["a", "b"]), Reason::Array), + ("an empty array", frame(Vec::::new()), Reason::Array), + ( + "an object", + frame(std::collections::BTreeMap::from([("a", 1u32)])), + Reason::Object, + ), + ("a passthrough", passthrough(), Reason::Passthrough), + ("a plain null", OwnedFrame::null(), Reason::Null), + ("a typed null", typed_null(), Reason::Null), + ]; + for (what, value, reason) in &cases { + // With no declared kind, and with a kind of each shape: what + // was found is reported, whatever was declared. + for kind in [ + None, + Some(ValueKind::Int64), + Some(ValueKind::Array), + Some(ValueKind::Object), + Some(ValueKind::Json), + ] { + let error = refused(value, kind).await; + assert_source_refusal(&error, *reason, &format!("{what} under {kind:?}")); + } + } + } + + #[tokio::test] + async fn undefined_under_a_declared_kind() { + for kind in [ValueKind::Int64, ValueKind::String, ValueKind::Json] { + let error = refused(&undefined(), Some(kind)).await; + assert_source_refusal(&error, Reason::Undefined, &format!("undefined as {kind}")); + } + } + + #[tokio::test] + async fn a_value_that_is_not_of_the_declared_kind() { + let cases = [ + ("text as int64", frame("34"), ValueKind::Int64), + ("a fraction as uint64", frame(34.5f64), ValueKind::UInt64), + ("300 as int8", frame(300i64), ValueKind::Int8), + ("an integer as string", frame(34i64), ValueKind::String), + ("an integer as date", frame(0i32), ValueKind::Date), + ("a scalar as array", frame(34i64), ValueKind::Array), + ("a scalar as object", frame("a"), ValueKind::Object), + ("an integer as json", frame(1i64), ValueKind::Json), + ("a boolean as json", frame(true), ValueKind::Json), + ]; + for (what, value, kind) in &cases { + let error = refused(value, Some(*kind)).await; + assert_source_refusal(&error, Reason::FieldType, what); + } + } + + #[tokio::test] + async fn text_that_is_not_a_json_document() { + let cases = [ + ("not JSON", r#"{"a": "#, Reason::JsonSyntax), + ( + "a repeated member", + r#"{"a":1,"a":2}"#, + Reason::JsonDuplicateKey, + ), + ( + "an integer outside 64 bits", + "18446744073709551616", + Reason::JsonIntegerRange, + ), + ]; + for (what, text, reason) in cases { + for crossing in [frame(text), frame(text.as_bytes().to_vec())] { + let error = refused(&crossing, Some(ValueKind::Json)).await; + assert_source_refusal(&error, reason, what); + } + } + } + + /// A refusal says what kind of value was found, and nothing of it. + #[tokio::test] + async fn without_any_of_the_value_in_the_error() { + let secret = "sk_live_4242424242"; + let cases = [ + (frame(vec![secret]), None), + (frame(secret), Some(ValueKind::Int64)), + ( + frame(format!(r#"{{"key": "{secret}""#)), + Some(ValueKind::Json), + ), + ]; + for (value, kind) in &cases { + let error = refused(value, *kind).await; + let shown = format!( + "{error} {error:?} {:?}", + error.help().map(|h| h.to_string()) + ); + assert!( + !shown.contains(secret) && !shown.contains("4242"), + "the refusal under {kind:?} shows the value: {shown}" + ); + } + } +} + +mod encrypt_with_no_declared_kind { + use super::*; + + /// `undefined` is a scalar. With no declared kind it is sealed as it + /// arrived, as a field that declares no type keeps one. + #[tokio::test] + async fn seals_undefined_as_it_arrived() { + let cipher = common::stack_cipher().await; + let keyset = cipher.default_keyset(); + let sealed = value::encrypt(&keyset, undefined().frame(), None) + .expect("undefined with no declared kind is taken") + .await + .expect("it seals"); + let opened = value::decrypt(&keyset, sealed, None) + .await + .expect("it opens"); + assert_eq!( + opened.frame(), + undefined().frame(), + "undefined opens as undefined" + ); + } + + #[tokio::test] + async fn seals_a_scalar_at_the_width_it_arrived_with() { + let cipher = common::stack_cipher().await; + let keyset = cipher.default_keyset(); + let sealed = value::encrypt(&keyset, int(Int::U8(7)).frame(), None) + .expect("a uint8 is one scalar") + .await + .expect("it seals"); + let opened = value::decrypt(&keyset, sealed, None) + .await + .expect("it opens"); + assert_eq!( + opened.frame().kind(), + Some(ValueKind::UInt8), + "no declared kind converts nothing" + ); + } +} + +mod encrypt_with_a_context { + use super::*; + + #[tokio::test] + async fn binds_the_ciphertext_to_it() { + let cipher = common::stack_cipher().await; + let keyset = cipher.default_keyset(); + let sealed = value::encrypt_with_context( + &keyset, + frame("ada@example.com").frame(), + None, + ("users", "email"), + ) + .expect("one scalar") + .await + .expect("it seals"); + + let without = value::decrypt(&keyset, sealed.clone(), None).await; + assert!( + matches!(without, Err(Error::Aead)), + "the empty context must not open it, got: {without:?}" + ); + let other = + value::decrypt_with_context(&keyset, sealed.clone(), None, ("users", "name")).await; + assert!( + matches!(other, Err(Error::Aead)), + "another context must not open it, got: {other:?}" + ); + let opened = value::decrypt_with_context(&keyset, sealed, None, ("users", "email")) + .await + .expect("the same context opens it"); + assert_eq!( + opened.frame(), + frame("ada@example.com").frame(), + "the value under its context" + ); + } + + /// The call shows the context it will use, as the typed call does. + #[tokio::test] + async fn runs_under_the_context_the_typed_call_runs_under() { + let cipher = common::stack_cipher().await; + let keyset = cipher.default_keyset(); + let run_time = + value::encrypt_with_context(&keyset, frame(34i64).frame(), None, ("users", "age")) + .expect("one scalar"); + let typed = keyset.encrypt_with_context(34i64, ("users", "age")); + assert_eq!( + run_time.context(), + typed.context(), + "the two calls name different contexts" + ); + let run_time = value::encrypt(&keyset, frame(34i64).frame(), None).expect("one scalar"); + let typed = keyset.encrypt(34i64); + assert_eq!( + run_time.context(), + typed.context(), + "the two calls name different empty contexts" + ); + } +} + +mod encrypt_all { + use super::*; + + #[tokio::test] + async fn seals_every_value_in_one_key_request_and_keeps_their_order() { + let (cipher, generates, retrieves) = common::counting_cipher().await; + let keyset = cipher.default_keyset(); + let values = [frame(1.0f64), frame(2i64), frame(3u16)]; + let sealed = value::encrypt_all( + &keyset, + values.iter().map(OwnedFrame::frame), + Some(ValueKind::UInt32), + ) + .expect("three scalars") + .await + .expect("they seal"); + assert_eq!(sealed.len(), 3, "one ciphertext for each value"); + assert_eq!( + generates.load(Ordering::SeqCst), + 1, + "one key request for the batch" + ); + + let mut opened = Vec::new(); + for ciphertext in sealed.clone() { + opened.push(keyset.decrypt::(ciphertext).await.expect("a u32")); + } + assert_eq!( + opened, + [1, 2, 3], + "the ciphertexts are in the values' order" + ); + + retrieves.store(0, Ordering::SeqCst); + let frames = value::decrypt_all(&keyset, sealed, Some(ValueKind::UInt32)) + .await + .expect("they open"); + assert_eq!( + retrieves.load(Ordering::SeqCst), + 1, + "one key request opens the batch" + ); + for (opened, expected) in frames.iter().zip([1u32, 2, 3]) { + assert_eq!( + opened.frame(), + frame(expected).frame(), + "the frames are in the ciphertexts' order" + ); + } + } + + #[tokio::test] + async fn binds_every_value_to_the_context() { + let cipher = common::stack_cipher().await; + let keyset = cipher.default_keyset(); + let values = [frame("a"), frame("b")]; + let sealed = value::encrypt_all_with_context( + &keyset, + values.iter().map(OwnedFrame::frame), + None, + ("users", "name"), + ) + .expect("two scalars") + .await + .expect("they seal"); + + let without = value::decrypt_all(&keyset, sealed.clone(), None).await; + assert!( + matches!(without, Err(Error::Aead)), + "the empty context must not open the batch, got: {without:?}" + ); + let opened = value::decrypt_all_with_context(&keyset, sealed, None, ("users", "name")) + .await + .expect("the same context opens the batch"); + assert_eq!(opened.len(), 2, "one frame for each ciphertext"); + assert_eq!(opened[0].frame(), frame("a").frame(), "the first value"); + assert_eq!(opened[1].frame(), frame("b").frame(), "the second value"); + } + + #[tokio::test] + async fn refuses_the_batch_for_one_refused_value_with_no_key_request() { + let (cipher, generates, _) = common::counting_cipher().await; + let keyset = cipher.default_keyset(); + let values = [frame("a"), OwnedFrame::null(), frame(vec!["b"])]; + let error = match value::encrypt_all(&keyset, values.iter().map(OwnedFrame::frame), None) { + Err(error) => error, + Ok(_) => panic!("a batch holding a null was taken"), + }; + assert_source_refusal(&error, Reason::Null, "the first refused value"); + assert_eq!( + generates.load(Ordering::SeqCst), + 0, + "a refused batch requests no data key" + ); + } + + #[tokio::test] + async fn makes_no_key_request_for_no_values() { + let (cipher, generates, retrieves) = common::counting_cipher().await; + let keyset = cipher.default_keyset(); + let sealed = value::encrypt_all(&keyset, std::iter::empty(), None) + .expect("no values") + .await + .expect("nothing to seal"); + assert!(sealed.is_empty(), "no ciphertexts for no values"); + let opened = value::decrypt_all(&keyset, sealed, None) + .await + .expect("nothing to open"); + assert!(opened.is_empty(), "no frames for no ciphertexts"); + assert_eq!( + ( + generates.load(Ordering::SeqCst), + retrieves.load(Ordering::SeqCst) + ), + (0, 0), + "an empty batch makes no key request" + ); + } +} + +mod decrypt { + use super::*; + + #[tokio::test] + async fn returns_the_value_as_it_was_sealed_with_no_declared_kind() { + let cipher = common::stack_cipher().await; + let keyset = cipher.default_keyset(); + let sealed = keyset.encrypt(34u64).await.expect("it seals"); + let opened = value::decrypt(&keyset, sealed, None) + .await + .expect("it opens"); + assert_eq!(opened.frame(), frame(34u64).frame(), "the sealed value"); + } + + #[tokio::test] + async fn returns_a_value_of_the_declared_kind_and_converts_nothing() { + let cipher = common::stack_cipher().await; + let keyset = cipher.default_keyset(); + let sealed = keyset.encrypt(34u64).await.expect("it seals"); + let opened = value::decrypt(&keyset, sealed.clone(), Some(ValueKind::UInt64)) + .await + .expect("a uint64 opens as uint64"); + assert_eq!(opened.frame(), frame(34u64).frame(), "the sealed value"); + + // An integer of another width is another kind: decrypt converts + // nothing, as a record's typed field converts nothing when it opens. + let narrower = value::decrypt(&keyset, sealed, Some(ValueKind::UInt32)).await; + assert!( + matches!(narrower, Err(Error::OpenedType { expected: "uint32" })), + "a uint64 must not open as uint32, got: {narrower:?}" + ); + } + + /// A refusal names the kind that was expected. It never says what the + /// value opened as. + #[tokio::test] + async fn refuses_another_kind_without_saying_what_the_value_is() { + let cipher = common::stack_cipher().await; + let keyset = cipher.default_keyset(); + let sealed = keyset + .encrypt(String::from("sk_live_4242424242")) + .await + .expect("it seals"); + let error = value::decrypt(&keyset, sealed, Some(ValueKind::Int64)) + .await + .expect_err("text must not open as int64"); + assert!( + matches!(error, Error::OpenedType { expected: "int64" }), + "expected OpenedType naming int64, got: {error:?}" + ); + let shown = format!( + "{error} {error:?} {:?}", + error.help().map(|h| h.to_string()) + ); + assert!( + !shown.contains("string") && !shown.contains("String") && !shown.contains("4242"), + "the refusal says what the value opened as: {shown}" + ); + } + + #[tokio::test] + async fn refuses_an_array_or_an_object_kind_before_any_key_request() { + let (cipher, _, retrieves) = common::counting_cipher().await; + let keyset = cipher.default_keyset(); + let sealed = keyset.encrypt(34u64).await.expect("it seals"); + for (kind, name) in [(ValueKind::Array, "array"), (ValueKind::Object, "object")] { + let one = value::decrypt(&keyset, sealed.clone(), Some(kind)).await; + assert!( + matches!(one, Err(Error::OpenedType { expected }) if expected == name), + "a ciphertext must not open as {name}, got: {one:?}" + ); + let many = value::decrypt_all(&keyset, vec![sealed.clone()], Some(kind)).await; + assert!( + matches!(many, Err(Error::OpenedType { expected }) if expected == name), + "a batch must not open as {name}, got: {many:?}" + ); + } + assert_eq!( + retrieves.load(Ordering::SeqCst), + 0, + "a kind no ciphertext holds is refused with no key request" + ); + } + + #[tokio::test] + async fn opens_a_null_only_with_no_declared_kind() { + let cipher = common::stack_cipher().await; + let keyset = cipher.default_keyset(); + let tree = keyset + .encrypt_tree(None::, ("users", "age")) + .await + .expect("a null seals as a tree of one leaf"); + let CipherText::Single(leaf) = tree else { + panic!("a null seals as one leaf"); + }; + let sealed = Ciphertext::from(leaf); + let opened = value::decrypt_with_context(&keyset, sealed.clone(), None, ("users", "age")) + .await + .expect("a null leaf opens with no declared kind"); + assert!( + opened.frame().is_null(), + "a null leaf opens as the null frame" + ); + + let declared = + value::decrypt_with_context(&keyset, sealed, Some(ValueKind::Int64), ("users", "age")) + .await; + assert!( + matches!(declared, Err(Error::OpenedType { expected: "int64" })), + "a null is not a value of the declared kind, got: {declared:?}" + ); + } + + #[tokio::test] + async fn opens_only_its_own_keysets_ciphertext_through_a_keyset() { + let (cipher, _, retrieves) = common::counting_cipher().await; + let other = cipher.keyset(IdentifiedBy::Name("another-keyset".to_owned().into())); + let sealed = value::encrypt(&other, frame("elsewhere").frame(), None) + .expect("one scalar") + .await + .expect("it seals under the other keyset"); + retrieves.store(0, Ordering::SeqCst); + + let keyset = cipher.default_keyset(); + let foreign = value::decrypt(&keyset, sealed.clone(), None).await; + assert!( + matches!(foreign, Err(Error::ForeignKeyset { .. })), + "a keyset must not open another keyset's ciphertext, got: {foreign:?}" + ); + let foreign = value::decrypt_all(&keyset, vec![sealed.clone()], None).await; + assert!( + matches!(foreign, Err(Error::ForeignKeyset { .. })), + "a keyset must not open a batch of another keyset's, got: {foreign:?}" + ); + assert_eq!( + retrieves.load(Ordering::SeqCst), + 0, + "a foreign ciphertext is refused before any key is retrieved" + ); + + let opened = value::decrypt(&cipher, sealed, None) + .await + .expect("the cipher opens a ciphertext of any of its keysets"); + assert_eq!(opened.frame(), frame("elsewhere").frame(), "the value"); + } + + #[tokio::test] + async fn refuses_a_batch_when_one_value_is_of_another_kind() { + let cipher = common::stack_cipher().await; + let keyset = cipher.default_keyset(); + let sealed = vec![ + keyset.encrypt(1i64).await.expect("it seals"), + keyset.encrypt(String::from("two")).await.expect("it seals"), + keyset.encrypt(3i64).await.expect("it seals"), + ]; + let opened = value::decrypt_all(&keyset, sealed.clone(), Some(ValueKind::Int64)).await; + assert!( + matches!(opened, Err(Error::OpenedType { expected: "int64" })), + "a batch holding text must not open as int64, got: {opened:?}" + ); + let opened = value::decrypt_all(&keyset, sealed, None) + .await + .expect("with no declared kind each value opens as it was sealed"); + assert_eq!( + opened + .iter() + .map(|value| value.frame().kind()) + .collect::>(), + [ + Some(ValueKind::Int64), + Some(ValueKind::String), + Some(ValueKind::Int64) + ], + "each value keeps its own kind" + ); + } +} + +mod decrypt_a_json_document { + use super::*; + + /// The frame a `json` value opens as: its JSON text in a bytes leaf. + fn document(text: &str) -> OwnedFrame { + frame(text.as_bytes().to_vec()) + } + + #[tokio::test] + async fn returns_the_documents_text_in_a_bytes_leaf() { + let cipher = common::stack_cipher().await; + let keyset = cipher.default_keyset(); + let sealed = keyset + .encrypt(JsonPlaintext::from(json!({"name": "Ada", "n": [1.5, -2]}))) + .await + .expect("a document seals"); + let opened = value::decrypt(&keyset, sealed.clone(), Some(ValueKind::Json)) + .await + .expect("a document opens as json"); + assert_eq!( + opened.frame(), + document(r#"{"n":[1.5,-2],"name":"Ada"}"#).frame(), + "the document's text, in a bytes leaf" + ); + assert_eq!( + opened.frame(), + dynamic::json_frame(&json!({"name": "Ada", "n": [1.5, -2]})) + .expect("a document frames") + .frame(), + "the frame a record's json field opens as" + ); + + // With no declared kind the leaf comes back as it was sealed: text. + let as_sealed = value::decrypt(&keyset, sealed, None) + .await + .expect("it opens"); + assert_eq!( + as_sealed.frame().kind(), + Some(ValueKind::String), + "a document is sealed as a text leaf" + ); + } + + #[tokio::test] + async fn round_trips_what_encrypt_sealed_as_json() { + let cipher = common::stack_cipher().await; + let keyset = cipher.default_keyset(); + let sealed = value::encrypt( + &keyset, + document(r#"{ "a" : [ 1 , null ] }"#).frame(), + Some(ValueKind::Json), + ) + .expect("a document") + .await + .expect("it seals"); + let opened = value::decrypt(&keyset, sealed.clone(), Some(ValueKind::Json)) + .await + .expect("it opens as json"); + assert_eq!( + opened.frame(), + document(r#"{"a":[1,null]}"#).frame(), + "the document, as the engine writes it" + ); + let typed: JsonPlaintext = keyset + .decrypt(sealed) + .await + .expect("the typed call opens it"); + assert_eq!( + typed.value(), + &json!({"a": [1, null]}), + "the typed document" + ); + } + + #[tokio::test] + async fn refuses_a_value_that_is_not_a_document() { + let cipher = common::stack_cipher().await; + let keyset = cipher.default_keyset(); + let not_documents = [ + ( + "text that is not JSON", + keyset.encrypt(String::from("{not json")).await, + ), + ("an integer", keyset.encrypt(7i64).await), + // The typed document reads a text leaf alone, and so does this. + ( + "JSON text in a bytes leaf", + keyset.encrypt(b"{}".to_vec()).await, + ), + ]; + for (what, sealed) in not_documents { + let sealed = sealed.expect("it seals"); + let opened = value::decrypt(&keyset, sealed.clone(), Some(ValueKind::Json)).await; + assert!( + matches!(opened, Err(Error::OpenedType { expected: "json" })), + "{what} must not open as json, got: {opened:?}" + ); + let many = value::decrypt_all(&keyset, vec![sealed], Some(ValueKind::Json)).await; + assert!( + matches!(many, Err(Error::OpenedType { expected: "json" })), + "a batch holding {what} must not open as json, got: {many:?}" + ); + } + } + + #[tokio::test] + async fn opens_a_batch_of_documents_in_order() { + let cipher = common::stack_cipher().await; + let keyset = cipher.default_keyset(); + let texts = [r#"{"a":1}"#, "null", r#"["x"]"#]; + let crossing: Vec = texts.iter().map(|text| frame(*text)).collect(); + let sealed = value::encrypt_all( + &keyset, + crossing.iter().map(OwnedFrame::frame), + Some(ValueKind::Json), + ) + .expect("three documents") + .await + .expect("they seal"); + let opened = value::decrypt_all(&keyset, sealed, Some(ValueKind::Json)) + .await + .expect("they open"); + assert_eq!(opened.len(), texts.len(), "one frame for each document"); + for (opened, text) in opened.iter().zip(texts) { + assert_eq!( + opened.frame(), + document(text).frame(), + "the document {text}" + ); + } + } +} diff --git a/packages/stack-encrypt/tests/value_bytes.rs b/packages/stack-encrypt/tests/value_bytes.rs index 93660f76f..57967889e 100644 --- a/packages/stack-encrypt/tests/value_bytes.rs +++ b/packages/stack-encrypt/tests/value_bytes.rs @@ -28,34 +28,24 @@ mod common; -use std::borrow::Cow; -use std::cell::RefCell; -use std::collections::HashMap; use std::path::PathBuf; -use std::sync::{Arc, Mutex}; +use std::sync::Arc; use common::conformance::{value, Input}; use common::frames::{frame, object}; -use common::{hex, DeterministicSource}; +use common::hex; +use common::leaves::{kept_cipher, reveal, Kept, KeptKeys}; use serde_json::{json, Map, Value as Json}; use stack_encrypt::dynamic::{self, frame::OwnedFrame, record}; use stack_encrypt::json::JsonPlaintext; use stack_encrypt::sem::EqualityTerm; use stack_encrypt::target::{equality, Borrowed, CallerContext}; use stack_encrypt::value::{Date, Decimal, Timestamp, Uuid as UuidValue}; -use stack_encrypt::{AsProtectedRef as _, CipherText, SealedValue, StackCipher, StackCipherText}; -use stack_kms::{ - DataKey, DataKeySource, DataKeyWithTag, GenerateKeyPayload, IdentifiedBy, IndexKey, - IndexKeySource, RetrieveKeyPayload, UnverifiedContext, -}; +use stack_encrypt::{AsProtectedRef as _, CipherText, StackCipher}; use uuid::Uuid; use vitaminc_aead::plaintext::{FixedType, Float, Int, Logical, Physical, Raw, TimeUnit, Width}; -use vitaminc_aead::seal::Cipher; -use vitaminc_aead::{ - Context, Encrypt, Frame, FrameWriter, IntoContext, LocalCipherText, Unspecified, -}; -use vitaminc_encrypt::{Aes256Cipher, Key as AesKey}; -use vitaminc_protected::{Buffer, Controlled as _, Protected}; +use vitaminc_aead::{Encrypt, Frame}; +use vitaminc_protected::{Buffer, Controlled as _}; const SEED: [u8; 32] = *b"stack-encrypt value bytes v1 "; @@ -66,142 +56,9 @@ fn fixture_path() -> PathBuf { PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/value_bytes_v1.json") } -// ============================================================================= -// Opening a sealed leaf to the plaintext sealed in it -// ============================================================================= - -/// [`DeterministicSource`], keeping each data key it generates by its IV, -/// so a test can open the leaves sealed under them without the engine. -struct KeptKeys { - inner: DeterministicSource, - keys: Arc, [u8; 32]>>>, -} - -impl stack_kms::KeySourceKind for KeptKeys { - type Kind = stack_kms::OwnIdentity; -} - -impl DataKeySource for KeptKeys { - async fn generate_keys( - &self, - payloads: Vec>, - keyset_id: Option, - unverified_context: Option>, - ) -> Result, stack_kms::Error> { - let keys = self - .inner - .generate_keys(payloads, keyset_id, unverified_context) - .await?; - let mut kept = self.keys.lock().unwrap(); - for key in &keys { - let _ = kept.insert(key.key.iv.to_vec(), *key.key.key()); - } - Ok(keys) - } - - async fn retrieve_keys( - &self, - payloads: Vec>, - keyset_id: Option, - unverified_context: Option<&UnverifiedContext>, - ) -> Result, stack_kms::Error> { - self.inner - .retrieve_keys(payloads, keyset_id, unverified_context) - .await - } -} - -impl IndexKeySource for KeptKeys { - async fn load_index_key( - &self, - keyset_id: Option, - ) -> Result<(Uuid, IndexKey), stack_kms::Error> { - self.inner.load_index_key(keyset_id).await - } -} - -/// A cipher over the kept keys, and the keys. -async fn cipher() -> ( - StackCipher, - Arc, [u8; 32]>>>, -) { - let keys = Arc::default(); - let cipher = StackCipher::builder() - .kms(KeptKeys { - inner: DeterministicSource::new(SEED), - keys: Arc::clone(&keys), - }) - .init() - .await - .expect("build cipher"); - (cipher, keys) -} - -/// A vitaminc cipher that opens a stored leaf with its kept key, under the -/// AAD the engine binds a leaf to (`stack-encrypt/leaf`, the format version, -/// the keyset, the AAD of the leaf's place and the key tag, as a PAE), and -/// keeps each plaintext it opened, in walk order. -struct Reveal<'k> { - keys: &'k HashMap, [u8; 32]>, - opened: RefCell>, -} - -impl Cipher for Reveal<'_> { - type Leaf = SealedValue; - type Error = Unspecified; - - fn seal(&self, _: Protected>, _: &Context<'_>) -> Result { - Err(Unspecified) - } - - fn open( - &self, - leaf: SealedValue, - aad: &Context<'_>, - ) -> Result>, Unspecified> { - let (keyset_id, iv, tag, ciphertext) = leaf.into_parts(); - let key = self.keys.get(iv.as_slice()).ok_or(Unspecified)?; - let aad = Context::pae(&[ - b"stack-encrypt/leaf", - &[SealedValue::FORMAT_VERSION], - keyset_id.as_bytes(), - aad.as_bytes(), - &tag, - ]); - let cipher = Aes256Cipher::new(&AesKey::from(*key))?; - let plaintext = cipher.open(LocalCipherText::from(ciphertext), &aad)?; - self.opened.borrow_mut().push(hex(plaintext.risky_ref())); - Ok(plaintext) - } -} - -/// The plaintext of every leaf of `tree`, sealed under `context`, in walk -/// order: a scalar's tagged bytes, a typed null's padded bytes, and an empty -/// container's marker as the empty string. -fn reveal<'c>( - keys: &Mutex, [u8; 32]>>, - tree: StackCipherText, - context: impl IntoContext<'c>, -) -> Vec { - let keys = keys.lock().unwrap(); - let reveal = Reveal { - keys: &keys, - opened: RefCell::default(), - }; - let mut out = Buffer::default(); - vitaminc_aead::decrypt_into( - &reveal, - tree, - context.into_context(), - FrameWriter::new(&mut out), - ) - .unwrap_or_else(|_| { - panic!( - "the leaves open under their kept keys: if every case fails here, \ - the AAD `Reveal` builds no longer mirrors `leaf_aad` in src/cipher.rs" - ) - }); - reveal.opened.into_inner() +/// A cipher over the kept keys of [`SEED`], and the keys. +async fn cipher() -> (StackCipher, Arc) { + kept_cipher(SEED).await } fn context_label() -> String { @@ -216,7 +73,7 @@ fn context_label() -> String { /// the leaf `encrypt_tree` seals it as. async fn typed( cipher: &StackCipher, - keys: &Mutex, [u8; 32]>>, + keys: &Kept, frame_of: T, sealed: T, ) -> Json { @@ -290,10 +147,7 @@ fn document() -> JsonPlaintext { JsonPlaintext::from(json!({"a": [1, "x"], "b": null})) } -async fn typed_section( - cipher: &StackCipher, - keys: &Mutex, [u8; 32]>>, -) -> Json { +async fn typed_section(cipher: &StackCipher, keys: &Kept) -> Json { let mut out = Map::new(); macro_rules! pin { ($name:literal, $value:expr) => { @@ -368,7 +222,7 @@ fn plan(spec: &Json) -> Result { /// refusal's code and reason. async fn seal_row( cipher: &StackCipher, - keys: &Mutex, [u8; 32]>>, + keys: &Kept, spec: Json, row: impl Encrypt, ) -> Json { @@ -440,10 +294,7 @@ const KINDS: &[(&str, &str)] = &[ ("bytes", "00ff10"), ]; -async fn dynamic_section( - cipher: &StackCipher, - keys: &Mutex, [u8; 32]>>, -) -> Json { +async fn dynamic_section(cipher: &StackCipher, keys: &Kept) -> Json { let mut out = Map::new(); for (kind, text) in KINDS { let value = value(&input(kind, text)); @@ -540,7 +391,7 @@ fn typed_null(ty: FixedType) -> Vec { async fn host_row_outcome( cipher: &StackCipher, - keys: &Mutex, [u8; 32]>>, + keys: &Kept, spec: Json, field_frame: &[u8], ) -> Json { @@ -581,10 +432,7 @@ fn envelope(logical: u8, parameter: u8, int64: &[u8; 8]) -> Vec { out } -async fn host_section( - cipher: &StackCipher, - keys: &Mutex, [u8; 32]>>, -) -> Json { +async fn host_section(cipher: &StackCipher, keys: &Kept) -> Json { let to = |raw: Raw<'_>| { vitaminc_aead::to_frame(raw) .expect("a host frame") @@ -680,10 +528,7 @@ async fn host_section( /// A typed null a host sends (Go's `vcvalue.TypedNull`, or a nil pointer to /// a fixed-width type), against each null policy of a typed field, an /// untyped field, and inside an untyped value. -async fn typed_null_section( - cipher: &StackCipher, - keys: &Mutex, [u8; 32]>>, -) -> Json { +async fn typed_null_section(cipher: &StackCipher, keys: &Kept) -> Json { let int32 = typed_null(FixedType::new(None, Width::I32).expect("a fixed type")); let int64 = typed_null(FixedType::new(None, Width::I64).expect("a fixed type")); let mut out = Map::new(); @@ -745,10 +590,7 @@ async fn typed_null_section( // A JSON document // ============================================================================= -async fn json_section( - cipher: &StackCipher, - keys: &Mutex, [u8; 32]>>, -) -> Json { +async fn json_section(cipher: &StackCipher, keys: &Kept) -> Json { let text = r#"{"a":[1,"x"],"b":null}"#; let opened = dynamic::json_frame(&json!({"a": [1, "x"], "b": null})).expect("a document"); let as_text = frame(String::from(text)); From 6ebb1a16093f6f8e3f4062fd759c7051a8aee1f2 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sat, 28 Nov 2026 16:14:57 +1100 Subject: [PATCH 03/19] feat(stack-encrypt)!: decrypt a ciphertext only into a scalar target `OpaqueDecode` was implemented for every `Decrypt` type that is `Zeroize`. So `keyset.decrypt::>(ciphertext)` compiled, requested a key, decrypted, and only then failed with `Error::OpenedType`. It could never succeed, because a `Ciphertext` holds one scalar. `OpaqueDecode` is now bounded on Vitamin C's `ScalarTarget`. A `Vec` of anything but bytes, a map and a derived struct no longer compile as the target of `keyset.decrypt`, `decrypt_with_context` or `T::decrypt_from(ciphertext, ..)`. Every target that could succeed still compiles: the scalars, `JsonPlaintext`, the date, timestamp, decimal and UUID values, a `Protected` or an `Option` of one, and `OwnedFrame`. `Option` stays because it does succeed today: it reads a sealed null as `None`. `OpaqueBlob` keeps its own impl. `ScalarTarget` is re-exported at the crate root beside `Decrypt`, so that the bound can be named from this crate. A newtype that derives `Decrypt` over a scalar adds the marker by hand. BREAKING CHANGE: a target that needs a container no longer compiles as the target of a single `Ciphertext`. Decrypt a tree of leaves with `keyset.decrypt_tree`, and a column of ciphertexts with `Vec::::decrypt_from`. A newtype that derives `Decrypt` over a scalar needs `impl ScalarTarget for T {}`. --- packages/stack-encrypt/CHANGELOG.md | 28 +++ packages/stack-encrypt/src/lib.rs | 5 +- packages/stack-encrypt/src/scalar.rs | 69 +++++-- packages/stack-encrypt/tests/scalar.rs | 36 ++-- .../tests/ui/owned_collection_elements.stderr | 2 +- .../tests/ui/pass/scalar_decrypt_targets.rs | 83 ++++++++ .../ui/scalar_decrypt_into_a_container.rs | 22 ++ .../ui/scalar_decrypt_into_a_container.stderr | 190 ++++++++++++++++++ 8 files changed, 408 insertions(+), 27 deletions(-) create mode 100644 packages/stack-encrypt/tests/ui/pass/scalar_decrypt_targets.rs create mode 100644 packages/stack-encrypt/tests/ui/scalar_decrypt_into_a_container.rs create mode 100644 packages/stack-encrypt/tests/ui/scalar_decrypt_into_a_container.stderr diff --git a/packages/stack-encrypt/CHANGELOG.md b/packages/stack-encrypt/CHANGELOG.md index 28a5f7007..79cbec8fb 100644 --- a/packages/stack-encrypt/CHANGELOG.md +++ b/packages/stack-encrypt/CHANGELOG.md @@ -50,6 +50,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 sealed leaf has a random nonce. The two interfaces agree on every other part: the keyset, the data key, the length, and the plaintext of the leaf. `tests/single_value.rs` holds them to that for every kind. + - `ScalarTarget` is re-exported from Vitamin C at the crate root. - **Encrypt a UUID as a UUID** (#1833). `value::Uuid` is vitaminc's wipeable UUID, built from the uuid crate's `Uuid` with `Uuid::new`. It @@ -546,6 +547,33 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Breaking +- **A `Ciphertext` decrypts only into a type that one scalar builds** + (#2009). `OpaqueDecode` was implemented for every `Decrypt` type that is + `Zeroize`. So `keyset.decrypt::>(ciphertext)` compiled, + requested a key, decrypted, and only then failed with + `Error::OpenedType`. It could never succeed, because a ciphertext holds + one scalar. `OpaqueDecode` is now bounded on Vitamin C's `ScalarTarget`, + so such a call does not compile. This applies to `keyset.decrypt`, + `keyset.decrypt_with_context`, `T::decrypt_from(ciphertext, ..)` and a + `Ciphertext` field of a derived record. + - Still accepted: every scalar (`bool`, the integers, the floats, + `String`, `Vec`, `[u8; N]`, `value::Date`, `value::Timestamp`, + `value::Decimal`, `value::Uuid`), `JsonPlaintext`, a `Protected` or an + `Option` of one, `OwnedFrame`, and any type of your own that + implements `FromScalar`. `OpaqueBlob` keeps its own way in. + - No longer accepted: a `Vec` of anything but bytes, a `HashMap` or a + `BTreeMap`, a struct that derives `Decrypt`, and a `Protected` or an + `Option` of one of those. + - A sequence, a map or a struct is a tree of leaves, which is a + `StackCipherText`. Decrypt one with `keyset.decrypt_tree`. A column of + ciphertexts is a `Vec`, which still decrypts into a `Vec` + with `Vec::::decrypt_from`. + - A newtype that derives `Decrypt` over a scalar, such as + `struct Email(String)`, decrypted from one ciphertext before. Add + `impl stack_encrypt::ScalarTarget for Email {}` to keep it. + - No stored byte changes. Every ciphertext that decrypted before still + decrypts into the same type. + - **`dynamic::ValueFrame` is removed. The engine reads a plaintext as a borrowed `Frame` and keeps one as vitaminc's `OwnedFrame`** (#1955). `dynamic::frame` re-exports both from vitaminc. A `Frame` is one value's diff --git a/packages/stack-encrypt/src/lib.rs b/packages/stack-encrypt/src/lib.rs index eac8764e7..1f51d50bd 100644 --- a/packages/stack-encrypt/src/lib.rs +++ b/packages/stack-encrypt/src/lib.rs @@ -372,6 +372,9 @@ endpoint — are `StackKmsBuilder`'s, and the two keyset-cache knobs are //! //! The scalar API accepts owned [`OpaqueEncode`] values. It wipes the owned source //! before returning the pending request, including on planning failure. A +//! ciphertext decrypts into an [`OpaqueDecode`] type: a type that one scalar +//! builds. A target that needs a container, such as a `Vec`, does +//! not compile. A //! successful decrypt returns an ordinary owned value: the caller is then //! responsible for its cleanup. A whole value decrypted as an //! [`OpaqueBlob`](crate::OpaqueBlob) is wiped on drop. Copy types may still have copies held by the @@ -778,7 +781,7 @@ pub use target::{ // derivations see the same bytes. pub use vitaminc_aead::{ CipherText, Context, ContextPiece, ContextTag, DecodeError, Decrypt, Encrypt, EncryptRef, - IntoAad, IntoContext, Node, PassthroughFrame, Unspecified, + IntoAad, IntoContext, Node, PassthroughFrame, ScalarTarget, Unspecified, }; /// A type with an order target of its own: what an order index /// ([`Ore`], [`Ope`], [`OreBlock`]), an order term ([`sem::OreTerm`], diff --git a/packages/stack-encrypt/src/scalar.rs b/packages/stack-encrypt/src/scalar.rs index 553be5448..b236cff27 100644 --- a/packages/stack-encrypt/src/scalar.rs +++ b/packages/stack-encrypt/src/scalar.rs @@ -4,8 +4,9 @@ use crate::target::{ DecryptFrom, DecryptSource, Decryption, EncryptInto, EncryptTarget, Encryption, OptionalContext, Pending, ScalarContext, }; -use crate::{CipherText, ContextPiece, Decrypt, Error, KeysetCipher, LeafBytesError, SealedValue}; +use crate::{CipherText, ContextPiece, Error, KeysetCipher, LeafBytesError, SealedValue}; use vitaminc_aead::plaintext::Scalar; +use vitaminc_aead::ScalarTarget; use vitaminc_protected::OpaqueDebug; use zeroize::Zeroize; @@ -111,20 +112,64 @@ pub trait OpaqueEncode: sealed::Encode + Zeroize + Send + 'static {} /// A plaintext type that one opaque [`Ciphertext`] decrypts to. /// -/// `OpaqueDecode` is implemented for every [`Decrypt`] type that also -/// implements [`Zeroize`], and for [`OpaqueBlob`](crate::OpaqueBlob). -/// The `Decrypt` types include each scalar, such as `String`, and a -/// [`Protected`](vitaminc_protected::Protected) of one, such as -/// `Protected`. The trait is sealed, as `OpaqueEncode` is. +/// A `Ciphertext` holds one scalar. So `OpaqueDecode` is implemented for +/// every type that one scalar builds, Vitamin C's [`ScalarTarget`], that +/// also implements [`Zeroize`]: +/// +/// - each scalar: `bool`, the integers, the floats, `String`, `Vec` and +/// `[u8; N]`, and the date, timestamp, decimal and UUID +/// [values](crate::value) +/// - [`JsonPlaintext`](crate::json::JsonPlaintext), a JSON document +/// - a [`Protected`](vitaminc_protected::Protected) of one, such as +/// `Protected` +/// - an `Option` of one, such as `Option`, which reads a sealed null +/// as `None` +/// - an `OwnedFrame`, the value as a frame, for a caller that learns the +/// value's kind only when the code runs +/// +/// [`OpaqueBlob`](crate::OpaqueBlob) is an `OpaqueDecode` type too. The +/// trait is sealed, as `OpaqueEncode` is. +/// +/// A target that needs a container does not compile: a `Vec` of anything +/// but bytes, a map, or a struct that derives `Decrypt`. Each of them reads +/// a tree of leaves, which is a +/// [`StackCipherText`](crate::StackCipherText). Decrypt one with +/// [`KeysetCipher::decrypt_tree`]. A column of ciphertexts is a +/// `Vec`, which decrypts into a `Vec` through +/// [`DecryptFrom`]. The [crate docs on collections](crate#collections) +/// explain how. +/// +/// ```compile_fail,E0277 +/// # fn example(keyset: &stack_encrypt::KeysetCipher<'_, K>, ciphertext: stack_encrypt::Ciphertext) { +/// // A ciphertext holds one scalar, never a sequence. +/// let _ = keyset.decrypt::>(ciphertext); +/// # } +/// ``` +/// +/// A type of your own is an `OpaqueDecode` type if it implements +/// `ScalarTarget` and `Zeroize`. A type that implements Vitamin C's +/// `FromScalar` is a `ScalarTarget` already. A newtype that derives +/// [`Decrypt`](crate::Decrypt) over a scalar is not, until you add the +/// marker. The derive is Vitamin C's, so your crate needs `vitaminc-aead` +/// as a dependency to use it. +/// +/// ``` +/// use stack_encrypt::{Decrypt, ScalarTarget}; +/// use zeroize::Zeroize; +/// +/// #[derive(Decrypt, Zeroize)] +/// struct Email(String); +/// +/// impl ScalarTarget for Email {} +/// +/// fn decrypts_from_one_ciphertext() {} +/// decrypts_from_one_ciphertext::(); +/// ``` /// /// A scalar decrypted into a bare type, such as `String`, is an ordinary /// owned value, and nothing wipes it when it is dropped: `Zeroize` is the /// bound, not a drop guard. Decrypt into a `Protected` to have it wiped on /// drop. A decrypted `OpaqueBlob` also wipes its value on drop. -/// -/// A `Ciphertext` holds one scalar. A target that is not a scalar, such as -/// `Vec`, compiles, but decryption refuses it with -/// [`Error::OpenedType`]. pub trait OpaqueDecode: sealed::Decode + Zeroize + Send + 'static {} // An owned `S` is sealed through a borrow of it. `&S` is one of Vitamin C's @@ -150,7 +195,7 @@ where for<'a> &'a S: Scalar, { } -impl sealed::Decode for P { +impl sealed::Decode for P { fn open<'a, K: 'static>( leaf: SealedValue, cipher: &'a crate::StackCipher, @@ -159,7 +204,7 @@ impl sealed::Decode for P { crate::target::core::open_opaque(CipherText::Single(leaf), cipher, context) } } -impl OpaqueDecode for P {} +impl OpaqueDecode for P {} /// One opaque ciphertext, with no exposed structural node variants. /// diff --git a/packages/stack-encrypt/tests/scalar.rs b/packages/stack-encrypt/tests/scalar.rs index 3a568025a..d5ebf3942 100644 --- a/packages/stack-encrypt/tests/scalar.rs +++ b/packages/stack-encrypt/tests/scalar.rs @@ -112,22 +112,32 @@ async fn a_scalar_decrypts_straight_into_a_protected() { } #[tokio::test] -async fn a_ciphertext_opens_only_as_a_scalar_whatever_the_target() { - // A `Ciphertext` holds one scalar. The bound is `Decrypt`, so a target - // that is not a scalar compiles. Opening refuses a sequence, and reads a - // nullable target as present. +async fn a_ciphertext_opens_as_a_nullable_target() { + // A `Ciphertext` holds one scalar, so its target is one a scalar builds. + // A sequence does not compile (`tests/ui/scalar_decrypt_into_a_container.rs`). + // A nullable target does: it reads a value as present, and a sealed null + // as absent. let cipher = common::stack_cipher().await; let keyset = cipher.default_keyset(); - let ct = keyset - .encrypt("alice@example.com".to_owned()) - .await - .unwrap(); - assert!(matches!( - keyset.decrypt::>(ct).await, - Err(Error::OpenedType { .. }) - )); let ct = keyset.encrypt(42i32).await.unwrap(); - assert_eq!(keyset.decrypt::>(ct).await.unwrap(), Some(42)); + assert_eq!( + keyset.decrypt::>(ct).await.unwrap(), + Some(42), + "a value opens as present" + ); + + let node = keyset.encrypt_tree(None::, "users/age").await.unwrap(); + let stack_encrypt::CipherText::Single(leaf) = node else { + panic!("a null seals as one leaf") + }; + assert_eq!( + keyset + .decrypt_with_context::>(Ciphertext::from(leaf), "users/age") + .await + .unwrap(), + None, + "a sealed null opens as absent" + ); } #[tokio::test] diff --git a/packages/stack-encrypt/tests/ui/owned_collection_elements.stderr b/packages/stack-encrypt/tests/ui/owned_collection_elements.stderr index 32a9624ab..1a74ef34c 100644 --- a/packages/stack-encrypt/tests/ui/owned_collection_elements.stderr +++ b/packages/stack-encrypt/tests/ui/owned_collection_elements.stderr @@ -102,7 +102,7 @@ error[E0277]: the trait bound `u8: vitaminc_aead::typed::FromScalar` is not sati i8 u128 and $N others - = note: required for `u8` to implement `Decrypt` + = note: required for `u8` to implement `ScalarTarget` = note: required for `u8` to implement `OpaqueDecode` = note: required for `stack_encrypt::Ciphertext` to implement `DecryptSource` = note: 1 redundant requirement hidden diff --git a/packages/stack-encrypt/tests/ui/pass/scalar_decrypt_targets.rs b/packages/stack-encrypt/tests/ui/pass/scalar_decrypt_targets.rs new file mode 100644 index 000000000..73a009a7a --- /dev/null +++ b/packages/stack-encrypt/tests/ui/pass/scalar_decrypt_targets.rs @@ -0,0 +1,83 @@ +//! The targets one `Ciphertext` decrypts into, which must compile: every +//! scalar, a `Protected` of one, a nullable one, a JSON document, the date, +//! timestamp, decimal and UUID values, an opaque blob and a frame. +//! `tests/ui/scalar_decrypt_into_a_container.rs` pins the targets that must +//! not. +use stack_encrypt::dynamic::frame::OwnedFrame; +use stack_encrypt::json::JsonPlaintext; +use stack_encrypt::value::{Date, Decimal, Timestamp, Uuid}; +use stack_encrypt::{ + Ciphertext, Decrypt, DecryptFrom, KeysetCipher, OpaqueBlob, OpaqueDecode, Protected, + ScalarTarget, StackCipher, +}; +use stack_kms::FakeDataKeySource; + +/// A newtype that derives `Decrypt` over a scalar. Its author adds the +/// marker, because the derive does not. +#[derive(Decrypt, zeroize::Zeroize)] +struct Email(String); +impl ScalarTarget for Email {} + +/// A whole value stored as one blob keeps its own way in. +#[derive(Default, serde::Deserialize, zeroize::Zeroize)] +struct Profile { + name: String, +} + +fn opens() {} + +fn targets() { + opens::(); + opens::(); + opens::(); + opens::(); + opens::(); + opens::(); + opens::(); + opens::(); + opens::(); + opens::(); + opens::(); + opens::(); + opens::(); + opens::>(); + opens::<[u8; 16]>(); + opens::(); + opens::(); + opens::(); + opens::(); + opens::(); + opens::>(); + opens::>>(); + opens::>(); + opens::>(); + opens::>(); + opens::>>(); + opens::>>(); + opens::(); + opens::(); + opens::>(); +} + +async fn calls( + cipher: &StackCipher, + keyset: &KeysetCipher<'_, FakeDataKeySource>, + ciphertext: Ciphertext, +) -> Result<(), stack_encrypt::Error> { + let _: i64 = keyset.decrypt(ciphertext.clone()).await?; + let _: Protected = keyset + .decrypt_with_context(ciphertext.clone(), ("users", "email")) + .await?; + let _ = keyset.decrypt::>(ciphertext.clone()).await?; + let _ = Vec::::decrypt_from(ciphertext.clone(), keyset).await?; + let _ = OwnedFrame::decrypt_from(ciphertext.clone(), cipher).await?; + let _ = Email::decrypt_from(ciphertext.clone(), cipher).await?; + // A column of ciphertexts is a `Vec` of them, one scalar each. + let _ = Vec::::decrypt_from(vec![ciphertext], keyset).await?; + Ok(()) +} + +fn main() { + let _ = targets; + let _ = calls; +} diff --git a/packages/stack-encrypt/tests/ui/scalar_decrypt_into_a_container.rs b/packages/stack-encrypt/tests/ui/scalar_decrypt_into_a_container.rs new file mode 100644 index 000000000..9b7a66e9c --- /dev/null +++ b/packages/stack-encrypt/tests/ui/scalar_decrypt_into_a_container.rs @@ -0,0 +1,22 @@ +//! A `Ciphertext` holds one scalar, so it decrypts only into a target that +//! one scalar builds. A sequence, a map, a derived struct and a protected +//! sequence each need a container, and do not compile. +//! `tests/ui/pass/scalar_decrypt_targets.rs` pins the targets that do. +use std::collections::{BTreeMap, HashMap}; + +use stack_encrypt::{Ciphertext, Decrypt, DecryptFrom, KeysetCipher, Protected}; + +#[derive(Decrypt, zeroize::Zeroize)] +struct Account { + id: u64, +} + +fn unsupported(keyset: &KeysetCipher<'_, K>, ciphertext: Ciphertext) { + let _ = keyset.decrypt::>(ciphertext.clone()); + let _ = keyset.decrypt::>(ciphertext.clone()); + let _ = keyset.decrypt::(ciphertext.clone()); + let _ = keyset.decrypt::>>(ciphertext.clone()); + let _ = keyset.decrypt_with_context::>(ciphertext.clone(), "users/tags"); + let _ = Vec::::decrypt_from(ciphertext, keyset); +} +fn main() {} diff --git a/packages/stack-encrypt/tests/ui/scalar_decrypt_into_a_container.stderr b/packages/stack-encrypt/tests/ui/scalar_decrypt_into_a_container.stderr new file mode 100644 index 000000000..7f65aa207 --- /dev/null +++ b/packages/stack-encrypt/tests/ui/scalar_decrypt_into_a_container.stderr @@ -0,0 +1,190 @@ +error[E0277]: the trait bound `Vec: OpaqueDecode` is not satisfied + --> tests/ui/scalar_decrypt_into_a_container.rs:15:30 + | +15 | let _ = keyset.decrypt::>(ciphertext.clone()); + | ------- ^^^^^^^^^^^ the trait `FromScalar` is not implemented for `Vec` + | | + | required by a bound introduced by this call + | +help: the trait `FromScalar` is implemented for `Vec` + --> $WORKSPACE/packages/vitaminc-aead/src/typed.rs + | + | impl FromScalar for Vec { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ + = note: required for `Vec` to implement `ScalarTarget` + = note: required for `Vec` to implement `OpaqueDecode` +note: required by a bound in `stack_encrypt::scalar::>::decrypt` + --> src/scalar.rs + | + | pub fn decrypt(&self, ciphertext: Ciphertext) -> Pending<'_, P, K> { + | ^^^^^^^^^^^^ required by this bound in `stack_encrypt::scalar::>::decrypt` + +error[E0277]: the trait bound `BTreeMap: OpaqueDecode` is not satisfied + --> tests/ui/scalar_decrypt_into_a_container.rs:16:30 + | +16 | let _ = keyset.decrypt::>(ciphertext.clone()); + | ------- ^^^^^^^^^^^^^^^^^^^^^ the trait `FromScalar` is not implemented for `BTreeMap` + | | + | required by a bound introduced by this call + | + = help: the following other types implement trait `FromScalar`: + JsonPlaintext + Vec + [u8; N] + bool + f32 + f64 + i128 + i16 + and $N others + = note: required for `BTreeMap` to implement `ScalarTarget` + = note: required for `BTreeMap` to implement `OpaqueDecode` +note: required by a bound in `stack_encrypt::scalar::>::decrypt` + --> src/scalar.rs + | + | pub fn decrypt(&self, ciphertext: Ciphertext) -> Pending<'_, P, K> { + | ^^^^^^^^^^^^ required by this bound in `stack_encrypt::scalar::>::decrypt` + +error[E0277]: the trait bound `BTreeMap: OpaqueDecode` is not satisfied + --> tests/ui/scalar_decrypt_into_a_container.rs:16:30 + | +16 | let _ = keyset.decrypt::>(ciphertext.clone()); + | ------- ^^^^^^^^^^^^^^^^^^^^^ the trait `DefaultIsZeroes` is not implemented for `BTreeMap` + | | + | required by a bound introduced by this call + | + = help: the following other types implement trait `DefaultIsZeroes`: + () + PhantomPinned + bool + char + f32 + f64 + i128 + i16 + and $N others + = note: required for `BTreeMap` to implement `Zeroize` + = note: required for `BTreeMap` to implement `OpaqueDecode` +note: required by a bound in `stack_encrypt::scalar::>::decrypt` + --> src/scalar.rs + | + | pub fn decrypt(&self, ciphertext: Ciphertext) -> Pending<'_, P, K> { + | ^^^^^^^^^^^^ required by this bound in `stack_encrypt::scalar::>::decrypt` + +error[E0277]: the trait bound `Account: OpaqueDecode` is not satisfied + --> tests/ui/scalar_decrypt_into_a_container.rs:17:30 + | +17 | let _ = keyset.decrypt::(ciphertext.clone()); + | ------- ^^^^^^^ unsatisfied trait bound + | | + | required by a bound introduced by this call + | +help: the trait `FromScalar` is not implemented for `Account` + --> tests/ui/scalar_decrypt_into_a_container.rs:10:1 + | +10 | struct Account { + | ^^^^^^^^^^^^^^ + = help: the following other types implement trait `FromScalar`: + JsonPlaintext + Vec + [u8; N] + bool + f32 + f64 + i128 + i16 + and $N others + = note: required for `Account` to implement `ScalarTarget` + = note: required for `Account` to implement `OpaqueDecode` +note: required by a bound in `stack_encrypt::scalar::>::decrypt` + --> src/scalar.rs + | + | pub fn decrypt(&self, ciphertext: Ciphertext) -> Pending<'_, P, K> { + | ^^^^^^^^^^^^ required by this bound in `stack_encrypt::scalar::>::decrypt` + +error[E0277]: the trait bound `Protected>: OpaqueDecode` is not satisfied + --> tests/ui/scalar_decrypt_into_a_container.rs:18:30 + | +18 | let _ = keyset.decrypt::>>(ciphertext.clone()); + | ------- ^^^^^^^^^^^^^^^^^^^ the trait `ScalarTarget` is not implemented for `Protected>` + | | + | required by a bound introduced by this call + | +help: the trait `ScalarTarget` is implemented for `Protected` + --> $WORKSPACE/packages/vitaminc-aead/src/typed.rs + | + | impl ScalarTarget for Protected {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + = note: required for `Protected>` to implement `OpaqueDecode` +note: required by a bound in `stack_encrypt::scalar::>::decrypt` + --> src/scalar.rs + | + | pub fn decrypt(&self, ciphertext: Ciphertext) -> Pending<'_, P, K> { + | ^^^^^^^^^^^^ required by this bound in `stack_encrypt::scalar::>::decrypt` + +error[E0277]: the trait bound `HashMap: OpaqueDecode` is not satisfied + --> tests/ui/scalar_decrypt_into_a_container.rs:19:43 + | +19 | let _ = keyset.decrypt_with_context::>(ciphertext.clone(), "users/tags"); + | -------------------- ^^^^^^^^^^^^^^^^^^^^^^^ the trait `FromScalar` is not implemented for `HashMap` + | | + | required by a bound introduced by this call + | + = help: the following other types implement trait `FromScalar`: + JsonPlaintext + Vec + [u8; N] + bool + f32 + f64 + i128 + i16 + and $N others + = note: required for `HashMap` to implement `ScalarTarget` + = note: required for `HashMap` to implement `OpaqueDecode` +note: required by a bound in `stack_encrypt::scalar::>::decrypt_with_context` + --> src/scalar.rs + | + | pub fn decrypt_with_context<'c, P: OpaqueDecode>( + | ^^^^^^^^^^^^ required by this bound in `stack_encrypt::scalar::>::decrypt_with_context` + +error[E0277]: the trait bound `HashMap: OpaqueDecode` is not satisfied + --> tests/ui/scalar_decrypt_into_a_container.rs:19:43 + | +19 | let _ = keyset.decrypt_with_context::>(ciphertext.clone(), "users/tags"); + | -------------------- ^^^^^^^^^^^^^^^^^^^^^^^ the trait `DefaultIsZeroes` is not implemented for `HashMap` + | | + | required by a bound introduced by this call + | + = help: the following other types implement trait `DefaultIsZeroes`: + () + PhantomPinned + bool + char + f32 + f64 + i128 + i16 + and $N others + = note: required for `HashMap` to implement `Zeroize` + = note: required for `HashMap` to implement `OpaqueDecode` +note: required by a bound in `stack_encrypt::scalar::>::decrypt_with_context` + --> src/scalar.rs + | + | pub fn decrypt_with_context<'c, P: OpaqueDecode>( + | ^^^^^^^^^^^^ required by this bound in `stack_encrypt::scalar::>::decrypt_with_context` + +error[E0277]: the trait bound `Vec: FromScalar` is not satisfied + --> tests/ui/scalar_decrypt_into_a_container.rs:20:13 + | +20 | let _ = Vec::::decrypt_from(ciphertext, keyset); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `FromScalar` is not implemented for `Vec` + | +help: the trait `FromScalar` is implemented for `Vec` + --> $WORKSPACE/packages/vitaminc-aead/src/typed.rs + | + | impl FromScalar for Vec { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ + = note: required for `Vec` to implement `ScalarTarget` + = note: required for `Vec` to implement `OpaqueDecode` + = note: required for `stack_encrypt::Ciphertext` to implement `DecryptSource>` From da9784a523a9cb3865ee36bc3ad1385c071530b7 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sat, 28 Nov 2026 16:15:03 +1100 Subject: [PATCH 04/19] refactor(recipher-js): encrypt through the engine's single-value call The addon wrapped each frame in a type of its own, `OneValue`, and implemented vitaminc's `Scalar` for it so that the engine's typed encrypt would take it. That claim was the addon's to keep true, and every other language SDK would have needed its own copy. The engine now has a run-time single-value encrypt and decrypt. The addon calls them and `OneValue` is gone, with the `zeroize` dependency only it used. Behaviour is unchanged. This build still encrypts a string only: the addon checks that first, so a caller still gets `recipher_js::not_a_string`, and it declares the kind `string` to the engine, which checks again. The frames are dropped, and so wiped, as soon as the engine has read them, before the key request is awaited. Decrypt declares no kind, because the type of a `Ciphertext` is known to TypeScript alone. --- .../packages/recipher-js/Cargo.lock | 1 - .../packages/recipher-js/crate/Cargo.toml | 3 - .../packages/recipher-js/crate/src/cipher.rs | 71 +++++++++++++--- .../recipher-js/crate/src/engine_tests.rs | 7 +- .../packages/recipher-js/crate/src/lib.rs | 1 - .../packages/recipher-js/crate/src/value.rs | 84 ------------------- 6 files changed, 63 insertions(+), 104 deletions(-) delete mode 100644 languages/typescript/packages/recipher-js/crate/src/value.rs diff --git a/languages/typescript/packages/recipher-js/Cargo.lock b/languages/typescript/packages/recipher-js/Cargo.lock index 2f2ed3116..0f2572e31 100644 --- a/languages/typescript/packages/recipher-js/Cargo.lock +++ b/languages/typescript/packages/recipher-js/Cargo.lock @@ -2510,7 +2510,6 @@ dependencies = [ "tokio", "vitaminc-aead 0.10.0", "vitaminc-protected 0.10.0", - "zeroize", ] [[package]] diff --git a/languages/typescript/packages/recipher-js/crate/Cargo.toml b/languages/typescript/packages/recipher-js/crate/Cargo.toml index 3d6fa1191..b79575a18 100644 --- a/languages/typescript/packages/recipher-js/crate/Cargo.toml +++ b/languages/typescript/packages/recipher-js/crate/Cargo.toml @@ -46,9 +46,6 @@ miette = "7.5.0" thiserror = "1.0.56" # For the structured fields of an engine error (`ErrorPayload::payload`). serde_json = "1" -# The engine's opaque path wipes a value it did not seal. The version the -# engine resolves. -zeroize = "1" [dev-dependencies] stack-encrypt = { path = "../../../../../packages/stack-encrypt", default-features = false, features = ["dynamic", "http", "test-support"] } diff --git a/languages/typescript/packages/recipher-js/crate/src/cipher.rs b/languages/typescript/packages/recipher-js/crate/src/cipher.rs index 200477e36..30c7eb1f0 100644 --- a/languages/typescript/packages/recipher-js/crate/src/cipher.rs +++ b/languages/typescript/packages/recipher-js/crate/src/cipher.rs @@ -16,16 +16,15 @@ use std::sync::Arc; use napi::bindgen_prelude::{JavaScriptClassExt, JsValue, Object, PromiseRaw, Unknown}; use napi::Env; use napi_derive::napi; -use stack_encrypt::dynamic::frame::OwnedFrame; +use stack_encrypt::dynamic::{frame::OwnedFrame, value, ValueKind}; use stack_encrypt::kms::{DataKeySource, IndexKeySource, StackKms}; -use stack_encrypt::{CipherRef, DecryptFrom, EncryptInto, KeysetCipher, StackCipher}; +use stack_encrypt::{CipherRef, KeysetCipher, StackCipher}; use vitaminc_protected::OpaqueDebug; use crate::ciphertext::Ciphertext; use crate::error::{Error, RecipherErrorFields}; use crate::js; use crate::outcome::{not_made, refused, spawn, Outcome}; -use crate::value::OneValue; /// The engine's cipher, with the key source it was built with. A napi class /// cannot be generic, so each key source is one variant. @@ -155,7 +154,7 @@ impl Keyset { env: &'e Env, value: Unknown<'_>, ) -> napi::Result>> { - let value = match js::read(env, value).and_then(OneValue::new) { + let value = match js::read(env, value).and_then(a_string) { Ok(value) => value, Err(error) => return refused(env, error), }; @@ -301,18 +300,45 @@ pub(crate) async fn open_in( }) } -/// Encrypts values under `keyset`. Each value becomes one ciphertext with -/// its own data key. All the values use one key request, however many -/// there are. +/// Returns `value`, if it is one string. This build encrypts a string +/// only. +/// +/// # Errors +/// +/// Returns `recipher_js::not_a_string` for any other value. +pub(crate) fn a_string(value: OwnedFrame) -> Outcome { + if value.frame().kind() == Some(ValueKind::String) { + Ok(value) + } else { + Err(Error::NotAString.into()) + } +} + +/// Encrypts strings under `keyset`, through the engine's run-time +/// single-value encrypt. Each value becomes one ciphertext with its own +/// data key. Rust's `keyset.encrypt(value)` returns the same ciphertext for +/// the same value. All the values use one key request, however many there +/// are. +/// +/// The engine checks each value again: a value that is not one string is +/// refused with the engine's own error, before any key request. pub(crate) async fn seal( keyset: &KeysetCipher<'_, K>, - values: Vec, + values: Vec, ) -> Outcome> where K: DataKeySource + IndexKeySource + Sync + 'static, { - values - .encrypt_into::, K>(keyset) + let pending = value::encrypt_all( + keyset, + values.iter().map(OwnedFrame::frame), + Some(ValueKind::String), + ) + .map_err(|error| RecipherErrorFields::engine(&error))?; + // The engine has read every value. Dropping the frames wipes them, so + // no value waits in a frame for the key request. + drop(values); + pending .await .map_err(|error| RecipherErrorFields::engine(&error)) } @@ -320,6 +346,10 @@ where /// Decrypts ciphertexts through `cipher`: a cipher, or one keyset of it. /// The function makes one key request for each keyset the ciphertexts /// were made under. +/// +/// It declares no kind, so each value comes back as it was encrypted. A +/// call has no type to declare at run time: the type of a `Ciphertext` +/// is known to TypeScript alone. pub(crate) async fn unseal<'c, K>( cipher: impl Into>, sealed: Vec, @@ -327,7 +357,7 @@ pub(crate) async fn unseal<'c, K>( where K: DataKeySource + IndexKeySource + Sync + 'static, { - Vec::::decrypt_from(sealed, cipher) + value::decrypt_all(cipher, sealed, None) .await .map_err(|error| RecipherErrorFields::engine(&error)) } @@ -336,6 +366,25 @@ where mod tests { use super::*; + #[test] + fn a_string_is_taken_and_another_value_is_not() { + assert!( + a_string(OwnedFrame::of("text").unwrap()).is_ok(), + "a string is taken" + ); + for other in [ + OwnedFrame::of(5i64).unwrap(), + OwnedFrame::of(vec!["a", "b"]).unwrap(), + OwnedFrame::null(), + ] { + let refused = a_string(other).unwrap_err(); + assert_eq!( + refused.code, "recipher_js::not_a_string", + "a value that is not a string is refused" + ); + } + } + #[test] fn a_build_without_the_test_cipher_says_how_to_get_one() { let error = RecipherErrorFields::from(Error::NoTesting); diff --git a/languages/typescript/packages/recipher-js/crate/src/engine_tests.rs b/languages/typescript/packages/recipher-js/crate/src/engine_tests.rs index 3eaae4240..5f3a39f0a 100644 --- a/languages/typescript/packages/recipher-js/crate/src/engine_tests.rs +++ b/languages/typescript/packages/recipher-js/crate/src/engine_tests.rs @@ -7,7 +7,6 @@ use stack_encrypt::kms::DeterministicSource; use stack_encrypt::StackCipher; use crate::cipher::{open_in, seal, unseal, Confined, Engine}; -use crate::value::OneValue; const SEED: [u8; 32] = [7; 32]; @@ -19,12 +18,12 @@ async fn engine() -> StackCipher { .unwrap() } -fn one(text: &str) -> OneValue { - OneValue::new(OwnedFrame::of(text).unwrap()).unwrap() +fn one(text: &str) -> OwnedFrame { + OwnedFrame::of(text).unwrap() } /// Encrypts `values` through the crate, with the test keys. -async fn sdk_seal(values: Vec) -> Vec { +async fn sdk_seal(values: Vec) -> Vec { seal(&engine().await.default_keyset(), values) .await .unwrap() diff --git a/languages/typescript/packages/recipher-js/crate/src/lib.rs b/languages/typescript/packages/recipher-js/crate/src/lib.rs index 858ed99b1..53356392c 100644 --- a/languages/typescript/packages/recipher-js/crate/src/lib.rs +++ b/languages/typescript/packages/recipher-js/crate/src/lib.rs @@ -55,7 +55,6 @@ mod ciphertext; mod error; mod js; mod outcome; -mod value; #[cfg(all(test, feature = "testing"))] mod engine_tests; diff --git a/languages/typescript/packages/recipher-js/crate/src/value.rs b/languages/typescript/packages/recipher-js/crate/src/value.rs deleted file mode 100644 index 1cb17ee93..000000000 --- a/languages/typescript/packages/recipher-js/crate/src/value.rs +++ /dev/null @@ -1,84 +0,0 @@ -//! A value that the engine encrypts as one leaf. -//! -//! The engine is the Stack Encrypt engine, the `stack-encrypt` crate. A -//! leaf is one value that the engine encrypts as a single ciphertext. - -use stack_encrypt::dynamic::plaintext::{depth, Error as _, Scalar, Sink, SourceError}; -use stack_encrypt::dynamic::{frame::OwnedFrame, ValueKind}; -use stack_encrypt::Encrypt; -use vitaminc_protected::OpaqueDebug; - -use crate::error::{Error, RecipherErrorFields}; - -/// A value checked to be one string. -/// -/// The engine encrypts the value through its opaque scalar path. That path -/// encrypts a whole value as one leaf. Rust's `keyset.encrypt(value)` uses -/// the same path. So each ciphertext has the form that Rust and Go write -/// for the same value. -/// -/// The engine encrypts a value as one opaque leaf only when its type -/// implements `Scalar`, a trait of vitaminc, CipherStash's cryptography -/// library. An [`OwnedFrame`] can contain any value of the engine's value -/// model, the set of value types the engine reads. So an [`OwnedFrame`] is -/// not a `Scalar`. This type checks that the frame contains one string. The -/// check runs once, before the engine reads the value. -/// -/// The opaque path also needs a value it can wipe (`Zeroize`). Wiping drops -/// the frame, and the frame wipes its own buffer when it drops. `Debug` -/// hides the value. -#[derive(OpaqueDebug)] -pub(crate) struct OneValue(Option); - -impl OneValue { - /// Returns `value` as a [`OneValue`], if it is one string. - /// - /// # Errors - /// - /// Returns `recipher_js::not_a_string` for any other value. - pub(crate) fn new(value: OwnedFrame) -> Result { - if value.frame().kind() == Some(ValueKind::String) { - Ok(Self(Some(value))) - } else { - Err(Error::NotAString.into()) - } - } -} - -impl zeroize::Zeroize for OneValue { - fn zeroize(&mut self) { - // Dropping the frame wipes its buffer. - self.0 = None; - } -} - -impl Encrypt for &OneValue { - const DEPTH: Option = depth::SCALAR; - fn visit(self, sink: S) -> Result { - match &self.0 { - Some(frame) => frame.visit(sink), - None => Err(S::Error::source(SourceError::msg("a wiped value"))), - } - } -} - -impl Scalar for &OneValue {} - -#[cfg(test)] -mod tests { - use super::OneValue; - use stack_encrypt::dynamic::frame::OwnedFrame; - - #[test] - fn a_string_is_one_value_and_another_value_is_not() { - assert!(OneValue::new(OwnedFrame::of("text").unwrap()).is_ok()); - let refused = OneValue::new(OwnedFrame::of(5i64).unwrap()).unwrap_err(); - assert_eq!(refused.code, "recipher_js::not_a_string"); - } - - #[test] - fn debug_hides_the_value() { - let value = OneValue::new(OwnedFrame::of("secret").unwrap()).unwrap(); - assert!(!format!("{value:?}").contains("secret")); - } -} From 6f37abbfc543433ab31ccfaa3364f1a118d7f1ee Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sat, 28 Nov 2026 16:15:04 +1100 Subject: [PATCH 05/19] test(conformance): add the single-value profile One value encrypted into one ciphertext is the simplest thing an SDK does, and no shared case said what it must write. `single-value-v1` gives each runner a value, the kind declared for it and a context. It covers every scalar kind, the exact conversions a declared kind makes, JSON documents, batches, and the refusals of an array, an object, a passthrough, a null, `undefined` and a value of another kind. The expected file is written by the Rust runner. It freezes each input's frame, the plaintext each leaf is sealed with, and a ciphertext every runner must open. Ciphertext bytes are never compared whole, because each sealed leaf has a random nonce. A runner compares the parts the nonce does not change. The Rust runner also holds the run-time interface to the typed one for every case a Rust type spells. `test:conformance` runs it. The Go runner comes with the Go SDK's single-value calls (#2010), and the README and the coverage map record it as pending. The corpus's shared input reader takes a `uuid` input for this profile. --- conformance/stack-encrypt/README.md | 20 +- conformance/stack-encrypt/coverage.md | 2 +- .../stack-encrypt/single-value-contract.md | 143 +++ .../v1/single-value-v1.cases.json | 909 ++++++++++++++++++ .../single-value-v1.expected.rust-native.json | 287 ++++++ packages/stack-encrypt/CHANGELOG.md | 3 + .../stack-encrypt/tests/common/conformance.rs | 18 + .../tests/single_value_conformance.rs | 654 +++++++++++++ .../__tests__/stack-conformance-ci.test.mjs | 3 + scripts/stack-conformance.sh | 2 +- 10 files changed, 2038 insertions(+), 3 deletions(-) create mode 100644 conformance/stack-encrypt/single-value-contract.md create mode 100644 conformance/stack-encrypt/v1/single-value-v1.cases.json create mode 100644 conformance/stack-encrypt/v1/single-value-v1.expected.rust-native.json create mode 100644 packages/stack-encrypt/tests/single_value_conformance.rs diff --git a/conformance/stack-encrypt/README.md b/conformance/stack-encrypt/README.md index d3e5093d7..6370d85f6 100644 --- a/conformance/stack-encrypt/README.md +++ b/conformance/stack-encrypt/README.md @@ -44,6 +44,8 @@ these rules. | `record-values-v1.cases.json` | cases | `tests/value_conformance.rs` | `value_conformance_test.go` | | `record-query-refusals-v1.cases.json` | cases | `tests/query_refusal_conformance.rs` | `query_refusal_conformance_test.go` | | `record-raw-frames-v1.cases.json` | cases | `tests/raw_frame_conformance.rs` | `raw_frame_conformance_test.go` | +| `single-value-v1.cases.json` | cases | `tests/single_value_conformance.rs` | — (pending, #2010) | +| `single-value-v1.expected.rust-native.json` | expected | `tests/single_value_conformance.rs` (writes it) | — (pending, #2010) | | `artifact-exchange-v1.cases.json` | cases | `tests/exchange_conformance.rs`, run by `scripts/stack-exchange-conformance.mjs` | `exchange_conformance_test.go`, run by `scripts/stack-exchange-conformance.mjs` | | `eql-json-v1.cases.json` | cases | `tests/json_operators.rs`; EQL's `tests/encryption/tests/json_tree_data_plan.rs` | `json_conformance_test.go` | | `eql-json-v1.enrollment.json` | enrollment | `scripts/stack-eql-conformance.mjs` runs the tests it names | `scripts/stack-eql-conformance.mjs` runs the tests it names | @@ -86,7 +88,8 @@ The same task runs the shared declaration acceptance/rejection corpus in both languages, with native observations of normalization. It also runs the shared runtime, read, context, value-boundary, query-refusal and raw-frame cases, and enrolls the existing value-kind, context-field and query-operator -fixtures described below. It ends with the fresh artifact exchange in both +fixtures described below. It runs the single-value cases in native Rust +only: their Go runner is pending. It ends with the fresh artifact exchange in both directions (`test:conformance:exchange`, which also needs the deterministic EQL guest). Set no fixture-update variables when checking conformance. @@ -177,6 +180,21 @@ in the Rust crate and `TestValueConformance`, `TestQueryRefusalConformance` and `TestRawFrameConformance` in the Go module; `test:conformance` runs all six. +## Single values + +The [single-value contract](single-value-contract.md) defines +`single-value-v1` in `v1/single-value-v1.cases.json`: one value encrypted into +one ciphertext through the engine's run-time interface, and decrypted from +one. The cases give a value, the kind declared for it and a context. They +cover every scalar kind, the exact conversions a declared kind makes, JSON +documents, batches, and the refusals of an array, an object, a passthrough, a +null, `undefined` and a value of another kind. +`v1/single-value-v1.expected.rust-native.json` freezes each input's frame, the +plaintext each leaf is sealed with, and a ciphertext every runner must open. +The native runner is `single_value_conformance` in the Rust crate, which +`test:conformance` runs. It also holds the run-time interface to the typed +one. The Go runner comes with the Go SDK's single-value calls (#2010). + ## `record-reads-v1` contract The [read contract](read-contract.md) defines cases in `v1/record-reads-v1.cases.json` for diff --git a/conformance/stack-encrypt/coverage.md b/conformance/stack-encrypt/coverage.md index 815fab2c5..902855454 100644 --- a/conformance/stack-encrypt/coverage.md +++ b/conformance/stack-encrypt/coverage.md @@ -7,7 +7,7 @@ Paths are relative to the repository root. New profile cases run from `v1/`. | Requirement | Existing evidence | Remaining work | |---|---|---| | Scalar value widths and lossless transport | Initial scalar cases, [value-kind requirements](fixture-contract.md#value-kind-requirements) and the [value boundary profile](values-contract.md) (`v1/record-values-v1.cases.json`: every kind's edges, float specials, bytes, decimal and timestamp precision, sealed/SQL nulls per kind, exact write conversions between widths, cross-kind write refusals, `undefined` on a typed field, Go host conversions); every positive case written fresh by each runner and opened by the other ([exchange profile](exchange-contract.md)) | Python/TS mappings; dates before year 1 and the timestamp range ends | -| Owned opaque ciphertext and storage envelope | `packages/stack-encrypt/tests/scalar.rs`, `frozen_bytes.rs`; initial cross-opening cases; `owned_records.rs`, which tests the owned record derives: passthrough fields are moved, sealed fields are wiped, nested and renamed fields work, a record can store its context, and a column makes one batch. Whole-value blobs: `packages/stack-encrypt/tests/opaque_blob.rs` (round trips, the bytes leaf shared with the structural writer, a pinned storage blob and a pinned sealed ciphertext, refusals by class after authentication, source wipe) and `languages/golang/encrypt/gensupport/gensupport_internal_test.go::TestOpaqueReadsARustWrittenBlob`; the storage profile itself is pinned upstream by Vitamin C's golden corpus; fresh sealed blobs exchanged in both directions by the [exchange profile](exchange-contract.md). JSON documents as one ciphertext: `packages/stack-encrypt/tests/json_plaintext.rs` (round trips, the text leaf shared with a sealed string, refusals after authentication, a generated-document property) and, as the EQL type `Json`, `packages/eql/tests/encryption/tests/v4_types.rs` with the Go-sealed rows `v4_json_rows.json` and the frozen `stored_v4_json_rows_v1.json`, opened in Rust and Go | Encoded targets; supported version matrix | +| Owned opaque ciphertext and storage envelope | `packages/stack-encrypt/tests/scalar.rs`, `frozen_bytes.rs`; initial cross-opening cases; `owned_records.rs`, which tests the owned record derives: passthrough fields are moved, sealed fields are wiped, nested and renamed fields work, a record can store its context, and a column makes one batch. Whole-value blobs: `packages/stack-encrypt/tests/opaque_blob.rs` (round trips, the bytes leaf shared with the structural writer, a pinned storage blob and a pinned sealed ciphertext, refusals by class after authentication, source wipe) and `languages/golang/encrypt/gensupport/gensupport_internal_test.go::TestOpaqueReadsARustWrittenBlob`; the storage profile itself is pinned upstream by Vitamin C's golden corpus; fresh sealed blobs exchanged in both directions by the [exchange profile](exchange-contract.md). One value of a kind known only at run time as one ciphertext: the [single-value profile](single-value-contract.md) (`v1/single-value-v1.cases.json`: every scalar kind, exact conversions, JSON documents, batches and the refusals, with the plaintext of each leaf and a frozen ciphertext), run by native Rust, and `packages/stack-encrypt/tests/single_value.rs`, which holds the run-time interface to the typed one. JSON documents as one ciphertext: `packages/stack-encrypt/tests/json_plaintext.rs` (round trips, the text leaf shared with a sealed string, refusals after authentication, a generated-document property) and, as the EQL type `Json`, `packages/eql/tests/encryption/tests/v4_types.rs` with the Go-sealed rows `v4_json_rows.json` and the frozen `stored_v4_json_rows_v1.json`, opened in Rust and Go | Encoded targets; supported version matrix; the Go runner of the single-value profile (#2010), and Python and TypeScript runners | | Record declaration and lowering | [Declaration grammar](declaration-grammar.md); `v1/record-declarations-v1.cases.json` shared by native Rust and Go; native normalization observations; existing record lowering suites; `packages/stack-encrypt/tests/owned_equivalence.rs`, which seals one mixed, searchable record three ways: through a hand-written owned target, the owned derive, and the data plan. All three use one provider that records its requests. The test compares the descriptors and the term bytes, and checks that each way decrypts the records of the others | EQL-resolver profile; SDK-to-declaration mappings; runtime source/read shapes | | Context binding and composition | `packages/stack-encrypt/tests/target.rs`, `descriptor.rs`, `record_lowering.rs`; `languages/golang/encrypt/context_field_test.go`; initial wrong-context cases | Shared composition vectors; expected-context and required-input matrix | | Query terms and diagnostics | [Query-operator requirements](fixture-contract.md#query-operator-requirements), existing Rust/Go runners, initial equality/query-error cases and the [query-refusal profile](query-refusals-contract.md) (`v1/record-query-refusals-v1.cases.json`: every scalar operator against every field capability that does not answer it, the listed range shapes, other-kind values and nulls, by class, with the typed query's refusal stage) | JSON operator and EQL target refusals | diff --git a/conformance/stack-encrypt/single-value-contract.md b/conformance/stack-encrypt/single-value-contract.md new file mode 100644 index 000000000..4f4a82641 --- /dev/null +++ b/conformance/stack-encrypt/single-value-contract.md @@ -0,0 +1,143 @@ +# Single-value profile + +`single-value-v1` describes the cases in `v1/single-value-v1.cases.json`: one +value encrypted into one ciphertext, and decrypted from one, through the +engine's run-time interface (`stack_encrypt::dynamic::value`). It is an +experimental test contract. + +The run-time interface takes a value as a transport frame, with the kind the +caller declares for it. It must return the ciphertext the typed Rust interface +(`keyset.encrypt`) returns for the same value, so that a value one language +encrypts, every other language decrypts. + +The Rust runner is `packages/stack-encrypt/tests/single_value_conformance.rs`. +The Go runner is pending: it comes with the Go SDK's single-value calls +(#2010). Python and TypeScript runners are pending too. A missing runner is not +a passing result. + +## Cases + +The file has a public deterministic-provider `seed`, a list of `cases` and a +list of `batches`. Each case has: + +| Key | Meaning | +|---|---| +| `id` | The case's name | +| `kind` | The name of the declared kind, or empty for no declared kind | +| `context` | The context's parts, or an empty list for the empty context | +| `input` | The value, in the `{type, text}` form the [value profile](values-contract.md#cases) defines | +| `stored` | The value the ciphertext holds, where it is not the input | +| `refused_as` | Kinds the ciphertext must refuse to open as | +| `expected_error` | For a refused case, the refusal's `code` and `reason` | + +A context of two parts is the pair of them: `["conformance", "value"]` is the +Rust context `("conformance", "value")`. A runner calls the form with no +context for an empty list, and the form with a context otherwise. + +This profile adds two input types to the value profile's: + +| `type` | `text` | +|---|---| +| `uuid` | The UUID in lowercase hex, in groups of 8, 4, 4, 4 and 12 digits | +| `shape` | The name of a value that `{type, text}` cannot spell (below) | + +| Shape | The value | +|---|---| +| `array` | The array of the two strings `a` and `b` | +| `empty_array` | The array with no elements | +| `object` | The object with one member, `a`, the `uint32` 1 | +| `passthrough` | A passthrough of the string `clear` | +| `typed_null` | A typed null of `int64` | + +A runner that cannot build a shape in its host language sends the frame the +artifact file records for the case. + +## Artifacts + +`v1/single-value-v1.expected.rust-native.json` holds one entry for each case, +written by the Rust runner: + +- `frame`: the input's transport frame, in hex. Every case has one. +- `leaf`: the plaintext the ciphertext's leaf is sealed with, in hex: the + leaf's type tag and its payload. Only an accepted case has one. +- `ciphertext`: a ciphertext of the value, in hex. Only an accepted case has + one. The typed Rust interface made it, where a Rust type spells the stored + value. No Rust type spells a lone `uint8` or JavaScript's `undefined`, so + the run-time interface made those two. + +Ciphertext bytes are never compared whole. Each sealed leaf carries a random +AES-GCM nonce, so two ciphertexts of one value differ. A runner compares the +parts of a ciphertext that the nonce does not change: the keyset, the data +key's IV and tag, the ciphertext's length, and the plaintext of the leaf. +The deterministic provider derives a data key from the seed, the context and +a counter. So a runner makes a fresh provider for each ciphertext it compares. + +Regenerate the artifacts deliberately, with `STACK_ENCRYPT_UPDATE_FIXTURES=1` +and the native runner, and review the case and artifact diff together. + +## Required behavior + +For a case with no `expected_error`: + +1. The input's frame equals the frozen `frame`. +2. The run-time encrypt accepts the value under the declared kind and the + context. The plaintext of the leaf it seals equals the frozen `leaf`. +3. The fresh ciphertext and the frozen `ciphertext` agree in every part that + the nonce does not change. +4. Each of the two ciphertexts opens, under the same context: + - with no declared kind, to `stored` (or to the input, where the case has + no `stored`); + - with the declared kind, to the same value. Under `json` it opens to the + stored JSON text in a bytes leaf. +5. Each ciphertext is refused when opened as a kind in `refused_as`. The + refusal's code is `stack_encrypt::opened_type`, and its `expected` field is + the kind's name. The refusal never says what the value opened as. +6. Each ciphertext is refused under the context `["conformance", "wrong"]`. + The deterministic provider refuses the key request as forbidden, which + models ZeroKMS. Other providers may report a wrong context differently. + +Native Rust also checks that the typed interface seals the same parts for the +stored value, and that the typed decrypt opens both ciphertexts. + +A case with `stored` is a conversion. A number of another width or kind is +sealed as the declared kind's value when the conversion is exact, by the rules +a record's typed field uses. A document under `json` is sealed as its compact +JSON text, in a text leaf. + +For a case with `expected_error`, the run-time encrypt refuses the value +before any key request, with the diagnostic `code` and `reason`. The refusal +names no field. The cases cover: + +- an array, an object, a passthrough, a plain null and a typed null, each with + no declared kind and with one: the reason says what was found (`array`, + `object`, `passthrough`, `null`); +- JavaScript's `undefined` under a declared kind (`undefined`); +- a value of another kind that does not convert exactly (`field_type`); +- text that is not a JSON document, under `json` (`json_syntax`, + `json_duplicate_key`, `json_integer_range`). + +With no declared kind, `undefined` is a scalar and is sealed as it arrived. +The case `as-is-undefined` pins that. A host with no `undefined` checks the +case's shape and skips it. + +## Batches + +Each entry of `batches` has a `kind`, a `context` and a list of `inputs`. An +accepted batch seals in one key request and opens in one, and the values come +back in the order of the inputs: `stored` where the batch has one, the inputs +otherwise. An empty batch makes no key request. A batch with `expected_error` +is refused whole, before any key request, for its first refused value. + +The key-request counts are native observations: the Rust runner counts them +on its key source. + +## Scope and remaining work + +The profile covers every scalar kind, the exact conversions, JSON documents +and the refusals of the run-time encrypt. It does not cover: + +- a ciphertext that holds a null, which only the tree interface seals; +- keyset confinement on decrypt, which + `packages/stack-encrypt/tests/single_value.rs` covers natively; +- fresh ciphertexts exchanged between languages. That comes with the first + second runner. diff --git a/conformance/stack-encrypt/v1/single-value-v1.cases.json b/conformance/stack-encrypt/v1/single-value-v1.cases.json new file mode 100644 index 000000000..0e34918af --- /dev/null +++ b/conformance/stack-encrypt/v1/single-value-v1.cases.json @@ -0,0 +1,909 @@ +{ + "version": 1, + "profile": "single-value-v1", + "seed": "0000000000000000000000000000000000000000000000000000000000000000", + "required_capabilities": [ + "single-value", + "value-kinds", + "context-binding", + "refusals" + ], + "cases": [ + { + "id": "as-is-string", + "kind": "", + "context": [], + "input": { + "type": "string", + "text": "ada@example.com" + }, + "refused_as": ["int64", "bytes", "json"] + }, + { + "id": "as-is-empty-string", + "kind": "", + "context": [], + "input": { + "type": "string", + "text": "" + } + }, + { + "id": "as-is-int64-above-js-safe", + "kind": "", + "context": [], + "input": { + "type": "int64", + "text": "9007199254740993" + }, + "refused_as": ["int32", "uint64", "float64", "string"] + }, + { + "id": "as-is-bool", + "kind": "", + "context": [], + "input": { + "type": "bool", + "text": "true" + } + }, + { + "id": "as-is-bytes", + "kind": "", + "context": [], + "input": { + "type": "bytes", + "text": "00ff10" + }, + "refused_as": ["string", "uuid"] + }, + { + "id": "as-is-float64-negative-zero", + "kind": "", + "context": [], + "input": { + "type": "float64", + "text": "-0" + } + }, + { + "id": "as-is-uint8", + "kind": "", + "context": [], + "input": { + "type": "uint8", + "text": "200" + } + }, + { + "id": "as-is-uuid", + "kind": "", + "context": [], + "input": { + "type": "uuid", + "text": "123e4567-e89b-12d3-a456-426614174000" + }, + "refused_as": ["bytes"] + }, + { + "id": "as-is-undefined", + "kind": "", + "context": [], + "input": { + "type": "undefined", + "text": "" + }, + "refused_as": ["int64"] + }, + { + "id": "as-is-string-with-context", + "kind": "", + "context": ["conformance", "value"], + "input": { + "type": "string", + "text": "ada@example.com" + } + }, + { + "id": "bool-false", + "kind": "bool", + "context": ["conformance", "value"], + "input": { + "type": "bool", + "text": "false" + } + }, + { + "id": "int8-min", + "kind": "int8", + "context": ["conformance", "value"], + "input": { + "type": "int8", + "text": "-128" + } + }, + { + "id": "int16-min", + "kind": "int16", + "context": ["conformance", "value"], + "input": { + "type": "int16", + "text": "-32768" + } + }, + { + "id": "int32-min", + "kind": "int32", + "context": ["conformance", "value"], + "input": { + "type": "int32", + "text": "-2147483648" + } + }, + { + "id": "int64-min", + "kind": "int64", + "context": ["conformance", "value"], + "input": { + "type": "int64", + "text": "-9223372036854775808" + } + }, + { + "id": "int128-min", + "kind": "int128", + "context": ["conformance", "value"], + "input": { + "type": "int128", + "text": "-170141183460469231731687303715884105728" + } + }, + { + "id": "uint8-max", + "kind": "uint8", + "context": ["conformance", "value"], + "input": { + "type": "uint8", + "text": "255" + } + }, + { + "id": "uint16-max", + "kind": "uint16", + "context": ["conformance", "value"], + "input": { + "type": "uint16", + "text": "65535" + } + }, + { + "id": "uint32-max", + "kind": "uint32", + "context": ["conformance", "value"], + "input": { + "type": "uint32", + "text": "4294967295" + } + }, + { + "id": "uint64-max", + "kind": "uint64", + "context": ["conformance", "value"], + "input": { + "type": "uint64", + "text": "18446744073709551615" + } + }, + { + "id": "uint128-max", + "kind": "uint128", + "context": ["conformance", "value"], + "input": { + "type": "uint128", + "text": "340282366920938463463374607431768211455" + } + }, + { + "id": "float32-fraction", + "kind": "float32", + "context": ["conformance", "value"], + "input": { + "type": "float32", + "text": "1.5" + } + }, + { + "id": "float64-infinity", + "kind": "float64", + "context": ["conformance", "value"], + "input": { + "type": "float64", + "text": "inf" + } + }, + { + "id": "decimal-trailing-zeros", + "kind": "decimal", + "context": ["conformance", "value"], + "input": { + "type": "decimal", + "text": "-1234.5600" + } + }, + { + "id": "date-leap-day", + "kind": "date", + "context": ["conformance", "value"], + "input": { + "type": "date", + "text": "2024-02-29" + } + }, + { + "id": "timestamp-nanoseconds", + "kind": "timestamp", + "context": ["conformance", "value"], + "input": { + "type": "timestamp", + "text": "2026-10-17T01:02:03.123456789Z" + } + }, + { + "id": "string-unicode", + "kind": "string", + "context": ["conformance", "value"], + "input": { + "type": "string", + "text": "café ☕" + } + }, + { + "id": "bytes-empty", + "kind": "bytes", + "context": ["conformance", "value"], + "input": { + "type": "bytes", + "text": "" + } + }, + { + "id": "uuid", + "kind": "uuid", + "context": ["conformance", "value"], + "input": { + "type": "uuid", + "text": "123e4567-e89b-12d3-a456-426614174000" + } + }, + { + "id": "uint64-given-float64", + "kind": "uint64", + "context": ["conformance", "value"], + "input": { + "type": "float64", + "text": "34" + }, + "stored": { + "type": "uint64", + "text": "34" + }, + "refused_as": ["float64", "uint32"] + }, + { + "id": "int8-given-int16", + "kind": "int8", + "context": ["conformance", "value"], + "input": { + "type": "int16", + "text": "1" + }, + "stored": { + "type": "int8", + "text": "1" + } + }, + { + "id": "int128-given-int64", + "kind": "int128", + "context": ["conformance", "value"], + "input": { + "type": "int64", + "text": "1" + }, + "stored": { + "type": "int128", + "text": "1" + } + }, + { + "id": "float32-given-float64", + "kind": "float32", + "context": ["conformance", "value"], + "input": { + "type": "float64", + "text": "1.5" + }, + "stored": { + "type": "float32", + "text": "1.5" + } + }, + { + "id": "float64-given-int32", + "kind": "float64", + "context": [], + "input": { + "type": "int32", + "text": "12" + }, + "stored": { + "type": "float64", + "text": "12" + } + }, + { + "id": "decimal-given-int64", + "kind": "decimal", + "context": ["conformance", "value"], + "input": { + "type": "int64", + "text": "5" + }, + "stored": { + "type": "decimal", + "text": "5" + } + }, + { + "id": "json-given-string", + "kind": "json", + "context": ["conformance", "value"], + "input": { + "type": "string", + "text": "{ \"b\": [1, 2.5, null], \"a\": \"é\" }" + }, + "stored": { + "type": "string", + "text": "{\"a\":\"é\",\"b\":[1,2.5,null]}" + }, + "refused_as": ["int64", "bytes"] + }, + { + "id": "json-given-bytes", + "kind": "json", + "context": [], + "input": { + "type": "bytes", + "text": "6e756c6c" + }, + "stored": { + "type": "string", + "text": "null" + } + }, + { + "id": "json-scalar-string", + "kind": "json", + "context": ["conformance", "value"], + "input": { + "type": "string", + "text": "\"plain\"" + }, + "stored": { + "type": "string", + "text": "\"plain\"" + } + }, + { + "id": "array-no-kind", + "kind": "", + "context": [], + "input": { + "type": "shape", + "text": "array" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_source", + "reason": "array" + } + }, + { + "id": "array-array", + "kind": "array", + "context": [], + "input": { + "type": "shape", + "text": "array" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_source", + "reason": "array" + } + }, + { + "id": "array-int64", + "kind": "int64", + "context": [], + "input": { + "type": "shape", + "text": "array" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_source", + "reason": "array" + } + }, + { + "id": "empty-array-no-kind", + "kind": "", + "context": ["conformance", "value"], + "input": { + "type": "shape", + "text": "empty_array" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_source", + "reason": "array" + } + }, + { + "id": "object-no-kind", + "kind": "", + "context": [], + "input": { + "type": "shape", + "text": "object" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_source", + "reason": "object" + } + }, + { + "id": "object-object", + "kind": "object", + "context": [], + "input": { + "type": "shape", + "text": "object" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_source", + "reason": "object" + } + }, + { + "id": "object-json", + "kind": "json", + "context": [], + "input": { + "type": "shape", + "text": "object" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_source", + "reason": "object" + } + }, + { + "id": "passthrough-no-kind", + "kind": "", + "context": [], + "input": { + "type": "shape", + "text": "passthrough" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_source", + "reason": "passthrough" + } + }, + { + "id": "passthrough-string", + "kind": "string", + "context": [], + "input": { + "type": "shape", + "text": "passthrough" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_source", + "reason": "passthrough" + } + }, + { + "id": "null-no-kind", + "kind": "", + "context": ["conformance", "value"], + "input": { + "type": "null", + "text": "" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_source", + "reason": "null" + } + }, + { + "id": "null-int64", + "kind": "int64", + "context": ["conformance", "value"], + "input": { + "type": "null", + "text": "" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_source", + "reason": "null" + } + }, + { + "id": "null-string", + "kind": "string", + "context": ["conformance", "value"], + "input": { + "type": "null", + "text": "" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_source", + "reason": "null" + } + }, + { + "id": "null-bool", + "kind": "bool", + "context": ["conformance", "value"], + "input": { + "type": "null", + "text": "" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_source", + "reason": "null" + } + }, + { + "id": "typed-null-no-kind", + "kind": "", + "context": [], + "input": { + "type": "shape", + "text": "typed_null" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_source", + "reason": "null" + } + }, + { + "id": "typed-null-int64", + "kind": "int64", + "context": [], + "input": { + "type": "shape", + "text": "typed_null" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_source", + "reason": "null" + } + }, + { + "id": "undefined-int32", + "kind": "int32", + "context": [], + "input": { + "type": "undefined", + "text": "" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_source", + "reason": "undefined" + } + }, + { + "id": "undefined-json", + "kind": "json", + "context": ["conformance", "value"], + "input": { + "type": "undefined", + "text": "" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_source", + "reason": "undefined" + } + }, + { + "id": "int64-given-string", + "kind": "int64", + "context": [], + "input": { + "type": "string", + "text": "34" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_source", + "reason": "field_type" + } + }, + { + "id": "uint64-given-fraction", + "kind": "uint64", + "context": [], + "input": { + "type": "float64", + "text": "34.5" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_source", + "reason": "field_type" + } + }, + { + "id": "int8-given-300", + "kind": "int8", + "context": [], + "input": { + "type": "int64", + "text": "300" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_source", + "reason": "field_type" + } + }, + { + "id": "date-given-int32", + "kind": "date", + "context": [], + "input": { + "type": "int32", + "text": "0" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_source", + "reason": "field_type" + } + }, + { + "id": "decimal-given-float64", + "kind": "decimal", + "context": [], + "input": { + "type": "float64", + "text": "1.5" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_source", + "reason": "field_type" + } + }, + { + "id": "string-given-int64", + "kind": "string", + "context": [], + "input": { + "type": "int64", + "text": "34" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_source", + "reason": "field_type" + } + }, + { + "id": "bytes-given-string", + "kind": "bytes", + "context": [], + "input": { + "type": "string", + "text": "" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_source", + "reason": "field_type" + } + }, + { + "id": "array-given-string", + "kind": "array", + "context": [], + "input": { + "type": "string", + "text": "a" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_source", + "reason": "field_type" + } + }, + { + "id": "object-given-int64", + "kind": "object", + "context": [], + "input": { + "type": "int64", + "text": "1" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_source", + "reason": "field_type" + } + }, + { + "id": "json-given-int64", + "kind": "json", + "context": [], + "input": { + "type": "int64", + "text": "1" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_source", + "reason": "field_type" + } + }, + { + "id": "json-syntax", + "kind": "json", + "context": [], + "input": { + "type": "string", + "text": "{\"a\": " + }, + "expected_error": { + "code": "stack_encrypt::dynamic_source", + "reason": "json_syntax" + } + }, + { + "id": "json-duplicate-key", + "kind": "json", + "context": [], + "input": { + "type": "string", + "text": "{\"a\":1,\"a\":2}" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_source", + "reason": "json_duplicate_key" + } + }, + { + "id": "json-integer-range", + "kind": "json", + "context": [], + "input": { + "type": "bytes", + "text": "3138343436373434303733373039353531363136" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_source", + "reason": "json_integer_range" + } + } + ], + "batches": [ + { + "id": "batch-strings", + "kind": "string", + "context": ["conformance", "value"], + "inputs": [ + { + "type": "string", + "text": "ada" + }, + { + "type": "string", + "text": "" + }, + { + "type": "string", + "text": "grace" + } + ] + }, + { + "id": "batch-converted", + "kind": "uint32", + "context": [], + "inputs": [ + { + "type": "float64", + "text": "1" + }, + { + "type": "int64", + "text": "2" + }, + { + "type": "uint16", + "text": "3" + } + ], + "stored": [ + { + "type": "uint32", + "text": "1" + }, + { + "type": "uint32", + "text": "2" + }, + { + "type": "uint32", + "text": "3" + } + ] + }, + { + "id": "batch-mixed-no-kind", + "kind": "", + "context": [], + "inputs": [ + { + "type": "int64", + "text": "1" + }, + { + "type": "string", + "text": "two" + }, + { + "type": "bool", + "text": "true" + } + ] + }, + { + "id": "batch-empty", + "kind": "", + "context": [], + "inputs": [] + }, + { + "id": "batch-with-null", + "kind": "", + "context": ["conformance", "value"], + "inputs": [ + { + "type": "string", + "text": "ada" + }, + { + "type": "null", + "text": "" + }, + { + "type": "string", + "text": "grace" + } + ], + "expected_error": { + "code": "stack_encrypt::dynamic_source", + "reason": "null" + } + }, + { + "id": "batch-with-mismatch", + "kind": "int64", + "context": [], + "inputs": [ + { + "type": "int64", + "text": "1" + }, + { + "type": "string", + "text": "two" + } + ], + "expected_error": { + "code": "stack_encrypt::dynamic_source", + "reason": "field_type" + } + } + ] +} diff --git a/conformance/stack-encrypt/v1/single-value-v1.expected.rust-native.json b/conformance/stack-encrypt/v1/single-value-v1.expected.rust-native.json new file mode 100644 index 000000000..5cf95189f --- /dev/null +++ b/conformance/stack-encrypt/v1/single-value-v1.expected.rust-native.json @@ -0,0 +1,287 @@ +{ + "version": 1, + "profile": "single-value-v1", + "producer": "rust-native/stack-encrypt-0.3.0", + "cases": { + "array-array": { + "frame": "f0020000000a01000000610a0100000062" + }, + "array-given-string": { + "frame": "0a0100000061" + }, + "array-int64": { + "frame": "f0020000000a01000000610a0100000062" + }, + "array-no-kind": { + "frame": "f0020000000a01000000610a0100000062" + }, + "as-is-bool": { + "frame": "03", + "leaf": "03", + "ciphertext": "0100000000000000000000000000000000953d2c5d27e5e549f2d84c34dffa03f4200046e77e88ca69bc28c79328ea2e7022660434e03342f93f07f852ccdcf45765de029fe04f1b508676453ac04e339b2f80f53847a5ff818dcf1c532fa846fb" + }, + "as-is-bytes": { + "frame": "0b0300000000ff10", + "leaf": "0b00ff10", + "ciphertext": "0100000000000000000000000000000000953d2c5d27e5e549f2d84c34dffa03f4200046e77e88ca69bc28c79328ea2e7022660434e03342f93f07f852ccdcf45765de02fa48756303bc32df4b8307a6f58ac8386d7f82425cccbe656ddd5e73615c571a" + }, + "as-is-empty-string": { + "frame": "0a00000000", + "leaf": "0a", + "ciphertext": "0100000000000000000000000000000000953d2c5d27e5e549f2d84c34dffa03f4200046e77e88ca69bc28c79328ea2e7022660434e03342f93f07f852ccdcf45765de0225bef2bfdae4755442824942ed0d94a1f3ec6cb626299e50653b372e98" + }, + "as-is-float64-negative-zero": { + "frame": "090000000000000080", + "leaf": "090000000000000080", + "ciphertext": "0100000000000000000000000000000000953d2c5d27e5e549f2d84c34dffa03f4200046e77e88ca69bc28c79328ea2e7022660434e03342f93f07f852ccdcf45765de02350d1ec5e03af0f13153705c6fb65b905d078d75d23a437399a38f864d524ed0f751b60d6b" + }, + "as-is-int64-above-js-safe": { + "frame": "050100000000002000", + "leaf": "050100000000002000", + "ciphertext": "0100000000000000000000000000000000953d2c5d27e5e549f2d84c34dffa03f4200046e77e88ca69bc28c79328ea2e7022660434e03342f93f07f852ccdcf45765de02a352279f2d7314d0814b67ade0b98d96c474f8fb7008e6071ba144db50a10e1e6634a5c5f7" + }, + "as-is-string": { + "frame": "0a0f000000616461406578616d706c652e636f6d", + "leaf": "0a616461406578616d706c652e636f6d", + "ciphertext": "0100000000000000000000000000000000953d2c5d27e5e549f2d84c34dffa03f4200046e77e88ca69bc28c79328ea2e7022660434e03342f93f07f852ccdcf45765de02b725799857a54d0788360432755b45db393f1b7e6f2f4c153f0c54bc7e5c1938148196d75552bf87b9aeb13b" + }, + "as-is-string-with-context": { + "frame": "0a0f000000616461406578616d706c652e636f6d", + "leaf": "0a616461406578616d706c652e636f6d", + "ciphertext": "01000000000000000000000000000000005902b1723e57208119a7343912d41d182000de8bb2e291bdcd46deccaa88a9e007ef2aec7757541decec19b7dfc96075ae4d025cadd464b84b4d38682d1e50b58f59a4992f4929674814ab6ace0325ee6b5b7c65981e3d20f187a1cd3cdd8c" + }, + "as-is-uint8": { + "frame": "0dc8", + "leaf": "0dc8", + "ciphertext": "0100000000000000000000000000000000953d2c5d27e5e549f2d84c34dffa03f4200046e77e88ca69bc28c79328ea2e7022660434e03342f93f07f852ccdcf45765de0282a2279d098f66f8776c5750e57acd502a6c3ecbbf4f77fa32e92a8aca60" + }, + "as-is-undefined": { + "frame": "01", + "leaf": "01", + "ciphertext": "0100000000000000000000000000000000953d2c5d27e5e549f2d84c34dffa03f4200046e77e88ca69bc28c79328ea2e7022660434e03342f93f07f852ccdcf45765de0222594e69e4a84eaed73cb6d3d6d595a94e3d1894ad2e840642632adb9e" + }, + "as-is-uuid": { + "frame": "f305000b10000000123e4567e89b12d3a456426614174000", + "leaf": "f305000b123e4567e89b12d3a456426614174000", + "ciphertext": "0100000000000000000000000000000000953d2c5d27e5e549f2d84c34dffa03f4200046e77e88ca69bc28c79328ea2e7022660434e03342f93f07f852ccdcf45765de02de2cfad59578fbdde2113e2408c83a2e622469ff2a8561c1df6f024c6c43603ffab884daca5df9dc618361b6e4163958" + }, + "bool-false": { + "frame": "02", + "leaf": "02", + "ciphertext": "01000000000000000000000000000000005902b1723e57208119a7343912d41d182000de8bb2e291bdcd46deccaa88a9e007ef2aec7757541decec19b7dfc96075ae4d0204b52dce3c7883f4357cb091a330b4d3b6b560a28f9c9e2eeb334df765" + }, + "bytes-empty": { + "frame": "0b00000000", + "leaf": "0b", + "ciphertext": "01000000000000000000000000000000005902b1723e57208119a7343912d41d182000de8bb2e291bdcd46deccaa88a9e007ef2aec7757541decec19b7dfc96075ae4d025e243904c6b98ce10005f8b7809b03b772109d33b767c90077102e2f2a" + }, + "bytes-given-string": { + "frame": "0a00000000" + }, + "date-given-int32": { + "frame": "0400000000" + }, + "date-leap-day": { + "frame": "1281460b00", + "leaf": "1281460b00", + "ciphertext": "01000000000000000000000000000000005902b1723e57208119a7343912d41d182000de8bb2e291bdcd46deccaa88a9e007ef2aec7757541decec19b7dfc96075ae4d02bf360e838a4e7e80dbb78b24519ac81dc083892471b3272c8ed466ca416d28124a" + }, + "decimal-given-float64": { + "frame": "09000000000000f83f" + }, + "decimal-given-int64": { + "frame": "050500000000000000", + "leaf": "1400000000050000000000000000000000", + "ciphertext": "01000000000000000000000000000000005902b1723e57208119a7343912d41d182000de8bb2e291bdcd46deccaa88a9e007ef2aec7757541decec19b7dfc96075ae4d028a8e782f7f1aa3a3067b3d8057ab95ede3b78d267ba118e90422a1bd0be22e700f37fbd32deaed33fc0ec5c41c" + }, + "decimal-trailing-zeros": { + "frame": "14000004800061bc000000000000000000", + "leaf": "14000004800061bc000000000000000000", + "ciphertext": "01000000000000000000000000000000005902b1723e57208119a7343912d41d182000de8bb2e291bdcd46deccaa88a9e007ef2aec7757541decec19b7dfc96075ae4d02eeaf9c1474e50601ee703ef75901fdcf953c9267d98b425ae42508aaeb3fa2d45adabb6470ea78059d509dae72" + }, + "empty-array-no-kind": { + "frame": "f000000000" + }, + "float32-fraction": { + "frame": "080000c03f", + "leaf": "080000c03f", + "ciphertext": "01000000000000000000000000000000005902b1723e57208119a7343912d41d182000de8bb2e291bdcd46deccaa88a9e007ef2aec7757541decec19b7dfc96075ae4d02693227bfd9a4e28995f12272ba296a599a9df3649e04e4ac24b7f73714618363c5" + }, + "float32-given-float64": { + "frame": "09000000000000f83f", + "leaf": "080000c03f", + "ciphertext": "01000000000000000000000000000000005902b1723e57208119a7343912d41d182000de8bb2e291bdcd46deccaa88a9e007ef2aec7757541decec19b7dfc96075ae4d02730a34dc8aea8436e24ede609ea29417503948651cc9232fbc9ae7dba32f867867" + }, + "float64-given-int32": { + "frame": "040c000000", + "leaf": "090000000000002840", + "ciphertext": "0100000000000000000000000000000000953d2c5d27e5e549f2d84c34dffa03f4200046e77e88ca69bc28c79328ea2e7022660434e03342f93f07f852ccdcf45765de021bfb53623f66f1b72532971cef2477fc61b379f9e973d3daa6f6afc05b813d85602137026c" + }, + "float64-infinity": { + "frame": "09000000000000f07f", + "leaf": "09000000000000f07f", + "ciphertext": "01000000000000000000000000000000005902b1723e57208119a7343912d41d182000de8bb2e291bdcd46deccaa88a9e007ef2aec7757541decec19b7dfc96075ae4d02636c99a930f39fd9ac116bf57de36cec9477a076fcf815f7b1acca891d8d028330396f0149" + }, + "int128-given-int64": { + "frame": "050100000000000000", + "leaf": "1001000000000000000000000000000000", + "ciphertext": "01000000000000000000000000000000005902b1723e57208119a7343912d41d182000de8bb2e291bdcd46deccaa88a9e007ef2aec7757541decec19b7dfc96075ae4d020f001346503a8a31858c52a494fa6552ad609605e0dce79835fac9ec3e33c208596ce7df6caf4b04ff7faeb954" + }, + "int128-min": { + "frame": "1000000000000000000000000000000080", + "leaf": "1000000000000000000000000000000080", + "ciphertext": "01000000000000000000000000000000005902b1723e57208119a7343912d41d182000de8bb2e291bdcd46deccaa88a9e007ef2aec7757541decec19b7dfc96075ae4d0203d9fc37a766f04e6eb14ebf0c05b7d0784c17df29a5802c6d05d3c433bb0890389a848b65b37f1c1b559c5aa8" + }, + "int16-min": { + "frame": "0e0080", + "leaf": "0e0080", + "ciphertext": "01000000000000000000000000000000005902b1723e57208119a7343912d41d182000de8bb2e291bdcd46deccaa88a9e007ef2aec7757541decec19b7dfc96075ae4d02bf38b95faaf29d4e843e72134abd32961e68d42d509a27e7d628d92983b493" + }, + "int32-min": { + "frame": "0400000080", + "leaf": "0400000080", + "ciphertext": "01000000000000000000000000000000005902b1723e57208119a7343912d41d182000de8bb2e291bdcd46deccaa88a9e007ef2aec7757541decec19b7dfc96075ae4d020a4033afe1a5b353a0f9661ae2981e6239d719ff4cf758c9fda3627e52f6ca8da3" + }, + "int64-given-string": { + "frame": "0a020000003334" + }, + "int64-min": { + "frame": "050000000000000080", + "leaf": "050000000000000080", + "ciphertext": "01000000000000000000000000000000005902b1723e57208119a7343912d41d182000de8bb2e291bdcd46deccaa88a9e007ef2aec7757541decec19b7dfc96075ae4d0226a292092dc07c14807aaee032309eb627272f40c4fd98a795f8e24c03814b23d4b54ca92e" + }, + "int8-given-300": { + "frame": "052c01000000000000" + }, + "int8-given-int16": { + "frame": "0e0100", + "leaf": "0c01", + "ciphertext": "01000000000000000000000000000000005902b1723e57208119a7343912d41d182000de8bb2e291bdcd46deccaa88a9e007ef2aec7757541decec19b7dfc96075ae4d024c557ec1d7f0e338af7d9c88878c47c5fe066178ec92f4953df25ae9b63e" + }, + "int8-min": { + "frame": "0c80", + "leaf": "0c80", + "ciphertext": "01000000000000000000000000000000005902b1723e57208119a7343912d41d182000de8bb2e291bdcd46deccaa88a9e007ef2aec7757541decec19b7dfc96075ae4d02306ce03ce2b20cb0a7337942f156669e16eb3b639055674875b8f8b79392" + }, + "json-duplicate-key": { + "frame": "0a0d0000007b2261223a312c2261223a327d" + }, + "json-given-bytes": { + "frame": "0b040000006e756c6c", + "leaf": "0a6e756c6c", + "ciphertext": "0100000000000000000000000000000000953d2c5d27e5e549f2d84c34dffa03f4200046e77e88ca69bc28c79328ea2e7022660434e03342f93f07f852ccdcf45765de02830450b50101f6a3b3f49caf66e78f55fe0365d5a7a308a715285840baddf67354" + }, + "json-given-int64": { + "frame": "050100000000000000" + }, + "json-given-string": { + "frame": "0a220000007b202262223a205b312c20322e352c206e756c6c5d2c202261223a2022c3a922207d", + "leaf": "0a7b2261223a22c3a9222c2262223a5b312c322e352c6e756c6c5d7d", + "ciphertext": "01000000000000000000000000000000005902b1723e57208119a7343912d41d182000de8bb2e291bdcd46deccaa88a9e007ef2aec7757541decec19b7dfc96075ae4d02e591294b87dde6fa2cd3f5509ab93920b87e3d0f6999bea7e0212abd9f4dced82bd64622c68752a866af0195253a784228a6ad4547d6f986" + }, + "json-integer-range": { + "frame": "0b140000003138343436373434303733373039353531363136" + }, + "json-scalar-string": { + "frame": "0a0700000022706c61696e22", + "leaf": "0a22706c61696e22", + "ciphertext": "01000000000000000000000000000000005902b1723e57208119a7343912d41d182000de8bb2e291bdcd46deccaa88a9e007ef2aec7757541decec19b7dfc96075ae4d028e622a3d896eba4f36057db0f1dc63b1a9f93f6191c3262bea067f4a68ddb3defd74d12c" + }, + "json-syntax": { + "frame": "0a060000007b2261223a20" + }, + "null-bool": { + "frame": "00" + }, + "null-int64": { + "frame": "00" + }, + "null-no-kind": { + "frame": "00" + }, + "null-string": { + "frame": "00" + }, + "object-given-int64": { + "frame": "050100000000000000" + }, + "object-json": { + "frame": "f10100000001000000610601000000" + }, + "object-no-kind": { + "frame": "f10100000001000000610601000000" + }, + "object-object": { + "frame": "f10100000001000000610601000000" + }, + "passthrough-no-kind": { + "frame": "f20a05000000636c656172" + }, + "passthrough-string": { + "frame": "f20a05000000636c656172" + }, + "string-given-int64": { + "frame": "052200000000000000" + }, + "string-unicode": { + "frame": "0a09000000636166c3a920e29895", + "leaf": "0a636166c3a920e29895", + "ciphertext": "01000000000000000000000000000000005902b1723e57208119a7343912d41d182000de8bb2e291bdcd46deccaa88a9e007ef2aec7757541decec19b7dfc96075ae4d02b06def1c5a6e1cbc44d41af64f5b733d3c2c6f22ab4d68f588725725fdeee215928cd6baa1dd" + }, + "timestamp-nanoseconds": { + "frame": "130bc9d26a0000000015cd5b07", + "leaf": "130bc9d26a0000000015cd5b07", + "ciphertext": "01000000000000000000000000000000005902b1723e57208119a7343912d41d182000de8bb2e291bdcd46deccaa88a9e007ef2aec7757541decec19b7dfc96075ae4d02a66b3872cd846657a41af5155ad5c0eeb680b54de242d99ed02d32287c9aad40d738aaa09230856e76" + }, + "typed-null-int64": { + "frame": "150500000000000000" + }, + "typed-null-no-kind": { + "frame": "150500000000000000" + }, + "uint128-max": { + "frame": "11ffffffffffffffffffffffffffffffff", + "leaf": "11ffffffffffffffffffffffffffffffff", + "ciphertext": "01000000000000000000000000000000005902b1723e57208119a7343912d41d182000de8bb2e291bdcd46deccaa88a9e007ef2aec7757541decec19b7dfc96075ae4d02433597c92b736ea642fdac7b846f29b6a30616f48ef97eeda089ff30745be880cddd611075b80ecf2a94a2712c" + }, + "uint16-max": { + "frame": "0fffff", + "leaf": "0fffff", + "ciphertext": "01000000000000000000000000000000005902b1723e57208119a7343912d41d182000de8bb2e291bdcd46deccaa88a9e007ef2aec7757541decec19b7dfc96075ae4d02ec21438b0724ce61a47824b18fd6800703b6c14d875b41b91d11c993986d8b" + }, + "uint32-max": { + "frame": "06ffffffff", + "leaf": "06ffffffff", + "ciphertext": "01000000000000000000000000000000005902b1723e57208119a7343912d41d182000de8bb2e291bdcd46deccaa88a9e007ef2aec7757541decec19b7dfc96075ae4d02b0e8441266090f216b6364619fa66c95f511fe1832467eca30f95ee24b9f93c079" + }, + "uint64-given-float64": { + "frame": "090000000000004140", + "leaf": "072200000000000000", + "ciphertext": "01000000000000000000000000000000005902b1723e57208119a7343912d41d182000de8bb2e291bdcd46deccaa88a9e007ef2aec7757541decec19b7dfc96075ae4d024d8ceabb74d6249c2115af1dcde9c55db0736dcdffc10de38b896c5594d946650b216d8423" + }, + "uint64-given-fraction": { + "frame": "090000000000404140" + }, + "uint64-max": { + "frame": "07ffffffffffffffff", + "leaf": "07ffffffffffffffff", + "ciphertext": "01000000000000000000000000000000005902b1723e57208119a7343912d41d182000de8bb2e291bdcd46deccaa88a9e007ef2aec7757541decec19b7dfc96075ae4d02a9104cf6c7fc888b3be880b0ef77c8c90c39cae789b8734075fa23f57eedc832a273f3da8b" + }, + "uint8-max": { + "frame": "0dff", + "leaf": "0dff", + "ciphertext": "01000000000000000000000000000000005902b1723e57208119a7343912d41d182000de8bb2e291bdcd46deccaa88a9e007ef2aec7757541decec19b7dfc96075ae4d0210713e7cf318d8bcdafc7ed5bda20a513d00948785335c60e21c2d3c0e7f" + }, + "undefined-int32": { + "frame": "01" + }, + "undefined-json": { + "frame": "01" + }, + "uuid": { + "frame": "f305000b10000000123e4567e89b12d3a456426614174000", + "leaf": "f305000b123e4567e89b12d3a456426614174000", + "ciphertext": "01000000000000000000000000000000005902b1723e57208119a7343912d41d182000de8bb2e291bdcd46deccaa88a9e007ef2aec7757541decec19b7dfc96075ae4d02f8a12b99d4ec25ceb2e20f075c6de2577470599a6e3fb6c88fde3663da1fd5be113edfe7087a06411b67a3d1bf773fa5" + } + } +} diff --git a/packages/stack-encrypt/CHANGELOG.md b/packages/stack-encrypt/CHANGELOG.md index 79cbec8fb..32aae2ae9 100644 --- a/packages/stack-encrypt/CHANGELOG.md +++ b/packages/stack-encrypt/CHANGELOG.md @@ -50,6 +50,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 sealed leaf has a random nonce. The two interfaces agree on every other part: the keyset, the data key, the length, and the plaintext of the leaf. `tests/single_value.rs` holds them to that for every kind. + - The conformance profile `single-value-v1` + (`conformance/stack-encrypt/single-value-contract.md`) has the shared + cases. - `ScalarTarget` is re-exported from Vitamin C at the crate root. - **Encrypt a UUID as a UUID** (#1833). `value::Uuid` is vitaminc's diff --git a/packages/stack-encrypt/tests/common/conformance.rs b/packages/stack-encrypt/tests/common/conformance.rs index ed4aecb07..12b3921a0 100644 --- a/packages/stack-encrypt/tests/common/conformance.rs +++ b/packages/stack-encrypt/tests/common/conformance.rs @@ -50,6 +50,7 @@ pub fn value(input: &Input) -> OwnedFrame { Physical::Int(Int::I128(mantissa)), )) } + "uuid" => frame(Raw(Some(Logical::Uuid), Physical::Bytes(&parse_uuid(text)))), "null" => { assert!(input.text.is_empty()); frame(Raw(None, Physical::Null)) @@ -201,6 +202,23 @@ fn parse_timestamp(text: &str) -> i128 { ((days * 86_400 + hour * 3_600 + minute * 60 + second) * 1_000_000_000) + nanos } +/// The sixteen bytes of a UUID from its canonical text: lowercase hex in +/// groups of 8, 4, 4, 4 and 12 digits, with `-` between them. Any other +/// spelling (uppercase, braces, no hyphens) is a corpus error. +fn parse_uuid(text: &str) -> [u8; 16] { + let groups: Vec<&str> = text.split('-').collect(); + let lengths: Vec = groups.iter().map(|group| group.len()).collect(); + let digits = groups.concat(); + assert!( + lengths == [8, 4, 4, 4, 12] + && digits + .bytes() + .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)), + "{text}: not a canonical lowercase UUID" + ); + super::unhex(&digits).try_into().expect("sixteen bytes") +} + /// A decimal's mantissa and scale from fixed-point text, keeping every /// trailing zero: `-1234.5600` is `(-12345600, 4)`. fn parse_decimal(text: &str) -> (i128, u8) { diff --git a/packages/stack-encrypt/tests/single_value_conformance.rs b/packages/stack-encrypt/tests/single_value_conformance.rs new file mode 100644 index 000000000..7ed8b44c1 --- /dev/null +++ b/packages/stack-encrypt/tests/single_value_conformance.rs @@ -0,0 +1,654 @@ +//! The shared single-value profile: one value as one ciphertext through the +//! run-time interface, with what it seals held to the typed interface and +//! to frozen artifacts. See conformance/stack-encrypt/single-value-contract.md. +// The typed `Uuid` reference needs the `uuid` feature, which `dynamic` does +// not turn on. +#![cfg(all(feature = "dynamic", feature = "uuid"))] +mod common; + +use std::collections::{BTreeMap, BTreeSet}; +use std::path::PathBuf; +use std::sync::atomic::Ordering; + +use common::conformance::{value, Input}; +use common::frames::{frame, object, owned}; +use common::leaves::{kept_cipher, parts}; +use common::{hex, unhex, CountingSource, DeterministicSource}; +use miette::Diagnostic as _; +use serde::{Deserialize, Serialize}; +use stack_encrypt::dynamic::{self, frame::OwnedFrame, value as single, ValueKind}; +use stack_encrypt::json::JsonPlaintext; +use stack_encrypt::kms::{DataKeySource, IndexKeySource}; +use stack_encrypt::value::{Date, Decimal, Timestamp, Uuid}; +use stack_encrypt::{ + AsProtectedRef as _, CipherRef, Ciphertext, ContextPiece, Decrypt as _, Encrypt as _, Error, + IntoContext, KeysetCipher, Pending, StackCipher, +}; +use vitaminc_aead::frame::{Frame, PASSTHROUGH}; +use vitaminc_aead::plaintext::{FixedType, Width}; + +const PROFILE: &str = "single-value-v1"; + +/// The values an input of type `shape` names: what `{type, text}` cannot +/// spell. A name outside this list is a corpus error. +const SHAPES: [&str; 5] = [ + "array", + "empty_array", + "object", + "passthrough", + "typed_null", +]; + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Corpus { + version: u32, + profile: String, + seed: String, + required_capabilities: Vec, + cases: Vec, + batches: Vec, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Case { + id: String, + /// The declared kind's name, or empty for none. + kind: String, + /// The context's parts, or empty for the empty context. + context: Vec, + input: Input, + /// The value the ciphertext holds, where it is not the input: a number + /// converted to the declared kind, or a document's compact JSON text. + stored: Option, + /// Kinds the ciphertext must refuse to open as. + refused_as: Option>, + expected_error: Option, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Batch { + id: String, + kind: String, + context: Vec, + inputs: Vec, + /// The values the ciphertexts hold, where they are not the inputs. + stored: Option>, + expected_error: Option, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct ExpectedError { + code: String, + reason: String, +} + +#[derive(Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +struct Artifacts { + version: u32, + profile: String, + producer: String, + cases: BTreeMap, +} + +#[derive(Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +struct Artifact { + /// The input's transport frame. + frame: String, + /// The plaintext the leaf is sealed with: its tag and payload. Absent + /// for a refused case. + #[serde(skip_serializing_if = "Option::is_none")] + leaf: Option, + /// A ciphertext of the value, frozen. Absent for a refused case. + #[serde(skip_serializing_if = "Option::is_none")] + ciphertext: Option, +} + +fn root() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../conformance/stack-encrypt/v1") +} + +/// The value an input of type `shape` names. +fn shape(name: &str) -> OwnedFrame { + assert!( + SHAPES.contains(&name), + "{name}: not a shape the profile names" + ); + match name { + "array" => frame(vec!["a", "b"]), + "empty_array" => frame(Vec::::new()), + "object" => object(vec![("a", frame(1u32))]), + "passthrough" => { + let mut bytes = vec![PASSTHROUGH]; + bytes.extend_from_slice(frame("clear").frame().as_bytes()); + owned(&bytes) + } + _ => OwnedFrame::typed_null(FixedType::plain(Width::I64).expect("a fixed type")), + } +} + +/// The frame an input names: a shape, or a value in the corpus's +/// `{type, text}` form. +fn input(input: &Input) -> OwnedFrame { + match input.kind.as_str() { + "shape" => shape(&input.text), + _ => value(input), + } +} + +fn declared(kind: &str) -> Option { + (!kind.is_empty()).then(|| kind.parse().expect("a kind's name")) +} + +/// A case's context, as a binding hands one over: a frame of its parts. +fn piece(parts: &[String]) -> ContextPiece<'static> { + let frame = recipher_frame::serde::to_vec(&parts).expect("a context frames"); + dynamic::context(frame.as_protected_ref()) + .expect("a context of two text parts") + .into_inner() +} + +/// The run-time encrypt: the form with no context for an empty context, +/// and the form with one otherwise. +fn seal<'a, K: 'static>( + keyset: &'a KeysetCipher<'_, K>, + value: Frame<'_>, + kind: Option, + context: &[String], +) -> Result, dynamic::Error> { + if context.is_empty() { + single::encrypt(keyset, value, kind) + } else { + single::encrypt_with_context(keyset, value, kind, piece(context)) + } +} + +fn seal_all<'a, K: 'static>( + keyset: &'a KeysetCipher<'_, K>, + values: &[OwnedFrame], + kind: Option, + context: &[String], +) -> Result, K>, dynamic::Error> { + let frames = values.iter().map(OwnedFrame::frame); + if context.is_empty() { + single::encrypt_all(keyset, frames, kind) + } else { + single::encrypt_all_with_context(keyset, frames, kind, piece(context)) + } +} + +fn open<'a, K: 'static>( + cipher: impl Into>, + ciphertext: Ciphertext, + kind: Option, + context: &[String], +) -> Pending<'a, OwnedFrame, K> { + if context.is_empty() { + single::decrypt(cipher, ciphertext, kind) + } else { + single::decrypt_with_context(cipher, ciphertext, kind, piece(context)) + } +} + +fn open_all<'a, K: 'static>( + cipher: impl Into>, + ciphertexts: Vec, + kind: Option, + context: &[String], +) -> Pending<'a, Vec, K> { + if context.is_empty() { + single::decrypt_all(cipher, ciphertexts, kind) + } else { + single::decrypt_all_with_context(cipher, ciphertexts, kind, piece(context)) + } +} + +/// The context `ciphertext`'s leaf is sealed under, for opening the leaf +/// with a kept key. +fn sealed_under(context: &[String]) -> ContextPiece<'static> { + if context.is_empty() { + ().into_context() + } else { + piece(context) + } +} + +/// The Rust types the typed interface spells a kind with. `$run` is handed +/// the type for `name`, or the match is `None` for a kind no Rust type +/// spells: a lone 8-bit unsigned integer, and JavaScript's `undefined`. +macro_rules! with_rust_type { + ($name:expr, $run:ident) => { + match $name { + "bool" => Some($run!(bool)), + "int8" => Some($run!(i8)), + "int16" => Some($run!(i16)), + "int32" => Some($run!(i32)), + "int64" => Some($run!(i64)), + "int128" => Some($run!(i128)), + "uint16" => Some($run!(u16)), + "uint32" => Some($run!(u32)), + "uint64" => Some($run!(u64)), + "uint128" => Some($run!(u128)), + "float32" => Some($run!(f32)), + "float64" => Some($run!(f64)), + "string" => Some($run!(String)), + "bytes" => Some($run!(Vec)), + "date" => Some($run!(Date)), + "timestamp" => Some($run!(Timestamp)), + "decimal" => Some($run!(Decimal)), + "uuid" => Some($run!(Uuid)), + "json" => Some($run!(JsonPlaintext)), + "uint8" | "undefined" => None, + other => panic!("{other}: no typed form is listed for this kind"), + } + }; +} + +/// The typed call's ciphertext of the value `stored` holds, as the Rust +/// type `name` names. +async fn typed_seal( + keyset: &KeysetCipher<'_, K>, + name: &str, + stored: &OwnedFrame, + context: &[String], +) -> Option +where + K: DataKeySource + IndexKeySource + Sync + 'static, +{ + macro_rules! seal_as { + ($ty:ty) => {{ + let value: $ty = stored + .visit(<$ty>::sink()) + .expect("the stored value as its Rust type"); + if context.is_empty() { + keyset.encrypt(value).await + } else { + keyset.encrypt_with_context(value, piece(context)).await + } + .expect("the typed call seals") + }}; + } + with_rust_type!(name, seal_as) +} + +/// The value the typed call opens `ciphertext` to, as the Rust type `name` +/// names, written as a frame. +async fn typed_open( + keyset: &KeysetCipher<'_, K>, + name: &str, + ciphertext: Ciphertext, + context: &[String], +) -> Option +where + K: DataKeySource + IndexKeySource + Sync + 'static, +{ + macro_rules! open_as { + ($ty:ty) => {{ + let value: $ty = if context.is_empty() { + keyset.decrypt(ciphertext).await + } else { + keyset + .decrypt_with_context(ciphertext, piece(context)) + .await + } + .expect("the typed call opens"); + frame(&value) + }}; + } + with_rust_type!(name, open_as) +} + +/// A cipher over the seeded source, with its `(generate, retrieve)` call +/// counters. +async fn counting( + seed: [u8; 32], +) -> ( + StackCipher>, + std::sync::Arc, + std::sync::Arc, +) { + let source = CountingSource::over(DeterministicSource::new(seed)); + let (generates, retrieves) = source.counters(); + let cipher = StackCipher::builder() + .kms(source) + .init() + .await + .expect("build cipher"); + (cipher, generates, retrieves) +} + +fn assert_refusal(id: &str, error: &dynamic::Error, expected: &ExpectedError) { + assert_eq!( + error.code().map(|code| code.to_string()).as_deref(), + Some(expected.code.as_str()), + "{id}: the diagnostic code" + ); + assert_eq!( + error.reason().map(|reason| reason.as_str()), + Some(expected.reason.as_str()), + "{id}: the reason" + ); + assert_eq!(error.field(), None, "{id}: a single value names no field"); +} + +fn is_forbidden(result: &Result) -> bool { + matches!( + result, + Err(Error::Kms(stack_kms::Error::RetrieveKey( + stack_kms::RetrieveKeyError::RequestFailed(error) + ))) if matches!(error.kind, zerokms_protocol::ViturRequestErrorKind::Forbidden) + ) +} + +/// One accepted case: what the run-time call seals is what the typed call +/// seals and what the artifact froze, and every reader opens it. +async fn accepted( + seed: [u8; 32], + case: &Case, + value: &OwnedFrame, + artifact: &mut Artifact, + baseline: Option<&Artifact>, +) { + let id = &case.id; + let kind = declared(&case.kind); + let stored_input = case.stored.as_ref().unwrap_or(&case.input); + let stored = input(stored_input); + let context = &case.context; + + let (cipher, keys) = kept_cipher(seed).await; + let keyset = cipher.default_keyset(); + let fresh = seal(&keyset, value.frame(), kind, context) + .unwrap_or_else(|error| panic!("{id}: the value is refused: {error}")) + .await + .unwrap_or_else(|error| panic!("{id}: the value does not seal: {error}")); + let fresh_parts = parts(&keys, fresh.clone(), sealed_under(context)); + + // The typed call, over a fresh source of the same seed, so that its + // data key is the one the run-time call was given. + let typed_name = if case.kind == "json" { + "json" + } else { + stored_input.kind.as_str() + }; + let (typed_cipher, typed_keys) = kept_cipher(seed).await; + let typed = typed_seal(&typed_cipher.default_keyset(), typed_name, &stored, context).await; + if let Some(typed) = &typed { + assert_eq!( + fresh_parts, + parts(&typed_keys, typed.clone(), sealed_under(context)), + "{id}: the run-time ciphertext differs from the typed one in a part that is not the nonce" + ); + } + + artifact.leaf = Some(fresh_parts.leaf.clone()); + artifact.ciphertext = Some(hex(&typed.unwrap_or_else(|| fresh.clone()).to_bytes())); + let reference: &Artifact = baseline.unwrap_or(artifact); + assert_eq!( + artifact.leaf, reference.leaf, + "{id}: the plaintext the leaf is sealed with" + ); + let frozen = Ciphertext::from_bytes(&unhex( + reference + .ciphertext + .as_deref() + .unwrap_or_else(|| panic!("{id}: an accepted case has a frozen ciphertext")), + )) + .unwrap_or_else(|error| panic!("{id}: the frozen ciphertext does not parse: {error}")); + assert_eq!( + parts(&keys, frozen.clone(), sealed_under(context)), + fresh_parts, + "{id}: the frozen ciphertext differs from a fresh one in a part that is not the nonce" + ); + + // Under the `json` kind a document opens as its text in a bytes leaf. + let opened_as_declared = if case.kind == "json" { + frame(stored_input.text.as_bytes().to_vec()) + } else { + input(stored_input) + }; + // No case seals under this context. + let wrong = ["conformance".to_owned(), "wrong".to_owned()]; + assert_ne!( + context[..], + wrong[..], + "{id}: a case uses the wrong context" + ); + for (origin, ciphertext) in [("fresh", fresh), ("frozen", frozen)] { + let opened = open(&keyset, ciphertext.clone(), None, context) + .await + .unwrap_or_else(|error| panic!("{id}: the {origin} ciphertext does not open: {error}")); + assert_eq!( + opened.frame(), + stored.frame(), + "{id}: the {origin} ciphertext opens to another value" + ); + if let Some(kind) = kind { + let opened = open(&keyset, ciphertext.clone(), Some(kind), context) + .await + .unwrap_or_else(|error| { + panic!("{id}: the {origin} ciphertext does not open as {kind}: {error}") + }); + assert_eq!( + opened.frame(), + opened_as_declared.frame(), + "{id}: the {origin} ciphertext opens as {kind} to another value" + ); + } + if let Some(opened) = typed_open(&keyset, typed_name, ciphertext.clone(), context).await { + assert_eq!( + opened.frame(), + stored.frame(), + "{id}: the typed call reads another value from the {origin} ciphertext" + ); + } + for name in case.refused_as.iter().flatten() { + let other = declared(name); + let refused = open(&keyset, ciphertext.clone(), other, context).await; + assert!( + matches!(&refused, Err(Error::OpenedType { expected }) if expected == name), + "{id}: the {origin} ciphertext must not open as {name}, got: {refused:?}" + ); + } + let refused = open(&keyset, ciphertext, None, &wrong).await; + assert!( + is_forbidden(&refused), + "{id}: the {origin} ciphertext must not open under another context, got: {refused:?}" + ); + } +} + +#[tokio::test] +async fn shared_single_value_profile() { + let update = common::fixture_updates_requested_or_panic(); + let corpus: Corpus = serde_json::from_str(include_str!( + "../../../conformance/stack-encrypt/v1/single-value-v1.cases.json" + )) + .expect("the cases file"); + assert_eq!(corpus.version, 1, "the corpus format version"); + assert_eq!(corpus.profile, PROFILE, "the profile"); + assert_eq!( + corpus.required_capabilities, + ["single-value", "value-kinds", "context-binding", "refusals"], + "the capabilities a runner needs" + ); + let seed: [u8; 32] = unhex(&corpus.seed).try_into().expect("a 32-byte seed"); + assert!(!corpus.cases.is_empty(), "the profile has cases"); + let ids: BTreeSet<&str> = corpus + .cases + .iter() + .map(|case| case.id.as_str()) + .chain(corpus.batches.iter().map(|batch| batch.id.as_str())) + .collect(); + assert_eq!( + ids.len(), + corpus.cases.len() + corpus.batches.len(), + "case IDs are distinct" + ); + assert!(!ids.contains(""), "no case ID is empty"); + + let path = root().join("single-value-v1.expected.rust-native.json"); + let baseline: Option = (!update).then(|| { + let artifacts: Artifacts = + serde_json::from_slice(&std::fs::read(&path).expect("the expected file")) + .expect("the expected file parses"); + assert_eq!(artifacts.version, 1, "the artifacts' format version"); + assert_eq!(artifacts.profile, PROFILE, "the artifacts' profile"); + assert!( + artifacts.producer.starts_with("rust-native"), + "the artifacts' producer: {}", + artifacts.producer + ); + assert_eq!( + artifacts + .cases + .keys() + .map(String::as_str) + .collect::>(), + corpus + .cases + .iter() + .map(|case| case.id.as_str()) + .collect::>(), + "the artifacts hold exactly the cases" + ); + artifacts + }); + + let mut output = BTreeMap::new(); + for case in &corpus.cases { + eprintln!("single value: {}", case.id); + let value = input(&case.input); + let mut artifact = Artifact { + frame: hex(value.frame().as_bytes()), + leaf: None, + ciphertext: None, + }; + let reference = baseline + .as_ref() + .map(|artifacts| &artifacts.cases[&case.id]); + if let Some(reference) = reference { + assert_eq!( + artifact.frame, reference.frame, + "{}: the input's frame", + case.id + ); + } + match &case.expected_error { + Some(expected) => { + assert!( + case.stored.is_none() && case.refused_as.is_none(), + "{}: a refused case stores nothing", + case.id + ); + let (cipher, generates, retrieves) = counting(seed).await; + let keyset = cipher.default_keyset(); + let error = match seal(&keyset, value.frame(), declared(&case.kind), &case.context) + { + Err(error) => error, + Ok(_) => panic!( + "{}: the value is taken where a refusal is expected", + case.id + ), + }; + assert_refusal(&case.id, &error, expected); + assert_eq!( + ( + generates.load(Ordering::SeqCst), + retrieves.load(Ordering::SeqCst) + ), + (0, 0), + "{}: a refused value makes no key request", + case.id + ); + if let Some(reference) = reference { + assert!( + reference.leaf.is_none() && reference.ciphertext.is_none(), + "{}: a refused case has no frozen ciphertext", + case.id + ); + } + } + None => accepted(seed, case, &value, &mut artifact, reference).await, + } + let _ = output.insert(case.id.clone(), artifact); + } + + for batch in &corpus.batches { + eprintln!("single value: {}", batch.id); + let id = &batch.id; + let kind = declared(&batch.kind); + let values: Vec = batch.inputs.iter().map(input).collect(); + let (cipher, generates, retrieves) = counting(seed).await; + let keyset = cipher.default_keyset(); + let sealed = match ( + seal_all(&keyset, &values, kind, &batch.context), + &batch.expected_error, + ) { + (Err(error), Some(expected)) => { + assert_refusal(id, &error, expected); + assert_eq!( + generates.load(Ordering::SeqCst), + 0, + "{id}: a refused batch makes no key request" + ); + continue; + } + (Err(error), None) => panic!("{id}: the batch is refused: {error}"), + (Ok(_), Some(_)) => panic!("{id}: the batch is taken where a refusal is expected"), + (Ok(pending), None) => pending + .await + .unwrap_or_else(|error| panic!("{id}: the batch does not seal: {error}")), + }; + let requests = usize::from(!values.is_empty()); + assert_eq!( + sealed.len(), + values.len(), + "{id}: one ciphertext for each value" + ); + assert_eq!( + generates.load(Ordering::SeqCst), + requests, + "{id}: the batch seals in one key request" + ); + let opened = open_all(&keyset, sealed, kind, &batch.context) + .await + .unwrap_or_else(|error| panic!("{id}: the batch does not open: {error}")); + assert_eq!( + retrieves.load(Ordering::SeqCst), + requests, + "{id}: the batch opens in one key request" + ); + let stored = batch.stored.as_ref().unwrap_or(&batch.inputs); + assert_eq!( + opened.len(), + stored.len(), + "{id}: one value for each ciphertext" + ); + for (position, (opened, expected)) in opened.iter().zip(stored).enumerate() { + assert_eq!( + opened.frame(), + input(expected).frame(), + "{id}: the value at position {position}" + ); + } + } + + if update { + let artifacts = Artifacts { + version: 1, + profile: PROFILE.into(), + producer: format!("rust-native/stack-encrypt-{}", env!("CARGO_PKG_VERSION")), + cases: output, + }; + std::fs::write( + &path, + serde_json::to_string_pretty(&artifacts).expect("the artifacts as JSON") + "\n", + ) + .expect("write the expected file"); + } +} diff --git a/scripts/__tests__/stack-conformance-ci.test.mjs b/scripts/__tests__/stack-conformance-ci.test.mjs index 2b6febf4f..0380fcd01 100644 --- a/scripts/__tests__/stack-conformance-ci.test.mjs +++ b/scripts/__tests__/stack-conformance-ci.test.mjs @@ -58,6 +58,9 @@ describe('shared Stack Encrypt conformance is required in CI', () => { /cargo nextest run[^\n]*--test raw_frame_conformance/, ) expect(script).toMatch(/cargo nextest run[^\n]*--test binding_conformance/) + expect(script).toMatch( + /cargo nextest run[^\n]*--test single_value_conformance/, + ) const selected = goSelection(script) for (const test of coreGoTests) { expect(selected.test(test), test).toBe(true) diff --git a/scripts/stack-conformance.sh b/scripts/stack-conformance.sh index df2bc5039..600ba556c 100644 --- a/scripts/stack-conformance.sh +++ b/scripts/stack-conformance.sh @@ -19,7 +19,7 @@ go_tests=$(node scripts/stack-conformance-selection.mjs) artifacts=$(mktemp -d) trap 'rm -rf "$artifacts"' EXIT -mise x --env test -- cargo nextest run --locked -p stack-encrypt --all-features --test conformance --test declarations --test runtime_conformance --test read_conformance --test context_conformance --test record_lowering --test plan_grammar --test value_kinds --test query_operators --test fixture_safety --test value_conformance --test query_refusal_conformance --test raw_frame_conformance --test exchange_conformance --test binding_conformance +mise x --env test -- cargo nextest run --locked -p stack-encrypt --all-features --test conformance --test declarations --test runtime_conformance --test read_conformance --test context_conformance --test record_lowering --test plan_grammar --test value_kinds --test query_operators --test fixture_safety --test value_conformance --test query_refusal_conformance --test raw_frame_conformance --test exchange_conformance --test binding_conformance --test single_value_conformance ( cd languages/golang STACK_CONFORMANCE_OUTPUT="$artifacts/go.json" CGO_ENABLED=0 \ From d2ce814409d090ceea020d885b93dd79a3cb7e0d Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sat, 28 Nov 2026 16:15:04 +1100 Subject: [PATCH 06/19] docs(stack-encrypt): describe the single-value calls for a binding author The guide to building a language integration said a binding does three things, all through a record's plan. A binding can now also encrypt one value into one ciphertext, with no plan, and a new SDK should reach for the engine's call and not write its own. The guide gains a section on `dynamic::value`, and its checklist names the single-value conformance profile. The crate docs point a binding author at the module from the section on language integrations. --- .../docs/language-integration.md | 28 +++++++++++++++++-- packages/stack-encrypt/src/lib.rs | 5 ++++ 2 files changed, 31 insertions(+), 2 deletions(-) diff --git a/packages/stack-encrypt/docs/language-integration.md b/packages/stack-encrypt/docs/language-integration.md index 1631f78f8..b95970f16 100644 --- a/packages/stack-encrypt/docs/language-integration.md +++ b/packages/stack-encrypt/docs/language-integration.md @@ -170,6 +170,30 @@ says which cipher opens ([`crate::CipherRef`]): A record encrypted with a scope or a binding is decrypted with the same ones, through `decrypt_from_with_context`. +### One value as one ciphertext + +A record is not the only stored form. Rust's `keyset.encrypt(value)` +encrypts one value into one [`crate::Ciphertext`], with no plan. A binding +does the same through [`crate::dynamic::value`]: + +- [`crate::dynamic::value::encrypt`] takes the value as a + [`crate::dynamic::frame::Frame`] and an optional declared kind + ([`crate::dynamic::ValueKind`]). It settles to the ciphertext the typed + Rust call makes for the same value, so every language reads what any + language wrote. +- [`crate::dynamic::value::decrypt`] takes a ciphertext and an optional + kind the value must open as. It settles to the value's frame. + +Each has a form that takes a context, and a form that takes many values and +makes one key request. A declared kind reads the value by the rules a +record's typed field uses, so a binding passes a language's own number. The +kind `json` takes a document as its JSON text. + +A ciphertext holds one scalar. An array, an object, a passthrough and a null +are refused before any key is requested, with a reason that says which was +found (`array`, `object`, `passthrough`, `null`). An SDK stores an absent +value as a database `NULL`. + ### Scopes and bindings A field is sealed under its label, `["profiles", "age"]`. A caller adds to @@ -833,8 +857,8 @@ done: each profile in `conformance/stack-encrypt/v1`, as `languages/golang/encrypt/*conformance_test.go` does for Go: scalar records, declarations, reads, runtime and nulls, contexts and bindings, - value boundaries, query refusals, raw frames and, if your binding links - the EQL types, EQL and JSON. Read the frozen expectations; never + value boundaries, query refusals, raw frames, single values and, if your + binding links the EQL types, EQL and JSON. Read the frozen expectations; never regenerate them to pass. A profile you have not run is not a pass. 2. **Fresh artifacts cross both ways.** The exchange profile (`conformance/stack-encrypt/exchange-contract.md`) has your binding open diff --git a/packages/stack-encrypt/src/lib.rs b/packages/stack-encrypt/src/lib.rs index 1f51d50bd..39ef000de 100644 --- a/packages/stack-encrypt/src/lib.rs +++ b/packages/stack-encrypt/src/lib.rs @@ -675,6 +675,11 @@ endpoint — are `StackKmsBuilder`'s, and the two keyset-cache knobs are //! module (feature `dynamic`). The guide to building such a binding, with //! the Go SDK as the reference, is `dynamic::guide`. //! +//! A binding holds a value as a frame, and learns its kind only when the +//! code runs. `dynamic::value` encrypts such a value as the one +//! [`Ciphertext`] that [`KeysetCipher::encrypt`] returns for it, and decrypts +//! one into a frame. +//! //! # Relationship to vitaminc //! //! A `KeysetCipher` seals through a vitaminc `Cipher`; everything vitaminc From 0ad383bc41bc19919cd0145f82254772df1b3729 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sat, 28 Nov 2026 17:30:15 +1100 Subject: [PATCH 07/19] fix(stack-encrypt): refuse undefined as a single value The run-time single-value encrypt refused a null and sealed JavaScript's `undefined` when no kind was declared. `undefined` is most often a property name spelt wrong, so sealing one stores a mistake as a real ciphertext, and no typed call can read it back. A record's typed field already refuses it for that reason. `dynamic::value::encrypt` now refuses `undefined` with `Reason::Undefined`, with a declared kind and with none, before any key is requested. Two other values have no kind and reached the same arm: - A scalar of a logical type this build does not know. It is still sealed as it arrived when no kind is declared. The leaf format carries such a type by its id so that a value of a newer type survives an older build, the leaf encoder writes it, and it opens again with no declared kind. A declared kind refuses it. Tests now pin both. - A known logical type over a value it does not admit. No frame holds one: the frame writer refuses to write it and the frame reader refuses its bytes. A test pins that it cannot reach `encrypt`. The conformance case `as-is-undefined` becomes the refused case `undefined-no-kind`. On an update, the Rust runner now keeps the frozen ciphertext of a case whose frame and leaf have not changed, and checks it as any run does. So a regeneration changes only the cases that changed, and a frozen ciphertext stays frozen. --- .../stack-encrypt/single-value-contract.md | 21 ++-- .../v1/single-value-v1.cases.json | 23 ++-- .../single-value-v1.expected.rust-native.json | 8 +- packages/stack-encrypt/CHANGELOG.md | 7 +- .../docs/language-integration.md | 3 +- packages/stack-encrypt/src/dynamic/value.rs | 49 +++++--- packages/stack-encrypt/tests/single_value.rs | 107 +++++++++++++++--- .../tests/single_value_conformance.rs | 26 ++++- 8 files changed, 188 insertions(+), 56 deletions(-) diff --git a/conformance/stack-encrypt/single-value-contract.md b/conformance/stack-encrypt/single-value-contract.md index 4f4a82641..ed23c1430 100644 --- a/conformance/stack-encrypt/single-value-contract.md +++ b/conformance/stack-encrypt/single-value-contract.md @@ -62,8 +62,8 @@ written by the Rust runner: leaf's type tag and its payload. Only an accepted case has one. - `ciphertext`: a ciphertext of the value, in hex. Only an accepted case has one. The typed Rust interface made it, where a Rust type spells the stored - value. No Rust type spells a lone `uint8` or JavaScript's `undefined`, so - the run-time interface made those two. + value. No Rust type spells a lone `uint8`, so the run-time interface made + that one. Ciphertext bytes are never compared whole. Each sealed leaf carries a random AES-GCM nonce, so two ciphertexts of one value differ. A runner compares the @@ -73,7 +73,10 @@ The deterministic provider derives a data key from the seed, the context and a counter. So a runner makes a fresh provider for each ciphertext it compares. Regenerate the artifacts deliberately, with `STACK_ENCRYPT_UPDATE_FIXTURES=1` -and the native runner, and review the case and artifact diff together. +and the native runner, and review the case and artifact diff together. An +update keeps the frozen ciphertext of a case whose frame and leaf have not +changed, and checks it as any run does. So a ciphertext stays frozen from one +update to the next, and the diff shows only the cases that changed. ## Required behavior @@ -111,14 +114,15 @@ names no field. The cases cover: - an array, an object, a passthrough, a plain null and a typed null, each with no declared kind and with one: the reason says what was found (`array`, `object`, `passthrough`, `null`); -- JavaScript's `undefined` under a declared kind (`undefined`); +- JavaScript's `undefined`, with a declared kind and with none (`undefined`); - a value of another kind that does not convert exactly (`field_type`); - text that is not a JSON document, under `json` (`json_syntax`, `json_duplicate_key`, `json_integer_range`). -With no declared kind, `undefined` is a scalar and is sealed as it arrived. -The case `as-is-undefined` pins that. A host with no `undefined` checks the -case's shape and skips it. +`undefined` is refused whatever kind is declared. It is most often a property +name spelt wrong, and no typed call could read it back. A host with no +`undefined` sends the frame the artifact file records for those cases, or +checks their shape and skips them. ## Batches @@ -137,6 +141,9 @@ The profile covers every scalar kind, the exact conversions, JSON documents and the refusals of the run-time encrypt. It does not cover: - a ciphertext that holds a null, which only the tree interface seals; +- a scalar of a logical type the engine does not know, which `{type, text}` + cannot spell. With no declared kind the engine seals it as it arrived, and + `packages/stack-encrypt/tests/single_value.rs` pins that natively; - keyset confinement on decrypt, which `packages/stack-encrypt/tests/single_value.rs` covers natively; - fresh ciphertexts exchanged between languages. That comes with the first diff --git a/conformance/stack-encrypt/v1/single-value-v1.cases.json b/conformance/stack-encrypt/v1/single-value-v1.cases.json index 0e34918af..f5c5b5939 100644 --- a/conformance/stack-encrypt/v1/single-value-v1.cases.json +++ b/conformance/stack-encrypt/v1/single-value-v1.cases.json @@ -85,16 +85,6 @@ }, "refused_as": ["bytes"] }, - { - "id": "as-is-undefined", - "kind": "", - "context": [], - "input": { - "type": "undefined", - "text": "" - }, - "refused_as": ["int64"] - }, { "id": "as-is-string-with-context", "kind": "", @@ -589,6 +579,19 @@ "reason": "null" } }, + { + "id": "undefined-no-kind", + "kind": "", + "context": [], + "input": { + "type": "undefined", + "text": "" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_source", + "reason": "undefined" + } + }, { "id": "undefined-int32", "kind": "int32", diff --git a/conformance/stack-encrypt/v1/single-value-v1.expected.rust-native.json b/conformance/stack-encrypt/v1/single-value-v1.expected.rust-native.json index 5cf95189f..399ddf2b6 100644 --- a/conformance/stack-encrypt/v1/single-value-v1.expected.rust-native.json +++ b/conformance/stack-encrypt/v1/single-value-v1.expected.rust-native.json @@ -55,11 +55,6 @@ "leaf": "0dc8", "ciphertext": "0100000000000000000000000000000000953d2c5d27e5e549f2d84c34dffa03f4200046e77e88ca69bc28c79328ea2e7022660434e03342f93f07f852ccdcf45765de0282a2279d098f66f8776c5750e57acd502a6c3ecbbf4f77fa32e92a8aca60" }, - "as-is-undefined": { - "frame": "01", - "leaf": "01", - "ciphertext": "0100000000000000000000000000000000953d2c5d27e5e549f2d84c34dffa03f4200046e77e88ca69bc28c79328ea2e7022660434e03342f93f07f852ccdcf45765de0222594e69e4a84eaed73cb6d3d6d595a94e3d1894ad2e840642632adb9e" - }, "as-is-uuid": { "frame": "f305000b10000000123e4567e89b12d3a456426614174000", "leaf": "f305000b123e4567e89b12d3a456426614174000", @@ -278,6 +273,9 @@ "undefined-json": { "frame": "01" }, + "undefined-no-kind": { + "frame": "01" + }, "uuid": { "frame": "f305000b10000000123e4567e89b12d3a456426614174000", "leaf": "f305000b123e4567e89b12d3a456426614174000", diff --git a/packages/stack-encrypt/CHANGELOG.md b/packages/stack-encrypt/CHANGELOG.md index 32aae2ae9..99c40170c 100644 --- a/packages/stack-encrypt/CHANGELOG.md +++ b/packages/stack-encrypt/CHANGELOG.md @@ -43,9 +43,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 passthrough and a null, plain or typed, before any key is requested. The refusal is `dynamic::Error::Source` with one of three new reasons, `Reason::Array`, `Reason::Object` and `Reason::Null`, or with - `Reason::Passthrough`. `undefined` under a declared kind is - `Reason::Undefined`, and a value of another kind is - `Reason::FieldType`. + `Reason::Passthrough`. JavaScript's `undefined` is refused with + `Reason::Undefined`, with a declared kind and with none: it is most + often a property name spelt wrong, and no typed call could read it + back. A value of another kind is `Reason::FieldType`. - Two ciphertexts of one value never have the same bytes, because each sealed leaf has a random nonce. The two interfaces agree on every other part: the keyset, the data key, the length, and the plaintext of diff --git a/packages/stack-encrypt/docs/language-integration.md b/packages/stack-encrypt/docs/language-integration.md index b95970f16..6074a7aa1 100644 --- a/packages/stack-encrypt/docs/language-integration.md +++ b/packages/stack-encrypt/docs/language-integration.md @@ -192,7 +192,8 @@ kind `json` takes a document as its JSON text. A ciphertext holds one scalar. An array, an object, a passthrough and a null are refused before any key is requested, with a reason that says which was found (`array`, `object`, `passthrough`, `null`). An SDK stores an absent -value as a database `NULL`. +value as a database `NULL`. JavaScript's `undefined` is refused too +(`undefined`), whatever kind is declared. ### Scopes and bindings diff --git a/packages/stack-encrypt/src/dynamic/value.rs b/packages/stack-encrypt/src/dynamic/value.rs index fe9b29ffd..fafe8ff1e 100644 --- a/packages/stack-encrypt/src/dynamic/value.rs +++ b/packages/stack-encrypt/src/dynamic/value.rs @@ -40,10 +40,10 @@ //! The kind [`ValueKind::Json`] is a JSON document. On encrypt, the frame //! holds the document's JSON text, in a text leaf or a bytes leaf. The //! engine checks the text by its own JSON rules and seals the document as -//! [`JsonPlaintext`] is sealed, so the -//! ciphertext is the one `keyset.encrypt(JsonPlaintext)` returns. On -//! decrypt, the frame holds the document's JSON text in a bytes leaf, as a -//! record's `json` field opens ([`json_frame`](super::json_frame)). +//! [`JsonPlaintext`] is sealed, so the ciphertext is the one +//! `keyset.encrypt(JsonPlaintext)` returns. On decrypt, the frame holds +//! the document's JSON text in a bytes leaf, as a record's `json` field +//! opens ([`json_frame`](super::json_frame)). //! //! # What is refused //! @@ -54,6 +54,16 @@ //! database `NULL`, or seal it in a record whose field declares how //! ([`NullMode`](super::NullMode)). //! +//! [`encrypt`] also refuses JavaScript's `undefined`, whatever kind is +//! declared. `undefined` is most often a property name spelt wrong, and no +//! typed call could read it back. +//! +//! A scalar of a logical type that this build does not know has no kind. +//! The frame and the leaf carry such a type by its id, so that a value of +//! a newer type survives an older build. With no declared kind, it is +//! sealed as it arrived, and it opens only with no declared kind. With a +//! declared kind, it is refused. +//! //! A refusal says which kind of value was found, and never the value. //! //! [`KeysetCipher::encrypt`]: crate::KeysetCipher::encrypt @@ -123,8 +133,8 @@ use crate::{Ciphertext, ContextPiece, DecryptFrom, KeysetCipher}; /// - [`Reason::Array`], [`Reason::Object`], [`Reason::Passthrough`] or /// [`Reason::Null`] for a value that is not one scalar. A typed null is a /// null. -/// - [`Reason::Undefined`] for JavaScript's `undefined` with a declared -/// kind. With no declared kind, `undefined` is sealed as it arrived. +/// - [`Reason::Undefined`] for JavaScript's `undefined`, with a declared +/// kind or with none. /// - [`Reason::FieldType`] for a value that is not of the declared kind and /// does not convert to it exactly. /// - [`Reason::JsonSyntax`], [`Reason::JsonDuplicateKey`] or @@ -391,21 +401,34 @@ pub fn decrypt_all_with_context<'a, 'c, K: 'static>( /// # Errors /// /// [`Error::Source`] with the reason that names what was found: an array, -/// an object, a null or a passthrough. +/// an object, a null, a passthrough or `undefined`. fn one_scalar(value: Frame<'_>) -> Result<(), Error> { let found = match value.kind() { Some(ValueKind::Array) => Reason::Array, Some(ValueKind::Object) => Reason::Object, Some(_) => return Ok(()), - // No kind: a null, a passthrough, `undefined`, or a scalar of a - // logical type this build does not know. The last two are scalars. + // A value of no kind is a null, a passthrough, `undefined`, or a + // scalar of a logical type this build does not know. None if value.is_null() => Reason::Null, None if value.has_passthrough() => Reason::Passthrough, + None if is_undefined(value) => Reason::Undefined, + // The leaf format carries a logical type it does not know, so that + // a value of a newer type survives an older build. It is one + // scalar, and it seals as it arrived. None => return Ok(()), }; Err(Error::bad_source(found)) } +/// Whether `value` is JavaScript's `undefined`. +fn is_undefined(value: Frame<'_>) -> bool { + value + .visit(OneScalar::new(|ty: Option, _: Physical<'_>| { + Ok(ty == Some(Logical::Undefined)) + })) + .unwrap_or(false) +} + /// Plan the seal of one value under `context`, as the typed call plans it: /// the value is walked into the same operation, so the leaf is the same. fn seal<'a, K: 'static>( @@ -418,16 +441,14 @@ fn seal<'a, K: 'static>( let sealed = match kind { None => encrypt_opaque(value, keyset, context), Some(ValueKind::Json) => { - // A document crosses as text or bytes, so this converts nothing. - // It refuses `undefined`, and a value that is neither. - let _ = convert(ValueKind::Json, value)?; + // A document crosses as text or bytes, so nothing is converted. let document = read_json(value).map_err(not_a_document)?; // The document is sealed through a borrow and wiped when it // drops here, as the typed call's owned document is. encrypt_opaque(&document, keyset, context) } - // The conversion also refuses `undefined`, and a value that is not - // of the declared kind. A converted value is wiped when it drops. + // The conversion also refuses a value that is not of the declared + // kind. A converted value is wiped when it drops. Some(kind) => match convert(kind, value)? { Some(converted) => encrypt_opaque(converted.frame(), keyset, context), None => encrypt_opaque(value, keyset, context), diff --git a/packages/stack-encrypt/tests/single_value.rs b/packages/stack-encrypt/tests/single_value.rs index 138e0f501..c8ae1b274 100644 --- a/packages/stack-encrypt/tests/single_value.rs +++ b/packages/stack-encrypt/tests/single_value.rs @@ -474,11 +474,24 @@ mod encrypt_refuses_before_any_key_request { } } + /// `undefined` is most often a property name spelt wrong, and no typed + /// call could read it back. So it is refused with a declared kind and + /// with none. #[tokio::test] - async fn undefined_under_a_declared_kind() { - for kind in [ValueKind::Int64, ValueKind::String, ValueKind::Json] { - let error = refused(&undefined(), Some(kind)).await; - assert_source_refusal(&error, Reason::Undefined, &format!("undefined as {kind}")); + async fn undefined_whatever_kind_is_declared() { + for kind in [ + None, + Some(ValueKind::Int64), + Some(ValueKind::String), + Some(ValueKind::Json), + Some(ValueKind::Array), + ] { + let error = refused(&undefined(), kind).await; + assert_source_refusal( + &error, + Reason::Undefined, + &format!("undefined under {kind:?}"), + ); } } @@ -553,23 +566,91 @@ mod encrypt_refuses_before_any_key_request { mod encrypt_with_no_declared_kind { use super::*; - /// `undefined` is a scalar. With no declared kind it is sealed as it - /// arrived, as a field that declares no type keeps one. + /// A scalar of a logical type this build does not know: the frame and + /// the leaf carry its type id, and no kind names it. + fn unknown_logical() -> OwnedFrame { + let unknown = Logical::from_wire(200, 9).expect("an id no build knows yet"); + frame(Raw(Some(unknown), Physical::Int(Int::I32(7)))) + } + + /// The leaf format carries a logical type it does not know, so a value + /// of a newer type survives an older build. The value is one scalar, + /// and it is sealed as it arrived. #[tokio::test] - async fn seals_undefined_as_it_arrived() { + async fn seals_a_scalar_of_an_unknown_logical_type_as_it_arrived() { let cipher = common::stack_cipher().await; let keyset = cipher.default_keyset(); - let sealed = value::encrypt(&keyset, undefined().frame(), None) - .expect("undefined with no declared kind is taken") + let value = unknown_logical(); + assert_eq!(value.frame().kind(), None, "no kind names the type"); + let sealed = value::encrypt(&keyset, value.frame(), None) + .expect("a scalar of an unknown logical type is one scalar") .await .expect("it seals"); - let opened = value::decrypt(&keyset, sealed, None) + let opened = value::decrypt(&keyset, sealed.clone(), None) .await - .expect("it opens"); + .expect("it opens with no declared kind"); assert_eq!( opened.frame(), - undefined().frame(), - "undefined opens as undefined" + value.frame(), + "the value opens with its type id" + ); + + // It opens as no declared kind, and as no Rust type. + let as_int = value::decrypt(&keyset, sealed.clone(), Some(ValueKind::Int32)).await; + assert!( + matches!(as_int, Err(Error::OpenedType { expected: "int32" })), + "an unknown logical type is not an int32, got: {as_int:?}" + ); + let typed = keyset.decrypt::(sealed).await; + assert!( + matches!(typed, Err(Error::OpenedType { .. })), + "no Rust type reads an unknown logical type, got: {typed:?}" + ); + } + + #[tokio::test] + async fn refuses_an_unknown_logical_type_under_a_declared_kind() { + for kind in [ValueKind::Int32, ValueKind::Date, ValueKind::Json] { + let error = refused(&unknown_logical(), Some(kind)).await; + assert_source_refusal( + &error, + Reason::FieldType, + &format!("an unknown logical type as {kind}"), + ); + } + } + + /// A known logical type over a value it does not admit never reaches + /// `encrypt`: no frame holds one. The frame writer refuses to write it, + /// and the frame reader refuses bytes that spell it. + #[test] + fn a_logical_type_over_a_value_it_does_not_admit_is_not_a_frame() { + let short_uuid = Raw(Some(Logical::Uuid), Physical::Bytes(&[7; 15])); + assert!( + OwnedFrame::of(short_uuid).is_err(), + "the writer must refuse a UUID of fifteen bytes" + ); + // A real UUID's frame, with one byte taken off the payload and off + // the length. + let uuid = frame(Raw(Some(Logical::Uuid), Physical::Bytes(&[7; 16]))); + let mut bytes = uuid.frame().as_bytes().to_vec(); + let length = bytes.len() - 16 - 4; + assert_eq!( + bytes[length..length + 4], + 16u32.to_le_bytes(), + "the payload's length sits before the payload" + ); + bytes[length..length + 4].copy_from_slice(&15u32.to_le_bytes()); + let _ = bytes.pop(); + assert!( + vitaminc_aead::Frame::parse(&bytes).is_err(), + "the reader must refuse a UUID of fifteen bytes" + ); + + let out_of_range = Raw(Some(Logical::Date), Physical::Int(Int::I64(i64::MAX))); + assert!( + OwnedFrame::of(out_of_range).is_err(), + "the writer must refuse a date outside the range" ); } diff --git a/packages/stack-encrypt/tests/single_value_conformance.rs b/packages/stack-encrypt/tests/single_value_conformance.rs index 7ed8b44c1..b4504f21a 100644 --- a/packages/stack-encrypt/tests/single_value_conformance.rs +++ b/packages/stack-encrypt/tests/single_value_conformance.rs @@ -220,7 +220,7 @@ fn sealed_under(context: &[String]) -> ContextPiece<'static> { /// The Rust types the typed interface spells a kind with. `$run` is handed /// the type for `name`, or the match is `None` for a kind no Rust type -/// spells: a lone 8-bit unsigned integer, and JavaScript's `undefined`. +/// spells: a lone 8-bit unsigned integer. macro_rules! with_rust_type { ($name:expr, $run:ident) => { match $name { @@ -243,7 +243,7 @@ macro_rules! with_rust_type { "decimal" => Some($run!(Decimal)), "uuid" => Some($run!(Uuid)), "json" => Some($run!(JsonPlaintext)), - "uint8" | "undefined" => None, + "uint8" => None, other => panic!("{other}: no typed form is listed for this kind"), } }; @@ -353,6 +353,7 @@ async fn accepted( value: &OwnedFrame, artifact: &mut Artifact, baseline: Option<&Artifact>, + kept: Option<&Artifact>, ) { let id = &case.id; let kind = declared(&case.kind); @@ -387,6 +388,13 @@ async fn accepted( artifact.leaf = Some(fresh_parts.leaf.clone()); artifact.ciphertext = Some(hex(&typed.unwrap_or_else(|| fresh.clone()).to_bytes())); + // An update keeps the frozen ciphertext of a case whose leaf has not + // changed. So a ciphertext stays frozen from one update to the next, + // and the checks below hold the kept one to today's engine. + if let Some(kept) = kept.filter(|kept| kept.leaf == artifact.leaf && kept.ciphertext.is_some()) + { + artifact.ciphertext.clone_from(&kept.ciphertext); + } let reference: &Artifact = baseline.unwrap_or(artifact); assert_eq!( artifact.leaf, reference.leaf, @@ -519,6 +527,12 @@ async fn shared_single_value_profile() { artifacts }); + // On an update, the artifacts already written, if there are any. + let previous: Option = update + .then(|| std::fs::read(&path).ok()) + .flatten() + .and_then(|bytes| serde_json::from_slice(&bytes).ok()); + let mut output = BTreeMap::new(); for case in &corpus.cases { eprintln!("single value: {}", case.id); @@ -573,7 +587,13 @@ async fn shared_single_value_profile() { ); } } - None => accepted(seed, case, &value, &mut artifact, reference).await, + None => { + let kept = previous + .as_ref() + .and_then(|artifacts| artifacts.cases.get(&case.id)) + .filter(|kept| kept.frame == artifact.frame); + accepted(seed, case, &value, &mut artifact, reference, kept).await; + } } let _ = output.insert(case.id.clone(), artifact); } From 0dc55d8620db6918fdabe4c512a2ed265f7fb9f8 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sat, 28 Nov 2026 17:30:16 +1100 Subject: [PATCH 08/19] docs(stack-encrypt): say that string and json share one stored form The docs of the run-time decrypt said a value of another kind is refused. But `json` is a declared kind, and not a stored one: a document is stored as a text leaf that holds its JSON text, which is how a string is stored. So a sealed document opens as `string`, and a sealed string whose text is a JSON document opens as `json`. A kind check cannot tell the two apart, and the docs now say so. They also say what decrypt as `json` does: it checks that the text parses, and returns the document as the engine writes it. That text can differ from the text that was sealed as a string. The conformance case `as-is-string` listed `json` among the kinds it is refused as, which read as if every string were. That refusal moves to its own case, `string-not-json-text`. Two new cases show a string whose text is a document opening as `json`, and `json-given-string` shows a document opening as `string`. A case can now list kinds it opens as, with the value for each. Rust tests pin the same behaviour. --- conformance/stack-encrypt/README.md | 5 +- .../stack-encrypt/single-value-contract.md | 20 +++++- .../v1/single-value-v1.cases.json | 64 ++++++++++++++++++- .../single-value-v1.expected.rust-native.json | 15 +++++ packages/stack-encrypt/CHANGELOG.md | 5 ++ .../docs/language-integration.md | 5 ++ packages/stack-encrypt/src/dynamic/value.rs | 38 +++++++++-- packages/stack-encrypt/tests/single_value.rs | 60 +++++++++++++++++ .../tests/single_value_conformance.rs | 28 +++++++- 9 files changed, 227 insertions(+), 13 deletions(-) diff --git a/conformance/stack-encrypt/README.md b/conformance/stack-encrypt/README.md index 6370d85f6..b629628a9 100644 --- a/conformance/stack-encrypt/README.md +++ b/conformance/stack-encrypt/README.md @@ -187,8 +187,9 @@ The [single-value contract](single-value-contract.md) defines one ciphertext through the engine's run-time interface, and decrypted from one. The cases give a value, the kind declared for it and a context. They cover every scalar kind, the exact conversions a declared kind makes, JSON -documents, batches, and the refusals of an array, an object, a passthrough, a -null, `undefined` and a value of another kind. +documents, the one stored form a string and a document share, batches, and +the refusals of an array, an object, a passthrough, a null, `undefined` and a +value of another kind. `v1/single-value-v1.expected.rust-native.json` freezes each input's frame, the plaintext each leaf is sealed with, and a ciphertext every runner must open. The native runner is `single_value_conformance` in the Rust crate, which diff --git a/conformance/stack-encrypt/single-value-contract.md b/conformance/stack-encrypt/single-value-contract.md index ed23c1430..118acc253 100644 --- a/conformance/stack-encrypt/single-value-contract.md +++ b/conformance/stack-encrypt/single-value-contract.md @@ -27,6 +27,7 @@ list of `batches`. Each case has: | `context` | The context's parts, or an empty list for the empty context | | `input` | The value, in the `{type, text}` form the [value profile](values-contract.md#cases) defines | | `stored` | The value the ciphertext holds, where it is not the input | +| `opens_as` | Kinds the ciphertext must open as, beside the declared one, each with the `value` it opens to | | `refused_as` | Kinds the ciphertext must refuse to open as | | `expected_error` | For a refused case, the refusal's `code` and `reason` | @@ -92,10 +93,11 @@ For a case with no `expected_error`: no `stored`); - with the declared kind, to the same value. Under `json` it opens to the stored JSON text in a bytes leaf. -5. Each ciphertext is refused when opened as a kind in `refused_as`. The +5. Each ciphertext opens as each kind in `opens_as`, to that entry's `value`. +6. Each ciphertext is refused when opened as a kind in `refused_as`. The refusal's code is `stack_encrypt::opened_type`, and its `expected` field is the kind's name. The refusal never says what the value opened as. -6. Each ciphertext is refused under the context `["conformance", "wrong"]`. +7. Each ciphertext is refused under the context `["conformance", "wrong"]`. The deterministic provider refuses the key request as forbidden, which models ZeroKMS. Other providers may report a wrong context differently. @@ -107,6 +109,20 @@ sealed as the declared kind's value when the conversion is exact, by the rules a record's typed field uses. A document under `json` is sealed as its compact JSON text, in a text leaf. +`json` is a declared kind, and not a stored one. A `string` and a document +share one stored form, a text leaf, so a kind check cannot tell them apart. +Three cases pin what follows from that: + +- `json-given-string`: a sealed document opens as `string`, to the JSON text + that was sealed. +- `string-json-number-text` and `string-json-spaced-text`: a sealed string + whose text is a JSON document opens as `json`. Decrypt as `json` checks that + the text parses, and returns the document as the engine writes it, in a + bytes leaf. So `{ "b" : [ 1 , null ], "a" : true }` comes back as + `{"a":true,"b":[1,null]}`. +- `string-not-json-text`: a sealed string whose text is not a JSON document is + refused as `json`. + For a case with `expected_error`, the run-time encrypt refuses the value before any key request, with the diagnostic `code` and `reason`. The refusal names no field. The cases cover: diff --git a/conformance/stack-encrypt/v1/single-value-v1.cases.json b/conformance/stack-encrypt/v1/single-value-v1.cases.json index f5c5b5939..e147d20dd 100644 --- a/conformance/stack-encrypt/v1/single-value-v1.cases.json +++ b/conformance/stack-encrypt/v1/single-value-v1.cases.json @@ -17,7 +17,7 @@ "type": "string", "text": "ada@example.com" }, - "refused_as": ["int64", "bytes", "json"] + "refused_as": ["int64", "bytes"] }, { "id": "as-is-empty-string", @@ -94,6 +94,59 @@ "text": "ada@example.com" } }, + { + "id": "string-json-number-text", + "kind": "", + "context": [], + "input": { + "type": "string", + "text": "42" + }, + "opens_as": [ + { + "kind": "json", + "value": { + "type": "bytes", + "text": "3432" + } + }, + { + "kind": "string", + "value": { + "type": "string", + "text": "42" + } + } + ] + }, + { + "id": "string-json-spaced-text", + "kind": "string", + "context": ["conformance", "value"], + "input": { + "type": "string", + "text": "{ \"b\" : [ 1 , null ], \"a\" : true }" + }, + "opens_as": [ + { + "kind": "json", + "value": { + "type": "bytes", + "text": "7b2261223a747275652c2262223a5b312c6e756c6c5d7d" + } + } + ] + }, + { + "id": "string-not-json-text", + "kind": "", + "context": [], + "input": { + "type": "string", + "text": "ada@example.com" + }, + "refused_as": ["json"] + }, { "id": "bool-false", "kind": "bool", @@ -356,6 +409,15 @@ "type": "string", "text": "{\"a\":\"é\",\"b\":[1,2.5,null]}" }, + "opens_as": [ + { + "kind": "string", + "value": { + "type": "string", + "text": "{\"a\":\"é\",\"b\":[1,2.5,null]}" + } + } + ], "refused_as": ["int64", "bytes"] }, { diff --git a/conformance/stack-encrypt/v1/single-value-v1.expected.rust-native.json b/conformance/stack-encrypt/v1/single-value-v1.expected.rust-native.json index 399ddf2b6..69a7558b1 100644 --- a/conformance/stack-encrypt/v1/single-value-v1.expected.rust-native.json +++ b/conformance/stack-encrypt/v1/single-value-v1.expected.rust-native.json @@ -218,6 +218,21 @@ "string-given-int64": { "frame": "052200000000000000" }, + "string-json-number-text": { + "frame": "0a020000003432", + "leaf": "0a3432", + "ciphertext": "0100000000000000000000000000000000953d2c5d27e5e549f2d84c34dffa03f4200046e77e88ca69bc28c79328ea2e7022660434e03342f93f07f852ccdcf45765de02c5470c71a49e4a40e9cc0ecf0d2c83331b14df48b422bab48a5b6527a49c38" + }, + "string-json-spaced-text": { + "frame": "0a220000007b20226222203a205b2031202c206e756c6c205d2c20226122203a2074727565207d", + "leaf": "0a7b20226222203a205b2031202c206e756c6c205d2c20226122203a2074727565207d", + "ciphertext": "01000000000000000000000000000000005902b1723e57208119a7343912d41d182000de8bb2e291bdcd46deccaa88a9e007ef2aec7757541decec19b7dfc96075ae4d0230b18ebf21ce9d80030906b36df0a068478d59ed3758f82f62f37c43aa058d84932cfb94cfc506bc765c338ebe5b6033ff00f8cba133f7103ebe9b0d8d9a0b" + }, + "string-not-json-text": { + "frame": "0a0f000000616461406578616d706c652e636f6d", + "leaf": "0a616461406578616d706c652e636f6d", + "ciphertext": "0100000000000000000000000000000000953d2c5d27e5e549f2d84c34dffa03f4200046e77e88ca69bc28c79328ea2e7022660434e03342f93f07f852ccdcf45765de02110a04698a1a246da6c8e432473b2e29e735e2c681205381dfea450121429847858582af90a83c75bbd405d8" + }, "string-unicode": { "frame": "0a09000000636166c3a920e29895", "leaf": "0a636166c3a920e29895", diff --git a/packages/stack-encrypt/CHANGELOG.md b/packages/stack-encrypt/CHANGELOG.md index 99c40170c..cdb2a781d 100644 --- a/packages/stack-encrypt/CHANGELOG.md +++ b/packages/stack-encrypt/CHANGELOG.md @@ -39,6 +39,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 bytes leaf. The engine checks the text and seals the document as `JsonPlaintext` is sealed. On decrypt, `json` returns the document's text in a bytes leaf, as a record's `json` field opens. + - `json` is a declared kind, and not a stored one. A document is stored + as a text leaf, as a string is, so a kind check cannot tell them + apart. A sealed document opens as `string`. A sealed string whose + text is a JSON document opens as `json`, which checks that the text + parses and returns it as the engine writes the document. - A ciphertext holds one scalar. `encrypt` refuses an array, an object, a passthrough and a null, plain or typed, before any key is requested. The refusal is `dynamic::Error::Source` with one of three new reasons, diff --git a/packages/stack-encrypt/docs/language-integration.md b/packages/stack-encrypt/docs/language-integration.md index 6074a7aa1..7d0b75ae3 100644 --- a/packages/stack-encrypt/docs/language-integration.md +++ b/packages/stack-encrypt/docs/language-integration.md @@ -195,6 +195,11 @@ found (`array`, `object`, `passthrough`, `null`). An SDK stores an absent value as a database `NULL`. JavaScript's `undefined` is refused too (`undefined`), whatever kind is declared. +`json` is a declared kind, and a document is stored as text. So a `string` +and a document share one stored form, and a kind check cannot tell them +apart: a sealed document opens as `string`, and a sealed string whose text +is a JSON document opens as `json`. + ### Scopes and bindings A field is sealed under its label, `["profiles", "age"]`. A caller adds to diff --git a/packages/stack-encrypt/src/dynamic/value.rs b/packages/stack-encrypt/src/dynamic/value.rs index fafe8ff1e..799efa2a3 100644 --- a/packages/stack-encrypt/src/dynamic/value.rs +++ b/packages/stack-encrypt/src/dynamic/value.rs @@ -32,8 +32,8 @@ //! the scalar is sealed as it arrived. //! //! On decrypt, a declared kind is the kind the value must open as. Nothing -//! is converted: a value of another kind is refused. With no declared -//! kind, the value comes back as it was sealed. +//! is converted: a value stored as another kind is refused. With no +//! declared kind, the value comes back as it was sealed. //! //! # A JSON document //! @@ -45,6 +45,24 @@ //! the document's JSON text in a bytes leaf, as a record's `json` field //! opens ([`json_frame`](super::json_frame)). //! +//! `json` is a declared kind, and not a stored one. A document is stored +//! as a text leaf that holds its JSON text, which is how a `string` is +//! stored too. So `string` and `json` share one stored form, and a kind +//! check cannot tell them apart: +//! +//! - A sealed document opens as `string`. The frame holds the JSON text +//! that was sealed. +//! - A sealed string opens as `json` when its text is a JSON document. The +//! string `42` is one, and so is `"ada"` with its quotes. The string +//! `ada` is not, and is refused. +//! +//! Decrypt as `json` checks that the text parses by the engine's JSON +//! rules. It then returns the document as the engine writes it, which is +//! the text a document is sealed as: no whitespace between tokens, and +//! each number in its shortest form. So for a value that was sealed as a +//! string, the text that comes back can differ from the text that was +//! sealed. +//! //! # What is refused //! //! A [`Ciphertext`] holds one scalar. So [`encrypt`] refuses an array, an @@ -273,6 +291,11 @@ pub fn encrypt_all_with_context<'a, 'f, 'c, K: 'static>( /// sealed. With [`ValueKind::Json`], the frame holds the document's JSON /// text in a bytes leaf. /// +/// `string` and `json` share one stored form, a text leaf. So a sealed +/// document opens as `string`, and a sealed string whose text is a JSON +/// document opens as `json`. The [module docs](self#a-json-document) say +/// what `json` checks and returns. +/// /// Pass `&keyset` to open only a ciphertext of that keyset: a ciphertext /// of another keyset is refused before any key is retrieved. Pass /// `&cipher` to open a ciphertext of any keyset the client can use. @@ -320,11 +343,12 @@ pub fn encrypt_all_with_context<'a, 'f, 'c, K: 'static>( /// [`Aead`](crate::Error::Aead) for a wrong context or an altered /// ciphertext. /// -/// A value that opens as another kind than `kind` is -/// [`OpenedType`](crate::Error::OpenedType). The error names the kind that -/// was expected. It never says what the value opened as. An array or an -/// object is refused the same way, before any key is retrieved: a -/// ciphertext never holds one. +/// A value that was stored as another kind than `kind` is +/// [`OpenedType`](crate::Error::OpenedType). So is text that is not a JSON +/// document, opened as `json`. The error names the kind that was expected. +/// It never says what the value opened as. An array or an object is +/// refused the same way, before any key is retrieved: a ciphertext never +/// holds one. /// /// [`KeysetCipher::encrypt`]: crate::KeysetCipher::encrypt /// [`KeysetCipher::decrypt`]: crate::KeysetCipher::decrypt diff --git a/packages/stack-encrypt/tests/single_value.rs b/packages/stack-encrypt/tests/single_value.rs index c8ae1b274..8502b5662 100644 --- a/packages/stack-encrypt/tests/single_value.rs +++ b/packages/stack-encrypt/tests/single_value.rs @@ -1138,6 +1138,66 @@ mod decrypt_a_json_document { } } + /// `json` is a declared kind, and a document is stored as text. So a + /// string and a document share one stored form, and a kind check + /// cannot tell them apart. + #[tokio::test] + async fn opens_a_string_that_holds_json_text_and_returns_it_as_the_engine_writes_it() { + let cipher = common::stack_cipher().await; + let keyset = cipher.default_keyset(); + let cases = [ + ("42", "42"), + (r#""ada""#, r#""ada""#), + ( + r#"{ "b" : [ 1 , null ], "a" : true }"#, + r#"{"a":true,"b":[1,null]}"#, + ), + ]; + for (sealed_text, opened_text) in cases { + let sealed = keyset + .encrypt(String::from(sealed_text)) + .await + .expect("a string seals"); + let opened = value::decrypt(&keyset, sealed.clone(), Some(ValueKind::Json)) + .await + .unwrap_or_else(|error| { + panic!("the string {sealed_text} holds JSON text and opens as json: {error}") + }); + assert_eq!( + opened.frame(), + document(opened_text).frame(), + "the string {sealed_text} opens as json to the text the engine writes" + ); + // The same ciphertext still opens as the string that was sealed. + let as_string = value::decrypt(&keyset, sealed, Some(ValueKind::String)) + .await + .expect("a string opens as string"); + assert_eq!( + as_string.frame(), + frame(sealed_text).frame(), + "the string {sealed_text} opens as string unchanged" + ); + } + } + + #[tokio::test] + async fn opens_a_sealed_document_as_a_string() { + let cipher = common::stack_cipher().await; + let keyset = cipher.default_keyset(); + let sealed = keyset + .encrypt(JsonPlaintext::from(json!({"name": "Ada", "n": [1.5, -2]}))) + .await + .expect("a document seals"); + let opened = value::decrypt(&keyset, sealed, Some(ValueKind::String)) + .await + .expect("a document is stored as text, so it opens as string"); + assert_eq!( + opened.frame(), + frame(r#"{"n":[1.5,-2],"name":"Ada"}"#).frame(), + "the frame holds the JSON text that was sealed, in a text leaf" + ); + } + #[tokio::test] async fn opens_a_batch_of_documents_in_order() { let cipher = common::stack_cipher().await; diff --git a/packages/stack-encrypt/tests/single_value_conformance.rs b/packages/stack-encrypt/tests/single_value_conformance.rs index b4504f21a..735a36c94 100644 --- a/packages/stack-encrypt/tests/single_value_conformance.rs +++ b/packages/stack-encrypt/tests/single_value_conformance.rs @@ -64,9 +64,19 @@ struct Case { stored: Option, /// Kinds the ciphertext must refuse to open as. refused_as: Option>, + /// Kinds the ciphertext must open as, beside the declared one, each + /// with the value it opens to. + opens_as: Option>, expected_error: Option, } +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct OpensAs { + kind: String, + value: Input, +} + #[derive(Deserialize)] #[serde(deny_unknown_fields)] struct Batch { @@ -454,6 +464,22 @@ async fn accepted( "{id}: the typed call reads another value from the {origin} ciphertext" ); } + for also in case.opens_as.iter().flatten() { + let opened = open(&keyset, ciphertext.clone(), declared(&also.kind), context) + .await + .unwrap_or_else(|error| { + panic!( + "{id}: the {origin} ciphertext does not open as {}: {error}", + also.kind + ) + }); + assert_eq!( + opened.frame(), + input(&also.value).frame(), + "{id}: the {origin} ciphertext opens as {} to another value", + also.kind + ); + } for name in case.refused_as.iter().flatten() { let other = declared(name); let refused = open(&keyset, ciphertext.clone(), other, context).await; @@ -555,7 +581,7 @@ async fn shared_single_value_profile() { match &case.expected_error { Some(expected) => { assert!( - case.stored.is_none() && case.refused_as.is_none(), + case.stored.is_none() && case.refused_as.is_none() && case.opens_as.is_none(), "{}: a refused case stores nothing", case.id ); From bf9b705d347efa90fd17f486635769f55abb7e45 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sat, 28 Nov 2026 17:30:16 +1100 Subject: [PATCH 09/19] docs(adr): record that a single ciphertext's target is now a scalar ADR-0012 said the target of a single `Ciphertext` is bounded on `Decrypt + Zeroize`, that a `Vec` target compiles and is refused when it opens, and that a compile error would need a new trait in Vitamin C. That trait now exists and the bound uses it, so the paragraph described the code as it was. The amendment records the new bound, `ScalarTarget + Zeroize`, and keeps the original text beside it, as the other ADRs do. --- .../docs/adr/0012-owned-record-declarations.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/packages/stack-encrypt/docs/adr/0012-owned-record-declarations.md b/packages/stack-encrypt/docs/adr/0012-owned-record-declarations.md index d04fcabcf..521132208 100644 --- a/packages/stack-encrypt/docs/adr/0012-owned-record-declarations.md +++ b/packages/stack-encrypt/docs/adr/0012-owned-record-declarations.md @@ -2,6 +2,7 @@ status: accepted date: 2026-11-03 revised: 2026-11-11 +amended: 2026-11-28 extends: ADR-0003, ADR-0004 --- @@ -181,6 +182,20 @@ case needs a trait for "a scalar, or a `Protected` of one". Rust allows that trait to be implemented for both only in Vitamin C, the crate that defines `FromScalar`. +> **Amended 2026-11-28 (#2011).** Vitamin C now has that trait, +> `ScalarTarget`: a decrypt target that one scalar builds. It is +> implemented for every `FromScalar` type, for an `Option` or a `Protected` +> of one, and for `OwnedFrame`. +> +> The bound of a single `Ciphertext`'s target is now +> `ScalarTarget + Zeroize`, and no longer `Decrypt + Zeroize`. So a target +> that is not a scalar, such as `Vec`, does not compile. +> `keyset.decrypt::>(ct)` compiles as before. The other +> stored types keep the bound `Decrypt + Zeroize`. +> +> A newtype that derives `Decrypt` over a scalar does not carry the marker. +> Its author adds `impl ScalarTarget` by hand. + ### 5. The structural traits are a bridge Each owned derive also implements the structural traits: From 37b629be97666e448d54bdb79dc9dd1c126fb9a2 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sat, 28 Nov 2026 17:30:16 +1100 Subject: [PATCH 10/19] docs(conformance): say the single-value profile runs in Rust only The checklist for a new binding listed single values among the profiles that Go's `*conformance_test.go` files run. Go has no single-value runner yet, so a reader looking for one to follow would find none. The checklist now names the Rust runner as the one to follow. The script test that asserts the conformance task was titled "runs all profiles in both languages" and included the single-value runner. It is split: one test for the profiles that have both runners, and one for the single-value profile, which also holds the README to recording the Go runner as pending. --- .../docs/language-integration.md | 8 ++++++-- .../__tests__/stack-conformance-ci.test.mjs | 20 +++++++++++++++---- 2 files changed, 22 insertions(+), 6 deletions(-) diff --git a/packages/stack-encrypt/docs/language-integration.md b/packages/stack-encrypt/docs/language-integration.md index 7d0b75ae3..ff1f2e915 100644 --- a/packages/stack-encrypt/docs/language-integration.md +++ b/packages/stack-encrypt/docs/language-integration.md @@ -863,8 +863,12 @@ done: each profile in `conformance/stack-encrypt/v1`, as `languages/golang/encrypt/*conformance_test.go` does for Go: scalar records, declarations, reads, runtime and nulls, contexts and bindings, - value boundaries, query refusals, raw frames, single values and, if your - binding links the EQL types, EQL and JSON. Read the frozen expectations; never + value boundaries, query refusals, raw frames and, if your + binding links the EQL types, EQL and JSON. Write one for the single-value + profile too, if your SDK encrypts one value into one ciphertext. Only + Rust runs that profile today: the Go runner is not written yet, so + `packages/stack-encrypt/tests/single_value_conformance.rs` is the + runner to follow. Read the frozen expectations; never regenerate them to pass. A profile you have not run is not a pass. 2. **Fresh artifacts cross both ways.** The exchange profile (`conformance/stack-encrypt/exchange-contract.md`) has your binding open diff --git a/scripts/__tests__/stack-conformance-ci.test.mjs b/scripts/__tests__/stack-conformance-ci.test.mjs index 0380fcd01..c26286286 100644 --- a/scripts/__tests__/stack-conformance-ci.test.mjs +++ b/scripts/__tests__/stack-conformance-ci.test.mjs @@ -31,7 +31,7 @@ function goSelection(script) { } describe('shared Stack Encrypt conformance is required in CI', () => { - it('the conformance task runs all profiles in both languages', () => { + it('the conformance task runs every profile that has both runners in both languages', () => { const script = readFileSync( join(REPO_ROOT, 'scripts/stack-conformance.sh'), 'utf8', @@ -58,15 +58,27 @@ describe('shared Stack Encrypt conformance is required in CI', () => { /cargo nextest run[^\n]*--test raw_frame_conformance/, ) expect(script).toMatch(/cargo nextest run[^\n]*--test binding_conformance/) - expect(script).toMatch( - /cargo nextest run[^\n]*--test single_value_conformance/, - ) const selected = goSelection(script) for (const test of coreGoTests) { expect(selected.test(test), test).toBe(true) } }) + it('the conformance task runs the single-value profile in Rust, which has no Go runner yet', () => { + const script = conformanceScript() + expect(script).toMatch( + /cargo nextest run[^\n]*--test single_value_conformance/, + ) + // When the Go runner is written, add it to `coreGoTests`, move the + // assertion above into the test of both languages, and delete this one. + const selected = goSelection(script) + expect(coreGoTests.some((test) => /SingleValue/.test(test))).toBe(false) + expect(selected.test('TestSingleValueConformance')).toBe(false) + expect(readRepo('conformance/stack-encrypt/README.md')).toMatch( + /single-value-v1\.cases\.json[^\n]*pending/, + ) + }) + it('selects exactly the core runners and indexed fixture tests', () => { const index = JSON.parse( readRepo('conformance/stack-encrypt/v1/fixture-enrollment.json'), From 5b4794bf774bf2d213976a8c3a44b7998c53badb Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sat, 28 Nov 2026 17:37:33 +1100 Subject: [PATCH 11/19] refactor(recipher-js): merge single-value calls with Pending::all The addon sealed its values through the engine's batch form of the run-time single-value encrypt. That form is being removed: the engine's `Pending::all` already merges any pending calls into one key request, so a batch form of each call adds nothing. `seal` now calls `value::encrypt` for each frame and merges the calls with `Pending::all`. It is still one key request, and the frames are still dropped before it is awaited. `unseal` goes back to `Vec::::decrypt_from`, the engine's typed decrypt of a column into frames: it checks no kind, which is what the addon wants, because the type of a `Ciphertext` is known to TypeScript alone. Behaviour is unchanged. --- .../packages/recipher-js/crate/src/cipher.rs | 28 +++++++++---------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/languages/typescript/packages/recipher-js/crate/src/cipher.rs b/languages/typescript/packages/recipher-js/crate/src/cipher.rs index 30c7eb1f0..af8380aee 100644 --- a/languages/typescript/packages/recipher-js/crate/src/cipher.rs +++ b/languages/typescript/packages/recipher-js/crate/src/cipher.rs @@ -18,7 +18,7 @@ use napi::Env; use napi_derive::napi; use stack_encrypt::dynamic::{frame::OwnedFrame, value, ValueKind}; use stack_encrypt::kms::{DataKeySource, IndexKeySource, StackKms}; -use stack_encrypt::{CipherRef, KeysetCipher, StackCipher}; +use stack_encrypt::{CipherRef, DecryptFrom, KeysetCipher, Pending, StackCipher}; use vitaminc_protected::OpaqueDebug; use crate::ciphertext::Ciphertext; @@ -317,8 +317,8 @@ pub(crate) fn a_string(value: OwnedFrame) -> Outcome { /// Encrypts strings under `keyset`, through the engine's run-time /// single-value encrypt. Each value becomes one ciphertext with its own /// data key. Rust's `keyset.encrypt(value)` returns the same ciphertext for -/// the same value. All the values use one key request, however many there -/// are. +/// the same value. The calls are merged, so all the values use one key +/// request, however many there are. /// /// The engine checks each value again: a value that is not one string is /// refused with the engine's own error, before any key request. @@ -329,16 +329,15 @@ pub(crate) async fn seal( where K: DataKeySource + IndexKeySource + Sync + 'static, { - let pending = value::encrypt_all( - keyset, - values.iter().map(OwnedFrame::frame), - Some(ValueKind::String), - ) - .map_err(|error| RecipherErrorFields::engine(&error))?; + let calls = values + .iter() + .map(|value| value::encrypt(keyset, value.frame(), Some(ValueKind::String))) + .collect::, _>>() + .map_err(|error| RecipherErrorFields::engine(&error))?; // The engine has read every value. Dropping the frames wipes them, so // no value waits in a frame for the key request. drop(values); - pending + Pending::all(keyset, calls) .await .map_err(|error| RecipherErrorFields::engine(&error)) } @@ -347,9 +346,10 @@ where /// The function makes one key request for each keyset the ciphertexts /// were made under. /// -/// It declares no kind, so each value comes back as it was encrypted. A -/// call has no type to declare at run time: the type of a `Ciphertext` -/// is known to TypeScript alone. +/// Each value comes back as it was encrypted, in a frame. A call has no +/// kind to check at run time: the type of a `Ciphertext` is known to +/// TypeScript alone. So this is the engine's typed decrypt into frames, +/// which checks no kind. pub(crate) async fn unseal<'c, K>( cipher: impl Into>, sealed: Vec, @@ -357,7 +357,7 @@ pub(crate) async fn unseal<'c, K>( where K: DataKeySource + IndexKeySource + Sync + 'static, { - value::decrypt_all(cipher, sealed, None) + Vec::::decrypt_from(sealed, cipher) .await .map_err(|error| RecipherErrorFields::engine(&error)) } From 4747dd5375ba6c1cf959b7a07a22988aa6863b1a Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sat, 28 Nov 2026 17:37:33 +1100 Subject: [PATCH 12/19] refactor(stack-encrypt): drop the batch forms of the single-value calls `dynamic::value` had four batch functions: `encrypt_all`, `decrypt_all` and their forms with a context. Each took one declared kind for every value, so a batch of values of different kinds could not use them. And each only did what `Pending::all` does for any pending calls: merge their key requests into one. The four functions are removed. The run-time interface is `encrypt`, `encrypt_with_context`, `decrypt` and `decrypt_with_context`. A binding makes one call for each value and merges the calls with `Pending::all`. That is one key request, the results come back in order, and each value keeps its own declared kind and context. `Pending::all` is public and works for the decrypt calls too, so no new API is needed. The docs of `encrypt` and `decrypt` each show a batch of values of different kinds merged into one key request. The conformance batches stay, and the Rust runner now runs them as a binding does, through `Pending::all`. Each batch lists a declared kind for each input, and a new batch mixes kinds. The tests keep "a batch makes one key request" and "a refused value stops the batch before any key request", and drop the ones that only exercised the removed functions. --- conformance/stack-encrypt/README.md | 3 +- .../stack-encrypt/single-value-contract.md | 19 +- .../v1/single-value-v1.cases.json | 45 ++- packages/stack-encrypt/CHANGELOG.md | 12 +- .../docs/language-integration.md | 12 +- packages/stack-encrypt/src/dynamic/value.rs | 257 +++++++----------- packages/stack-encrypt/tests/single_value.rs | 236 +++++++--------- .../tests/single_value_conformance.rs | 49 ++-- 8 files changed, 300 insertions(+), 333 deletions(-) diff --git a/conformance/stack-encrypt/README.md b/conformance/stack-encrypt/README.md index b629628a9..f6d60731c 100644 --- a/conformance/stack-encrypt/README.md +++ b/conformance/stack-encrypt/README.md @@ -187,7 +187,8 @@ The [single-value contract](single-value-contract.md) defines one ciphertext through the engine's run-time interface, and decrypted from one. The cases give a value, the kind declared for it and a context. They cover every scalar kind, the exact conversions a declared kind makes, JSON -documents, the one stored form a string and a document share, batches, and +documents, the one stored form a string and a document share, batches of +single-value calls merged into one key request, and the refusals of an array, an object, a passthrough, a null, `undefined` and a value of another kind. `v1/single-value-v1.expected.rust-native.json` freezes each input's frame, the diff --git a/conformance/stack-encrypt/single-value-contract.md b/conformance/stack-encrypt/single-value-contract.md index 118acc253..dad0cb2e1 100644 --- a/conformance/stack-encrypt/single-value-contract.md +++ b/conformance/stack-encrypt/single-value-contract.md @@ -142,11 +142,20 @@ checks their shape and skips them. ## Batches -Each entry of `batches` has a `kind`, a `context` and a list of `inputs`. An -accepted batch seals in one key request and opens in one, and the values come -back in the order of the inputs: `stored` where the batch has one, the inputs -otherwise. An empty batch makes no key request. A batch with `expected_error` -is refused whole, before any key request, for its first refused value. +The run-time interface has no batch call. A binding encrypts many values by +making one single-value call for each value, and merging the pending calls +into one key request. In Rust the merge is `Pending::all`. It decrypts many +ciphertexts the same way. Each call has its own declared kind, so one batch +can hold values of different kinds. + +Each entry of `batches` has a list of `inputs`, a list of `kinds` with the +kind declared for each input (empty for none), and a `context` for all of +them. A runner seals and opens each entry as a binding does. An accepted +batch seals in one key request and opens in one, and the values come back in +the order of the inputs: `stored` where the batch has one, the inputs +otherwise. An empty batch makes no key request. In a batch with +`expected_error`, the single-value call refuses one of the values with that +`code` and `reason`, and the batch makes no key request. The key-request counts are native observations: the Rust runner counts them on its key source. diff --git a/conformance/stack-encrypt/v1/single-value-v1.cases.json b/conformance/stack-encrypt/v1/single-value-v1.cases.json index e147d20dd..f11c2d1da 100644 --- a/conformance/stack-encrypt/v1/single-value-v1.cases.json +++ b/conformance/stack-encrypt/v1/single-value-v1.cases.json @@ -853,7 +853,7 @@ "batches": [ { "id": "batch-strings", - "kind": "string", + "kinds": ["string", "string", "string"], "context": ["conformance", "value"], "inputs": [ { @@ -872,7 +872,7 @@ }, { "id": "batch-converted", - "kind": "uint32", + "kinds": ["uint32", "uint32", "uint32"], "context": [], "inputs": [ { @@ -905,7 +905,7 @@ }, { "id": "batch-mixed-no-kind", - "kind": "", + "kinds": ["", "", ""], "context": [], "inputs": [ { @@ -922,15 +922,48 @@ } ] }, + { + "id": "batch-mixed-kinds", + "kinds": ["uint64", "string", ""], + "context": ["conformance", "value"], + "inputs": [ + { + "type": "float64", + "text": "34" + }, + { + "type": "string", + "text": "ada" + }, + { + "type": "bool", + "text": "true" + } + ], + "stored": [ + { + "type": "uint64", + "text": "34" + }, + { + "type": "string", + "text": "ada" + }, + { + "type": "bool", + "text": "true" + } + ] + }, { "id": "batch-empty", - "kind": "", + "kinds": [], "context": [], "inputs": [] }, { "id": "batch-with-null", - "kind": "", + "kinds": ["", "", ""], "context": ["conformance", "value"], "inputs": [ { @@ -953,7 +986,7 @@ }, { "id": "batch-with-mismatch", - "kind": "int64", + "kinds": ["int64", "int64"], "context": [], "inputs": [ { diff --git a/packages/stack-encrypt/CHANGELOG.md b/packages/stack-encrypt/CHANGELOG.md index cdb2a781d..84f95c931 100644 --- a/packages/stack-encrypt/CHANGELOG.md +++ b/packages/stack-encrypt/CHANGELOG.md @@ -24,10 +24,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 into an `OwnedFrame` that holds one scalar. Pass `&keyset` to open only that keyset's ciphertexts, or `&cipher` to open a ciphertext of any keyset. - - Each has a form with a context (`encrypt_with_context`, - `decrypt_with_context`) and a form for many values that makes one key - request (`encrypt_all`, `decrypt_all`, and the two `_all_with_context` - forms). + - Each has a form with a context: `encrypt_with_context` and + `decrypt_with_context`. + - There is no batch call. Each call returns a `Pending`, which has not + sent its key request. To encrypt or decrypt many values, make one call + for each value and merge them with `Pending::all`: awaiting the merged + call makes one key request, and the results come back in order. Each + value keeps its own declared kind, so one batch can hold values of + different kinds. - On encrypt, a declared kind converts a number of another width or kind when the conversion is exact, by the rules a record's typed field uses. With no declared kind, the scalar is sealed as it arrived. diff --git a/packages/stack-encrypt/docs/language-integration.md b/packages/stack-encrypt/docs/language-integration.md index ff1f2e915..d5e03ed5e 100644 --- a/packages/stack-encrypt/docs/language-integration.md +++ b/packages/stack-encrypt/docs/language-integration.md @@ -184,10 +184,14 @@ does the same through [`crate::dynamic::value`]: - [`crate::dynamic::value::decrypt`] takes a ciphertext and an optional kind the value must open as. It settles to the value's frame. -Each has a form that takes a context, and a form that takes many values and -makes one key request. A declared kind reads the value by the rules a -record's typed field uses, so a binding passes a language's own number. The -kind `json` takes a document as its JSON text. +Each has a form that takes a context. A declared kind reads the value by +the rules a record's typed field uses, so a binding passes a language's own +number. The kind `json` takes a document as its JSON text. + +There is no batch call. Each call returns a [`crate::Pending`], so a binding +makes one call for each value and merges them with [`crate::Pending::all`]. +Awaiting the merged call makes one key request, and each value keeps its own +declared kind. A ciphertext holds one scalar. An array, an object, a passthrough and a null are refused before any key is requested, with a reason that says which was diff --git a/packages/stack-encrypt/src/dynamic/value.rs b/packages/stack-encrypt/src/dynamic/value.rs index 799efa2a3..c75557fd6 100644 --- a/packages/stack-encrypt/src/dynamic/value.rs +++ b/packages/stack-encrypt/src/dynamic/value.rs @@ -14,10 +14,18 @@ //! - [`decrypt`] opens a ciphertext into an [`OwnedFrame`] that holds one //! scalar. //! -//! Each has a form that takes a context ([`encrypt_with_context`], -//! [`decrypt_with_context`]) and a form that takes many values and makes -//! one key request ([`encrypt_all`], [`decrypt_all`], and the two -//! `_all_with_context` forms). +//! Each has a form that takes a context: [`encrypt_with_context`] and +//! [`decrypt_with_context`]. +//! +//! # Many values in one key request +//! +//! Each call returns a [`Pending`], which holds its key request and has +//! not sent it. To encrypt or decrypt many values, make one call for each +//! value and merge the results with [`Pending::all`]. Awaiting the merged +//! call makes one key request for all of them, and the values come back +//! in order. Each value keeps its own declared kind and its own context, +//! so one batch can hold values of different kinds. The examples on +//! [`encrypt`] and [`decrypt`] show how. //! //! # The declared kind //! @@ -144,6 +152,54 @@ use crate::{Ciphertext, ContextPiece, DecryptFrom, KeysetCipher}; /// # }).unwrap(); /// ``` /// +/// # Many values in one key request +/// +/// Call `encrypt` for each value, then merge the pending calls with +/// [`Pending::all`]. Nothing is requested until the merged call is +/// awaited, and it makes one key request for every value. Each value has +/// its own data key and is authenticated on its own. The ciphertexts come +/// back in the order of the calls. +/// +/// Each call takes its own declared kind, so one batch can hold values of +/// different kinds. A value that is refused is an `Err` here, before any +/// call is merged. So a batch with a refused value requests no key. +/// +/// ``` +/// use stack_encrypt::dynamic::{frame::OwnedFrame, value, ValueKind}; +/// use stack_encrypt::{Pending, StackCipher}; +/// +/// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { +/// // With no `.kms(..)`, the cipher uses ZeroKMS. It reads credentials from +/// // the environment, or from the profile that `npx stash auth login` writes. +/// let cipher = StackCipher::builder() +/// # .kms(stack_encrypt::kms::FakeDataKeySource::new()) +/// .init() +/// .await?; +/// let keyset = cipher.default_keyset(); +/// +/// // Three values, each with the kind the caller declares for it. +/// let values = [ +/// (OwnedFrame::of(34.0f64)?, Some(ValueKind::UInt64)), +/// (OwnedFrame::of("ada@example.com")?, Some(ValueKind::String)), +/// (OwnedFrame::of(true)?, None), +/// ]; +/// +/// // One call for each value. A refused value stops here, with no request. +/// let mut calls = Vec::new(); +/// for (frame, kind) in &values { +/// calls.push(value::encrypt(&keyset, frame.frame(), *kind)?); +/// } +/// +/// // One key request for all three. +/// let stored = Pending::all(&keyset, calls).await?; +/// assert_eq!(stored.len(), 3); +/// +/// let age: u64 = keyset.decrypt(stored[0].clone()).await?; +/// assert_eq!(age, 34); +/// # Ok::<(), Box>(()) +/// # }).unwrap(); +/// ``` +/// /// # Errors /// /// [`Error::Source`], decided here, before any key is requested: @@ -216,73 +272,6 @@ pub fn encrypt_with_context<'a, 'c, K: 'static>( seal(keyset, value, kind, context.into_context().into_owned()) } -/// Encrypt each of `values` as a [`Ciphertext`] of its own, with the empty -/// context, in one key request. -/// -/// The ciphertexts come back in the order of the values. Each value has -/// its own data key and is authenticated on its own, as the elements of a -/// `Vec` are when the typed call encrypts one into a `Vec`. -/// `kind` is declared for every value. No values make no key request. -/// -/// To encrypt values of different declared kinds in one key request, call -/// [`encrypt`] for each and merge the results with -/// [`Pending::all`](crate::Pending::all). -/// -/// ``` -/// use stack_encrypt::dynamic::{frame::OwnedFrame, value, ValueKind}; -/// use stack_encrypt::StackCipher; -/// -/// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { -/// // With no `.kms(..)`, the cipher uses ZeroKMS. It reads credentials from -/// // the environment, or from the profile that `npx stash auth login` writes. -/// let cipher = StackCipher::builder() -/// # .kms(stack_encrypt::kms::FakeDataKeySource::new()) -/// .init() -/// .await?; -/// let keyset = cipher.default_keyset(); -/// -/// let emails = [OwnedFrame::of("ada@example.com")?, OwnedFrame::of("grace@example.com")?]; -/// let stored = value::encrypt_all( -/// &keyset, -/// emails.iter().map(OwnedFrame::frame), -/// Some(ValueKind::String), -/// )? -/// .await?; -/// assert_eq!(stored.len(), 2); -/// -/// let opened = value::decrypt_all(&keyset, stored, Some(ValueKind::String)).await?; -/// assert_eq!(opened[1].frame(), emails[1].frame()); -/// # Ok::<(), Box>(()) -/// # }).unwrap(); -/// ``` -/// -/// # Errors -/// -/// As [`encrypt`], for the first value that is refused. Nothing is -/// requested for the values before it. -pub fn encrypt_all<'a, 'f, K: 'static>( - keyset: &'a KeysetCipher<'_, K>, - values: impl IntoIterator>, - kind: Option, -) -> Result, K>, Error> { - seal_all(keyset, values, kind, ().into_context()) -} - -/// [`encrypt_all`], authenticating `context` for every value. -/// -/// # Errors -/// -/// As [`encrypt_all`]. A context that cannot be used fails the pending -/// request. -pub fn encrypt_all_with_context<'a, 'f, 'c, K: 'static>( - keyset: &'a KeysetCipher<'_, K>, - values: impl IntoIterator>, - kind: Option, - context: impl IntoContext<'c>, -) -> Result, K>, Error> { - seal_all(keyset, values, kind, context.into_context().into_owned()) -} - /// Decrypt a [`Ciphertext`] that was sealed with the empty context, into a /// frame that holds its one scalar. /// @@ -334,6 +323,51 @@ pub fn encrypt_all_with_context<'a, 'f, 'c, K: 'static>( /// # }).unwrap(); /// ``` /// +/// # Many values in one key request +/// +/// Call `decrypt` for each ciphertext, then merge the pending calls with +/// [`Pending::all`]. Awaiting the merged call makes one key request for +/// each keyset the ciphertexts were sealed under. The frames come back in +/// the order of the calls. Each call takes its own declared kind. +/// +/// Pass the same cipher or keyset to `Pending::all` as to each `decrypt`. +/// If one value fails, the merged call fails with that value's error, and +/// the frames opened before it are dropped. A frame wipes its buffer when +/// it drops. +/// +/// ``` +/// use stack_encrypt::dynamic::{frame::OwnedFrame, value, ValueKind}; +/// use stack_encrypt::{Pending, StackCipher}; +/// +/// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { +/// // With no `.kms(..)`, the cipher uses ZeroKMS. It reads credentials from +/// // the environment, or from the profile that `npx stash auth login` writes. +/// let cipher = StackCipher::builder() +/// # .kms(stack_encrypt::kms::FakeDataKeySource::new()) +/// .init() +/// .await?; +/// let keyset = cipher.default_keyset(); +/// +/// // Two ciphertexts of different kinds, as a database returns them. +/// let stored = [ +/// (keyset.encrypt(34u64).await?, Some(ValueKind::UInt64)), +/// (keyset.encrypt(String::from("ada@example.com")).await?, Some(ValueKind::String)), +/// ]; +/// +/// // One call for each ciphertext, with the kind it must open as. +/// let calls: Vec<_> = stored +/// .into_iter() +/// .map(|(ciphertext, kind)| value::decrypt(&keyset, ciphertext, kind)) +/// .collect(); +/// +/// // One key request for both. +/// let opened = Pending::all(&keyset, calls).await?; +/// assert_eq!(opened[0].frame(), OwnedFrame::of(34u64)?.frame()); +/// assert_eq!(opened[1].frame(), OwnedFrame::of("ada@example.com")?.frame()); +/// # Ok::<(), Box>(()) +/// # }).unwrap(); +/// ``` +/// /// # Errors /// /// The pending request fails with the engine's [`Error`](crate::Error), as @@ -383,43 +417,6 @@ pub fn decrypt_with_context<'a, 'c, K: 'static>( ) } -/// Decrypt each of `ciphertexts` that was sealed with the empty context, -/// in one key request for each keyset they were sealed under. -/// -/// The frames come back in the order of the ciphertexts. `kind` is the -/// kind every value must open as. No ciphertexts make no key request. -/// -/// # Errors -/// -/// As [`decrypt`], for the first ciphertext that fails. The values opened -/// before it are wiped. -pub fn decrypt_all<'a, K: 'static>( - cipher_ref: impl Into>, - ciphertexts: Vec, - kind: Option, -) -> Pending<'a, Vec, K> { - open_all(cipher_ref.into(), ciphertexts, kind, ().into_context()) -} - -/// [`decrypt_all`], under the context every value was encrypted with. -/// -/// # Errors -/// -/// As [`decrypt_all`]. -pub fn decrypt_all_with_context<'a, 'c, K: 'static>( - cipher_ref: impl Into>, - ciphertexts: Vec, - kind: Option, - context: impl IntoContext<'c>, -) -> Pending<'a, Vec, K> { - open_all( - cipher_ref.into(), - ciphertexts, - kind, - context.into_context().into_owned(), - ) -} - /// Check that `value` is one scalar a ciphertext can hold. /// /// # Errors @@ -481,22 +478,6 @@ fn seal<'a, K: 'static>( Ok(sealed.try_map(Ciphertext::from_tree)) } -/// [`seal`] for each value, merged into one request. -fn seal_all<'a, 'f, K: 'static>( - keyset: &'a KeysetCipher<'_, K>, - values: impl IntoIterator>, - kind: Option, - context: ContextPiece<'static>, -) -> Result, K>, Error> { - // A refused value returns here. The pending requests of the values - // before it are dropped, and each wipes the plaintext it planned. - let sealed = values - .into_iter() - .map(|value| seal(keyset, value, kind, context.clone())) - .collect::, Error>>()?; - Ok(Pending::all(keyset, sealed)) -} - /// The refusal of a value that is not a document under the `json` kind. fn not_a_document(error: JsonValueError) -> Error { Error::bad_source(match error { @@ -538,34 +519,6 @@ fn open<'a, K: 'static>( } } -/// [`open`] for each ciphertext, merged into one request. -fn open_all<'a, K: 'static>( - cipher_ref: CipherRef<'a, K>, - ciphertexts: Vec, - kind: Option, - context: ContextPiece<'static>, -) -> Pending<'a, Vec, K> { - if let Some(kind) = kind.filter(|kind| !is_scalar_kind(*kind)) { - return Pending::failed(cipher_ref, not_opened_as(kind)); - } - let opened = Vec::::decrypt_from_with_context( - ciphertexts, - cipher_ref, - ScalarContext::from(context), - ); - match kind { - None => opened, - // A value that fails here drops the frames around it, and each - // frame wipes its buffer when it drops. - Some(kind) => opened.try_map(move |values| { - values - .into_iter() - .map(|value| opened_as(kind, value)) - .collect() - }), - } -} - /// The opened `value` as a value of `kind`: the value itself, or for a /// document its JSON text in a bytes leaf. /// diff --git a/packages/stack-encrypt/tests/single_value.rs b/packages/stack-encrypt/tests/single_value.rs index 8502b5662..602f2b0d6 100644 --- a/packages/stack-encrypt/tests/single_value.rs +++ b/packages/stack-encrypt/tests/single_value.rs @@ -735,91 +735,98 @@ mod encrypt_with_a_context { } } -mod encrypt_all { +/// The run-time interface has no batch call. A binding makes one call for +/// each value and merges them with `Pending::all`, which sends one key +/// request. +mod many_values_merged_with_pending_all { use super::*; #[tokio::test] - async fn seals_every_value_in_one_key_request_and_keeps_their_order() { + async fn seal_and_open_in_one_key_request_each_and_keep_their_order() { let (cipher, generates, retrieves) = common::counting_cipher().await; let keyset = cipher.default_keyset(); - let values = [frame(1.0f64), frame(2i64), frame(3u16)]; - let sealed = value::encrypt_all( - &keyset, - values.iter().map(OwnedFrame::frame), + // Each value has its own declared kind, and the last its own context. + let values = [frame(1.0f64), frame("two"), frame(true), frame(4i64)]; + let kinds = [ Some(ValueKind::UInt32), - ) - .expect("three scalars") - .await - .expect("they seal"); - assert_eq!(sealed.len(), 3, "one ciphertext for each value"); + Some(ValueKind::String), + None, + Some(ValueKind::Int64), + ]; + let mut calls = Vec::new(); + for (value, kind) in values.iter().zip(kinds).take(3) { + calls.push(value::encrypt(&keyset, value.frame(), kind).expect("one scalar")); + } + calls.push( + value::encrypt_with_context(&keyset, values[3].frame(), kinds[3], ("users", "n")) + .expect("one scalar"), + ); assert_eq!( generates.load(Ordering::SeqCst), - 1, - "one key request for the batch" + 0, + "a call requests no key until it is awaited" ); - - let mut opened = Vec::new(); - for ciphertext in sealed.clone() { - opened.push(keyset.decrypt::(ciphertext).await.expect("a u32")); - } + let sealed = stack_encrypt::Pending::all(&keyset, calls) + .await + .expect("the merged call seals"); + assert_eq!(sealed.len(), 4, "one ciphertext for each value"); assert_eq!( - opened, - [1, 2, 3], - "the ciphertexts are in the values' order" + generates.load(Ordering::SeqCst), + 1, + "one key request seals the batch" ); retrieves.store(0, Ordering::SeqCst); - let frames = value::decrypt_all(&keyset, sealed, Some(ValueKind::UInt32)) + let mut calls = Vec::new(); + for (ciphertext, kind) in sealed.iter().cloned().zip(kinds).take(3) { + calls.push(value::decrypt(&keyset, ciphertext, kind)); + } + calls.push(value::decrypt_with_context( + &keyset, + sealed[3].clone(), + kinds[3], + ("users", "n"), + )); + let opened = stack_encrypt::Pending::all(&keyset, calls) .await - .expect("they open"); + .expect("the merged call opens"); assert_eq!( retrieves.load(Ordering::SeqCst), 1, "one key request opens the batch" ); - for (opened, expected) in frames.iter().zip([1u32, 2, 3]) { + let expected = [frame(1u32), frame("two"), frame(true), frame(4i64)]; + assert_eq!( + opened.len(), + expected.len(), + "one frame for each ciphertext" + ); + for (position, (opened, expected)) in opened.iter().zip(&expected).enumerate() { assert_eq!( opened.frame(), - frame(expected).frame(), - "the frames are in the ciphertexts' order" + expected.frame(), + "the value at position {position} is in its call's place" ); } - } - - #[tokio::test] - async fn binds_every_value_to_the_context() { - let cipher = common::stack_cipher().await; - let keyset = cipher.default_keyset(); - let values = [frame("a"), frame("b")]; - let sealed = value::encrypt_all_with_context( - &keyset, - values.iter().map(OwnedFrame::frame), - None, - ("users", "name"), - ) - .expect("two scalars") - .await - .expect("they seal"); - let without = value::decrypt_all(&keyset, sealed.clone(), None).await; + // The value sealed under a context opens only under it. + let without = value::decrypt(&keyset, sealed[3].clone(), kinds[3]).await; assert!( matches!(without, Err(Error::Aead)), - "the empty context must not open the batch, got: {without:?}" + "the empty context must not open a value sealed under one, got: {without:?}" ); - let opened = value::decrypt_all_with_context(&keyset, sealed, None, ("users", "name")) - .await - .expect("the same context opens the batch"); - assert_eq!(opened.len(), 2, "one frame for each ciphertext"); - assert_eq!(opened[0].frame(), frame("a").frame(), "the first value"); - assert_eq!(opened[1].frame(), frame("b").frame(), "the second value"); } #[tokio::test] - async fn refuses_the_batch_for_one_refused_value_with_no_key_request() { + async fn a_refused_value_stops_the_batch_before_any_key_request() { let (cipher, generates, _) = common::counting_cipher().await; let keyset = cipher.default_keyset(); let values = [frame("a"), OwnedFrame::null(), frame(vec!["b"])]; - let error = match value::encrypt_all(&keyset, values.iter().map(OwnedFrame::frame), None) { + let calls: Result, dynamic::Error> = values + .iter() + .map(|value| value::encrypt(&keyset, value.frame(), None)) + .collect(); + let error = match calls { Err(error) => error, Ok(_) => panic!("a batch holding a null was taken"), }; @@ -827,30 +834,46 @@ mod encrypt_all { assert_eq!( generates.load(Ordering::SeqCst), 0, - "a refused batch requests no data key" + "a batch with a refused value requests no data key" ); } #[tokio::test] - async fn makes_no_key_request_for_no_values() { - let (cipher, generates, retrieves) = common::counting_cipher().await; + async fn a_value_of_another_kind_fails_the_merged_decrypt() { + let cipher = common::stack_cipher().await; let keyset = cipher.default_keyset(); - let sealed = value::encrypt_all(&keyset, std::iter::empty(), None) - .expect("no values") - .await - .expect("nothing to seal"); - assert!(sealed.is_empty(), "no ciphertexts for no values"); - let opened = value::decrypt_all(&keyset, sealed, None) + let sealed = [ + keyset.encrypt(1i64).await.expect("it seals"), + keyset.encrypt(String::from("two")).await.expect("it seals"), + keyset.encrypt(3i64).await.expect("it seals"), + ]; + let open_all = |kind: Option| { + let calls = sealed + .iter() + .cloned() + .map(|ciphertext| value::decrypt(&keyset, ciphertext, kind)) + .collect(); + stack_encrypt::Pending::all(&keyset, calls) + }; + let opened = open_all(Some(ValueKind::Int64)).await; + assert!( + matches!(opened, Err(Error::OpenedType { expected: "int64" })), + "a batch holding text must not open as int64, got: {opened:?}" + ); + let opened = open_all(None) .await - .expect("nothing to open"); - assert!(opened.is_empty(), "no frames for no ciphertexts"); + .expect("with no declared kind each value opens as it was sealed"); assert_eq!( - ( - generates.load(Ordering::SeqCst), - retrieves.load(Ordering::SeqCst) - ), - (0, 0), - "an empty batch makes no key request" + opened + .iter() + .map(|value| value.frame().kind()) + .collect::>(), + [ + Some(ValueKind::Int64), + Some(ValueKind::String), + Some(ValueKind::Int64) + ], + "each value keeps its own kind" ); } } @@ -926,11 +949,6 @@ mod decrypt { matches!(one, Err(Error::OpenedType { expected }) if expected == name), "a ciphertext must not open as {name}, got: {one:?}" ); - let many = value::decrypt_all(&keyset, vec![sealed.clone()], Some(kind)).await; - assert!( - matches!(many, Err(Error::OpenedType { expected }) if expected == name), - "a batch must not open as {name}, got: {many:?}" - ); } assert_eq!( retrieves.load(Ordering::SeqCst), @@ -984,11 +1002,6 @@ mod decrypt { matches!(foreign, Err(Error::ForeignKeyset { .. })), "a keyset must not open another keyset's ciphertext, got: {foreign:?}" ); - let foreign = value::decrypt_all(&keyset, vec![sealed.clone()], None).await; - assert!( - matches!(foreign, Err(Error::ForeignKeyset { .. })), - "a keyset must not open a batch of another keyset's, got: {foreign:?}" - ); assert_eq!( retrieves.load(Ordering::SeqCst), 0, @@ -1000,37 +1013,6 @@ mod decrypt { .expect("the cipher opens a ciphertext of any of its keysets"); assert_eq!(opened.frame(), frame("elsewhere").frame(), "the value"); } - - #[tokio::test] - async fn refuses_a_batch_when_one_value_is_of_another_kind() { - let cipher = common::stack_cipher().await; - let keyset = cipher.default_keyset(); - let sealed = vec![ - keyset.encrypt(1i64).await.expect("it seals"), - keyset.encrypt(String::from("two")).await.expect("it seals"), - keyset.encrypt(3i64).await.expect("it seals"), - ]; - let opened = value::decrypt_all(&keyset, sealed.clone(), Some(ValueKind::Int64)).await; - assert!( - matches!(opened, Err(Error::OpenedType { expected: "int64" })), - "a batch holding text must not open as int64, got: {opened:?}" - ); - let opened = value::decrypt_all(&keyset, sealed, None) - .await - .expect("with no declared kind each value opens as it was sealed"); - assert_eq!( - opened - .iter() - .map(|value| value.frame().kind()) - .collect::>(), - [ - Some(ValueKind::Int64), - Some(ValueKind::String), - Some(ValueKind::Int64) - ], - "each value keeps its own kind" - ); - } } mod decrypt_a_json_document { @@ -1125,16 +1107,11 @@ mod decrypt_a_json_document { ]; for (what, sealed) in not_documents { let sealed = sealed.expect("it seals"); - let opened = value::decrypt(&keyset, sealed.clone(), Some(ValueKind::Json)).await; + let opened = value::decrypt(&keyset, sealed, Some(ValueKind::Json)).await; assert!( matches!(opened, Err(Error::OpenedType { expected: "json" })), "{what} must not open as json, got: {opened:?}" ); - let many = value::decrypt_all(&keyset, vec![sealed], Some(ValueKind::Json)).await; - assert!( - matches!(many, Err(Error::OpenedType { expected: "json" })), - "a batch holding {what} must not open as json, got: {many:?}" - ); } } @@ -1197,31 +1174,4 @@ mod decrypt_a_json_document { "the frame holds the JSON text that was sealed, in a text leaf" ); } - - #[tokio::test] - async fn opens_a_batch_of_documents_in_order() { - let cipher = common::stack_cipher().await; - let keyset = cipher.default_keyset(); - let texts = [r#"{"a":1}"#, "null", r#"["x"]"#]; - let crossing: Vec = texts.iter().map(|text| frame(*text)).collect(); - let sealed = value::encrypt_all( - &keyset, - crossing.iter().map(OwnedFrame::frame), - Some(ValueKind::Json), - ) - .expect("three documents") - .await - .expect("they seal"); - let opened = value::decrypt_all(&keyset, sealed, Some(ValueKind::Json)) - .await - .expect("they open"); - assert_eq!(opened.len(), texts.len(), "one frame for each document"); - for (opened, text) in opened.iter().zip(texts) { - assert_eq!( - opened.frame(), - document(text).frame(), - "the document {text}" - ); - } - } } diff --git a/packages/stack-encrypt/tests/single_value_conformance.rs b/packages/stack-encrypt/tests/single_value_conformance.rs index 735a36c94..0816f6eac 100644 --- a/packages/stack-encrypt/tests/single_value_conformance.rs +++ b/packages/stack-encrypt/tests/single_value_conformance.rs @@ -81,7 +81,9 @@ struct OpensAs { #[serde(deny_unknown_fields)] struct Batch { id: String, - kind: String, + /// The kind declared for each input, in order: a name, or empty for + /// none. + kinds: Vec, context: Vec, inputs: Vec, /// The values the ciphertexts hold, where they are not the inputs. @@ -178,18 +180,21 @@ fn seal<'a, K: 'static>( } } +/// A batch, as a binding seals one: one single-value call for each value, +/// each with its own declared kind, merged into one key request. A refused +/// value is the batch's refusal, and nothing is merged. fn seal_all<'a, K: 'static>( keyset: &'a KeysetCipher<'_, K>, values: &[OwnedFrame], - kind: Option, + kinds: &[Option], context: &[String], ) -> Result, K>, dynamic::Error> { - let frames = values.iter().map(OwnedFrame::frame); - if context.is_empty() { - single::encrypt_all(keyset, frames, kind) - } else { - single::encrypt_all_with_context(keyset, frames, kind, piece(context)) - } + let calls = values + .iter() + .zip(kinds) + .map(|(value, kind)| seal(keyset, value.frame(), *kind, context)) + .collect::, _>>()?; + Ok(Pending::all(keyset, calls)) } fn open<'a, K: 'static>( @@ -205,17 +210,20 @@ fn open<'a, K: 'static>( } } +/// A batch, as a binding opens one: one single-value call for each +/// ciphertext, each with its own declared kind, merged into one key request. fn open_all<'a, K: 'static>( - cipher: impl Into>, + keyset: &'a KeysetCipher<'_, K>, ciphertexts: Vec, - kind: Option, + kinds: &[Option], context: &[String], ) -> Pending<'a, Vec, K> { - if context.is_empty() { - single::decrypt_all(cipher, ciphertexts, kind) - } else { - single::decrypt_all_with_context(cipher, ciphertexts, kind, piece(context)) - } + let calls = ciphertexts + .into_iter() + .zip(kinds) + .map(|(ciphertext, kind)| open(keyset, ciphertext, *kind, context)) + .collect(); + Pending::all(keyset, calls) } /// The context `ciphertext`'s leaf is sealed under, for opening the leaf @@ -627,12 +635,17 @@ async fn shared_single_value_profile() { for batch in &corpus.batches { eprintln!("single value: {}", batch.id); let id = &batch.id; - let kind = declared(&batch.kind); + let kinds: Vec> = batch.kinds.iter().map(|kind| declared(kind)).collect(); let values: Vec = batch.inputs.iter().map(input).collect(); + assert_eq!( + kinds.len(), + values.len(), + "{id}: one declared kind for each input" + ); let (cipher, generates, retrieves) = counting(seed).await; let keyset = cipher.default_keyset(); let sealed = match ( - seal_all(&keyset, &values, kind, &batch.context), + seal_all(&keyset, &values, &kinds, &batch.context), &batch.expected_error, ) { (Err(error), Some(expected)) => { @@ -661,7 +674,7 @@ async fn shared_single_value_profile() { requests, "{id}: the batch seals in one key request" ); - let opened = open_all(&keyset, sealed, kind, &batch.context) + let opened = open_all(&keyset, sealed, &kinds, &batch.context) .await .unwrap_or_else(|error| panic!("{id}: the batch does not open: {error}")); assert_eq!( From d81ba192d921f1ff3697ec20d7ab27af95566181 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sat, 28 Nov 2026 18:00:27 +1100 Subject: [PATCH 13/19] feat(stack-encrypt): give a single-value refusal its own error variant The run-time single-value encrypt reported a refused value as `dynamic::Error::Source`, whose message begins "record source does not fit the plan". A single value has no record and no plan, so the message told the caller about things their call does not have. A refusal is now `dynamic::Error::Value { reason }`, with the code `stack_encrypt::dynamic_value`. Its message is about one value: "the value cannot be encrypted as one ciphertext", then what was found. It names no field. The reasons and their names are unchanged. Two reasons have phrases written for a record's field: a value of another type ("... than its field declares") and `undefined` ("... where its field declares a type"). The new variant words those two for a value, and leaves the phrases themselves alone, so a record's messages do not change. The Go guest classes the new variant as the caller's input, as it does a source refusal. Without that it would fall to the catch-all and be reported as an engine fault. The conformance cases expect the new code. Decrypt refusals are unchanged: a value of another kind is still `Error::OpenedType`. --- .../stack-encrypt/single-value-contract.md | 5 +- .../v1/single-value-v1.cases.json | 66 +++++++++---------- languages/golang/encrypt/guest/src/status.rs | 9 +++ packages/stack-encrypt/CHANGELOG.md | 7 +- .../docs/language-integration.md | 6 +- packages/stack-encrypt/src/codes.rs | 1 + packages/stack-encrypt/src/dynamic/value.rs | 19 ++++-- packages/stack-encrypt/src/refusal.rs | 57 +++++++++++++--- packages/stack-encrypt/tests/single_value.rs | 54 ++++++++++++--- 9 files changed, 160 insertions(+), 64 deletions(-) diff --git a/conformance/stack-encrypt/single-value-contract.md b/conformance/stack-encrypt/single-value-contract.md index dad0cb2e1..c92de3d4a 100644 --- a/conformance/stack-encrypt/single-value-contract.md +++ b/conformance/stack-encrypt/single-value-contract.md @@ -124,8 +124,9 @@ Three cases pin what follows from that: refused as `json`. For a case with `expected_error`, the run-time encrypt refuses the value -before any key request, with the diagnostic `code` and `reason`. The refusal -names no field. The cases cover: +before any key request, with the diagnostic `code` and `reason`. The code of +every such refusal is `stack_encrypt::dynamic_value`: a single value has its +own refusal, with no record, plan or field in it. The cases cover: - an array, an object, a passthrough, a plain null and a typed null, each with no declared kind and with one: the reason says what was found (`array`, diff --git a/conformance/stack-encrypt/v1/single-value-v1.cases.json b/conformance/stack-encrypt/v1/single-value-v1.cases.json index f11c2d1da..2dc39594a 100644 --- a/conformance/stack-encrypt/v1/single-value-v1.cases.json +++ b/conformance/stack-encrypt/v1/single-value-v1.cases.json @@ -455,7 +455,7 @@ "text": "array" }, "expected_error": { - "code": "stack_encrypt::dynamic_source", + "code": "stack_encrypt::dynamic_value", "reason": "array" } }, @@ -468,7 +468,7 @@ "text": "array" }, "expected_error": { - "code": "stack_encrypt::dynamic_source", + "code": "stack_encrypt::dynamic_value", "reason": "array" } }, @@ -481,7 +481,7 @@ "text": "array" }, "expected_error": { - "code": "stack_encrypt::dynamic_source", + "code": "stack_encrypt::dynamic_value", "reason": "array" } }, @@ -494,7 +494,7 @@ "text": "empty_array" }, "expected_error": { - "code": "stack_encrypt::dynamic_source", + "code": "stack_encrypt::dynamic_value", "reason": "array" } }, @@ -507,7 +507,7 @@ "text": "object" }, "expected_error": { - "code": "stack_encrypt::dynamic_source", + "code": "stack_encrypt::dynamic_value", "reason": "object" } }, @@ -520,7 +520,7 @@ "text": "object" }, "expected_error": { - "code": "stack_encrypt::dynamic_source", + "code": "stack_encrypt::dynamic_value", "reason": "object" } }, @@ -533,7 +533,7 @@ "text": "object" }, "expected_error": { - "code": "stack_encrypt::dynamic_source", + "code": "stack_encrypt::dynamic_value", "reason": "object" } }, @@ -546,7 +546,7 @@ "text": "passthrough" }, "expected_error": { - "code": "stack_encrypt::dynamic_source", + "code": "stack_encrypt::dynamic_value", "reason": "passthrough" } }, @@ -559,7 +559,7 @@ "text": "passthrough" }, "expected_error": { - "code": "stack_encrypt::dynamic_source", + "code": "stack_encrypt::dynamic_value", "reason": "passthrough" } }, @@ -572,7 +572,7 @@ "text": "" }, "expected_error": { - "code": "stack_encrypt::dynamic_source", + "code": "stack_encrypt::dynamic_value", "reason": "null" } }, @@ -585,7 +585,7 @@ "text": "" }, "expected_error": { - "code": "stack_encrypt::dynamic_source", + "code": "stack_encrypt::dynamic_value", "reason": "null" } }, @@ -598,7 +598,7 @@ "text": "" }, "expected_error": { - "code": "stack_encrypt::dynamic_source", + "code": "stack_encrypt::dynamic_value", "reason": "null" } }, @@ -611,7 +611,7 @@ "text": "" }, "expected_error": { - "code": "stack_encrypt::dynamic_source", + "code": "stack_encrypt::dynamic_value", "reason": "null" } }, @@ -624,7 +624,7 @@ "text": "typed_null" }, "expected_error": { - "code": "stack_encrypt::dynamic_source", + "code": "stack_encrypt::dynamic_value", "reason": "null" } }, @@ -637,7 +637,7 @@ "text": "typed_null" }, "expected_error": { - "code": "stack_encrypt::dynamic_source", + "code": "stack_encrypt::dynamic_value", "reason": "null" } }, @@ -650,7 +650,7 @@ "text": "" }, "expected_error": { - "code": "stack_encrypt::dynamic_source", + "code": "stack_encrypt::dynamic_value", "reason": "undefined" } }, @@ -663,7 +663,7 @@ "text": "" }, "expected_error": { - "code": "stack_encrypt::dynamic_source", + "code": "stack_encrypt::dynamic_value", "reason": "undefined" } }, @@ -676,7 +676,7 @@ "text": "" }, "expected_error": { - "code": "stack_encrypt::dynamic_source", + "code": "stack_encrypt::dynamic_value", "reason": "undefined" } }, @@ -689,7 +689,7 @@ "text": "34" }, "expected_error": { - "code": "stack_encrypt::dynamic_source", + "code": "stack_encrypt::dynamic_value", "reason": "field_type" } }, @@ -702,7 +702,7 @@ "text": "34.5" }, "expected_error": { - "code": "stack_encrypt::dynamic_source", + "code": "stack_encrypt::dynamic_value", "reason": "field_type" } }, @@ -715,7 +715,7 @@ "text": "300" }, "expected_error": { - "code": "stack_encrypt::dynamic_source", + "code": "stack_encrypt::dynamic_value", "reason": "field_type" } }, @@ -728,7 +728,7 @@ "text": "0" }, "expected_error": { - "code": "stack_encrypt::dynamic_source", + "code": "stack_encrypt::dynamic_value", "reason": "field_type" } }, @@ -741,7 +741,7 @@ "text": "1.5" }, "expected_error": { - "code": "stack_encrypt::dynamic_source", + "code": "stack_encrypt::dynamic_value", "reason": "field_type" } }, @@ -754,7 +754,7 @@ "text": "34" }, "expected_error": { - "code": "stack_encrypt::dynamic_source", + "code": "stack_encrypt::dynamic_value", "reason": "field_type" } }, @@ -767,7 +767,7 @@ "text": "" }, "expected_error": { - "code": "stack_encrypt::dynamic_source", + "code": "stack_encrypt::dynamic_value", "reason": "field_type" } }, @@ -780,7 +780,7 @@ "text": "a" }, "expected_error": { - "code": "stack_encrypt::dynamic_source", + "code": "stack_encrypt::dynamic_value", "reason": "field_type" } }, @@ -793,7 +793,7 @@ "text": "1" }, "expected_error": { - "code": "stack_encrypt::dynamic_source", + "code": "stack_encrypt::dynamic_value", "reason": "field_type" } }, @@ -806,7 +806,7 @@ "text": "1" }, "expected_error": { - "code": "stack_encrypt::dynamic_source", + "code": "stack_encrypt::dynamic_value", "reason": "field_type" } }, @@ -819,7 +819,7 @@ "text": "{\"a\": " }, "expected_error": { - "code": "stack_encrypt::dynamic_source", + "code": "stack_encrypt::dynamic_value", "reason": "json_syntax" } }, @@ -832,7 +832,7 @@ "text": "{\"a\":1,\"a\":2}" }, "expected_error": { - "code": "stack_encrypt::dynamic_source", + "code": "stack_encrypt::dynamic_value", "reason": "json_duplicate_key" } }, @@ -845,7 +845,7 @@ "text": "3138343436373434303733373039353531363136" }, "expected_error": { - "code": "stack_encrypt::dynamic_source", + "code": "stack_encrypt::dynamic_value", "reason": "json_integer_range" } } @@ -980,7 +980,7 @@ } ], "expected_error": { - "code": "stack_encrypt::dynamic_source", + "code": "stack_encrypt::dynamic_value", "reason": "null" } }, @@ -999,7 +999,7 @@ } ], "expected_error": { - "code": "stack_encrypt::dynamic_source", + "code": "stack_encrypt::dynamic_value", "reason": "field_type" } } diff --git a/languages/golang/encrypt/guest/src/status.rs b/languages/golang/encrypt/guest/src/status.rs index 570dd9e5b..eea4f922a 100644 --- a/languages/golang/encrypt/guest/src/status.rs +++ b/languages/golang/encrypt/guest/src/status.rs @@ -189,6 +189,9 @@ pub fn status_for_dynamic(error: &stack_encrypt::dynamic::Error) -> u32 { | Error::Plan { .. } | Error::UntypedIndex { .. } | Error::Source { .. } + // One value that a single ciphertext cannot hold: an array, an + // object, a null, or a value of another kind than the one declared. + | Error::Value { .. } | Error::Record { .. } // A `match` predicate refused at an offset in its text: a construct // the grammar does not read or the index cannot answer, a variable @@ -577,6 +580,12 @@ mod tests { reason: Reason::FieldMissing, }, ), + ( + "a refused single value", + Error::Value { + reason: Reason::Null, + }, + ), ( "a bad record", Error::Record { diff --git a/packages/stack-encrypt/CHANGELOG.md b/packages/stack-encrypt/CHANGELOG.md index 84f95c931..3a29762da 100644 --- a/packages/stack-encrypt/CHANGELOG.md +++ b/packages/stack-encrypt/CHANGELOG.md @@ -50,9 +50,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 parses and returns it as the engine writes the document. - A ciphertext holds one scalar. `encrypt` refuses an array, an object, a passthrough and a null, plain or typed, before any key is requested. - The refusal is `dynamic::Error::Source` with one of three new reasons, - `Reason::Array`, `Reason::Object` and `Reason::Null`, or with - `Reason::Passthrough`. JavaScript's `undefined` is refused with + The refusal is a new variant, `dynamic::Error::Value`, with the code + `stack_encrypt::dynamic_value`. It names no field, and its message is + about one value. It carries one of three new reasons, `Reason::Array`, + `Reason::Object` and `Reason::Null`, or `Reason::Passthrough`. JavaScript's `undefined` is refused with `Reason::Undefined`, with a declared kind and with none: it is most often a property name spelt wrong, and no typed call could read it back. A value of another kind is `Reason::FieldType`. diff --git a/packages/stack-encrypt/docs/language-integration.md b/packages/stack-encrypt/docs/language-integration.md index d5e03ed5e..4c36ea765 100644 --- a/packages/stack-encrypt/docs/language-integration.md +++ b/packages/stack-encrypt/docs/language-integration.md @@ -194,8 +194,10 @@ Awaiting the merged call makes one key request, and each value keeps its own declared kind. A ciphertext holds one scalar. An array, an object, a passthrough and a null -are refused before any key is requested, with a reason that says which was -found (`array`, `object`, `passthrough`, `null`). An SDK stores an absent +are refused before any key is requested. The refusal is +[`crate::dynamic::Error::Value`], with the code +`stack_encrypt::dynamic_value` and a reason that says which was found +(`array`, `object`, `passthrough`, `null`). An SDK stores an absent value as a database `NULL`. JavaScript's `undefined` is refused too (`undefined`), whatever kind is declared. diff --git a/packages/stack-encrypt/src/codes.rs b/packages/stack-encrypt/src/codes.rs index 10ced550e..9f038b63c 100644 --- a/packages/stack-encrypt/src/codes.rs +++ b/packages/stack-encrypt/src/codes.rs @@ -219,6 +219,7 @@ mod tests { Error::Plan { .. } => Error::bad_plan(Reason::NoFields), Error::UntypedIndex { .. } => Error::UntypedIndex { field: name() }, Error::Source { .. } => Error::bad_source(Reason::FieldMissing), + Error::Value { .. } => Error::bad_value(Reason::Null), Error::Record { .. } => Error::bad_record(Reason::NoCiphertextNode), Error::Predicate { .. } => Error::Predicate { field: Some(name()), diff --git a/packages/stack-encrypt/src/dynamic/value.rs b/packages/stack-encrypt/src/dynamic/value.rs index c75557fd6..232d4f398 100644 --- a/packages/stack-encrypt/src/dynamic/value.rs +++ b/packages/stack-encrypt/src/dynamic/value.rs @@ -202,7 +202,7 @@ use crate::{Ciphertext, ContextPiece, DecryptFrom, KeysetCipher}; /// /// # Errors /// -/// [`Error::Source`], decided here, before any key is requested: +/// [`Error::Value`], decided here, before any key is requested: /// /// - [`Reason::Array`], [`Reason::Object`], [`Reason::Passthrough`] or /// [`Reason::Null`] for a value that is not one scalar. A typed null is a @@ -421,7 +421,7 @@ pub fn decrypt_with_context<'a, 'c, K: 'static>( /// /// # Errors /// -/// [`Error::Source`] with the reason that names what was found: an array, +/// [`Error::Value`] with the reason that names what was found: an array, /// an object, a null, a passthrough or `undefined`. fn one_scalar(value: Frame<'_>) -> Result<(), Error> { let found = match value.kind() { @@ -438,7 +438,7 @@ fn one_scalar(value: Frame<'_>) -> Result<(), Error> { // scalar, and it seals as it arrived. None => return Ok(()), }; - Err(Error::bad_source(found)) + Err(Error::bad_value(found)) } /// Whether `value` is JavaScript's `undefined`. @@ -470,7 +470,7 @@ fn seal<'a, K: 'static>( } // The conversion also refuses a value that is not of the declared // kind. A converted value is wiped when it drops. - Some(kind) => match convert(kind, value)? { + Some(kind) => match convert(kind, value).map_err(of_one_value)? { Some(converted) => encrypt_opaque(converted.frame(), keyset, context), None => encrypt_opaque(value, keyset, context), }, @@ -478,9 +478,18 @@ fn seal<'a, K: 'static>( Ok(sealed.try_map(Ciphertext::from_tree)) } +/// A refusal that the shared conversion made as a record field's, as the +/// refusal of one value: the same reason, with no field to name. +fn of_one_value(error: Error) -> Error { + match error.reason() { + Some(reason) => Error::bad_value(reason), + None => error, + } +} + /// The refusal of a value that is not a document under the `json` kind. fn not_a_document(error: JsonValueError) -> Error { - Error::bad_source(match error { + Error::bad_value(match error { JsonValueError::NotText => Reason::FieldType, JsonValueError::Text(error) => json_reason(error), }) diff --git a/packages/stack-encrypt/src/refusal.rs b/packages/stack-encrypt/src/refusal.rs index 80add0beb..106468254 100644 --- a/packages/stack-encrypt/src/refusal.rs +++ b/packages/stack-encrypt/src/refusal.rs @@ -58,7 +58,8 @@ use crate::target::IndexSpec; /// /// Not every variant has a [`Reason`]. [`Context`](Error::Context), /// [`Plan`](Error::Plan), [`Source`](Error::Source), -/// [`Record`](Error::Record) and [`Predicate`](Error::Predicate) do: it is +/// [`Record`](Error::Record), [`Predicate`](Error::Predicate) and +/// [`Value`](Error::Value) do: it is /// in the message, in [`reason`](Self::reason) and in the payload /// (`reason`). The others carry their own payload fields instead: /// [`Term`](Error::Term) names the index it was asked for (`index`), @@ -140,10 +141,7 @@ pub enum Error { /// not carry or carries twice, or a passthrough or a repeated map key /// under a field the plan seals, or a value of another type than its /// field declares that does not convert to it exactly, or `undefined` - /// for a field that declares a type. Also one value that a single - /// ciphertext cannot hold ([`value::encrypt`](crate::dynamic::value::encrypt)): - /// an array, an object, a passthrough or a null, or a value that is not - /// of the kind declared for it. Also a query its field does not answer: an operator + /// for a field that declares a type. Also a query its field does not answer: an operator /// the field's type does not answer, an input that cannot be read as the /// field's type ([`read`](crate::dynamic::read)) or is not the pair a range takes, a page of /// values to verify that holds a value of another type, or statistics @@ -210,6 +208,24 @@ pub enum Error { at: usize, }, + /// One value cannot be encrypted on its own, as a single ciphertext + /// ([`value::encrypt`](crate::dynamic::value::encrypt)). The value is + /// an array, an object, a passthrough, a null or `undefined`. Or it is + /// not of the kind declared for it. Or, under the `json` kind, its text + /// is not a JSON document. + /// + /// The refusal names no field, because there is no record. It says + /// which kind of value was found, and never the value. + #[error("the value cannot be encrypted as one ciphertext: {}", value_text(*reason))] + #[diagnostic( + code(stack_encrypt::dynamic_value), + help("One ciphertext holds one value that is present: text, a number, a boolean, bytes, a date, a timestamp, a decimal, a UUID or a JSON document. Encrypt a list one value at a time, and store an absent value as a database NULL.") + )] + Value { + /// What was wrong with the value. + reason: Reason, + }, + /// An invariant this module maintains did not hold — a slot count that /// did not line up, a re-proof that should not have been able to fail. /// Always a bug here, never a statement about the caller's data. @@ -242,7 +258,29 @@ fn in_field_text(field: &Option) -> String { .unwrap_or_default() } +/// What a single-value refusal says for `reason`. +/// +/// Two reasons have phrases written for a record's field: a value of +/// another type, and `undefined`. A single value has no field, so each is +/// reworded here. Every other reason says what was found, and reads the +/// same for one value. +fn value_text(reason: Reason) -> String { + match reason { + Reason::FieldType => { + "it is not of the kind declared for it, and does not convert to that kind exactly" + .to_owned() + } + Reason::Undefined => "it is undefined".to_owned(), + found => found.to_string(), + } +} + impl Error { + /// A single-value refusal. + pub(crate) fn bad_value(reason: Reason) -> Self { + Self::Value { reason } + } + /// A context error with no field named yet. pub(crate) fn bad_context(reason: Reason) -> Self { Self::Context { @@ -310,7 +348,7 @@ impl Error { Self::UntypedIndex { field } => Some(field), #[cfg(feature = "dynamic")] Self::Target(_) => None, - Self::Internal | Self::Cipher(_) => None, + Self::Value { .. } | Self::Internal | Self::Cipher(_) => None, } } @@ -332,15 +370,16 @@ impl Error { } } - /// What was wrong, for a context, plan, source, record or predicate - /// error. + /// What was wrong, for a context, plan, source, record, predicate or + /// single-value error. pub fn reason(&self) -> Option { match self { Self::Context { reason, .. } | Self::Plan { reason, .. } | Self::Source { reason, .. } | Self::Record { reason, .. } - | Self::Predicate { reason, .. } => Some(*reason), + | Self::Predicate { reason, .. } + | Self::Value { reason } => Some(*reason), #[cfg(feature = "dynamic")] Self::Target(_) => None, Self::Term { .. } | Self::UntypedIndex { .. } | Self::Internal | Self::Cipher(_) => { diff --git a/packages/stack-encrypt/tests/single_value.rs b/packages/stack-encrypt/tests/single_value.rs index 602f2b0d6..6c383f5f6 100644 --- a/packages/stack-encrypt/tests/single_value.rs +++ b/packages/stack-encrypt/tests/single_value.rs @@ -428,17 +428,51 @@ async fn refused(value: &OwnedFrame, kind: Option) -> dynamic::Error single } -fn assert_source_refusal(error: &dynamic::Error, reason: Reason, what: &str) { +/// A single-value refusal: its own variant and code, the reason, and a +/// message about one value, with no record, plan or field in it. +fn assert_value_refusal(error: &dynamic::Error, reason: Reason, what: &str) { + use stack_encrypt::ErrorPayload as _; assert!( - matches!(error, dynamic::Error::Source { field: None, .. }), - "{what}: expected a source refusal naming no field, got: {error:?}" + matches!(error, dynamic::Error::Value { .. }), + "{what}: expected a single-value refusal, got: {error:?}" ); assert_eq!(error.reason(), Some(reason), "{what}: the reason"); + assert_eq!(error.field(), None, "{what}: one value names no field"); assert_eq!( error.code().map(|code| code.to_string()).as_deref(), - Some("stack_encrypt::dynamic_source"), + Some("stack_encrypt::dynamic_value"), "{what}: the diagnostic code" ); + assert_eq!( + error + .payload() + .get("reason") + .and_then(|value| value.as_str()), + Some(reason.as_str()), + "{what}: the payload carries the reason" + ); + // Two reasons have phrases written for a record's field. One value has + // no field, so its refusal words them for a value. + let found = match reason { + Reason::FieldType => { + "it is not of the kind declared for it, and does not convert to that kind exactly" + .to_owned() + } + Reason::Undefined => "it is undefined".to_owned(), + found => found.to_string(), + }; + let message = error.to_string(); + assert_eq!( + message, + format!("the value cannot be encrypted as one ciphertext: {found}"), + "{what}: the message is about one value" + ); + for word in ["field", "record", "plan"] { + assert!( + !message.contains(word), + "{what}: the message speaks of a {word}, and one value has none: {message}" + ); + } } mod encrypt_refuses_before_any_key_request { @@ -469,7 +503,7 @@ mod encrypt_refuses_before_any_key_request { Some(ValueKind::Json), ] { let error = refused(value, kind).await; - assert_source_refusal(&error, *reason, &format!("{what} under {kind:?}")); + assert_value_refusal(&error, *reason, &format!("{what} under {kind:?}")); } } } @@ -487,7 +521,7 @@ mod encrypt_refuses_before_any_key_request { Some(ValueKind::Array), ] { let error = refused(&undefined(), kind).await; - assert_source_refusal( + assert_value_refusal( &error, Reason::Undefined, &format!("undefined under {kind:?}"), @@ -510,7 +544,7 @@ mod encrypt_refuses_before_any_key_request { ]; for (what, value, kind) in &cases { let error = refused(value, Some(*kind)).await; - assert_source_refusal(&error, Reason::FieldType, what); + assert_value_refusal(&error, Reason::FieldType, what); } } @@ -532,7 +566,7 @@ mod encrypt_refuses_before_any_key_request { for (what, text, reason) in cases { for crossing in [frame(text), frame(text.as_bytes().to_vec())] { let error = refused(&crossing, Some(ValueKind::Json)).await; - assert_source_refusal(&error, reason, what); + assert_value_refusal(&error, reason, what); } } } @@ -612,7 +646,7 @@ mod encrypt_with_no_declared_kind { async fn refuses_an_unknown_logical_type_under_a_declared_kind() { for kind in [ValueKind::Int32, ValueKind::Date, ValueKind::Json] { let error = refused(&unknown_logical(), Some(kind)).await; - assert_source_refusal( + assert_value_refusal( &error, Reason::FieldType, &format!("an unknown logical type as {kind}"), @@ -830,7 +864,7 @@ mod many_values_merged_with_pending_all { Err(error) => error, Ok(_) => panic!("a batch holding a null was taken"), }; - assert_source_refusal(&error, Reason::Null, "the first refused value"); + assert_value_refusal(&error, Reason::Null, "the first refused value"); assert_eq!( generates.load(Ordering::SeqCst), 0, From 3b0d6437bbb52364f0aff41de2eb4c68d153f53b Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sat, 28 Nov 2026 18:08:54 +1100 Subject: [PATCH 14/19] feat(vitaminc-aead)!: derive ScalarTarget from a target's sink `ScalarTarget` was an open marker with one impl for each kind of target. That left two faults. A newtype that derives `Decrypt` over a scalar, such as `struct Email(String)`, did not carry it, so its author had to write `impl ScalarTarget for Email {}` to decrypt it from one ciphertext. And nothing stopped the same line for a target that reads only a container, which then compiled and refused every leaf. The marker now sits on sinks. `TakesScalar` means one scalar satisfies the sink, and the sinks that read a scalar carry it: `ScalarSink`, `ScalarProtected` and `OwnedFrameSink`, and `Optional`, `ProtectedOptional`, `Wrapped` and `Wrap` over a sink that carries it. `ScalarTarget` has one blanket impl, for every target whose sink is marked. A derived newtype's sink is `Wrapped` over its inner type's sink, so a newtype of a scalar is a `ScalarTarget` with no code, and a newtype of a `Vec` is not. No one can implement `ScalarTarget` by hand. The blanket impl does not ensure that alone: the compiler accepts a second impl for a type whose sink is defined in the same crate as that impl, because it can see the sink is not marked. The sink `#[derive(Decrypt)]` generates for a struct with named fields is such a sink. So `ScalarTarget` also has a private supertrait that holds only for a target whose sink is marked. A compile-fail test pins both cases. A sink written by hand opts in by implementing `TakesScalar`. That is the one promise the compiler still does not check. `ScalarTarget` and `TakesScalar` carry `diagnostic::on_unimplemented`. The error for `keyset.decrypt::>` now says that one ciphertext holds one value, and names what to decrypt instead: a `Vec` element by element, or a tree with `decrypt_tree`. stack-encrypt's docs, changelog and ADR amendment no longer tell a newtype's author to write the marker, and its compile tests cover a derived newtype with no marker. BREAKING CHANGE: `ScalarTarget` can no longer be implemented directly. Remove any `impl ScalarTarget for T {}`. A derived newtype of a scalar needs none, and a target with a sink of its own implements `TakesScalar` for that sink. --- packages/stack-encrypt/CHANGELOG.md | 16 +- .../adr/0012-owned-record-declarations.md | 11 +- packages/stack-encrypt/src/scalar.rs | 33 ++- .../tests/ui/owned_collection_elements.stderr | 1 + .../tests/ui/pass/scalar_decrypt_targets.rs | 24 +- .../ui/scalar_decrypt_into_a_container.rs | 9 +- .../ui/scalar_decrypt_into_a_container.stderr | 221 ++++++++++++------ packages/vitaminc-aead/CHANGELOG.md | 13 +- packages/vitaminc-aead/src/frame/owned.rs | 10 +- packages/vitaminc-aead/src/lib.rs | 1 + packages/vitaminc-aead/src/typed.rs | 196 +++++++++++++--- packages/vitaminc-aead/tests/scalar_target.rs | 126 +++++++++- .../derived_newtype_of_a_container.rs | 13 ++ .../derived_newtype_of_a_container.stderr | 25 ++ .../derived_struct_needs_a_map.stderr | 34 +-- .../hand_written_impl_for_a_derived_struct.rs | 14 ++ ...d_written_impl_for_a_derived_struct.stderr | 32 +++ .../hand_written_impl_for_a_newtype.rs | 12 + .../hand_written_impl_for_a_newtype.stderr | 10 + .../ui/scalar_target/map_needs_a_map.stderr | 52 +++-- .../scalar_target/vec_needs_a_sequence.stderr | 21 +- ...ed_container_is_not_a_scalar_target.stderr | 68 ++++-- 22 files changed, 712 insertions(+), 230 deletions(-) create mode 100644 packages/vitaminc-aead/tests/ui/scalar_target/derived_newtype_of_a_container.rs create mode 100644 packages/vitaminc-aead/tests/ui/scalar_target/derived_newtype_of_a_container.stderr create mode 100644 packages/vitaminc-aead/tests/ui/scalar_target/hand_written_impl_for_a_derived_struct.rs create mode 100644 packages/vitaminc-aead/tests/ui/scalar_target/hand_written_impl_for_a_derived_struct.stderr create mode 100644 packages/vitaminc-aead/tests/ui/scalar_target/hand_written_impl_for_a_newtype.rs create mode 100644 packages/vitaminc-aead/tests/ui/scalar_target/hand_written_impl_for_a_newtype.stderr diff --git a/packages/stack-encrypt/CHANGELOG.md b/packages/stack-encrypt/CHANGELOG.md index 3a29762da..8542e1460 100644 --- a/packages/stack-encrypt/CHANGELOG.md +++ b/packages/stack-encrypt/CHANGELOG.md @@ -573,18 +573,22 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Still accepted: every scalar (`bool`, the integers, the floats, `String`, `Vec`, `[u8; N]`, `value::Date`, `value::Timestamp`, `value::Decimal`, `value::Uuid`), `JsonPlaintext`, a `Protected` or an - `Option` of one, `OwnedFrame`, and any type of your own that + `Option` of one, `OwnedFrame`, a newtype that derives `Decrypt` over + one, such as `struct Email(String)`, and any type of your own that implements `FromScalar`. `OpaqueBlob` keeps its own way in. - No longer accepted: a `Vec` of anything but bytes, a `HashMap` or a - `BTreeMap`, a struct that derives `Decrypt`, and a `Protected` or an - `Option` of one of those. + `BTreeMap`, a struct that derives `Decrypt` with named fields, and a + newtype, a `Protected` or an `Option` of one of those. + - You write nothing to make a type of your own a target, and you + cannot: no one implements `ScalarTarget` by hand. A type is one when + one scalar builds it, which the compiler works out from how the type + decrypts. + - The compile error says that one ciphertext holds one value, and what + to decrypt instead. - A sequence, a map or a struct is a tree of leaves, which is a `StackCipherText`. Decrypt one with `keyset.decrypt_tree`. A column of ciphertexts is a `Vec`, which still decrypts into a `Vec` with `Vec::::decrypt_from`. - - A newtype that derives `Decrypt` over a scalar, such as - `struct Email(String)`, decrypted from one ciphertext before. Add - `impl stack_encrypt::ScalarTarget for Email {}` to keep it. - No stored byte changes. Every ciphertext that decrypted before still decrypts into the same type. diff --git a/packages/stack-encrypt/docs/adr/0012-owned-record-declarations.md b/packages/stack-encrypt/docs/adr/0012-owned-record-declarations.md index 521132208..ac91576e5 100644 --- a/packages/stack-encrypt/docs/adr/0012-owned-record-declarations.md +++ b/packages/stack-encrypt/docs/adr/0012-owned-record-declarations.md @@ -183,18 +183,17 @@ that trait to be implemented for both only in Vitamin C, the crate that defines `FromScalar`. > **Amended 2026-11-28 (#2011).** Vitamin C now has that trait, -> `ScalarTarget`: a decrypt target that one scalar builds. It is -> implemented for every `FromScalar` type, for an `Option` or a `Protected` -> of one, and for `OwnedFrame`. +> `ScalarTarget`: a decrypt target that one scalar builds. No one +> implements it by hand. A target is one when its sink is one that a scalar +> satisfies, which Vitamin C marks on its own sinks. So every `FromScalar` +> type is one, and so are an `Option`, a `Protected` or a derived newtype +> of one, and `OwnedFrame`. > > The bound of a single `Ciphertext`'s target is now > `ScalarTarget + Zeroize`, and no longer `Decrypt + Zeroize`. So a target > that is not a scalar, such as `Vec`, does not compile. > `keyset.decrypt::>(ct)` compiles as before. The other > stored types keep the bound `Decrypt + Zeroize`. -> -> A newtype that derives `Decrypt` over a scalar does not carry the marker. -> Its author adds `impl ScalarTarget` by hand. ### 5. The structural traits are a bridge diff --git a/packages/stack-encrypt/src/scalar.rs b/packages/stack-encrypt/src/scalar.rs index b236cff27..6dcc48dc2 100644 --- a/packages/stack-encrypt/src/scalar.rs +++ b/packages/stack-encrypt/src/scalar.rs @@ -124,6 +124,8 @@ pub trait OpaqueEncode: sealed::Encode + Zeroize + Send + 'static {} /// `Protected` /// - an `Option` of one, such as `Option`, which reads a sealed null /// as `None` +/// - a newtype that derives [`Decrypt`](crate::Decrypt) over one, such as +/// `struct Email(String)` /// - an `OwnedFrame`, the value as a frame, for a caller that learns the /// value's kind only when the code runs /// @@ -146,24 +148,35 @@ pub trait OpaqueEncode: sealed::Encode + Zeroize + Send + 'static {} /// # } /// ``` /// -/// A type of your own is an `OpaqueDecode` type if it implements -/// `ScalarTarget` and `Zeroize`. A type that implements Vitamin C's -/// `FromScalar` is a `ScalarTarget` already. A newtype that derives -/// [`Decrypt`](crate::Decrypt) over a scalar is not, until you add the -/// marker. The derive is Vitamin C's, so your crate needs `vitaminc-aead` -/// as a dependency to use it. +/// A type of your own is an `OpaqueDecode` type when one scalar builds it +/// and it implements `Zeroize`. You write no marker for that, and you +/// cannot: `ScalarTarget` follows from how the type decrypts. A newtype +/// that derives `Decrypt` over a scalar works as it is, and so does a type +/// that implements Vitamin C's `FromScalar`. The derive is Vitamin C's, so +/// your crate needs `vitaminc-aead` as a dependency to use it. /// /// ``` -/// use stack_encrypt::{Decrypt, ScalarTarget}; +/// # async fn example() -> Result<(), stack_encrypt::Error> { +/// use stack_encrypt::{Decrypt, StackCipher}; /// use zeroize::Zeroize; /// /// #[derive(Decrypt, Zeroize)] /// struct Email(String); /// -/// impl ScalarTarget for Email {} +/// // With no `.kms(..)`, the cipher uses ZeroKMS. It reads credentials from +/// // the environment, or from the profile that `npx stash auth login` writes. +/// let cipher = StackCipher::builder() +/// # .kms(stack_encrypt::kms::FakeDataKeySource::new()) +/// .init() +/// .await?; +/// let keyset = cipher.default_keyset(); +/// let stored = keyset.encrypt(String::from("ada@example.com")).await?; /// -/// fn decrypts_from_one_ciphertext() {} -/// decrypts_from_one_ciphertext::(); +/// let email: Email = keyset.decrypt(stored).await?; +/// assert_eq!(email.0, "ada@example.com"); +/// # Ok(()) +/// # } +/// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(example()).unwrap(); /// ``` /// /// A scalar decrypted into a bare type, such as `String`, is an ordinary diff --git a/packages/stack-encrypt/tests/ui/owned_collection_elements.stderr b/packages/stack-encrypt/tests/ui/owned_collection_elements.stderr index 1a74ef34c..bf2021ce1 100644 --- a/packages/stack-encrypt/tests/ui/owned_collection_elements.stderr +++ b/packages/stack-encrypt/tests/ui/owned_collection_elements.stderr @@ -102,6 +102,7 @@ error[E0277]: the trait bound `u8: vitaminc_aead::typed::FromScalar` is not sati i8 u128 and $N others + = note: required for `u8` to implement `Decrypt` = note: required for `u8` to implement `ScalarTarget` = note: required for `u8` to implement `OpaqueDecode` = note: required for `stack_encrypt::Ciphertext` to implement `DecryptSource` diff --git a/packages/stack-encrypt/tests/ui/pass/scalar_decrypt_targets.rs b/packages/stack-encrypt/tests/ui/pass/scalar_decrypt_targets.rs index 73a009a7a..53a284781 100644 --- a/packages/stack-encrypt/tests/ui/pass/scalar_decrypt_targets.rs +++ b/packages/stack-encrypt/tests/ui/pass/scalar_decrypt_targets.rs @@ -1,6 +1,7 @@ //! The targets one `Ciphertext` decrypts into, which must compile: every //! scalar, a `Protected` of one, a nullable one, a JSON document, the date, -//! timestamp, decimal and UUID values, an opaque blob and a frame. +//! timestamp, decimal and UUID values, a derived newtype of one with no +//! marker written for it, an opaque blob and a frame. //! `tests/ui/scalar_decrypt_into_a_container.rs` pins the targets that must //! not. use stack_encrypt::dynamic::frame::OwnedFrame; @@ -8,15 +9,23 @@ use stack_encrypt::json::JsonPlaintext; use stack_encrypt::value::{Date, Decimal, Timestamp, Uuid}; use stack_encrypt::{ Ciphertext, Decrypt, DecryptFrom, KeysetCipher, OpaqueBlob, OpaqueDecode, Protected, - ScalarTarget, StackCipher, + StackCipher, }; use stack_kms::FakeDataKeySource; -/// A newtype that derives `Decrypt` over a scalar. Its author adds the -/// marker, because the derive does not. +/// A newtype that derives `Decrypt` over a scalar decrypts from one +/// ciphertext as it is. Nothing else is written for it. #[derive(Decrypt, zeroize::Zeroize)] struct Email(String); -impl ScalarTarget for Email {} + +/// The same over an integer, over another newtype, and over a nullable +/// scalar. +#[derive(Decrypt, zeroize::Zeroize)] +struct UserId(u64); +#[derive(Decrypt, zeroize::Zeroize)] +struct PrimaryEmail(Email); +#[derive(Decrypt, zeroize::Zeroize)] +struct Nickname(Option); /// A whole value stored as one blob keeps its own way in. #[derive(Default, serde::Deserialize, zeroize::Zeroize)] @@ -56,6 +65,10 @@ fn targets() { opens::>>(); opens::(); opens::(); + opens::(); + opens::(); + opens::(); + opens::>(); opens::>(); } @@ -72,6 +85,7 @@ async fn calls( let _ = Vec::::decrypt_from(ciphertext.clone(), keyset).await?; let _ = OwnedFrame::decrypt_from(ciphertext.clone(), cipher).await?; let _ = Email::decrypt_from(ciphertext.clone(), cipher).await?; + let _: UserId = keyset.decrypt(ciphertext.clone()).await?; // A column of ciphertexts is a `Vec` of them, one scalar each. let _ = Vec::::decrypt_from(vec![ciphertext], keyset).await?; Ok(()) diff --git a/packages/stack-encrypt/tests/ui/scalar_decrypt_into_a_container.rs b/packages/stack-encrypt/tests/ui/scalar_decrypt_into_a_container.rs index 9b7a66e9c..4ae5843d8 100644 --- a/packages/stack-encrypt/tests/ui/scalar_decrypt_into_a_container.rs +++ b/packages/stack-encrypt/tests/ui/scalar_decrypt_into_a_container.rs @@ -1,6 +1,7 @@ //! A `Ciphertext` holds one scalar, so it decrypts only into a target that -//! one scalar builds. A sequence, a map, a derived struct and a protected -//! sequence each need a container, and do not compile. +//! one scalar builds. A sequence, a map, a derived struct, a derived +//! newtype of a sequence and a protected sequence each need a container, +//! and do not compile. //! `tests/ui/pass/scalar_decrypt_targets.rs` pins the targets that do. use std::collections::{BTreeMap, HashMap}; @@ -11,10 +12,14 @@ struct Account { id: u64, } +#[derive(Decrypt, zeroize::Zeroize)] +struct Tags(Vec); + fn unsupported(keyset: &KeysetCipher<'_, K>, ciphertext: Ciphertext) { let _ = keyset.decrypt::>(ciphertext.clone()); let _ = keyset.decrypt::>(ciphertext.clone()); let _ = keyset.decrypt::(ciphertext.clone()); + let _ = keyset.decrypt::(ciphertext.clone()); let _ = keyset.decrypt::>>(ciphertext.clone()); let _ = keyset.decrypt_with_context::>(ciphertext.clone(), "users/tags"); let _ = Vec::::decrypt_from(ciphertext, keyset); diff --git a/packages/stack-encrypt/tests/ui/scalar_decrypt_into_a_container.stderr b/packages/stack-encrypt/tests/ui/scalar_decrypt_into_a_container.stderr index 7f65aa207..c3ab7b7f8 100644 --- a/packages/stack-encrypt/tests/ui/scalar_decrypt_into_a_container.stderr +++ b/packages/stack-encrypt/tests/ui/scalar_decrypt_into_a_container.stderr @@ -1,16 +1,25 @@ -error[E0277]: the trait bound `Vec: OpaqueDecode` is not satisfied - --> tests/ui/scalar_decrypt_into_a_container.rs:15:30 +error[E0277]: one ciphertext holds one value, and this decrypt target is not built from one value + --> tests/ui/scalar_decrypt_into_a_container.rs:19:30 | -15 | let _ = keyset.decrypt::>(ciphertext.clone()); - | ------- ^^^^^^^^^^^ the trait `FromScalar` is not implemented for `Vec` +19 | let _ = keyset.decrypt::>(ciphertext.clone()); + | ------- ^^^^^^^^^^^ this target cannot be decrypted from one ciphertext | | | required by a bound introduced by this call | -help: the trait `FromScalar` is implemented for `Vec` - --> $WORKSPACE/packages/vitaminc-aead/src/typed.rs - | - | impl FromScalar for Vec { - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ + = help: the trait `TakesScalar` is not implemented for `vitaminc_aead::typed::List` + = note: `vitaminc_aead::typed::List` is the target's sink, and it does not read a single scalar + = note: a single ciphertext decrypts into a scalar such as `String`, `i64` or `Vec`, an `Option` or a `Protected` of one, or a newtype that derives `Decrypt` over one + = note: to decrypt many values, decrypt a `Vec`, which opens each ciphertext into one element; to decrypt a sequence, a map or a struct that was encrypted as a tree, use `decrypt_tree` + = help: the following other types implement trait `TakesScalar`: + Optional + OwnedFrameSink + ProtectedOptional + ScalarProtected + ScalarSink + Wrap + Wrapped + = note: there are multiple different versions of crate `vitaminc_aead` in the dependency graph + = help: you can use `cargo tree` to explore your dependency tree = note: required for `Vec` to implement `ScalarTarget` = note: required for `Vec` to implement `OpaqueDecode` note: required by a bound in `stack_encrypt::scalar::>::decrypt` @@ -19,24 +28,28 @@ note: required by a bound in `stack_encrypt::scalar::>: | pub fn decrypt(&self, ciphertext: Ciphertext) -> Pending<'_, P, K> { | ^^^^^^^^^^^^ required by this bound in `stack_encrypt::scalar::>::decrypt` -error[E0277]: the trait bound `BTreeMap: OpaqueDecode` is not satisfied - --> tests/ui/scalar_decrypt_into_a_container.rs:16:30 +error[E0277]: one ciphertext holds one value, and this decrypt target is not built from one value + --> tests/ui/scalar_decrypt_into_a_container.rs:20:30 | -16 | let _ = keyset.decrypt::>(ciphertext.clone()); - | ------- ^^^^^^^^^^^^^^^^^^^^^ the trait `FromScalar` is not implemented for `BTreeMap` +20 | let _ = keyset.decrypt::>(ciphertext.clone()); + | ------- ^^^^^^^^^^^^^^^^^^^^^ this target cannot be decrypted from one ciphertext | | | required by a bound introduced by this call | - = help: the following other types implement trait `FromScalar`: - JsonPlaintext - Vec - [u8; N] - bool - f32 - f64 - i128 - i16 - and $N others + = help: the trait `TakesScalar` is not implemented for `Dict>` + = note: `Dict>` is the target's sink, and it does not read a single scalar + = note: a single ciphertext decrypts into a scalar such as `String`, `i64` or `Vec`, an `Option` or a `Protected` of one, or a newtype that derives `Decrypt` over one + = note: to decrypt many values, decrypt a `Vec`, which opens each ciphertext into one element; to decrypt a sequence, a map or a struct that was encrypted as a tree, use `decrypt_tree` + = help: the following other types implement trait `TakesScalar`: + Optional + OwnedFrameSink + ProtectedOptional + ScalarProtected + ScalarSink + Wrap + Wrapped + = note: there are multiple different versions of crate `vitaminc_aead` in the dependency graph + = help: you can use `cargo tree` to explore your dependency tree = note: required for `BTreeMap` to implement `ScalarTarget` = note: required for `BTreeMap` to implement `OpaqueDecode` note: required by a bound in `stack_encrypt::scalar::>::decrypt` @@ -46,9 +59,9 @@ note: required by a bound in `stack_encrypt::scalar::>: | ^^^^^^^^^^^^ required by this bound in `stack_encrypt::scalar::>::decrypt` error[E0277]: the trait bound `BTreeMap: OpaqueDecode` is not satisfied - --> tests/ui/scalar_decrypt_into_a_container.rs:16:30 + --> tests/ui/scalar_decrypt_into_a_container.rs:20:30 | -16 | let _ = keyset.decrypt::>(ciphertext.clone()); +20 | let _ = keyset.decrypt::>(ciphertext.clone()); | ------- ^^^^^^^^^^^^^^^^^^^^^ the trait `DefaultIsZeroes` is not implemented for `BTreeMap` | | | required by a bound introduced by this call @@ -71,29 +84,30 @@ note: required by a bound in `stack_encrypt::scalar::>: | pub fn decrypt(&self, ciphertext: Ciphertext) -> Pending<'_, P, K> { | ^^^^^^^^^^^^ required by this bound in `stack_encrypt::scalar::>::decrypt` -error[E0277]: the trait bound `Account: OpaqueDecode` is not satisfied - --> tests/ui/scalar_decrypt_into_a_container.rs:17:30 +error[E0277]: one ciphertext holds one value, and this decrypt target is not built from one value + --> tests/ui/scalar_decrypt_into_a_container.rs:21:30 | -17 | let _ = keyset.decrypt::(ciphertext.clone()); - | ------- ^^^^^^^ unsatisfied trait bound +21 | let _ = keyset.decrypt::(ciphertext.clone()); + | ------- ^^^^^^^ this target cannot be decrypted from one ciphertext | | | required by a bound introduced by this call | -help: the trait `FromScalar` is not implemented for `Account` - --> tests/ui/scalar_decrypt_into_a_container.rs:10:1 +help: the trait `TakesScalar` is not implemented for `__AccountDecryptSink` + --> tests/ui/scalar_decrypt_into_a_container.rs:10:10 | -10 | struct Account { - | ^^^^^^^^^^^^^^ - = help: the following other types implement trait `FromScalar`: - JsonPlaintext - Vec - [u8; N] - bool - f32 - f64 - i128 - i16 - and $N others +10 | #[derive(Decrypt, zeroize::Zeroize)] + | ^^^^^^^ + = note: `__AccountDecryptSink` is the target's sink, and it does not read a single scalar + = note: a single ciphertext decrypts into a scalar such as `String`, `i64` or `Vec`, an `Option` or a `Protected` of one, or a newtype that derives `Decrypt` over one + = note: to decrypt many values, decrypt a `Vec`, which opens each ciphertext into one element; to decrypt a sequence, a map or a struct that was encrypted as a tree, use `decrypt_tree` + = help: the following other types implement trait `TakesScalar`: + Optional + OwnedFrameSink + ProtectedOptional + ScalarProtected + ScalarSink + Wrap + Wrapped = note: required for `Account` to implement `ScalarTarget` = note: required for `Account` to implement `OpaqueDecode` note: required by a bound in `stack_encrypt::scalar::>::decrypt` @@ -101,20 +115,62 @@ note: required by a bound in `stack_encrypt::scalar::>: | | pub fn decrypt(&self, ciphertext: Ciphertext) -> Pending<'_, P, K> { | ^^^^^^^^^^^^ required by this bound in `stack_encrypt::scalar::>::decrypt` + = note: this error originates in the derive macro `Decrypt` (in Nightly builds, run with -Z macro-backtrace for more info) -error[E0277]: the trait bound `Protected>: OpaqueDecode` is not satisfied - --> tests/ui/scalar_decrypt_into_a_container.rs:18:30 +error[E0277]: one ciphertext holds one value, and this decrypt target is not built from one value + --> tests/ui/scalar_decrypt_into_a_container.rs:22:30 | -18 | let _ = keyset.decrypt::>>(ciphertext.clone()); - | ------- ^^^^^^^^^^^^^^^^^^^ the trait `ScalarTarget` is not implemented for `Protected>` +22 | let _ = keyset.decrypt::(ciphertext.clone()); + | ------- ^^^^ this target cannot be decrypted from one ciphertext | | | required by a bound introduced by this call | -help: the trait `ScalarTarget` is implemented for `Protected` - --> $WORKSPACE/packages/vitaminc-aead/src/typed.rs + = help: the trait `TakesScalar` is not implemented for `vitaminc_aead::typed::List` + = note: `vitaminc_aead::typed::List` is the target's sink, and it does not read a single scalar + = note: a single ciphertext decrypts into a scalar such as `String`, `i64` or `Vec`, an `Option` or a `Protected` of one, or a newtype that derives `Decrypt` over one + = note: to decrypt many values, decrypt a `Vec`, which opens each ciphertext into one element; to decrypt a sequence, a map or a struct that was encrypted as a tree, use `decrypt_tree` + = help: the following other types implement trait `TakesScalar`: + Optional + OwnedFrameSink + ProtectedOptional + ScalarProtected + ScalarSink + Wrap + Wrapped + = note: there are multiple different versions of crate `vitaminc_aead` in the dependency graph + = help: you can use `cargo tree` to explore your dependency tree + = note: required for `Wrapped, __TagsDecryptWrap>` to implement `TakesScalar` + = note: required for `Tags` to implement `ScalarTarget` + = note: required for `Tags` to implement `OpaqueDecode` +note: required by a bound in `stack_encrypt::scalar::>::decrypt` + --> src/scalar.rs | - | impl ScalarTarget for Protected {} - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | pub fn decrypt(&self, ciphertext: Ciphertext) -> Pending<'_, P, K> { + | ^^^^^^^^^^^^ required by this bound in `stack_encrypt::scalar::>::decrypt` + +error[E0277]: one ciphertext holds one value, and this decrypt target is not built from one value + --> tests/ui/scalar_decrypt_into_a_container.rs:23:30 + | +23 | let _ = keyset.decrypt::>>(ciphertext.clone()); + | ------- ^^^^^^^^^^^^^^^^^^^ this target cannot be decrypted from one ciphertext + | | + | required by a bound introduced by this call + | + = help: the trait `TakesScalar` is not implemented for `ProtectedList` + = note: `ProtectedList` is the target's sink, and it does not read a single scalar + = note: a single ciphertext decrypts into a scalar such as `String`, `i64` or `Vec`, an `Option` or a `Protected` of one, or a newtype that derives `Decrypt` over one + = note: to decrypt many values, decrypt a `Vec`, which opens each ciphertext into one element; to decrypt a sequence, a map or a struct that was encrypted as a tree, use `decrypt_tree` + = help: the following other types implement trait `TakesScalar`: + Optional + OwnedFrameSink + ProtectedOptional + ScalarProtected + ScalarSink + Wrap + Wrapped + = note: there are multiple different versions of crate `vitaminc_aead` in the dependency graph + = help: you can use `cargo tree` to explore your dependency tree + = note: required for `Protected>` to implement `ScalarTarget` = note: required for `Protected>` to implement `OpaqueDecode` note: required by a bound in `stack_encrypt::scalar::>::decrypt` --> src/scalar.rs @@ -122,24 +178,28 @@ note: required by a bound in `stack_encrypt::scalar::>: | pub fn decrypt(&self, ciphertext: Ciphertext) -> Pending<'_, P, K> { | ^^^^^^^^^^^^ required by this bound in `stack_encrypt::scalar::>::decrypt` -error[E0277]: the trait bound `HashMap: OpaqueDecode` is not satisfied - --> tests/ui/scalar_decrypt_into_a_container.rs:19:43 +error[E0277]: one ciphertext holds one value, and this decrypt target is not built from one value + --> tests/ui/scalar_decrypt_into_a_container.rs:24:43 | -19 | let _ = keyset.decrypt_with_context::>(ciphertext.clone(), "users/tags"); - | -------------------- ^^^^^^^^^^^^^^^^^^^^^^^ the trait `FromScalar` is not implemented for `HashMap` +24 | let _ = keyset.decrypt_with_context::>(ciphertext.clone(), "users/tags"); + | -------------------- ^^^^^^^^^^^^^^^^^^^^^^^ this target cannot be decrypted from one ciphertext | | | required by a bound introduced by this call | - = help: the following other types implement trait `FromScalar`: - JsonPlaintext - Vec - [u8; N] - bool - f32 - f64 - i128 - i16 - and $N others + = help: the trait `TakesScalar` is not implemented for `Dict>` + = note: `Dict>` is the target's sink, and it does not read a single scalar + = note: a single ciphertext decrypts into a scalar such as `String`, `i64` or `Vec`, an `Option` or a `Protected` of one, or a newtype that derives `Decrypt` over one + = note: to decrypt many values, decrypt a `Vec`, which opens each ciphertext into one element; to decrypt a sequence, a map or a struct that was encrypted as a tree, use `decrypt_tree` + = help: the following other types implement trait `TakesScalar`: + Optional + OwnedFrameSink + ProtectedOptional + ScalarProtected + ScalarSink + Wrap + Wrapped + = note: there are multiple different versions of crate `vitaminc_aead` in the dependency graph + = help: you can use `cargo tree` to explore your dependency tree = note: required for `HashMap` to implement `ScalarTarget` = note: required for `HashMap` to implement `OpaqueDecode` note: required by a bound in `stack_encrypt::scalar::>::decrypt_with_context` @@ -149,9 +209,9 @@ note: required by a bound in `stack_encrypt::scalar::>: | ^^^^^^^^^^^^ required by this bound in `stack_encrypt::scalar::>::decrypt_with_context` error[E0277]: the trait bound `HashMap: OpaqueDecode` is not satisfied - --> tests/ui/scalar_decrypt_into_a_container.rs:19:43 + --> tests/ui/scalar_decrypt_into_a_container.rs:24:43 | -19 | let _ = keyset.decrypt_with_context::>(ciphertext.clone(), "users/tags"); +24 | let _ = keyset.decrypt_with_context::>(ciphertext.clone(), "users/tags"); | -------------------- ^^^^^^^^^^^^^^^^^^^^^^^ the trait `DefaultIsZeroes` is not implemented for `HashMap` | | | required by a bound introduced by this call @@ -174,17 +234,26 @@ note: required by a bound in `stack_encrypt::scalar::>: | pub fn decrypt_with_context<'c, P: OpaqueDecode>( | ^^^^^^^^^^^^ required by this bound in `stack_encrypt::scalar::>::decrypt_with_context` -error[E0277]: the trait bound `Vec: FromScalar` is not satisfied - --> tests/ui/scalar_decrypt_into_a_container.rs:20:13 - | -20 | let _ = Vec::::decrypt_from(ciphertext, keyset); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `FromScalar` is not implemented for `Vec` +error[E0277]: one ciphertext holds one value, and this decrypt target is not built from one value + --> tests/ui/scalar_decrypt_into_a_container.rs:25:13 | -help: the trait `FromScalar` is implemented for `Vec` - --> $WORKSPACE/packages/vitaminc-aead/src/typed.rs +25 | let _ = Vec::::decrypt_from(ciphertext, keyset); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ this target cannot be decrypted from one ciphertext | - | impl FromScalar for Vec { - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ + = help: the trait `TakesScalar` is not implemented for `vitaminc_aead::typed::List` + = note: `vitaminc_aead::typed::List` is the target's sink, and it does not read a single scalar + = note: a single ciphertext decrypts into a scalar such as `String`, `i64` or `Vec`, an `Option` or a `Protected` of one, or a newtype that derives `Decrypt` over one + = note: to decrypt many values, decrypt a `Vec`, which opens each ciphertext into one element; to decrypt a sequence, a map or a struct that was encrypted as a tree, use `decrypt_tree` + = help: the following other types implement trait `TakesScalar`: + Optional + OwnedFrameSink + ProtectedOptional + ScalarProtected + ScalarSink + Wrap + Wrapped + = note: there are multiple different versions of crate `vitaminc_aead` in the dependency graph + = help: you can use `cargo tree` to explore your dependency tree = note: required for `Vec` to implement `ScalarTarget` = note: required for `Vec` to implement `OpaqueDecode` = note: required for `stack_encrypt::Ciphertext` to implement `DecryptSource>` diff --git a/packages/vitaminc-aead/CHANGELOG.md b/packages/vitaminc-aead/CHANGELOG.md index 8282e1430..ab5b256bb 100644 --- a/packages/vitaminc-aead/CHANGELOG.md +++ b/packages/vitaminc-aead/CHANGELOG.md @@ -19,11 +19,14 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). - `ScalarTarget` (also `typed::ScalarTarget`): a marker for a decrypt target that one scalar builds. It is the decrypt-side counterpart of `Scalar`. A caller that opens exactly one leaf bounds its target on it, so a target that needs a sequence or a map does not compile. - It is implemented for every `FromScalar` type, for an `Option` of a `ScalarTarget`, for a `Protected` of a `ScalarTarget` that is `DecryptProtected`, and for `OwnedFrame`. - A `Vec` other than `Vec`, a map and a derived struct with named fields do not implement it. - A derived fieldless enum implements it, because the derive gives it `FromScalar`. - A derived newtype does not: add an empty `impl ScalarTarget` for a newtype of a scalar target. - The trait is open, and nothing in this crate bounds on it, so no existing code changes. + No one implements it by hand, and no one can: a target is a `ScalarTarget` when its sink is marked `TakesScalar`. + So every `FromScalar` type is one, and so are an `Option` of one, a `Protected` of a scalar or of an `Option` of one, `OwnedFrame`, a fieldless enum that derives `Decrypt`, and a newtype that derives `Decrypt` over one. + A `Vec` other than `Vec`, a map, a derived struct with named fields, and a newtype of one of those are not. + Its `#[diagnostic::on_unimplemented]` message says that one ciphertext holds one value, and what to decrypt instead. + Nothing in this crate bounds on it, so no existing code changes. +- `TakesScalar` (also `typed::TakesScalar`): a marker for a sink that one scalar satisfies. + It is implemented for `ScalarSink`, `ScalarProtected` and `OwnedFrameSink`, and for `Optional`, `ProtectedOptional`, `Wrapped` and `Wrap` over a sink that carries it. + A sink written by hand opts in with an empty impl, which makes its target a `ScalarTarget`. - `plaintext::ValueKind`: what a value is, without the value, with the text name a schema spells it with (`"int32"`, `"timestamp"`, `"object"`, `"json"`, …). It covers every scalar, an array, an object and a JSON document. `ValueKind::Uuid` (`"uuid"`) is a UUID: `Logical::Uuid` over sixteen bytes. Its zero is sixteen zero bytes, its null is a typed null as long as a UUID leaf, and it holds only a UUID. diff --git a/packages/vitaminc-aead/src/frame/owned.rs b/packages/vitaminc-aead/src/frame/owned.rs index 5efe1d9c8..19c11bff0 100644 --- a/packages/vitaminc-aead/src/frame/owned.rs +++ b/packages/vitaminc-aead/src/frame/owned.rs @@ -9,7 +9,7 @@ use crate::plaintext::{ Encrypt, EncryptRef, FixedType, Logical, MapSink, Physical, SeqSink, Sink, SourceError, }; use crate::tags; -use crate::typed::{DecodeError, Decrypt, ScalarTarget}; +use crate::typed::{DecodeError, Decrypt, TakesScalar}; /// One value as a transport frame, in a [`Buffer`] of its own: a value /// kept past the call that wrote it, and what a ciphertext opens into. @@ -136,10 +136,6 @@ impl Decrypt for OwnedFrame { } } -/// One leaf always builds a frame: the frame of the one scalar, or of the -/// null, that the leaf holds. -impl ScalarTarget for OwnedFrame {} - /// Wipes the bytes and leaves the plain null, the frame a buffer of no /// value holds: an `OwnedFrame` always holds one frame, so a zeroized one /// reads, walks and seals as a null. @@ -174,6 +170,10 @@ impl From for DecodeError { /// written. pub struct OwnedFrameSink(()); +/// One scalar always builds a frame: the frame of that scalar, or of the +/// null. So an [`OwnedFrame`] is a target one leaf builds. +impl TakesScalar for OwnedFrameSink {} + /// A container an [`OwnedFrameSink`] is opening: a sequence or a map /// written in place into the frame's buffer, which it owns until it ends. /// A map refuses a repeated key, without naming it. diff --git a/packages/vitaminc-aead/src/lib.rs b/packages/vitaminc-aead/src/lib.rs index 6c25316a4..64e044960 100644 --- a/packages/vitaminc-aead/src/lib.rs +++ b/packages/vitaminc-aead/src/lib.rs @@ -79,6 +79,7 @@ pub use shape::{Refusal, Unencryptable}; #[doc(inline)] pub use typed::{ decrypt, decrypt_async, DecodeError, Decrypt, DecryptProtected, FromScalar, ScalarTarget, + TakesScalar, }; #[doc(inline)] pub use walk::{decrypt_into, decrypt_into_async, decrypt_to_frame, walk, DecryptError}; diff --git a/packages/vitaminc-aead/src/typed.rs b/packages/vitaminc-aead/src/typed.rs index ade8eaee1..ead64f4ce 100644 --- a/packages/vitaminc-aead/src/typed.rs +++ b/packages/vitaminc-aead/src/typed.rs @@ -16,9 +16,11 @@ //! read a map, each value through `T`'s sink. //! //! [`ScalarTarget`] marks a target that one scalar builds: the scalar -//! targets, an `Option` or a `Protected` of one, and an +//! targets, an `Option`, a `Protected` or a derived newtype of one, and an //! [`OwnedFrame`](crate::OwnedFrame). A caller that opens exactly one leaf -//! bounds on it, so a target that needs a container does not compile. +//! bounds on it, so a target that needs a container does not compile. No +//! one implements it: a target is one when its sink is marked +//! [`TakesScalar`]. //! //! `Protected` is a target for every `T` that implements //! [`DecryptProtected`]: any scalar target that can be wiped, and a @@ -278,24 +280,31 @@ impl Decrypt for T { /// that only a container builds then fails to compile, where a bound on /// [`Decrypt`] alone would let it open the leaf and refuse it afterwards. /// -/// These targets implement it: +/// You do not implement this trait, and you cannot. A target is a +/// `ScalarTarget` when its sink is one that a scalar satisfies: when +/// [`Decrypt::Sink`] implements [`TakesScalar`]. So these targets are +/// `ScalarTarget`s, with no code of their own: /// /// - Every [`FromScalar`] type: `bool`, the integers (except `u8`), the /// floats, `String`, `Vec`, `[u8; N]`, this crate's date, timestamp, /// decimal and UUID values, the jiff, `rust_decimal` and uuid types behind -/// their features, and any type of your own that implements `FromScalar`. +/// their features, a fieldless enum that derives `Decrypt`, and any type +/// of your own that implements `FromScalar`. +/// - A newtype that derives `Decrypt` over a `ScalarTarget`, such as +/// `struct Email(String)`. /// - `Option` of a `ScalarTarget`. A null leaf builds `None`. -/// - `Protected` of a `ScalarTarget` that also implements -/// [`DecryptProtected`]. +/// - `Protected` of a `FromScalar` type that can be wiped, and of an +/// `Option` of one. /// - [`OwnedFrame`](crate::OwnedFrame). One leaf always builds a frame that /// holds one scalar. /// -/// These targets do not, because each needs a container: a `Vec` other -/// than `Vec`, a `HashMap` or a `BTreeMap`, and a struct that derives -/// `Decrypt` with named fields. +/// These targets are not, because each needs a container: a `Vec` other +/// than `Vec`, a `HashMap` or a `BTreeMap`, a struct that derives +/// `Decrypt` with named fields, and a newtype or an `Option` of one of +/// those. /// /// ``` -/// use vitaminc_aead::{Decrypt, OwnedFrame, ScalarTarget}; +/// use vitaminc_aead::{Decrypt, Encrypt, OwnedFrame, ScalarTarget}; /// use vitaminc_protected::Protected; /// /// /// Opens exactly one leaf. @@ -308,6 +317,14 @@ impl Decrypt for T { /// let _ = opens_one_leaf::>(); /// let _ = opens_one_leaf::>(); /// let _ = opens_one_leaf::(); +/// +/// // A derived newtype of a scalar is one too, as it is. +/// #[derive(Decrypt, Debug, PartialEq)] +/// struct Email(String); +/// +/// let email = "ada@example.com".visit(opens_one_leaf::())?; +/// assert_eq!(email, Email(String::from("ada@example.com"))); +/// # Ok::<(), vitaminc_aead::DecodeError>(()) /// ``` /// /// A `Vec` needs a sequence, so it does not compile: @@ -318,35 +335,125 @@ impl Decrypt for T { /// opens_one_leaf::>(); /// ``` /// -/// The trait is open, as `Scalar` is. A hand-written target whose sink -/// reads a scalar implements it with an empty impl. So does a newtype that -/// derives `Decrypt` over a scalar target: the derive does not implement -/// the marker. +/// A target with a sink written by hand becomes a `ScalarTarget` by marking +/// that sink. See [`TakesScalar`]. +#[diagnostic::on_unimplemented( + message = "one ciphertext holds one value, and `{Self}` is not built from one value", + label = "this target cannot be decrypted from one ciphertext", + note = "a single ciphertext decrypts into a scalar such as `String`, `i64` or `Vec`, an `Option` or a `Protected` of one, or a newtype that derives `Decrypt` over one", + note = "to decrypt many values, decrypt a `Vec`, which opens each ciphertext into one element; to decrypt a sequence, a map or a struct that was encrypted as a tree, use `decrypt_tree`" +)] +pub trait ScalarTarget: Decrypt + sealed::SinkTakesScalar {} + +/// The one way to be a [`ScalarTarget`]: a sink that a scalar satisfies. +impl ScalarTarget for T where T::Sink: TakesScalar {} + +mod sealed { + use super::{Decrypt, TakesScalar}; + + /// What closes [`ScalarTarget`](super::ScalarTarget) to an impl + /// written by hand. + /// + /// The blanket impl of `ScalarTarget` does not close it alone. The + /// compiler accepts a second impl for a type whose sink is defined in + /// the same crate as that impl, such as the sink `#[derive(Decrypt)]` + /// generates for a struct with named fields: it can see that the sink + /// is not marked, so the two impls do not overlap. This trait cannot + /// be named outside this module, and it holds only for a target whose + /// sink is marked. So such an impl is refused. + pub trait SinkTakesScalar {} + + impl SinkTakesScalar for T where T::Sink: TakesScalar {} +} + +/// A sink that one scalar satisfies: given one scalar, it can build its +/// value. +/// +/// This marker is what makes a target a [`ScalarTarget`]. Every sink of +/// this crate that reads a scalar carries it: [`ScalarSink`] and +/// [`ScalarProtected`], [`Optional`] and [`ProtectedOptional`] over such a +/// sink, [`Wrapped`] and [`Wrap`] over such a sink, and +/// [`OwnedFrameSink`](crate::frame::OwnedFrameSink). The sinks that need a +/// container do not: [`List`], [`Dict`], the protected list, and the sink +/// `#[derive(Decrypt)]` generates for a struct with named fields. +/// +/// So a target built from these sinks needs nothing more. A derived +/// newtype's sink is [`Wrapped`] over its inner type's sink, and is marked +/// exactly when the inner sink is. +/// +/// # A sink written by hand +/// +/// Implement this trait only for a sink of your own whose +/// [`scalar`](Sink::scalar) method can succeed. The compiler does not check +/// that: a sink that carries the marker and refuses every scalar compiles, +/// and then refuses every leaf it is given. /// /// ``` -/// use vitaminc_aead::{Decrypt, Encrypt, ScalarTarget}; +/// use vitaminc_aead::typed::{Never, TakesScalar}; +/// use vitaminc_aead::{ +/// DecodeError, Decrypt, Encrypt, EncryptRef, FixedType, Logical, Physical, ScalarTarget, +/// Sink, +/// }; /// -/// #[derive(Decrypt, Debug, PartialEq)] -/// struct Email(String); +/// /// A flag stored as the text `yes` or `no`. +/// #[derive(Debug, PartialEq)] +/// struct Flag(bool); +/// +/// struct FlagSink; +/// +/// impl Sink for FlagSink { +/// type Ok = Flag; +/// type Error = DecodeError; +/// type Seq = Never; +/// type Map = Never; +/// +/// fn scalar(self, ty: Option, value: Physical<'_>) -> Result { +/// match (ty, value) { +/// (None, Physical::Text("yes")) => Ok(Flag(true)), +/// (None, Physical::Text("no")) => Ok(Flag(false)), +/// _ => Err(DecodeError::Expected("flag")), +/// } +/// } +/// fn typed_null(self, _: FixedType) -> Result { +/// Err(DecodeError::Expected("flag")) +/// } +/// fn seq(self, _: Option) -> Result, DecodeError> { +/// Err(DecodeError::Expected("flag")) +/// } +/// fn map(self, _: Option) -> Result, DecodeError> { +/// Err(DecodeError::Expected("flag")) +/// } +/// fn passthrough(self, _: &P) -> Result { +/// Err(DecodeError::Expected("flag")) +/// } +/// } /// -/// impl ScalarTarget for Email {} +/// impl Decrypt for Flag { +/// type Sink = FlagSink; +/// fn sink() -> FlagSink { +/// FlagSink +/// } +/// } +/// +/// // One scalar satisfies the sink, so `Flag` is a `ScalarTarget`. +/// impl TakesScalar for FlagSink {} /// /// fn opens_one_leaf() -> T::Sink { /// T::sink() /// } -/// -/// let email = "ada@example.com".visit(opens_one_leaf::())?; -/// assert_eq!(email, Email(String::from("ada@example.com"))); -/// # Ok::<(), vitaminc_aead::DecodeError>(()) +/// assert_eq!("yes".visit(opens_one_leaf::())?, Flag(true)); +/// # Ok::<(), DecodeError>(()) /// ``` -/// -/// Implement it only for a target that a scalar can build. The marker is a -/// promise the compiler does not check: a target that carries it and reads -/// only a container compiles, and then refuses every leaf it is given. -pub trait ScalarTarget: Decrypt {} +#[diagnostic::on_unimplemented( + message = "one ciphertext holds one value, and this decrypt target is not built from one value", + label = "this target cannot be decrypted from one ciphertext", + note = "`{Self}` is the target's sink, and it does not read a single scalar", + note = "a single ciphertext decrypts into a scalar such as `String`, `i64` or `Vec`, an `Option` or a `Protected` of one, or a newtype that derives `Decrypt` over one", + note = "to decrypt many values, decrypt a `Vec`, which opens each ciphertext into one element; to decrypt a sequence, a map or a struct that was encrypted as a tree, use `decrypt_tree`" +)] +pub trait TakesScalar: Sink {} -/// Every type that decodes from one scalar is built by one scalar. -impl ScalarTarget for T {} +impl TakesScalar for ScalarSink {} /// A sink nothing is ever walked into: the element and entry type of a /// container sink that hands out none, such as [`Never`] and the map sink @@ -895,6 +1002,11 @@ impl, W: Rewrap> Sink for Wrapped { } } +/// The inner sink's scalar, rewrapped: a scalar satisfies the wrapper +/// exactly when it satisfies the sink inside. So a derived newtype of a +/// scalar target is a scalar target. +impl + TakesScalar, W: Rewrap> TakesScalar for Wrapped {} + /// A container sink whose `end` passes its result through `W`. pub struct WrappedEnd(Q, PhantomData); @@ -1147,9 +1259,9 @@ impl Decrypt for Option { } } -/// A null leaf builds `None`, and any other scalar builds `Some` of what -/// `T` builds. -impl ScalarTarget for Option {} +/// A null builds `None`, and any other scalar builds `Some` of what `T`'s +/// sink builds. +impl TakesScalar for Optional where T::Sink: TakesScalar {} /// A type that can be decrypted straight into `Protected`: it names /// the sink that builds the wrapped value. @@ -1178,11 +1290,6 @@ impl Decrypt for Protected { } } -/// What one scalar builds, it also builds inside the wrapper. A -/// `Protected>` of anything but bytes is not covered, because -/// `Vec` is not a `ScalarTarget`. -impl ScalarTarget for Protected {} - /// Any scalar target that can be wiped, read into `Protected`. A heap /// type (`String`, `Vec`) is copied once, into the wrapper's buffer. /// An inline type (an integer, `[u8; N]`) moves by value, so a move can @@ -1199,6 +1306,8 @@ impl DecryptProtected for T { /// containers and passthrough, as [`ScalarSink`] does. pub struct ScalarProtected(PhantomData); +impl TakesScalar for ScalarProtected {} + impl Sink for ScalarProtected { type Ok = Protected; type Error = DecodeError; @@ -1324,6 +1433,10 @@ impl DecryptProtected for Option { /// The sink for `Protected>`. pub struct ProtectedOptional(T::ProtectedSink); +/// A null builds a protected `None`, and any other scalar builds a +/// protected `Some` of what `T`'s protected sink builds. +impl TakesScalar for ProtectedOptional where T::ProtectedSink: TakesScalar {} + impl Sink for ProtectedOptional { type Ok = Protected>; type Error = DecodeError; @@ -1403,6 +1516,15 @@ where } } +/// The inner sink's scalar, moved into `Protected`: a scalar satisfies the +/// wrapper exactly when it satisfies the sink inside. +impl TakesScalar for Wrap +where + S: Sink + TakesScalar, + S::Ok: Zeroize, +{ +} + /// A container sink whose result is moved into `Protected` at its end. pub struct WrapEnd(Q); diff --git a/packages/vitaminc-aead/tests/scalar_target.rs b/packages/vitaminc-aead/tests/scalar_target.rs index 78e819634..a84ac8d04 100644 --- a/packages/vitaminc-aead/tests/scalar_target.rs +++ b/packages/vitaminc-aead/tests/scalar_target.rs @@ -1,11 +1,14 @@ //! `ScalarTarget`, the decrypt-side marker for a target that one scalar //! builds: the counterpart of `Scalar`. //! -//! The marker is only worth having if it agrees with the sinks. So for every -//! kind of target that carries it, these tests walk one scalar into the -//! target's sink and check what it builds. The compile-fail half lives in -//! `tests/ui/scalar_target/`: a sequence, a map, a derived struct and a -//! protected sequence do not carry the marker. +//! No target implements the marker itself: a target carries it when its +//! sink is one a scalar satisfies (`TakesScalar`). The marker is only worth +//! having if it agrees with the sinks. So for every kind of target that +//! carries it, these tests walk one scalar into the target's sink and check +//! what it builds. The compile-fail half lives in `tests/ui/scalar_target/`: +//! a sequence, a map, a derived struct, a newtype of a sequence and a +//! protected sequence do not carry the marker, and no one can give it to +//! them by hand. use vitaminc_aead::plaintext::Raw; use vitaminc_aead::{ @@ -141,17 +144,120 @@ fn a_hand_written_scalar_target_carries_the_marker() { ); } -/// A derived newtype reads what its inner type reads. The derive does not -/// add the marker, so the newtype's author does. +/// A derived newtype reads what its inner type reads. Its sink wraps the +/// inner type's sink, so it is a scalar target with no code of its own. #[test] -fn a_derived_newtype_takes_the_marker_by_hand() { +fn a_derived_newtype_of_a_scalar_target_is_one_as_it_is() { #[derive(Decrypt, Debug, PartialEq)] struct Email(String); - impl ScalarTarget for Email {} assert_eq!( built_by_one_scalar::("ada@example.com"), Email(String::from("ada@example.com")), - "a derived newtype of a scalar target" + "a derived newtype of a string" + ); + + #[derive(Decrypt, Debug, PartialEq)] + struct UserId(u64); + assert_eq!( + built_by_one_scalar::(42u64), + UserId(42), + "a derived newtype of an integer" + ); + + // A newtype of a newtype, and a nullable newtype. + #[derive(Decrypt, Debug, PartialEq)] + struct Primary(Email); + assert_eq!( + built_by_one_scalar::("ada@example.com"), + Primary(Email(String::from("ada@example.com"))), + "a derived newtype of a derived newtype" + ); + assert_eq!( + built_by_one_scalar::>(null()), + None, + "an Option of a derived newtype reads a null" + ); + + #[derive(Decrypt, Debug, PartialEq)] + struct MaybeId(Option); + assert_eq!( + built_by_one_scalar::(null()), + MaybeId(None), + "a derived newtype of an Option reads a null" + ); +} + +/// A newtype decrypts into `Protected` once its author says how. `Wrap` +/// moves what the newtype's own sink builds into the wrapper, and a scalar +/// satisfies it when it satisfies that sink. +#[test] +fn a_protected_newtype_is_a_scalar_target_through_wrap() { + use vitaminc_aead::typed::Wrap; + use vitaminc_aead::DecryptProtected; + use zeroize::Zeroize; + + #[derive(Decrypt, Zeroize)] + struct Email(String); + impl DecryptProtected for Email { + type ProtectedSink = Wrap<::Sink>; + fn protected_sink() -> Self::ProtectedSink { + Wrap(Email::sink()) + } + } + let email = built_by_one_scalar::>("ada@example.com"); + assert_eq!( + email.risky_ref().0, + "ada@example.com", + "a protected derived newtype" + ); +} + +/// A target with a sink of its own is a scalar target once that sink is +/// marked as one a scalar satisfies. +#[test] +fn a_hand_written_sink_opts_in_by_its_marker() { + use vitaminc_aead::typed::{Never, TakesScalar}; + use vitaminc_aead::{DecodeError, EncryptRef, Sink}; + + #[derive(Debug, PartialEq)] + struct Flag(bool); + struct FlagSink; + impl Sink for FlagSink { + type Ok = Flag; + type Error = DecodeError; + type Seq = Never; + type Map = Never; + fn scalar(self, ty: Option, value: Physical<'_>) -> Result { + match (ty, value) { + (None, Physical::Text("yes")) => Ok(Flag(true)), + (None, Physical::Text("no")) => Ok(Flag(false)), + _ => Err(DecodeError::Expected("flag")), + } + } + fn typed_null(self, _: FixedType) -> Result { + Err(DecodeError::Expected("flag")) + } + fn seq(self, _: Option) -> Result, DecodeError> { + Err(DecodeError::Expected("flag")) + } + fn map(self, _: Option) -> Result, DecodeError> { + Err(DecodeError::Expected("flag")) + } + fn passthrough(self, _: &P) -> Result { + Err(DecodeError::Expected("flag")) + } + } + impl Decrypt for Flag { + type Sink = FlagSink; + fn sink() -> FlagSink { + FlagSink + } + } + impl TakesScalar for FlagSink {} + assert_eq!( + built_by_one_scalar::("no"), + Flag(false), + "a target whose own sink is marked" ); } diff --git a/packages/vitaminc-aead/tests/ui/scalar_target/derived_newtype_of_a_container.rs b/packages/vitaminc-aead/tests/ui/scalar_target/derived_newtype_of_a_container.rs new file mode 100644 index 000000000..aeef7ead7 --- /dev/null +++ b/packages/vitaminc-aead/tests/ui/scalar_target/derived_newtype_of_a_container.rs @@ -0,0 +1,13 @@ +//! A derived newtype reads what its inner type reads. Over a sequence it +//! needs a sequence, so one scalar does not build it. + +use vitaminc_aead::{Decrypt, ScalarTarget}; + +#[derive(Decrypt)] +struct Tags(Vec); + +fn opens_one_leaf() {} + +fn main() { + opens_one_leaf::(); +} diff --git a/packages/vitaminc-aead/tests/ui/scalar_target/derived_newtype_of_a_container.stderr b/packages/vitaminc-aead/tests/ui/scalar_target/derived_newtype_of_a_container.stderr new file mode 100644 index 000000000..d0881d12d --- /dev/null +++ b/packages/vitaminc-aead/tests/ui/scalar_target/derived_newtype_of_a_container.stderr @@ -0,0 +1,25 @@ +error[E0277]: one ciphertext holds one value, and this decrypt target is not built from one value + --> tests/ui/scalar_target/derived_newtype_of_a_container.rs:12:22 + | +12 | opens_one_leaf::(); + | ^^^^ this target cannot be decrypted from one ciphertext + | + = help: the trait `TakesScalar` is not implemented for `vitaminc_aead::typed::List` + = note: `vitaminc_aead::typed::List` is the target's sink, and it does not read a single scalar + = note: a single ciphertext decrypts into a scalar such as `String`, `i64` or `Vec`, an `Option` or a `Protected` of one, or a newtype that derives `Decrypt` over one + = note: to decrypt many values, decrypt a `Vec`, which opens each ciphertext into one element; to decrypt a sequence, a map or a struct that was encrypted as a tree, use `decrypt_tree` + = help: the following other types implement trait `TakesScalar`: + Optional + OwnedFrameSink + ProtectedOptional + ScalarProtected + ScalarSink + Wrap + Wrapped + = note: required for `Wrapped, __TagsDecryptWrap>` to implement `TakesScalar` + = note: required for `Tags` to implement `ScalarTarget` +note: required by a bound in `opens_one_leaf` + --> tests/ui/scalar_target/derived_newtype_of_a_container.rs:9:22 + | + 9 | fn opens_one_leaf() {} + | ^^^^^^^^^^^^ required by this bound in `opens_one_leaf` diff --git a/packages/vitaminc-aead/tests/ui/scalar_target/derived_struct_needs_a_map.stderr b/packages/vitaminc-aead/tests/ui/scalar_target/derived_struct_needs_a_map.stderr index 8a446fa62..c99f50987 100644 --- a/packages/vitaminc-aead/tests/ui/scalar_target/derived_struct_needs_a_map.stderr +++ b/packages/vitaminc-aead/tests/ui/scalar_target/derived_struct_needs_a_map.stderr @@ -1,27 +1,29 @@ -error[E0277]: the trait bound `Account: ScalarTarget` is not satisfied +error[E0277]: one ciphertext holds one value, and this decrypt target is not built from one value --> tests/ui/scalar_target/derived_struct_needs_a_map.rs:14:22 | 14 | opens_one_leaf::(); - | ^^^^^^^ unsatisfied trait bound + | ^^^^^^^ this target cannot be decrypted from one ciphertext | -help: the trait `FromScalar` is not implemented for `Account` - --> tests/ui/scalar_target/derived_struct_needs_a_map.rs:7:1 +help: the trait `TakesScalar` is not implemented for `__AccountDecryptSink` + --> tests/ui/scalar_target/derived_struct_needs_a_map.rs:6:10 | - 7 | struct Account { - | ^^^^^^^^^^^^^^ - = help: the following other types implement trait `FromScalar`: - Vec - [u8; N] - bool - f32 - f64 - i128 - i16 - i32 - and $N others + 6 | #[derive(Decrypt)] + | ^^^^^^^ + = note: `__AccountDecryptSink` is the target's sink, and it does not read a single scalar + = note: a single ciphertext decrypts into a scalar such as `String`, `i64` or `Vec`, an `Option` or a `Protected` of one, or a newtype that derives `Decrypt` over one + = note: to decrypt many values, decrypt a `Vec`, which opens each ciphertext into one element; to decrypt a sequence, a map or a struct that was encrypted as a tree, use `decrypt_tree` + = help: the following other types implement trait `TakesScalar`: + Optional + OwnedFrameSink + ProtectedOptional + ScalarProtected + ScalarSink + Wrap + Wrapped = note: required for `Account` to implement `ScalarTarget` note: required by a bound in `opens_one_leaf` --> tests/ui/scalar_target/derived_struct_needs_a_map.rs:11:22 | 11 | fn opens_one_leaf() {} | ^^^^^^^^^^^^ required by this bound in `opens_one_leaf` + = note: this error originates in the derive macro `Decrypt` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/packages/vitaminc-aead/tests/ui/scalar_target/hand_written_impl_for_a_derived_struct.rs b/packages/vitaminc-aead/tests/ui/scalar_target/hand_written_impl_for_a_derived_struct.rs new file mode 100644 index 000000000..b42c7e69d --- /dev/null +++ b/packages/vitaminc-aead/tests/ui/scalar_target/hand_written_impl_for_a_derived_struct.rs @@ -0,0 +1,14 @@ +//! No one implements `ScalarTarget` by hand. A derived struct's sink is +//! generated beside the struct, and it is not marked, because it reads a +//! map. An impl written for the struct is refused for that reason. + +use vitaminc_aead::{Decrypt, ScalarTarget}; + +#[derive(Decrypt)] +struct Account { + id: u64, +} + +impl ScalarTarget for Account {} + +fn main() {} diff --git a/packages/vitaminc-aead/tests/ui/scalar_target/hand_written_impl_for_a_derived_struct.stderr b/packages/vitaminc-aead/tests/ui/scalar_target/hand_written_impl_for_a_derived_struct.stderr new file mode 100644 index 000000000..387953dc3 --- /dev/null +++ b/packages/vitaminc-aead/tests/ui/scalar_target/hand_written_impl_for_a_derived_struct.stderr @@ -0,0 +1,32 @@ +error[E0277]: one ciphertext holds one value, and this decrypt target is not built from one value + --> tests/ui/scalar_target/hand_written_impl_for_a_derived_struct.rs:12:23 + | +12 | impl ScalarTarget for Account {} + | ^^^^^^^ this target cannot be decrypted from one ciphertext + | +help: the trait `TakesScalar` is not implemented for `__AccountDecryptSink` + --> tests/ui/scalar_target/hand_written_impl_for_a_derived_struct.rs:7:10 + | + 7 | #[derive(Decrypt)] + | ^^^^^^^ + = note: `__AccountDecryptSink` is the target's sink, and it does not read a single scalar + = note: a single ciphertext decrypts into a scalar such as `String`, `i64` or `Vec`, an `Option` or a `Protected` of one, or a newtype that derives `Decrypt` over one + = note: to decrypt many values, decrypt a `Vec`, which opens each ciphertext into one element; to decrypt a sequence, a map or a struct that was encrypted as a tree, use `decrypt_tree` + = help: the following other types implement trait `TakesScalar`: + Optional + OwnedFrameSink + ProtectedOptional + ScalarProtected + ScalarSink + Wrap + Wrapped + = note: required for `Account` to implement `typed::sealed::SinkTakesScalar` +note: required by a bound in `ScalarTarget` + --> src/typed.rs + | + | pub trait ScalarTarget: Decrypt + sealed::SinkTakesScalar {} + | ^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `ScalarTarget` + = note: `ScalarTarget` is a "sealed trait", because to implement it you also need to implement `vitaminc_aead::typed::sealed::SinkTakesScalar`, which is not accessible; this is usually done to force you to use one of the provided types that already implement it + = help: the following type implements the trait: + T + = note: this error originates in the derive macro `Decrypt` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/packages/vitaminc-aead/tests/ui/scalar_target/hand_written_impl_for_a_newtype.rs b/packages/vitaminc-aead/tests/ui/scalar_target/hand_written_impl_for_a_newtype.rs new file mode 100644 index 000000000..72d88c0f8 --- /dev/null +++ b/packages/vitaminc-aead/tests/ui/scalar_target/hand_written_impl_for_a_newtype.rs @@ -0,0 +1,12 @@ +//! No one implements `ScalarTarget` by hand. A target is one when its sink +//! is marked. A derived newtype's sink is this crate's, so an impl written +//! for a newtype of a sequence conflicts with the one impl there is. + +use vitaminc_aead::{Decrypt, ScalarTarget}; + +#[derive(Decrypt)] +struct Tags(Vec); + +impl ScalarTarget for Tags {} + +fn main() {} diff --git a/packages/vitaminc-aead/tests/ui/scalar_target/hand_written_impl_for_a_newtype.stderr b/packages/vitaminc-aead/tests/ui/scalar_target/hand_written_impl_for_a_newtype.stderr new file mode 100644 index 000000000..27eb7bfbf --- /dev/null +++ b/packages/vitaminc-aead/tests/ui/scalar_target/hand_written_impl_for_a_newtype.stderr @@ -0,0 +1,10 @@ +error[E0119]: conflicting implementations of trait `ScalarTarget` for type `Tags` + --> tests/ui/scalar_target/hand_written_impl_for_a_newtype.rs:10:1 + | +10 | impl ScalarTarget for Tags {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = note: conflicting implementation in crate `vitaminc_aead`: + - impl ScalarTarget for T + where T: Decrypt, ::Sink: TakesScalar, ::Sink: ?Sized; + = note: upstream crates may add a new impl of trait `vitaminc_aead::TakesScalar` for type `::Sink` in future versions diff --git a/packages/vitaminc-aead/tests/ui/scalar_target/map_needs_a_map.stderr b/packages/vitaminc-aead/tests/ui/scalar_target/map_needs_a_map.stderr index 5a312990d..46d8737fd 100644 --- a/packages/vitaminc-aead/tests/ui/scalar_target/map_needs_a_map.stderr +++ b/packages/vitaminc-aead/tests/ui/scalar_target/map_needs_a_map.stderr @@ -1,19 +1,21 @@ -error[E0277]: the trait bound `HashMap: ScalarTarget` is not satisfied +error[E0277]: one ciphertext holds one value, and this decrypt target is not built from one value --> tests/ui/scalar_target/map_needs_a_map.rs:11:22 | 11 | opens_one_leaf::>(); - | ^^^^^^^^^^^^^^^^^^^^ the trait `FromScalar` is not implemented for `HashMap` + | ^^^^^^^^^^^^^^^^^^^^ this target cannot be decrypted from one ciphertext | - = help: the following other types implement trait `FromScalar`: - Vec - [u8; N] - bool - f32 - f64 - i128 - i16 - i32 - and $N others + = help: the trait `TakesScalar` is not implemented for `Dict>` + = note: `Dict>` is the target's sink, and it does not read a single scalar + = note: a single ciphertext decrypts into a scalar such as `String`, `i64` or `Vec`, an `Option` or a `Protected` of one, or a newtype that derives `Decrypt` over one + = note: to decrypt many values, decrypt a `Vec`, which opens each ciphertext into one element; to decrypt a sequence, a map or a struct that was encrypted as a tree, use `decrypt_tree` + = help: the following other types implement trait `TakesScalar`: + Optional + OwnedFrameSink + ProtectedOptional + ScalarProtected + ScalarSink + Wrap + Wrapped = note: required for `HashMap` to implement `ScalarTarget` note: required by a bound in `opens_one_leaf` --> tests/ui/scalar_target/map_needs_a_map.rs:8:22 @@ -21,22 +23,24 @@ note: required by a bound in `opens_one_leaf` 8 | fn opens_one_leaf() {} | ^^^^^^^^^^^^ required by this bound in `opens_one_leaf` -error[E0277]: the trait bound `BTreeMap: ScalarTarget` is not satisfied +error[E0277]: one ciphertext holds one value, and this decrypt target is not built from one value --> tests/ui/scalar_target/map_needs_a_map.rs:12:22 | 12 | opens_one_leaf::>(); - | ^^^^^^^^^^^^^^^^^^^^^ the trait `FromScalar` is not implemented for `BTreeMap` + | ^^^^^^^^^^^^^^^^^^^^^ this target cannot be decrypted from one ciphertext | - = help: the following other types implement trait `FromScalar`: - Vec - [u8; N] - bool - f32 - f64 - i128 - i16 - i32 - and $N others + = help: the trait `TakesScalar` is not implemented for `Dict>` + = note: `Dict>` is the target's sink, and it does not read a single scalar + = note: a single ciphertext decrypts into a scalar such as `String`, `i64` or `Vec`, an `Option` or a `Protected` of one, or a newtype that derives `Decrypt` over one + = note: to decrypt many values, decrypt a `Vec`, which opens each ciphertext into one element; to decrypt a sequence, a map or a struct that was encrypted as a tree, use `decrypt_tree` + = help: the following other types implement trait `TakesScalar`: + Optional + OwnedFrameSink + ProtectedOptional + ScalarProtected + ScalarSink + Wrap + Wrapped = note: required for `BTreeMap` to implement `ScalarTarget` note: required by a bound in `opens_one_leaf` --> tests/ui/scalar_target/map_needs_a_map.rs:8:22 diff --git a/packages/vitaminc-aead/tests/ui/scalar_target/vec_needs_a_sequence.stderr b/packages/vitaminc-aead/tests/ui/scalar_target/vec_needs_a_sequence.stderr index e72844bf8..3beadeaf5 100644 --- a/packages/vitaminc-aead/tests/ui/scalar_target/vec_needs_a_sequence.stderr +++ b/packages/vitaminc-aead/tests/ui/scalar_target/vec_needs_a_sequence.stderr @@ -1,14 +1,21 @@ -error[E0277]: the trait bound `Vec: ScalarTarget` is not satisfied +error[E0277]: one ciphertext holds one value, and this decrypt target is not built from one value --> tests/ui/scalar_target/vec_needs_a_sequence.rs:11:22 | 11 | opens_one_leaf::>(); - | ^^^^^^^^^^^ the trait `FromScalar` is not implemented for `Vec` + | ^^^^^^^^^^^ this target cannot be decrypted from one ciphertext | -help: the trait `FromScalar` is implemented for `Vec` - --> src/typed.rs - | - | impl FromScalar for Vec { - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ + = help: the trait `TakesScalar` is not implemented for `vitaminc_aead::typed::List` + = note: `vitaminc_aead::typed::List` is the target's sink, and it does not read a single scalar + = note: a single ciphertext decrypts into a scalar such as `String`, `i64` or `Vec`, an `Option` or a `Protected` of one, or a newtype that derives `Decrypt` over one + = note: to decrypt many values, decrypt a `Vec`, which opens each ciphertext into one element; to decrypt a sequence, a map or a struct that was encrypted as a tree, use `decrypt_tree` + = help: the following other types implement trait `TakesScalar`: + Optional + OwnedFrameSink + ProtectedOptional + ScalarProtected + ScalarSink + Wrap + Wrapped = note: required for `Vec` to implement `ScalarTarget` note: required by a bound in `opens_one_leaf` --> tests/ui/scalar_target/vec_needs_a_sequence.rs:7:22 diff --git a/packages/vitaminc-aead/tests/ui/scalar_target/wrapped_container_is_not_a_scalar_target.stderr b/packages/vitaminc-aead/tests/ui/scalar_target/wrapped_container_is_not_a_scalar_target.stderr index c10ce0697..b102239f6 100644 --- a/packages/vitaminc-aead/tests/ui/scalar_target/wrapped_container_is_not_a_scalar_target.stderr +++ b/packages/vitaminc-aead/tests/ui/scalar_target/wrapped_container_is_not_a_scalar_target.stderr @@ -1,48 +1,74 @@ -error[E0277]: the trait bound `Option>: ScalarTarget` is not satisfied +error[E0277]: one ciphertext holds one value, and this decrypt target is not built from one value --> tests/ui/scalar_target/wrapped_container_is_not_a_scalar_target.rs:12:22 | 12 | opens_one_leaf::>>(); - | ^^^^^^^^^^^^^^^^ the trait `ScalarTarget` is not implemented for `Option>` + | ^^^^^^^^^^^^^^^^ this target cannot be decrypted from one ciphertext | -help: the trait `ScalarTarget` is implemented for `Option` - --> src/typed.rs - | - | impl ScalarTarget for Option {} - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + = help: the trait `TakesScalar` is not implemented for `vitaminc_aead::typed::List` + = note: `vitaminc_aead::typed::List` is the target's sink, and it does not read a single scalar + = note: a single ciphertext decrypts into a scalar such as `String`, `i64` or `Vec`, an `Option` or a `Protected` of one, or a newtype that derives `Decrypt` over one + = note: to decrypt many values, decrypt a `Vec`, which opens each ciphertext into one element; to decrypt a sequence, a map or a struct that was encrypted as a tree, use `decrypt_tree` + = help: the following other types implement trait `TakesScalar`: + Optional + OwnedFrameSink + ProtectedOptional + ScalarProtected + ScalarSink + Wrap + Wrapped + = note: required for `Optional>` to implement `TakesScalar` + = note: required for `Option>` to implement `ScalarTarget` note: required by a bound in `opens_one_leaf` --> tests/ui/scalar_target/wrapped_container_is_not_a_scalar_target.rs:9:22 | 9 | fn opens_one_leaf() {} | ^^^^^^^^^^^^ required by this bound in `opens_one_leaf` -error[E0277]: the trait bound `Protected>: ScalarTarget` is not satisfied +error[E0277]: one ciphertext holds one value, and this decrypt target is not built from one value --> tests/ui/scalar_target/wrapped_container_is_not_a_scalar_target.rs:13:22 | 13 | opens_one_leaf::>>(); - | ^^^^^^^^^^^^^^^^^^^ the trait `ScalarTarget` is not implemented for `Protected>` - | -help: the trait `ScalarTarget` is implemented for `Protected` - --> src/typed.rs + | ^^^^^^^^^^^^^^^^^^^ this target cannot be decrypted from one ciphertext | - | impl ScalarTarget for Protected {} - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + = help: the trait `TakesScalar` is not implemented for `ProtectedList` + = note: `ProtectedList` is the target's sink, and it does not read a single scalar + = note: a single ciphertext decrypts into a scalar such as `String`, `i64` or `Vec`, an `Option` or a `Protected` of one, or a newtype that derives `Decrypt` over one + = note: to decrypt many values, decrypt a `Vec`, which opens each ciphertext into one element; to decrypt a sequence, a map or a struct that was encrypted as a tree, use `decrypt_tree` + = help: the following other types implement trait `TakesScalar`: + Optional + OwnedFrameSink + ProtectedOptional + ScalarProtected + ScalarSink + Wrap + Wrapped + = note: required for `Protected>` to implement `ScalarTarget` note: required by a bound in `opens_one_leaf` --> tests/ui/scalar_target/wrapped_container_is_not_a_scalar_target.rs:9:22 | 9 | fn opens_one_leaf() {} | ^^^^^^^^^^^^ required by this bound in `opens_one_leaf` -error[E0277]: the trait bound `Protected>>: ScalarTarget` is not satisfied +error[E0277]: one ciphertext holds one value, and this decrypt target is not built from one value --> tests/ui/scalar_target/wrapped_container_is_not_a_scalar_target.rs:14:22 | 14 | opens_one_leaf::>>>(); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `ScalarTarget` is not implemented for `Protected>>` - | -help: the trait `ScalarTarget` is implemented for `Protected` - --> src/typed.rs + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ this target cannot be decrypted from one ciphertext | - | impl ScalarTarget for Protected {} - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + = help: the trait `TakesScalar` is not implemented for `ProtectedList` + = note: `ProtectedList` is the target's sink, and it does not read a single scalar + = note: a single ciphertext decrypts into a scalar such as `String`, `i64` or `Vec`, an `Option` or a `Protected` of one, or a newtype that derives `Decrypt` over one + = note: to decrypt many values, decrypt a `Vec`, which opens each ciphertext into one element; to decrypt a sequence, a map or a struct that was encrypted as a tree, use `decrypt_tree` + = help: the following other types implement trait `TakesScalar`: + Optional + OwnedFrameSink + ProtectedOptional + ScalarProtected + ScalarSink + Wrap + Wrapped + = note: required for `ProtectedOptional>` to implement `TakesScalar` + = note: required for `Protected>>` to implement `ScalarTarget` note: required by a bound in `opens_one_leaf` --> tests/ui/scalar_target/wrapped_container_is_not_a_scalar_target.rs:9:22 | From 5c2cbc4b1a4cdbb2261035229ae4b5c08dcd5d12 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sat, 28 Nov 2026 19:24:31 +1100 Subject: [PATCH 15/19] docs(stack-encrypt): rewrite the single-value prose in plain language The prose that this branch added was hard to read. Its reader is a developer who knows Rust, but who was not part of this work. The prose used the terms frame, kind, leaf, sink, and refusal without defining them. Many sentences had two ideas. Things were given a person's verb: a ciphertext "holds" a value, and a binding "knows" a kind. This commit rewrites that prose to follow the plain-language skill. The checker of the skill reports no "must fix" finding for the rewritten prose. Each doc comment, document, or changelog entry defines a term where it first uses that term. Each sentence has one idea. Lists replace long sentences that named many items. The rewrite covers these places: - the rustdoc and comments of `dynamic::value`, of the error enum, and of `ScalarTarget` and `TakesScalar` - the comments of the tests - the conformance contract and README - the two changelogs, the binding guide, and the ADR amendment Three message strings change. Each was written on this branch, with the same faults: - The help text of `Error::Value` says that one ciphertext "contains" one value. - The message of `Error::Value` for a value of another kind is "it does not convert exactly to the declared kind". The test that pins the message changes to match. - The compile error for a target that is not a scalar target says "`T` cannot be decrypted from one ciphertext". Each note of that error is one sentence. The compile-fail snapshots are recorded again. The conformance contract writes "issue #2010" where it wrote "#2010". The README has its sentence about the single-value cases in a paragraph of its own. No error code, reason, or stored byte changes. --- conformance/stack-encrypt/README.md | 44 +- conformance/stack-encrypt/coverage.md | 2 +- .../stack-encrypt/single-value-contract.md | 288 +++++++----- languages/golang/encrypt/guest/src/status.rs | 2 +- .../packages/recipher-js/crate/src/cipher.rs | 28 +- packages/stack-encrypt/CHANGELOG.md | 160 +++---- .../adr/0012-owned-record-declarations.md | 17 +- .../docs/language-integration.md | 89 ++-- packages/stack-encrypt/src/dynamic/mod.rs | 25 +- packages/stack-encrypt/src/dynamic/value.rs | 413 ++++++++++-------- packages/stack-encrypt/src/lib.rs | 28 +- packages/stack-encrypt/src/refusal.rs | 80 ++-- packages/stack-encrypt/src/scalar.rs | 59 +-- .../stack-encrypt/tests/common/conformance.rs | 7 +- packages/stack-encrypt/tests/common/leaves.rs | 65 +-- packages/stack-encrypt/tests/scalar.rs | 7 +- packages/stack-encrypt/tests/single_value.rs | 164 +++---- .../tests/single_value_conformance.rs | 97 ++-- .../tests/ui/pass/scalar_decrypt_targets.rs | 27 +- .../ui/scalar_decrypt_into_a_container.rs | 10 +- .../ui/scalar_decrypt_into_a_container.stderr | 77 ++-- packages/vitaminc-aead/CHANGELOG.md | 26 +- packages/vitaminc-aead/src/frame/owned.rs | 4 +- packages/vitaminc-aead/src/typed.rs | 178 ++++---- packages/vitaminc-aead/tests/scalar_target.rs | 58 +-- .../derived_newtype_of_a_container.rs | 4 +- .../derived_newtype_of_a_container.stderr | 11 +- .../derived_struct_needs_a_map.rs | 4 +- .../derived_struct_needs_a_map.stderr | 11 +- .../hand_written_impl_for_a_derived_struct.rs | 7 +- ...d_written_impl_for_a_derived_struct.stderr | 19 +- .../hand_written_impl_for_a_newtype.rs | 7 +- .../hand_written_impl_for_a_newtype.stderr | 4 +- .../tests/ui/scalar_target/map_needs_a_map.rs | 4 +- .../ui/scalar_target/map_needs_a_map.stderr | 22 +- .../ui/scalar_target/vec_needs_a_sequence.rs | 6 +- .../scalar_target/vec_needs_a_sequence.stderr | 11 +- ...rapped_container_is_not_a_scalar_target.rs | 8 +- ...ed_container_is_not_a_scalar_target.stderr | 33 +- 39 files changed, 1192 insertions(+), 914 deletions(-) diff --git a/conformance/stack-encrypt/README.md b/conformance/stack-encrypt/README.md index f6d60731c..300bb29a6 100644 --- a/conformance/stack-encrypt/README.md +++ b/conformance/stack-encrypt/README.md @@ -44,8 +44,8 @@ these rules. | `record-values-v1.cases.json` | cases | `tests/value_conformance.rs` | `value_conformance_test.go` | | `record-query-refusals-v1.cases.json` | cases | `tests/query_refusal_conformance.rs` | `query_refusal_conformance_test.go` | | `record-raw-frames-v1.cases.json` | cases | `tests/raw_frame_conformance.rs` | `raw_frame_conformance_test.go` | -| `single-value-v1.cases.json` | cases | `tests/single_value_conformance.rs` | — (pending, #2010) | -| `single-value-v1.expected.rust-native.json` | expected | `tests/single_value_conformance.rs` (writes it) | — (pending, #2010) | +| `single-value-v1.cases.json` | cases | `tests/single_value_conformance.rs` | — (pending, issue #2010) | +| `single-value-v1.expected.rust-native.json` | expected | `tests/single_value_conformance.rs` (writes it) | — (pending, issue #2010) | | `artifact-exchange-v1.cases.json` | cases | `tests/exchange_conformance.rs`, run by `scripts/stack-exchange-conformance.mjs` | `exchange_conformance_test.go`, run by `scripts/stack-exchange-conformance.mjs` | | `eql-json-v1.cases.json` | cases | `tests/json_operators.rs`; EQL's `tests/encryption/tests/json_tree_data_plan.rs` | `json_conformance_test.go` | | `eql-json-v1.enrollment.json` | enrollment | `scripts/stack-eql-conformance.mjs` runs the tests it names | `scripts/stack-eql-conformance.mjs` runs the tests it names | @@ -88,11 +88,13 @@ The same task runs the shared declaration acceptance/rejection corpus in both languages, with native observations of normalization. It also runs the shared runtime, read, context, value-boundary, query-refusal and raw-frame cases, and enrolls the existing value-kind, context-field and query-operator -fixtures described below. It runs the single-value cases in native Rust -only: their Go runner is pending. It ends with the fresh artifact exchange in both +fixtures described below. It ends with the fresh artifact exchange in both directions (`test:conformance:exchange`, which also needs the deterministic EQL guest). Set no fixture-update variables when checking conformance. +The task runs the single-value cases in native Rust only, because the Go +runner of that profile is pending. + The Rust runner is `packages/stack-encrypt/tests/conformance.rs`; the Go runner is `languages/golang/encrypt/conformance_test.go`. Go calls the record interface used by generated code. Testing public SDK declarations is a separate layer. @@ -183,19 +185,27 @@ six. ## Single values The [single-value contract](single-value-contract.md) defines -`single-value-v1` in `v1/single-value-v1.cases.json`: one value encrypted into -one ciphertext through the engine's run-time interface, and decrypted from -one. The cases give a value, the kind declared for it and a context. They -cover every scalar kind, the exact conversions a declared kind makes, JSON -documents, the one stored form a string and a document share, batches of -single-value calls merged into one key request, and -the refusals of an array, an object, a passthrough, a null, `undefined` and a -value of another kind. -`v1/single-value-v1.expected.rust-native.json` freezes each input's frame, the -plaintext each leaf is sealed with, and a ciphertext every runner must open. -The native runner is `single_value_conformance` in the Rust crate, which -`test:conformance` runs. It also holds the run-time interface to the typed -one. The Go runner comes with the Go SDK's single-value calls (#2010). +`single-value-v1` in `v1/single-value-v1.cases.json`, and the terms used here. +The profile encrypts one value as one ciphertext through the run-time +interface of the engine, and decrypts it again. Each case gives a value, the +kind declared for it, and a context. The cases cover: + +- every scalar kind +- the exact conversions that a declared kind makes +- JSON documents +- the one stored form of a string and a document +- batches of single-value calls merged into one key request +- the refusals of an array, an object, a passthrough, a null, `undefined`, + and a value of another kind + +`v1/single-value-v1.expected.rust-native.json` freezes three things for each +case: the frame of the input, the plaintext that the leaf is sealed with, and +a ciphertext that every runner must open. + +The native runner is `single_value_conformance` in the Rust crate. +`test:conformance` runs it. The runner also compares the run-time interface +with the typed interface. The Go runner is pending. The Go runner will be +written with the single-value calls of the Go SDK (issue #2010). ## `record-reads-v1` contract diff --git a/conformance/stack-encrypt/coverage.md b/conformance/stack-encrypt/coverage.md index 902855454..90b570655 100644 --- a/conformance/stack-encrypt/coverage.md +++ b/conformance/stack-encrypt/coverage.md @@ -7,7 +7,7 @@ Paths are relative to the repository root. New profile cases run from `v1/`. | Requirement | Existing evidence | Remaining work | |---|---|---| | Scalar value widths and lossless transport | Initial scalar cases, [value-kind requirements](fixture-contract.md#value-kind-requirements) and the [value boundary profile](values-contract.md) (`v1/record-values-v1.cases.json`: every kind's edges, float specials, bytes, decimal and timestamp precision, sealed/SQL nulls per kind, exact write conversions between widths, cross-kind write refusals, `undefined` on a typed field, Go host conversions); every positive case written fresh by each runner and opened by the other ([exchange profile](exchange-contract.md)) | Python/TS mappings; dates before year 1 and the timestamp range ends | -| Owned opaque ciphertext and storage envelope | `packages/stack-encrypt/tests/scalar.rs`, `frozen_bytes.rs`; initial cross-opening cases; `owned_records.rs`, which tests the owned record derives: passthrough fields are moved, sealed fields are wiped, nested and renamed fields work, a record can store its context, and a column makes one batch. Whole-value blobs: `packages/stack-encrypt/tests/opaque_blob.rs` (round trips, the bytes leaf shared with the structural writer, a pinned storage blob and a pinned sealed ciphertext, refusals by class after authentication, source wipe) and `languages/golang/encrypt/gensupport/gensupport_internal_test.go::TestOpaqueReadsARustWrittenBlob`; the storage profile itself is pinned upstream by Vitamin C's golden corpus; fresh sealed blobs exchanged in both directions by the [exchange profile](exchange-contract.md). One value of a kind known only at run time as one ciphertext: the [single-value profile](single-value-contract.md) (`v1/single-value-v1.cases.json`: every scalar kind, exact conversions, JSON documents, batches and the refusals, with the plaintext of each leaf and a frozen ciphertext), run by native Rust, and `packages/stack-encrypt/tests/single_value.rs`, which holds the run-time interface to the typed one. JSON documents as one ciphertext: `packages/stack-encrypt/tests/json_plaintext.rs` (round trips, the text leaf shared with a sealed string, refusals after authentication, a generated-document property) and, as the EQL type `Json`, `packages/eql/tests/encryption/tests/v4_types.rs` with the Go-sealed rows `v4_json_rows.json` and the frozen `stored_v4_json_rows_v1.json`, opened in Rust and Go | Encoded targets; supported version matrix; the Go runner of the single-value profile (#2010), and Python and TypeScript runners | +| Owned opaque ciphertext and storage envelope | `packages/stack-encrypt/tests/scalar.rs`, `frozen_bytes.rs`; initial cross-opening cases; `owned_records.rs`, which tests the owned record derives: passthrough fields are moved, sealed fields are wiped, nested and renamed fields work, a record can store its context, and a column makes one batch. Whole-value blobs: `packages/stack-encrypt/tests/opaque_blob.rs` (round trips, the bytes leaf shared with the structural writer, a pinned storage blob and a pinned sealed ciphertext, refusals by class after authentication, source wipe) and `languages/golang/encrypt/gensupport/gensupport_internal_test.go::TestOpaqueReadsARustWrittenBlob`; the storage profile itself is pinned upstream by Vitamin C's golden corpus; fresh sealed blobs exchanged in both directions by the [exchange profile](exchange-contract.md). One value of a kind known only at run time, as one ciphertext: the [single-value profile](single-value-contract.md), run by native Rust (`v1/single-value-v1.cases.json`: every scalar kind, exact conversions, JSON documents, batches, and the refusals, with the plaintext of each leaf and a frozen ciphertext). `packages/stack-encrypt/tests/single_value.rs` compares the run-time interface with the typed interface. JSON documents as one ciphertext: `packages/stack-encrypt/tests/json_plaintext.rs` (round trips, the text leaf shared with a sealed string, refusals after authentication, a generated-document property) and, as the EQL type `Json`, `packages/eql/tests/encryption/tests/v4_types.rs` with the Go-sealed rows `v4_json_rows.json` and the frozen `stored_v4_json_rows_v1.json`, opened in Rust and Go | Encoded targets; supported version matrix; the Go runner of the single-value profile (issue #2010), and Python and TypeScript runners | | Record declaration and lowering | [Declaration grammar](declaration-grammar.md); `v1/record-declarations-v1.cases.json` shared by native Rust and Go; native normalization observations; existing record lowering suites; `packages/stack-encrypt/tests/owned_equivalence.rs`, which seals one mixed, searchable record three ways: through a hand-written owned target, the owned derive, and the data plan. All three use one provider that records its requests. The test compares the descriptors and the term bytes, and checks that each way decrypts the records of the others | EQL-resolver profile; SDK-to-declaration mappings; runtime source/read shapes | | Context binding and composition | `packages/stack-encrypt/tests/target.rs`, `descriptor.rs`, `record_lowering.rs`; `languages/golang/encrypt/context_field_test.go`; initial wrong-context cases | Shared composition vectors; expected-context and required-input matrix | | Query terms and diagnostics | [Query-operator requirements](fixture-contract.md#query-operator-requirements), existing Rust/Go runners, initial equality/query-error cases and the [query-refusal profile](query-refusals-contract.md) (`v1/record-query-refusals-v1.cases.json`: every scalar operator against every field capability that does not answer it, the listed range shapes, other-kind values and nulls, by class, with the typed query's refusal stage) | JSON operator and EQL target refusals | diff --git a/conformance/stack-encrypt/single-value-contract.md b/conformance/stack-encrypt/single-value-contract.md index c92de3d4a..7cab722de 100644 --- a/conformance/stack-encrypt/single-value-contract.md +++ b/conformance/stack-encrypt/single-value-contract.md @@ -1,46 +1,65 @@ # Single-value profile -`single-value-v1` describes the cases in `v1/single-value-v1.cases.json`: one -value encrypted into one ciphertext, and decrypted from one, through the -engine's run-time interface (`stack_encrypt::dynamic::value`). It is an -experimental test contract. - -The run-time interface takes a value as a transport frame, with the kind the -caller declares for it. It must return the ciphertext the typed Rust interface -(`keyset.encrypt`) returns for the same value, so that a value one language -encrypts, every other language decrypts. +`single-value-v1` is the conformance profile for one value encrypted as one +ciphertext. The profile describes the cases in +`v1/single-value-v1.cases.json`. The cases run through the run-time interface +of the engine, `stack_encrypt::dynamic::value`. The profile is an experimental +test contract. + +The run-time interface takes a value as a frame, with a declared kind. The +typed Rust interface must decrypt the result. The run-time interface must +decrypt a ciphertext that the typed Rust interface made. So every language +can decrypt a value that one language encrypted. + +## Terms + +- A frame is one value written as bytes, in the format that the engine reads. +- A kind is the name of what a value is, such as `string` or `uint64`. The + declared kind is the kind that the caller says the value has. +- A leaf is the encrypted form of one scalar. A ciphertext of one value + contains one leaf. +- To seal a value is to encrypt and authenticate it. To open a ciphertext is + to decrypt it and check it. +- A passthrough is a value that a record stores without encrypting it. +- A refusal is an error that the engine returns for a value it does not + accept. +- The typed interface is the Rust API for a value of a Rust type: + `keyset.encrypt` and `keyset.decrypt`. + +## Runners The Rust runner is `packages/stack-encrypt/tests/single_value_conformance.rs`. -The Go runner is pending: it comes with the Go SDK's single-value calls -(#2010). Python and TypeScript runners are pending too. A missing runner is not -a passing result. +The Go runner is pending. The Go runner will be written with the single-value +calls of the Go SDK (issue #2010). The Python and TypeScript runners are +pending too. A missing runner is not a passing result. ## Cases -The file has a public deterministic-provider `seed`, a list of `cases` and a -list of `batches`. Each case has: +The file has three parts: a public `seed` for the deterministic key provider, +a list of `cases`, and a list of `batches`. Each case has these keys: | Key | Meaning | |---|---| -| `id` | The case's name | +| `id` | The name of the case | | `kind` | The name of the declared kind, or empty for no declared kind | -| `context` | The context's parts, or an empty list for the empty context | -| `input` | The value, in the `{type, text}` form the [value profile](values-contract.md#cases) defines | -| `stored` | The value the ciphertext holds, where it is not the input | -| `opens_as` | Kinds the ciphertext must open as, beside the declared one, each with the `value` it opens to | -| `refused_as` | Kinds the ciphertext must refuse to open as | -| `expected_error` | For a refused case, the refusal's `code` and `reason` | +| `context` | The parts of the context, or an empty list for the empty context | +| `input` | The value, in the `{type, text}` form that the [value profile](values-contract.md#cases) defines | +| `stored` | The value in the ciphertext, where it differs from the input | +| `opens_as` | Kinds that the ciphertext must open as, other than the declared kind. Each entry has the `value` that the ciphertext opens to. | +| `refused_as` | Kinds that the ciphertext must not open as | +| `expected_error` | For a refused case, the `code` and `reason` of the refusal | -A context of two parts is the pair of them: `["conformance", "value"]` is the -Rust context `("conformance", "value")`. A runner calls the form with no -context for an empty list, and the form with a context otherwise. +A context of two parts is a pair. For example, `["conformance", "value"]` is +the Rust context `("conformance", "value")`. For an empty list, a runner calls +the form with no context. For any other list, a runner calls the form with a +context. -This profile adds two input types to the value profile's: +This profile adds two input types to those of the value profile: | `type` | `text` | |---|---| -| `uuid` | The UUID in lowercase hex, in groups of 8, 4, 4, 4 and 12 digits | -| `shape` | The name of a value that `{type, text}` cannot spell (below) | +| `uuid` | The UUID in lowercase hex, in groups of 8, 4, 4, 4, and 12 digits | +| `shape` | The name of a value that `{type, text}` cannot spell. The next table lists the names. | | Shape | The value | |---|---| @@ -50,127 +69,160 @@ This profile adds two input types to the value profile's: | `passthrough` | A passthrough of the string `clear` | | `typed_null` | A typed null of `int64` | -A runner that cannot build a shape in its host language sends the frame the -artifact file records for the case. +Some host languages cannot build every shape. A runner in such a language +sends the frame that the artifact file records for the case. ## Artifacts -`v1/single-value-v1.expected.rust-native.json` holds one entry for each case, -written by the Rust runner: +The Rust runner writes `v1/single-value-v1.expected.rust-native.json`. The +file has one entry for each case: -- `frame`: the input's transport frame, in hex. Every case has one. -- `leaf`: the plaintext the ciphertext's leaf is sealed with, in hex: the - leaf's type tag and its payload. Only an accepted case has one. +- `frame`: the frame of the input, in hex. Every case has one. +- `leaf`: the plaintext that the leaf of the ciphertext is sealed with, in + hex. That plaintext is the type tag of the leaf and its payload. Only an + accepted case has one. - `ciphertext`: a ciphertext of the value, in hex. Only an accepted case has - one. The typed Rust interface made it, where a Rust type spells the stored - value. No Rust type spells a lone `uint8`, so the run-time interface made - that one. + one. + +The typed Rust interface made each `ciphertext` where a Rust type spells the +stored value. No Rust type spells a lone `uint8`, so the run-time interface +made the ciphertext of that case. -Ciphertext bytes are never compared whole. Each sealed leaf carries a random +A runner never compares whole ciphertexts. Each sealed leaf has a random AES-GCM nonce, so two ciphertexts of one value differ. A runner compares the -parts of a ciphertext that the nonce does not change: the keyset, the data -key's IV and tag, the ciphertext's length, and the plaintext of the leaf. -The deterministic provider derives a data key from the seed, the context and -a counter. So a runner makes a fresh provider for each ciphertext it compares. +parts of a ciphertext that the nonce does not change: + +- the keyset +- the IV and tag of the data key +- the length of the ciphertext +- the plaintext of the leaf + +The deterministic provider derives a data key from the seed, the context, and +a counter. So a runner makes a new provider for each ciphertext it compares. Regenerate the artifacts deliberately, with `STACK_ENCRYPT_UPDATE_FIXTURES=1` -and the native runner, and review the case and artifact diff together. An -update keeps the frozen ciphertext of a case whose frame and leaf have not -changed, and checks it as any run does. So a ciphertext stays frozen from one -update to the next, and the diff shows only the cases that changed. +and the native runner. Review the diff of the cases and the diff of the +artifacts together. + +An update keeps the frozen ciphertext of a case whose frame and leaf have not +changed. The update checks that ciphertext as any run does. So a ciphertext +stays frozen from one update to the next, and the diff shows only the cases +that changed. ## Required behavior -For a case with no `expected_error`: +### An accepted case + +A case with no `expected_error` is an accepted case. For each one: -1. The input's frame equals the frozen `frame`. -2. The run-time encrypt accepts the value under the declared kind and the - context. The plaintext of the leaf it seals equals the frozen `leaf`. -3. The fresh ciphertext and the frozen `ciphertext` agree in every part that +1. The frame of the input equals the frozen `frame`. +2. The run-time encrypt accepts the value with the declared kind and the + context. The plaintext of the leaf that it seals equals the frozen `leaf`. +3. The new ciphertext and the frozen `ciphertext` agree in every part that the nonce does not change. -4. Each of the two ciphertexts opens, under the same context: - - with no declared kind, to `stored` (or to the input, where the case has - no `stored`); - - with the declared kind, to the same value. Under `json` it opens to the - stored JSON text in a bytes leaf. -5. Each ciphertext opens as each kind in `opens_as`, to that entry's `value`. -6. Each ciphertext is refused when opened as a kind in `refused_as`. The - refusal's code is `stack_encrypt::opened_type`, and its `expected` field is - the kind's name. The refusal never says what the value opened as. -7. Each ciphertext is refused under the context `["conformance", "wrong"]`. - The deterministic provider refuses the key request as forbidden, which - models ZeroKMS. Other providers may report a wrong context differently. - -Native Rust also checks that the typed interface seals the same parts for the -stored value, and that the typed decrypt opens both ciphertexts. - -A case with `stored` is a conversion. A number of another width or kind is -sealed as the declared kind's value when the conversion is exact, by the rules -a record's typed field uses. A document under `json` is sealed as its compact -JSON text, in a text leaf. - -`json` is a declared kind, and not a stored one. A `string` and a document -share one stored form, a text leaf, so a kind check cannot tell them apart. -Three cases pin what follows from that: +4. Each of the two ciphertexts opens under the same context, with no declared + kind. The result is `stored`, or the input where the case has no `stored`. +5. Each of the two ciphertexts opens under the same context, with the + declared kind, to the same value. With the kind `json`, the result is the + stored JSON text as a bytes value. +6. Each ciphertext opens as each kind in `opens_as`, to the `value` of that + entry. +7. Each ciphertext is refused when it is opened as a kind in `refused_as`. + The code of the refusal is `stack_encrypt::opened_type`. The `expected` + field of the refusal is the name of the kind. The refusal never says what + the value opened as. +8. Each ciphertext is refused under the context `["conformance", "wrong"]`. + The deterministic provider refuses the key request as forbidden, as + ZeroKMS does. Other providers can report a wrong context differently. + +Native Rust also checks two things. The typed interface seals the same parts +for the stored value. The typed decrypt opens both ciphertexts. + +### Conversions + +A case with `stored` is a conversion. The engine seals a number of another +width or kind as the value of the declared kind, when the conversion is exact. +The conversion rules are the ones that a typed field of a record uses. The +engine seals a document with the kind `json` as its compact JSON text. + +### Strings and JSON documents + +`json` is a declared kind and not a stored kind. A `string` and a document +have one stored form: text. So a check of the stored kind cannot distinguish +them. Three groups of cases pin the consequences: - `json-given-string`: a sealed document opens as `string`, to the JSON text that was sealed. - `string-json-number-text` and `string-json-spaced-text`: a sealed string whose text is a JSON document opens as `json`. Decrypt as `json` checks that - the text parses, and returns the document as the engine writes it, in a - bytes leaf. So `{ "b" : [ 1 , null ], "a" : true }` comes back as + the text parses. Decrypt then returns the document as the engine writes it, + as a bytes value. So `{ "b" : [ 1 , null ], "a" : true }` comes back as `{"a":true,"b":[1,null]}`. - `string-not-json-text`: a sealed string whose text is not a JSON document is refused as `json`. -For a case with `expected_error`, the run-time encrypt refuses the value -before any key request, with the diagnostic `code` and `reason`. The code of -every such refusal is `stack_encrypt::dynamic_value`: a single value has its -own refusal, with no record, plan or field in it. The cases cover: +### A refused case -- an array, an object, a passthrough, a plain null and a typed null, each with - no declared kind and with one: the reason says what was found (`array`, - `object`, `passthrough`, `null`); -- JavaScript's `undefined`, with a declared kind and with none (`undefined`); -- a value of another kind that does not convert exactly (`field_type`); -- text that is not a JSON document, under `json` (`json_syntax`, - `json_duplicate_key`, `json_integer_range`). +A case with `expected_error` is a refused case. The run-time encrypt refuses +the value before any key request, with the diagnostic `code` and `reason` of +the case. The code of every such refusal is `stack_encrypt::dynamic_value`. A +single value has its own refusal, with no record, plan, or field in it. -`undefined` is refused whatever kind is declared. It is most often a property -name spelt wrong, and no typed call could read it back. A host with no -`undefined` sends the frame the artifact file records for those cases, or -checks their shape and skips them. +The cases cover these values: + +- An array, an object, a passthrough, a plain null, and a typed null. Each is + tested with no declared kind and with one. The reason names what was found: + `array`, `object`, `passthrough`, or `null`. +- JavaScript's `undefined`, with a declared kind and with none. The reason is + `undefined`. +- A value of another kind that does not convert exactly. The reason is + `field_type`. +- Text that is not a JSON document, with the kind `json`. The reason is + `json_syntax`, `json_duplicate_key`, or `json_integer_range`. + +The engine refuses `undefined` with any declared kind. An `undefined` value is +most often a misspelt property name. No typed call could read it back. + +A host language with no `undefined` has two options for those cases. The +runner can send the frame that the artifact file records. Or the runner can +check that the cases are well formed, and skip them. ## Batches -The run-time interface has no batch call. A binding encrypts many values by -making one single-value call for each value, and merging the pending calls -into one key request. In Rust the merge is `Pending::all`. It decrypts many -ciphertexts the same way. Each call has its own declared kind, so one batch -can hold values of different kinds. +The run-time interface has no batch call. To encrypt many values, a binding +makes one single-value call for each value. The binding then merges the +pending calls into one key request. In Rust, `Pending::all` merges the calls. +A binding decrypts many ciphertexts the same way. + +Each call has its own declared kind, so one batch can contain values of +different kinds. Each entry of `batches` has three keys: + +- `inputs`: a list of values +- `kinds`: the declared kind for each input, or empty for none +- `context`: one context for all the inputs + +A runner seals and opens each entry as a binding does: -Each entry of `batches` has a list of `inputs`, a list of `kinds` with the -kind declared for each input (empty for none), and a `context` for all of -them. A runner seals and opens each entry as a binding does. An accepted -batch seals in one key request and opens in one, and the values come back in -the order of the inputs: `stored` where the batch has one, the inputs -otherwise. An empty batch makes no key request. In a batch with -`expected_error`, the single-value call refuses one of the values with that -`code` and `reason`, and the batch makes no key request. +- An accepted batch seals in one key request and opens in one key request. + The values come back in the order of the inputs. The expected values are + `stored` where the batch has one, and the inputs otherwise. +- An empty batch makes no key request. +- In a batch with `expected_error`, the single-value call refuses one of the + values with that `code` and `reason`. The batch then makes no key request. -The key-request counts are native observations: the Rust runner counts them -on its key source. +The counts of key requests are native observations: the Rust runner counts +them on its key source. ## Scope and remaining work -The profile covers every scalar kind, the exact conversions, JSON documents -and the refusals of the run-time encrypt. It does not cover: - -- a ciphertext that holds a null, which only the tree interface seals; -- a scalar of a logical type the engine does not know, which `{type, text}` - cannot spell. With no declared kind the engine seals it as it arrived, and - `packages/stack-encrypt/tests/single_value.rs` pins that natively; -- keyset confinement on decrypt, which - `packages/stack-encrypt/tests/single_value.rs` covers natively; -- fresh ciphertexts exchanged between languages. That comes with the first - second runner. +The profile covers every scalar kind, the exact conversions, JSON documents, +and the refusals of the run-time encrypt. The profile does not cover these: + +- A ciphertext of a null. Only the tree interface seals one. +- A scalar of a logical type that the engine does not define. The + `{type, text}` form cannot spell one. With no declared kind, the engine + seals such a scalar as it arrived. + `packages/stack-encrypt/tests/single_value.rs` tests that natively. +- Decrypt limited to one keyset. + `packages/stack-encrypt/tests/single_value.rs` tests that natively. +- New ciphertexts exchanged between languages. That needs a second runner. diff --git a/languages/golang/encrypt/guest/src/status.rs b/languages/golang/encrypt/guest/src/status.rs index eea4f922a..a2b784127 100644 --- a/languages/golang/encrypt/guest/src/status.rs +++ b/languages/golang/encrypt/guest/src/status.rs @@ -189,7 +189,7 @@ pub fn status_for_dynamic(error: &stack_encrypt::dynamic::Error) -> u32 { | Error::Plan { .. } | Error::UntypedIndex { .. } | Error::Source { .. } - // One value that a single ciphertext cannot hold: an array, an + // One value that a single ciphertext cannot contain: an array, an // object, a null, or a value of another kind than the one declared. | Error::Value { .. } | Error::Record { .. } diff --git a/languages/typescript/packages/recipher-js/crate/src/cipher.rs b/languages/typescript/packages/recipher-js/crate/src/cipher.rs index af8380aee..30cd68af6 100644 --- a/languages/typescript/packages/recipher-js/crate/src/cipher.rs +++ b/languages/typescript/packages/recipher-js/crate/src/cipher.rs @@ -300,8 +300,7 @@ pub(crate) async fn open_in( }) } -/// Returns `value`, if it is one string. This build encrypts a string -/// only. +/// Returns `value` when it is one string. This build only encrypts strings. /// /// # Errors /// @@ -314,14 +313,13 @@ pub(crate) fn a_string(value: OwnedFrame) -> Outcome { } } -/// Encrypts strings under `keyset`, through the engine's run-time -/// single-value encrypt. Each value becomes one ciphertext with its own -/// data key. Rust's `keyset.encrypt(value)` returns the same ciphertext for -/// the same value. The calls are merged, so all the values use one key -/// request, however many there are. +/// Encrypts strings under `keyset`, with the engine's +/// `dynamic::value::encrypt`. Each value becomes one ciphertext with its own +/// data key. Rust's `keyset.decrypt::` decrypts each ciphertext. The +/// function merges the calls, so all the values use one key request. /// -/// The engine checks each value again: a value that is not one string is -/// refused with the engine's own error, before any key request. +/// The engine checks each value again. The engine refuses a value that is +/// not one string with its own error, before any key request. pub(crate) async fn seal( keyset: &KeysetCipher<'_, K>, values: Vec, @@ -334,8 +332,8 @@ where .map(|value| value::encrypt(keyset, value.frame(), Some(ValueKind::String))) .collect::, _>>() .map_err(|error| RecipherErrorFields::engine(&error))?; - // The engine has read every value. Dropping the frames wipes them, so - // no value waits in a frame for the key request. + // The engine has read every value. `drop` wipes the frames, so no value + // stays in a frame during the key request. drop(values); Pending::all(keyset, calls) .await @@ -346,10 +344,10 @@ where /// The function makes one key request for each keyset the ciphertexts /// were made under. /// -/// Each value comes back as it was encrypted, in a frame. A call has no -/// kind to check at run time: the type of a `Ciphertext` is known to -/// TypeScript alone. So this is the engine's typed decrypt into frames, -/// which checks no kind. +/// Each value comes back in a frame, as it was encrypted. A call has no +/// kind to check at run time, because the type of a `Ciphertext` exists +/// only in TypeScript. So this function uses the engine's typed decrypt +/// into frames. That decrypt checks no kind. pub(crate) async fn unseal<'c, K>( cipher: impl Into>, sealed: Vec, diff --git a/packages/stack-encrypt/CHANGELOG.md b/packages/stack-encrypt/CHANGELOG.md index 8542e1460..64c000068 100644 --- a/packages/stack-encrypt/CHANGELOG.md +++ b/packages/stack-encrypt/CHANGELOG.md @@ -10,60 +10,66 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added - **Encrypt and decrypt one value whose type is known only at run time** - (#2009). `dynamic::value` does for a value in a frame what - `keyset.encrypt` and `keyset.decrypt` do for a value of a Rust type. A - language SDK holds a value as a frame, and knows the value's kind only - when the code runs. + (#2009). `dynamic::value` has two functions for a value in a frame. The + two functions are the run-time counterparts of the typed `keyset.encrypt` + and `keyset.decrypt`. A frame is one value written as bytes. A language + SDK has each value as a frame. The kind of the value is only known when + the code runs. - `dynamic::value::encrypt(&keyset, frame, kind)` takes a borrowed - `Frame` and an optional declared `ValueKind`. It returns the - `Ciphertext` that `keyset.encrypt` returns for the same value: the same - leaf, under the same key request and the same context. So - `keyset.decrypt::` opens it, and each language opens what another - wrote. - - `dynamic::value::decrypt(cipher, ciphertext, kind)` opens a ciphertext - into an `OwnedFrame` that holds one scalar. Pass `&keyset` to open only - that keyset's ciphertexts, or `&cipher` to open a ciphertext of any - keyset. - - Each has a form with a context: `encrypt_with_context` and + `Frame` and an optional declared `ValueKind`. The call returns a + `Ciphertext` that `keyset.decrypt::` decrypts. So each language can + decrypt what another language encrypted. + - `dynamic::value::decrypt(cipher, ciphertext, kind)` decrypts a + ciphertext into an `OwnedFrame` of one scalar. Pass `&keyset` to + decrypt only the ciphertexts of that keyset. Pass `&cipher` to decrypt + a ciphertext of any keyset. + - Each function has a form with a context: `encrypt_with_context` and `decrypt_with_context`. - - There is no batch call. Each call returns a `Pending`, which has not - sent its key request. To encrypt or decrypt many values, make one call - for each value and merge them with `Pending::all`: awaiting the merged - call makes one key request, and the results come back in order. Each - value keeps its own declared kind, so one batch can hold values of - different kinds. + - There is no batch call. Each call returns a `Pending`. A `Pending` does + not send its key request until it is awaited. To encrypt or decrypt + many values, make one call for each value. Then merge the calls with + `Pending::all`. Awaiting the merged call makes one key request, and + returns the results in order. + - Each value keeps its own declared kind, so one merged call can contain + values of different kinds. - On encrypt, a declared kind converts a number of another width or kind - when the conversion is exact, by the rules a record's typed field uses. - With no declared kind, the scalar is sealed as it arrived. - - On decrypt, a declared kind is the kind the value must open as. - Nothing is converted. A value of another kind is `Error::OpenedType`, - which names the kind that was expected and never says what the value - opened as. - - The kind `json` takes a document as its JSON text, in a text leaf or a - bytes leaf. The engine checks the text and seals the document as - `JsonPlaintext` is sealed. On decrypt, `json` returns the document's - text in a bytes leaf, as a record's `json` field opens. - - `json` is a declared kind, and not a stored one. A document is stored - as a text leaf, as a string is, so a kind check cannot tell them - apart. A sealed document opens as `string`. A sealed string whose - text is a JSON document opens as `json`, which checks that the text - parses and returns it as the engine writes the document. - - A ciphertext holds one scalar. `encrypt` refuses an array, an object, a - passthrough and a null, plain or typed, before any key is requested. - The refusal is a new variant, `dynamic::Error::Value`, with the code - `stack_encrypt::dynamic_value`. It names no field, and its message is - about one value. It carries one of three new reasons, `Reason::Array`, - `Reason::Object` and `Reason::Null`, or `Reason::Passthrough`. JavaScript's `undefined` is refused with - `Reason::Undefined`, with a declared kind and with none: it is most - often a property name spelt wrong, and no typed call could read it - back. A value of another kind is `Reason::FieldType`. + when the conversion is exact. The rules are those of a typed field of a + record. With no declared kind, the scalar is stored as it arrived. + - On decrypt, a declared kind is the kind that the value must have been + stored as. Nothing is converted. A value of another kind is + `Error::OpenedType`. That error names the kind that was expected, and + never says what kind the value had. + - The kind `json` takes a document as its JSON text, as a text value or a + bytes value. The engine checks the text, and stores the document as it + stores a `JsonPlaintext`. On decrypt, `json` returns the text of the + document as a bytes value. A `json` field of a record decrypts to the + same form. + - `json` is a declared kind and not a stored kind. The engine stores a + document as text, as it stores a string. So a check of the stored kind + cannot distinguish them. An encrypted document decrypts as `string`. An + encrypted string whose text is a JSON document decrypts as `json`. + - Decrypt as `json` checks that the text parses, and returns the document + as the engine writes it. + - A ciphertext contains one scalar. `encrypt` refuses an array, an + object, a passthrough, and a null before it requests any key. The null + can be plain or typed. + - The refusal is a new variant, `dynamic::Error::Value`, with the code + `stack_encrypt::dynamic_value`. The error names no field, and its + message is about one value. The reason is `Reason::Passthrough`, or one + of three new reasons: `Reason::Array`, `Reason::Object`, and + `Reason::Null`. + - `encrypt` refuses JavaScript's `undefined` with `Reason::Undefined`, + with a declared kind and with none. An `undefined` value is most often + a misspelt property name. No typed call could read it back. A value of + another kind is `Reason::FieldType`. - Two ciphertexts of one value never have the same bytes, because each - sealed leaf has a random nonce. The two interfaces agree on every + encrypted scalar has a random nonce. The two interfaces agree on every other part: the keyset, the data key, the length, and the plaintext of - the leaf. `tests/single_value.rs` holds them to that for every kind. - - The conformance profile `single-value-v1` - (`conformance/stack-encrypt/single-value-contract.md`) has the shared - cases. + the encrypted scalar. `tests/single_value.rs` tests that for every + kind. + - The conformance profile `single-value-v1` has the shared cases. The + contract of the profile is + `conformance/stack-encrypt/single-value-contract.md`. - `ScalarTarget` is re-exported from Vitamin C at the crate root. - **Encrypt a UUID as a UUID** (#1833). `value::Uuid` is vitaminc's @@ -561,34 +567,42 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Breaking -- **A `Ciphertext` decrypts only into a type that one scalar builds** +- **A `Ciphertext` decrypts only into a type that is built from one scalar** (#2009). `OpaqueDecode` was implemented for every `Decrypt` type that is `Zeroize`. So `keyset.decrypt::>(ciphertext)` compiled, requested a key, decrypted, and only then failed with - `Error::OpenedType`. It could never succeed, because a ciphertext holds - one scalar. `OpaqueDecode` is now bounded on Vitamin C's `ScalarTarget`, - so such a call does not compile. This applies to `keyset.decrypt`, - `keyset.decrypt_with_context`, `T::decrypt_from(ciphertext, ..)` and a - `Ciphertext` field of a derived record. - - Still accepted: every scalar (`bool`, the integers, the floats, - `String`, `Vec`, `[u8; N]`, `value::Date`, `value::Timestamp`, - `value::Decimal`, `value::Uuid`), `JsonPlaintext`, a `Protected` or an - `Option` of one, `OwnedFrame`, a newtype that derives `Decrypt` over - one, such as `struct Email(String)`, and any type of your own that - implements `FromScalar`. `OpaqueBlob` keeps its own way in. - - No longer accepted: a `Vec` of anything but bytes, a `HashMap` or a - `BTreeMap`, a struct that derives `Decrypt` with named fields, and a - newtype, a `Protected` or an `Option` of one of those. - - You write nothing to make a type of your own a target, and you - cannot: no one implements `ScalarTarget` by hand. A type is one when - one scalar builds it, which the compiler works out from how the type + `Error::OpenedType`. That call could never succeed, because a ciphertext + contains one scalar. `OpaqueDecode` is now bounded on Vitamin C's + `ScalarTarget`, so such a call does not compile. + - The bound applies to `keyset.decrypt`, `keyset.decrypt_with_context`, + `T::decrypt_from(ciphertext, ..)`, and a `Ciphertext` field of a derived + record. + - Still accepted: + - every scalar: `bool`, the integers, the floats, `String`, `Vec`, + `[u8; N]`, `value::Date`, `value::Timestamp`, `value::Decimal`, and + `value::Uuid` + - `JsonPlaintext` + - a `Protected` or an `Option` of a scalar + - `OwnedFrame` + - a newtype that derives `Decrypt` over a scalar, such as + `struct Email(String)` + - any type of your own that implements `FromScalar` + - `OpaqueBlob`, through its own impl + - No longer accepted: + - a `Vec` of anything but bytes + - a `HashMap` or a `BTreeMap` + - a struct that derives `Decrypt` with named fields + - a newtype, a `Protected`, or an `Option` of one of those + - You write no code to make a type of your own a target. You cannot + implement `ScalarTarget` directly. A type is a `ScalarTarget` when it + is built from one scalar. The compiler derives that from how the type decrypts. - - The compile error says that one ciphertext holds one value, and what - to decrypt instead. - - A sequence, a map or a struct is a tree of leaves, which is a - `StackCipherText`. Decrypt one with `keyset.decrypt_tree`. A column of - ciphertexts is a `Vec`, which still decrypts into a `Vec` - with `Vec::::decrypt_from`. + - The compile error says that one ciphertext contains one value, and + names what to decrypt instead. + - A sequence, a map, or a struct is stored as a tree of encrypted + scalars: a `StackCipherText`. Decrypt one with `keyset.decrypt_tree`. + - A column of ciphertexts is a `Vec`. A `Vec` + still decrypts into a `Vec` with `Vec::::decrypt_from`. - No stored byte changes. Every ciphertext that decrypted before still decrypts into the same type. diff --git a/packages/stack-encrypt/docs/adr/0012-owned-record-declarations.md b/packages/stack-encrypt/docs/adr/0012-owned-record-declarations.md index ac91576e5..93a22bc6e 100644 --- a/packages/stack-encrypt/docs/adr/0012-owned-record-declarations.md +++ b/packages/stack-encrypt/docs/adr/0012-owned-record-declarations.md @@ -182,12 +182,17 @@ case needs a trait for "a scalar, or a `Protected` of one". Rust allows that trait to be implemented for both only in Vitamin C, the crate that defines `FromScalar`. -> **Amended 2026-11-28 (#2011).** Vitamin C now has that trait, -> `ScalarTarget`: a decrypt target that one scalar builds. No one -> implements it by hand. A target is one when its sink is one that a scalar -> satisfies, which Vitamin C marks on its own sinks. So every `FromScalar` -> type is one, and so are an `Option`, a `Protected` or a derived newtype -> of one, and `OwnedFrame`. +> **Amended 2026-11-28 (pull request #2011).** Vitamin C now has that +> trait, `ScalarTarget`: a decrypt target that is built from one scalar. +> No one implements `ScalarTarget` directly. +> +> A sink is the type that builds a decrypt target. Vitamin C marks each of +> its sinks that builds its value from one scalar. A target is a +> `ScalarTarget` when its sink has that mark. +> +> So every `FromScalar` type is a `ScalarTarget`. An `Option`, a +> `Protected`, and a derived newtype of a scalar target are `ScalarTarget`s +> too. `OwnedFrame` is also one. > > The bound of a single `Ciphertext`'s target is now > `ScalarTarget + Zeroize`, and no longer `Decrypt + Zeroize`. So a target diff --git a/packages/stack-encrypt/docs/language-integration.md b/packages/stack-encrypt/docs/language-integration.md index 4c36ea765..acd8196f9 100644 --- a/packages/stack-encrypt/docs/language-integration.md +++ b/packages/stack-encrypt/docs/language-integration.md @@ -177,34 +177,38 @@ encrypts one value into one [`crate::Ciphertext`], with no plan. A binding does the same through [`crate::dynamic::value`]: - [`crate::dynamic::value::encrypt`] takes the value as a - [`crate::dynamic::frame::Frame`] and an optional declared kind - ([`crate::dynamic::ValueKind`]). It settles to the ciphertext the typed - Rust call makes for the same value, so every language reads what any - language wrote. -- [`crate::dynamic::value::decrypt`] takes a ciphertext and an optional - kind the value must open as. It settles to the value's frame. - -Each has a form that takes a context. A declared kind reads the value by -the rules a record's typed field uses, so a binding passes a language's own -number. The kind `json` takes a document as its JSON text. - -There is no batch call. Each call returns a [`crate::Pending`], so a binding -makes one call for each value and merges them with [`crate::Pending::all`]. -Awaiting the merged call makes one key request, and each value keeps its own -declared kind. - -A ciphertext holds one scalar. An array, an object, a passthrough and a null -are refused before any key is requested. The refusal is + [`crate::dynamic::frame::Frame`], and an optional declared kind + ([`crate::dynamic::ValueKind`]). The call settles to a ciphertext that the + typed Rust call can decrypt. So every language can read what any language + wrote. +- [`crate::dynamic::value::decrypt`] takes a ciphertext, and an optional + kind that the value must have been stored as. The call settles to the + frame of the value. + +Each function has a form that takes a context. A declared kind reads the +value by the rules that a typed field of a record uses. So a binding can +pass a number in the form that its language uses. The kind `json` takes a +document as its JSON text. + +There is no batch call. Each call returns a [`crate::Pending`]. So a binding +makes one call for each value, and merges the calls with +[`crate::Pending::all`]. Awaiting the merged call makes one key request. +Each value keeps its own declared kind. + +A ciphertext contains one scalar. The engine refuses an array, an object, a +passthrough, and a null before it requests any key. The refusal is [`crate::dynamic::Error::Value`], with the code -`stack_encrypt::dynamic_value` and a reason that says which was found -(`array`, `object`, `passthrough`, `null`). An SDK stores an absent -value as a database `NULL`. JavaScript's `undefined` is refused too -(`undefined`), whatever kind is declared. +`stack_encrypt::dynamic_value`. The reason of the refusal names what was +found: `array`, `object`, `passthrough`, or `null`. An SDK stores an absent +value as a database `NULL`. -`json` is a declared kind, and a document is stored as text. So a `string` -and a document share one stored form, and a kind check cannot tell them -apart: a sealed document opens as `string`, and a sealed string whose text -is a JSON document opens as `json`. +The engine also refuses JavaScript's `undefined`, with any declared kind. +The reason is `undefined`. + +`json` is a declared kind, and the engine stores a document as text. So a +`string` and a document have one stored form. A check of the stored kind +cannot distinguish them. A stored document decrypts as `string`. A stored +string whose text is a JSON document decrypts as `json`. ### Scopes and bindings @@ -866,16 +870,29 @@ lists every profile and its Rust and Go runners. Before a binding is called done: 1. **The conformance profiles pass in your language.** Write a runner for - each profile in `conformance/stack-encrypt/v1`, as - `languages/golang/encrypt/*conformance_test.go` does for Go: scalar - records, declarations, reads, runtime and nulls, contexts and bindings, - value boundaries, query refusals, raw frames and, if your - binding links the EQL types, EQL and JSON. Write one for the single-value - profile too, if your SDK encrypts one value into one ciphertext. Only - Rust runs that profile today: the Go runner is not written yet, so - `packages/stack-encrypt/tests/single_value_conformance.rs` is the - runner to follow. Read the frozen expectations; never - regenerate them to pass. A profile you have not run is not a pass. + each profile in `conformance/stack-encrypt/v1`. The files + `languages/golang/encrypt/*conformance_test.go` are the Go runners. The + profiles are: + + - scalar records + - declarations + - reads + - runtime and nulls + - contexts and bindings + - value boundaries + - query refusals + - raw frames + + If your binding links the EQL types, the EQL and JSON profiles apply + too. + + If your SDK encrypts one value into one ciphertext, write a runner for + the single-value profile too. Only Rust runs that profile today, because + the Go runner is not written yet. So follow + `packages/stack-encrypt/tests/single_value_conformance.rs`. + + Read the frozen expectations. Never regenerate them to make a run pass. + A profile that you have not run is not a pass. 2. **Fresh artifacts cross both ways.** The exchange profile (`conformance/stack-encrypt/exchange-contract.md`) has your binding open what Rust wrote in the same run, and Rust open what your binding wrote, diff --git a/packages/stack-encrypt/src/dynamic/mod.rs b/packages/stack-encrypt/src/dynamic/mod.rs index 222a32976..a4c71a839 100644 --- a/packages/stack-encrypt/src/dynamic/mod.rs +++ b/packages/stack-encrypt/src/dynamic/mod.rs @@ -32,10 +32,11 @@ //! * [`frame::OwnedFrame`] — the engine's plaintext for a value whose type //! is known only at run time: vitaminc's, re-exported with the rest of the //! frame. -//! * [`value`] — one value as one [`Ciphertext`](crate::Ciphertext), and -//! back: what [`KeysetCipher::encrypt`](crate::KeysetCipher::encrypt) and -//! [`KeysetCipher::decrypt`](crate::KeysetCipher::decrypt) do for a value -//! of a Rust type, for a value in a frame. +//! * [`value`] — encrypts one value in a frame as one +//! [`Ciphertext`](crate::Ciphertext), and decrypts it again. +//! [`KeysetCipher::encrypt`](crate::KeysetCipher::encrypt) and +//! [`KeysetCipher::decrypt`](crate::KeysetCipher::decrypt) do the same for +//! a value of a Rust type. //! * [`term`](term()) — one index term for a value, derived at the one //! scalar it is walked to. //! * [`record`] — a record's declaration as data, *lowered* into the @@ -63,13 +64,15 @@ //! //! # What is not here //! -//! Encrypting a whole value as a tree of leaves is not: an -//! [`OwnedFrame`](frame::OwnedFrame), like any source, -//! implements `Encrypt` already, so `keyset.encrypt_tree(value, aad)` is the whole -//! of it and needs nothing from this module. ([`value`] encrypts one scalar -//! as one opaque ciphertext, which is a different stored form.) Nor is a second executor: nothing here calls -//! the term functions or the seal path to produce a record. A capability a -//! data plan needs and the combinators lack is added to the combinators, +//! Encrypting a whole value as a tree of leaves is not here. An +//! [`OwnedFrame`](frame::OwnedFrame) implements `Encrypt` already, like any +//! source. So `keyset.encrypt_tree(value, aad)` encrypts it, and needs +//! nothing from this module. [`value`] encrypts one scalar as one opaque +//! ciphertext. That is a different stored form. +//! +//! A second executor is not here either: nothing in this module calls the +//! term functions or the seal path to produce a record. When a data plan +//! needs a capability that the combinators lack, add it to the combinators, //! once. //! //! # Stability diff --git a/packages/stack-encrypt/src/dynamic/value.rs b/packages/stack-encrypt/src/dynamic/value.rs index 232d4f398..988290130 100644 --- a/packages/stack-encrypt/src/dynamic/value.rs +++ b/packages/stack-encrypt/src/dynamic/value.rs @@ -1,96 +1,130 @@ -//! One value as one ciphertext, for a value whose type is known only at -//! run time. +//! Encrypt and decrypt one value whose type is only known when the code +//! runs. //! //! [`KeysetCipher::encrypt`] encrypts one value of a Rust type into one -//! [`Ciphertext`], and [`KeysetCipher::decrypt`] reads it back. A language -//! binding has no Rust type to name. It holds a value as a transport frame -//! ([`Frame`]), and knows the value's kind only when the code runs. This -//! module is the same pair of operations over a frame. +//! [`Ciphertext`]. [`KeysetCipher::decrypt`] decrypts that ciphertext into a +//! Rust type. This documentation names those two methods the typed calls. A +//! language binding has no Rust type to name. So this module has the same +//! two operations for a value that arrives as a frame. //! -//! - [`encrypt`] seals the one scalar a frame holds. The result is the -//! [`Ciphertext`] that `keyset.encrypt` returns for the same value: the -//! same leaf, under the same key request and the same context. So a value -//! that one language encrypts, every other language decrypts. -//! - [`decrypt`] opens a ciphertext into an [`OwnedFrame`] that holds one -//! scalar. +//! # Terms //! -//! Each has a form that takes a context: [`encrypt_with_context`] and -//! [`decrypt_with_context`]. +//! - A *frame* is one value written as bytes, in the format that the engine +//! reads. A [`Frame`] borrows those bytes. An [`OwnedFrame`] owns them, +//! and wipes them when it is dropped. +//! - A *scalar* is one value that has no parts: text, a number, a boolean, +//! bytes, a date, a timestamp, a decimal, or a UUID. +//! - A *kind* is the name of what a value is, such as `string`, `int64`, or +//! `timestamp`. [`ValueKind`] lists the kinds. +//! - A *leaf* is the encrypted form of one scalar or of one null. A +//! [`Ciphertext`] contains exactly one leaf. +//! - A *context* is data that is authenticated with a value. The +//! ciphertext does not store the context, so decrypting needs the same +//! context. +//! - A *key request* is one request to the key service for data keys. +//! - A *refusal* is an error that a function returns for a value it does not +//! accept. +//! +//! # The functions +//! +//! - [`encrypt`] encrypts the one scalar in a frame. The typed +//! `keyset.decrypt` decrypts the result. So every language can decrypt a +//! value that one language encrypted. +//! - [`decrypt`] decrypts a ciphertext into an [`OwnedFrame`] of one scalar. +//! - [`encrypt_with_context`] and [`decrypt_with_context`] do the same with +//! a context. //! //! # Many values in one key request //! -//! Each call returns a [`Pending`], which holds its key request and has -//! not sent it. To encrypt or decrypt many values, make one call for each -//! value and merge the results with [`Pending::all`]. Awaiting the merged -//! call makes one key request for all of them, and the values come back -//! in order. Each value keeps its own declared kind and its own context, -//! so one batch can hold values of different kinds. The examples on -//! [`encrypt`] and [`decrypt`] show how. +//! Each call returns a [`Pending`]. A `Pending` is a prepared call. The key +//! request of a `Pending` is not sent until the `Pending` is awaited. +//! +//! To encrypt or decrypt many values, make one call for each value. Then +//! merge the results with [`Pending::all`]. Awaiting the merged call makes +//! one key request for each keyset, and returns the results in the order of +//! the calls. +//! +//! Each value has its own declared kind and its own context. So one merged +//! call can contain values of different kinds. The examples on [`encrypt`] +//! and [`decrypt`] show how. //! //! # The declared kind //! -//! Each function takes an optional [`ValueKind`]: the kind the caller -//! declares for the value. +//! Each function takes an optional [`ValueKind`]. That is the declared kind: +//! the kind that the caller says the value has. +//! +//! When [`encrypt`] has a declared kind, it stores the value as that kind. +//! `encrypt` converts a number of another width or kind when the conversion +//! is exact. The conversion rules are those of [`read`](super::read), the +//! function that reads a typed field of a record. //! -//! On encrypt, a declared kind is the kind the value is sealed as. A number -//! of another width or kind is converted when the conversion is exact, by -//! the rules of [`read`](super::read), which a record's typed field uses -//! too. So a JavaScript `34`, which arrives as a float, seals as the -//! integer `34` when the caller declares `uint64`. With no declared kind, -//! the scalar is sealed as it arrived. +//! For example, a JavaScript `34` arrives as a float. `encrypt` stores it as +//! the integer `34` when the caller declares `uint64`. With no declared +//! kind, `encrypt` stores the scalar as it arrived. //! -//! On decrypt, a declared kind is the kind the value must open as. Nothing -//! is converted: a value stored as another kind is refused. With no -//! declared kind, the value comes back as it was sealed. +//! When [`decrypt`] has a declared kind, the value must have been stored as +//! that kind. `decrypt` converts nothing, and refuses a value that was +//! stored as another kind. With no declared kind, `decrypt` returns the +//! value as it was stored. //! //! # A JSON document //! -//! The kind [`ValueKind::Json`] is a JSON document. On encrypt, the frame -//! holds the document's JSON text, in a text leaf or a bytes leaf. The -//! engine checks the text by its own JSON rules and seals the document as -//! [`JsonPlaintext`] is sealed, so the ciphertext is the one -//! `keyset.encrypt(JsonPlaintext)` returns. On decrypt, the frame holds -//! the document's JSON text in a bytes leaf, as a record's `json` field -//! opens ([`json_frame`](super::json_frame)). +//! The kind [`ValueKind::Json`] is a JSON document. //! -//! `json` is a declared kind, and not a stored one. A document is stored -//! as a text leaf that holds its JSON text, which is how a `string` is -//! stored too. So `string` and `json` share one stored form, and a kind -//! check cannot tell them apart: +//! [`encrypt`] takes the JSON text of the document, as a text value or a +//! bytes value in the frame. `encrypt` checks the text by the engine's JSON +//! rules. `encrypt` then stores the document as +//! `keyset.encrypt(JsonPlaintext)` stores a [`JsonPlaintext`]. //! -//! - A sealed document opens as `string`. The frame holds the JSON text -//! that was sealed. -//! - A sealed string opens as `json` when its text is a JSON document. The -//! string `42` is one, and so is `"ada"` with its quotes. The string -//! `ada` is not, and is refused. +//! [`decrypt`] returns the JSON text of the document as a bytes value in the +//! frame. A `json` field of a record decrypts to the same form +//! ([`json_frame`](super::json_frame)). //! -//! Decrypt as `json` checks that the text parses by the engine's JSON -//! rules. It then returns the document as the engine writes it, which is -//! the text a document is sealed as: no whitespace between tokens, and -//! each number in its shortest form. So for a value that was sealed as a -//! string, the text that comes back can differ from the text that was -//! sealed. +//! `json` is a declared kind and not a stored kind. The engine stores a +//! document as its JSON text, in the same stored form as a `string`. So a +//! check of the stored kind cannot distinguish `string` from `json`: +//! +//! - An encrypted document decrypts as `string`. The frame contains the JSON +//! text that was stored. +//! - An encrypted string decrypts as `json` when its text is a JSON +//! document. The string `42` is a document. So is `"ada"` with its quotes. +//! The string `ada` is not a document, so `decrypt` refuses it. +//! +//! [`decrypt`] with the kind `json` checks that the text parses by the +//! engine's JSON rules. `decrypt` then returns the document as the engine +//! writes it: with no whitespace between tokens, and with each number in its +//! shortest form. So when a value was encrypted as a string, the text that +//! `decrypt` returns as `json` can differ from the text that was encrypted. //! //! # What is refused //! -//! A [`Ciphertext`] holds one scalar. So [`encrypt`] refuses an array, an -//! object, a passthrough and a null before any key is requested. The typed -//! call has no form for a null either: `Option` is not an +//! A [`Ciphertext`] contains one scalar. So [`encrypt`] refuses an array, an +//! object, a passthrough, and a null. A passthrough is a value that a record +//! stores without encrypting it. `encrypt` returns each refusal before it +//! requests any key. +//! +//! The typed call cannot encrypt a null either: `Option` is not an //! [`OpaqueEncode`](crate::OpaqueEncode) type. Store an absent value as a -//! database `NULL`, or seal it in a record whose field declares how -//! ([`NullMode`](super::NullMode)). +//! database `NULL`. Or encrypt it in a record, where the field declares how +//! a null is stored ([`NullMode`](super::NullMode)). +//! +//! [`encrypt`] also refuses JavaScript's `undefined`, with any declared kind +//! or with none. An `undefined` value is most often a misspelt property +//! name. No typed call could decrypt it. //! -//! [`encrypt`] also refuses JavaScript's `undefined`, whatever kind is -//! declared. `undefined` is most often a property name spelt wrong, and no -//! typed call could read it back. +//! A logical type is a meaning that the frame format gives to a plain +//! scalar, such as a date stored as an integer. A scalar can have a logical +//! type that this build does not define. Such a scalar has no kind. The frame +//! format and the leaf format record an unknown logical type by its numeric +//! id. So an older build can store and return a value of a type that a newer +//! build added. //! -//! A scalar of a logical type that this build does not know has no kind. -//! The frame and the leaf carry such a type by its id, so that a value of -//! a newer type survives an older build. With no declared kind, it is -//! sealed as it arrived, and it opens only with no declared kind. With a -//! declared kind, it is refused. +//! - With no declared kind, [`encrypt`] stores such a scalar as it arrived. +//! [`decrypt`] returns it only when no kind is declared. +//! - With a declared kind, [`encrypt`] refuses such a scalar. //! -//! A refusal says which kind of value was found, and never the value. +//! A refusal names the kind of value that was found. A refusal never +//! contains the value. //! //! [`KeysetCipher::encrypt`]: crate::KeysetCipher::encrypt //! [`KeysetCipher::decrypt`]: crate::KeysetCipher::decrypt @@ -108,19 +142,18 @@ use crate::target::core::encrypt_opaque; use crate::target::{CipherRef, Pending, ScalarContext}; use crate::{Ciphertext, ContextPiece, DecryptFrom, KeysetCipher}; -/// Encrypt the one scalar `value` holds as one [`Ciphertext`], with the -/// empty context. +/// Encrypt the one scalar in `value` as one [`Ciphertext`], with the empty +/// context. /// -/// The result is the ciphertext [`KeysetCipher::encrypt`] returns for the -/// same value: `keyset.decrypt::` opens it, and so does [`decrypt`]. -/// `kind` is the kind the caller declares for the value, or `None` to seal -/// the scalar as it arrived. The [module docs](self) say how a declared -/// kind converts a value, and how a JSON document is sealed. +/// [`KeysetCipher::decrypt`] and [`decrypt`] both decrypt the result. `kind` +/// is the kind that the caller declares for the value. Pass `None` to store +/// the scalar as it arrived. The [module docs](self) describe how a declared +/// kind converts a value, and how a JSON document is stored. /// -/// The frame is read here, before this returns. The pending request holds -/// only the value as it will be sealed, in a buffer that is wiped. The -/// frame stays the caller's, to wipe when the caller is done with it. An -/// [`OwnedFrame`] wipes itself when it drops. +/// `encrypt` reads the frame before it returns. The pending call keeps only +/// the value in the form that will be encrypted, in a buffer that is wiped. +/// The caller still owns the frame, and wipes it when the caller no longer +/// needs it. An [`OwnedFrame`] wipes its bytes when it is dropped. /// /// ``` /// use stack_encrypt::dynamic::{frame::OwnedFrame, value, ValueKind}; @@ -135,17 +168,17 @@ use crate::{Ciphertext, ContextPiece, DecryptFrom, KeysetCipher}; /// .await?; /// let keyset = cipher.default_keyset(); /// -/// // A binding holds the value as a frame. A JavaScript number is a float. +/// // A binding has the value as a frame. A JavaScript number is a float. /// let age = OwnedFrame::of(34.0f64)?; /// -/// // The caller declares the kind, so the value is sealed as the integer. +/// // The caller declares the kind, so the value is stored as an integer. /// let stored = value::encrypt(&keyset, age.frame(), Some(ValueKind::UInt64))?.await?; /// -/// // The typed call reads it, as it reads a ciphertext it made itself. +/// // The typed call decrypts it. /// let typed: u64 = keyset.decrypt(stored.clone()).await?; /// assert_eq!(typed, 34); /// -/// // So does the run-time call, into a frame of the declared kind. +/// // `value::decrypt` decrypts it too, into a frame of the declared kind. /// let opened = value::decrypt(&keyset, stored, Some(ValueKind::UInt64)).await?; /// assert_eq!(opened.frame(), OwnedFrame::of(34u64)?.frame()); /// # Ok::<(), Box>(()) @@ -155,14 +188,16 @@ use crate::{Ciphertext, ContextPiece, DecryptFrom, KeysetCipher}; /// # Many values in one key request /// /// Call `encrypt` for each value, then merge the pending calls with -/// [`Pending::all`]. Nothing is requested until the merged call is -/// awaited, and it makes one key request for every value. Each value has -/// its own data key and is authenticated on its own. The ciphertexts come -/// back in the order of the calls. +/// [`Pending::all`]. Awaiting the merged call makes one key request for +/// every value. No key is requested before that. The ciphertexts come back +/// in the order of the calls. +/// +/// Each value gets its own data key. Each value is authenticated separately. +/// Each call takes its own declared kind, so one merged call can contain +/// values of different kinds. /// -/// Each call takes its own declared kind, so one batch can hold values of -/// different kinds. A value that is refused is an `Err` here, before any -/// call is merged. So a batch with a refused value requests no key. +/// `encrypt` returns `Err` for a refused value before any call is merged. So +/// a set of values with one refused value requests no key. /// /// ``` /// use stack_encrypt::dynamic::{frame::OwnedFrame, value, ValueKind}; @@ -184,7 +219,8 @@ use crate::{Ciphertext, ContextPiece, DecryptFrom, KeysetCipher}; /// (OwnedFrame::of(true)?, None), /// ]; /// -/// // One call for each value. A refused value stops here, with no request. +/// // One call for each value. A refused value returns here, before any +/// // key request. /// let mut calls = Vec::new(); /// for (frame, kind) in &values { /// calls.push(value::encrypt(&keyset, frame.frame(), *kind)?); @@ -202,24 +238,26 @@ use crate::{Ciphertext, ContextPiece, DecryptFrom, KeysetCipher}; /// /// # Errors /// -/// [`Error::Value`], decided here, before any key is requested: +/// `encrypt` returns [`Error::Value`] before it requests any key. The reason +/// in the error is one of these: /// -/// - [`Reason::Array`], [`Reason::Object`], [`Reason::Passthrough`] or +/// - [`Reason::Array`], [`Reason::Object`], [`Reason::Passthrough`], or /// [`Reason::Null`] for a value that is not one scalar. A typed null is a /// null. /// - [`Reason::Undefined`] for JavaScript's `undefined`, with a declared /// kind or with none. -/// - [`Reason::FieldType`] for a value that is not of the declared kind and -/// does not convert to it exactly. -/// - [`Reason::JsonSyntax`], [`Reason::JsonDuplicateKey`] or -/// [`Reason::JsonIntegerRange`] for text that is not a document, under -/// the kind [`ValueKind::Json`]. +/// - [`Reason::FieldType`] for a value of another kind that does not convert +/// exactly to the declared kind. +/// - [`Reason::JsonSyntax`], [`Reason::JsonDuplicateKey`], or +/// [`Reason::JsonIntegerRange`] for text that is not a JSON document, when +/// the declared kind is [`ValueKind::Json`]. /// -/// The error names no field and holds nothing of the value. A failure of -/// the pending request is the engine's [`Error`](crate::Error), as it is -/// for [`KeysetCipher::encrypt`]. +/// The error names no field and contains no part of the value. When the +/// pending call fails, the error is the engine's [`Error`](crate::Error), as +/// it is for [`KeysetCipher::encrypt`]. /// /// [`KeysetCipher::encrypt`]: crate::KeysetCipher::encrypt +/// [`KeysetCipher::decrypt`]: crate::KeysetCipher::decrypt pub fn encrypt<'a, K: 'static>( keyset: &'a KeysetCipher<'_, K>, value: Frame<'_>, @@ -228,9 +266,10 @@ pub fn encrypt<'a, K: 'static>( seal(keyset, value, kind, ().into_context()) } -/// [`encrypt`], authenticating `context`, as -/// [`KeysetCipher::encrypt_with_context`] does. Decrypting needs the same -/// context. +/// Encrypt as [`encrypt`] does, and authenticate `context` with the value. +/// +/// [`KeysetCipher::encrypt_with_context`] does the same for a typed value. +/// Decrypting needs the same context. /// /// ``` /// use stack_encrypt::dynamic::{frame::OwnedFrame, value}; @@ -259,8 +298,8 @@ pub fn encrypt<'a, K: 'static>( /// /// # Errors /// -/// As [`encrypt`]. A context that cannot be used fails the pending -/// request, as it does for the typed call. +/// The errors of [`encrypt`]. A context that cannot be used fails the +/// pending call, as it does for the typed call. /// /// [`KeysetCipher::encrypt_with_context`]: crate::KeysetCipher::encrypt_with_context pub fn encrypt_with_context<'a, 'c, K: 'static>( @@ -272,28 +311,32 @@ pub fn encrypt_with_context<'a, 'c, K: 'static>( seal(keyset, value, kind, context.into_context().into_owned()) } -/// Decrypt a [`Ciphertext`] that was sealed with the empty context, into a -/// frame that holds its one scalar. +/// Decrypt a [`Ciphertext`] that was encrypted with the empty context. The +/// result is a frame that contains the one scalar. /// -/// It opens what [`encrypt`] and [`KeysetCipher::encrypt`] seal. `kind` is -/// the kind the value must open as, or `None` to take the value as it was -/// sealed. With [`ValueKind::Json`], the frame holds the document's JSON -/// text in a bytes leaf. +/// `decrypt` decrypts a ciphertext from [`encrypt`] or from +/// [`KeysetCipher::encrypt`]. `kind` is the kind that the value must have +/// been stored as. Pass `None` to take the value as it was stored. With +/// [`ValueKind::Json`], the frame contains the JSON text of the document as +/// a bytes value. /// -/// `string` and `json` share one stored form, a text leaf. So a sealed -/// document opens as `string`, and a sealed string whose text is a JSON -/// document opens as `json`. The [module docs](self#a-json-document) say -/// what `json` checks and returns. +/// `string` and `json` have one stored form. So an encrypted document +/// decrypts as `string`. An encrypted string whose text is a JSON document +/// decrypts as `json`. The [section on a JSON document](self#a-json-document) +/// describes what `json` checks and returns. /// -/// Pass `&keyset` to open only a ciphertext of that keyset: a ciphertext -/// of another keyset is refused before any key is retrieved. Pass -/// `&cipher` to open a ciphertext of any keyset the client can use. +/// Pass `&keyset` to decrypt only a ciphertext of that keyset. `decrypt` +/// then refuses a ciphertext of another keyset before it retrieves any key. +/// Pass `&cipher` to decrypt a ciphertext of any keyset that the client can +/// use. /// -/// The frame is plaintext. It wipes its buffer when it drops. +/// The frame is plaintext. An [`OwnedFrame`] wipes its bytes when it is +/// dropped. /// -/// With no declared kind, a ciphertext that holds a null opens as the null -/// frame. [`encrypt`] seals no null, but -/// [`KeysetCipher::encrypt_tree`](crate::KeysetCipher::encrypt_tree) does. +/// With no declared kind, a ciphertext of a null decrypts as the null frame. +/// [`encrypt`] never encrypts a null. +/// [`KeysetCipher::encrypt_tree`](crate::KeysetCipher::encrypt_tree) can +/// encrypt one. /// /// ``` /// use stack_encrypt::dynamic::{frame::OwnedFrame, value, ValueKind}; @@ -308,15 +351,15 @@ pub fn encrypt_with_context<'a, 'c, K: 'static>( /// .await?; /// let keyset = cipher.default_keyset(); /// -/// // A ciphertext the typed call made. +/// // A ciphertext that the typed call made. /// let stored = keyset.encrypt(String::from("ada@example.com")).await?; /// -/// // It opens as the kind it was sealed as. +/// // The ciphertext decrypts as the kind it was stored as. /// let email = value::decrypt(&keyset, stored.clone(), Some(ValueKind::String)).await?; /// assert_eq!(email.frame(), OwnedFrame::of("ada@example.com")?.frame()); /// -/// // It does not open as another kind. The error names the kind that was -/// // expected, and nothing about the value. +/// // The ciphertext does not decrypt as another kind. The error names the +/// // expected kind, and nothing about the value. /// let refused = value::decrypt(&keyset, stored, Some(ValueKind::Int64)).await; /// assert!(matches!(refused, Err(Error::OpenedType { expected: "int64" }))); /// # Ok::<(), Box>(()) @@ -326,14 +369,14 @@ pub fn encrypt_with_context<'a, 'c, K: 'static>( /// # Many values in one key request /// /// Call `decrypt` for each ciphertext, then merge the pending calls with -/// [`Pending::all`]. Awaiting the merged call makes one key request for -/// each keyset the ciphertexts were sealed under. The frames come back in +/// [`Pending::all`]. Awaiting the merged call makes one key request for each +/// keyset that the ciphertexts were encrypted under. The frames come back in /// the order of the calls. Each call takes its own declared kind. /// -/// Pass the same cipher or keyset to `Pending::all` as to each `decrypt`. -/// If one value fails, the merged call fails with that value's error, and -/// the frames opened before it are dropped. A frame wipes its buffer when -/// it drops. +/// Pass the same cipher or keyset to `Pending::all` as to each `decrypt`. If +/// one value fails, the merged call fails with the error of that value. The +/// frames that were decrypted before that value are dropped. A dropped frame +/// wipes its bytes. /// /// ``` /// use stack_encrypt::dynamic::{frame::OwnedFrame, value, ValueKind}; @@ -354,7 +397,7 @@ pub fn encrypt_with_context<'a, 'c, K: 'static>( /// (keyset.encrypt(String::from("ada@example.com")).await?, Some(ValueKind::String)), /// ]; /// -/// // One call for each ciphertext, with the kind it must open as. +/// // One call for each ciphertext, with the kind it must decrypt as. /// let calls: Vec<_> = stored /// .into_iter() /// .map(|(ciphertext, kind)| value::decrypt(&keyset, ciphertext, kind)) @@ -370,19 +413,23 @@ pub fn encrypt_with_context<'a, 'c, K: 'static>( /// /// # Errors /// -/// The pending request fails with the engine's [`Error`](crate::Error), as +/// The pending call fails with the engine's [`Error`](crate::Error), as /// [`KeysetCipher::decrypt`] does: -/// [`ForeignKeyset`](crate::Error::ForeignKeyset) before any key is -/// retrieved, a key provider's error, or -/// [`Aead`](crate::Error::Aead) for a wrong context or an altered -/// ciphertext. -/// -/// A value that was stored as another kind than `kind` is -/// [`OpenedType`](crate::Error::OpenedType). So is text that is not a JSON -/// document, opened as `json`. The error names the kind that was expected. -/// It never says what the value opened as. An array or an object is -/// refused the same way, before any key is retrieved: a ciphertext never -/// holds one. +/// +/// - [`ForeignKeyset`](crate::Error::ForeignKeyset) for a ciphertext of +/// another keyset, before any key is retrieved. +/// - The error of a key provider. +/// - [`Aead`](crate::Error::Aead) for a wrong context or an altered +/// ciphertext. +/// - [`OpenedType`](crate::Error::OpenedType) for a value that was stored as +/// another kind than `kind`. +/// - [`OpenedType`](crate::Error::OpenedType) for text that is not a JSON +/// document, when `kind` is `json`. +/// +/// `OpenedType` names the kind that was expected. `OpenedType` never says +/// what kind the value had. A ciphertext never contains an array or an +/// object. So `decrypt` fails the same way for those two kinds, before any +/// key is retrieved. /// /// [`KeysetCipher::encrypt`]: crate::KeysetCipher::encrypt /// [`KeysetCipher::decrypt`]: crate::KeysetCipher::decrypt @@ -394,13 +441,15 @@ pub fn decrypt<'a, K: 'static>( open(cipher_ref.into(), ciphertext, kind, ().into_context()) } -/// [`decrypt`], under the context the value was encrypted with, as -/// [`KeysetCipher::decrypt_with_context`] does. +/// Decrypt as [`decrypt`] does, with the context that the value was +/// encrypted with. +/// +/// [`KeysetCipher::decrypt_with_context`] does the same for a typed value. /// /// # Errors /// -/// As [`decrypt`]. Another context than the one the value was sealed with -/// fails the pending request. +/// The errors of [`decrypt`]. A context other than the one that the value +/// was encrypted with fails the pending call. /// /// [`KeysetCipher::decrypt_with_context`]: crate::KeysetCipher::decrypt_with_context pub fn decrypt_with_context<'a, 'c, K: 'static>( @@ -417,25 +466,25 @@ pub fn decrypt_with_context<'a, 'c, K: 'static>( ) } -/// Check that `value` is one scalar a ciphertext can hold. +/// Check that `value` is one scalar that a ciphertext can contain. /// /// # Errors /// -/// [`Error::Value`] with the reason that names what was found: an array, -/// an object, a null, a passthrough or `undefined`. +/// [`Error::Value`]. The reason names what was found: an array, an object, a +/// null, a passthrough, or `undefined`. fn one_scalar(value: Frame<'_>) -> Result<(), Error> { let found = match value.kind() { Some(ValueKind::Array) => Reason::Array, Some(ValueKind::Object) => Reason::Object, Some(_) => return Ok(()), // A value of no kind is a null, a passthrough, `undefined`, or a - // scalar of a logical type this build does not know. + // scalar of a logical type that this build does not define. None if value.is_null() => Reason::Null, None if value.has_passthrough() => Reason::Passthrough, None if is_undefined(value) => Reason::Undefined, - // The leaf format carries a logical type it does not know, so that - // a value of a newer type survives an older build. It is one - // scalar, and it seals as it arrived. + // The leaf format records a logical type that this build does not + // define. So an older build can store a value of a newer type. Such + // a value is one scalar. `seal` stores it as it arrived. None => return Ok(()), }; Err(Error::bad_value(found)) @@ -450,8 +499,9 @@ fn is_undefined(value: Frame<'_>) -> bool { .unwrap_or(false) } -/// Plan the seal of one value under `context`, as the typed call plans it: -/// the value is walked into the same operation, so the leaf is the same. +/// Plan the encryption of one value under `context`, as the typed call plans +/// it. Both calls write the value into the same operation, so the leaf has +/// the same form. fn seal<'a, K: 'static>( keyset: &'a KeysetCipher<'_, K>, value: Frame<'_>, @@ -462,14 +512,15 @@ fn seal<'a, K: 'static>( let sealed = match kind { None => encrypt_opaque(value, keyset, context), Some(ValueKind::Json) => { - // A document crosses as text or bytes, so nothing is converted. + // A document arrives as text or bytes, so nothing is converted. let document = read_json(value).map_err(not_a_document)?; - // The document is sealed through a borrow and wiped when it - // drops here, as the typed call's owned document is. + // The document is encrypted through a borrow. The document is + // wiped when it is dropped here, as the typed call's owned + // document is. encrypt_opaque(&document, keyset, context) } // The conversion also refuses a value that is not of the declared - // kind. A converted value is wiped when it drops. + // kind. A converted value is wiped when it is dropped. Some(kind) => match convert(kind, value).map_err(of_one_value)? { Some(converted) => encrypt_opaque(converted.frame(), keyset, context), None => encrypt_opaque(value, keyset, context), @@ -478,8 +529,8 @@ fn seal<'a, K: 'static>( Ok(sealed.try_map(Ciphertext::from_tree)) } -/// A refusal that the shared conversion made as a record field's, as the -/// refusal of one value: the same reason, with no field to name. +/// Turn a refusal that the shared conversion made for a record field into +/// the refusal of one value. The reason stays the same. No field is named. fn of_one_value(error: Error) -> Error { match error.reason() { Some(reason) => Error::bad_value(reason), @@ -487,7 +538,8 @@ fn of_one_value(error: Error) -> Error { } } -/// The refusal of a value that is not a document under the `json` kind. +/// The refusal of a value that is not a document, when the declared kind is +/// `json`. fn not_a_document(error: JsonValueError) -> Error { Error::bad_value(match error { JsonValueError::NotText => Reason::FieldType, @@ -495,22 +547,22 @@ fn not_a_document(error: JsonValueError) -> Error { }) } -/// The refusal of a value that opened as another kind than the one -/// declared. It names the declared kind alone. +/// The error for a value that was stored as another kind than the declared +/// kind. The error names only the declared kind. fn not_opened_as(kind: ValueKind) -> crate::Error { crate::Error::OpenedType { expected: kind.name(), } } -/// Whether a ciphertext can hold a value of `kind`. A ciphertext holds one -/// scalar, so it holds no array and no object. +/// Whether a ciphertext can contain a value of `kind`. A ciphertext contains +/// one scalar, so it never contains an array or an object. fn is_scalar_kind(kind: ValueKind) -> bool { !matches!(kind, ValueKind::Array | ValueKind::Object) } -/// Open one ciphertext under `context`, as the typed call opens it into an -/// [`OwnedFrame`], and check the value against `kind`. +/// Decrypt one ciphertext under `context` into an [`OwnedFrame`], as the +/// typed call does. Then check the value against `kind`. fn open<'a, K: 'static>( cipher_ref: CipherRef<'a, K>, ciphertext: Ciphertext, @@ -528,13 +580,14 @@ fn open<'a, K: 'static>( } } -/// The opened `value` as a value of `kind`: the value itself, or for a -/// document its JSON text in a bytes leaf. +/// Return the decrypted `value` as a value of `kind`. For a document, that +/// is the JSON text as a bytes value. For every other kind, that is the +/// value itself. /// /// # Errors /// -/// [`crate::Error::OpenedType`] naming `kind`, for a value of another -/// kind. A frame that is refused is dropped, which wipes it. +/// [`crate::Error::OpenedType`] that names `kind`, for a value of another +/// kind. A refused frame is dropped, and a dropped frame wipes its bytes. fn opened_as(kind: ValueKind, value: OwnedFrame) -> Result { if kind == ValueKind::Json { return document_frame(&value); @@ -546,13 +599,13 @@ fn opened_as(kind: ValueKind, value: OwnedFrame) -> Result Result { let document = value .visit(OneScalar::new( diff --git a/packages/stack-encrypt/src/lib.rs b/packages/stack-encrypt/src/lib.rs index 39ef000de..077268c39 100644 --- a/packages/stack-encrypt/src/lib.rs +++ b/packages/stack-encrypt/src/lib.rs @@ -370,15 +370,19 @@ endpoint — are `StackKmsBuilder`'s, and the two keyset-cache knobs are //! human-readable format such as JSON, raw bytes in a binary one. Parsing //! does not authenticate a value; decryption does. //! -//! The scalar API accepts owned [`OpaqueEncode`] values. It wipes the owned source -//! before returning the pending request, including on planning failure. A -//! ciphertext decrypts into an [`OpaqueDecode`] type: a type that one scalar -//! builds. A target that needs a container, such as a `Vec`, does -//! not compile. A -//! successful decrypt returns an ordinary owned value: the caller is then +//! The scalar API accepts owned [`OpaqueEncode`] values. The API wipes the +//! owned source before it returns the pending request, including when +//! planning fails. +//! +//! A ciphertext decrypts into an [`OpaqueDecode`] type: a type that is built +//! from one scalar. A target that needs a container, such as a +//! `Vec`, does not compile. +//! +//! A successful decrypt returns an ordinary owned value. The caller is then //! responsible for its cleanup. A whole value decrypted as an -//! [`OpaqueBlob`](crate::OpaqueBlob) is wiped on drop. Copy types may still have copies held by the -//! caller, and this is not a guarantee about every compiler-generated copy. +//! [`OpaqueBlob`](crate::OpaqueBlob) is wiped on drop. The caller can +//! still have copies of a `Copy` type. This crate makes no guarantee about +//! the copies that the compiler generates. //! //! For target-directed conversion, import [`EncryptInto`] and [`DecryptFrom`]: //! @@ -675,10 +679,10 @@ endpoint — are `StackKmsBuilder`'s, and the two keyset-cache knobs are //! module (feature `dynamic`). The guide to building such a binding, with //! the Go SDK as the reference, is `dynamic::guide`. //! -//! A binding holds a value as a frame, and learns its kind only when the -//! code runs. `dynamic::value` encrypts such a value as the one -//! [`Ciphertext`] that [`KeysetCipher::encrypt`] returns for it, and decrypts -//! one into a frame. +//! A binding has each value as a frame: one value written as bytes. The kind +//! of the value is only known when the code runs. `dynamic::value` encrypts +//! such a value as one [`Ciphertext`], and decrypts a ciphertext into a +//! frame. The typed [`KeysetCipher::decrypt`] decrypts the same ciphertext. //! //! # Relationship to vitaminc //! diff --git a/packages/stack-encrypt/src/refusal.rs b/packages/stack-encrypt/src/refusal.rs index 106468254..81e8d4540 100644 --- a/packages/stack-encrypt/src/refusal.rs +++ b/packages/stack-encrypt/src/refusal.rs @@ -56,16 +56,22 @@ use crate::target::IndexSpec; /// [`read`](crate::dynamic::read)); [`in_field`](Self::in_field) names it /// from the caller's side. /// -/// Not every variant has a [`Reason`]. [`Context`](Error::Context), -/// [`Plan`](Error::Plan), [`Source`](Error::Source), -/// [`Record`](Error::Record), [`Predicate`](Error::Predicate) and -/// [`Value`](Error::Value) do: it is -/// in the message, in [`reason`](Self::reason) and in the payload -/// (`reason`). The others carry their own payload fields instead: -/// [`Term`](Error::Term) names the index it was asked for (`index`), -/// [`UntypedIndex`](Error::UntypedIndex) the field (`field`), `Target` and -/// `Cipher` carry the payload of the error they hold, and `Internal` carries -/// none. A binding reads `reason` when it is there, and does not require it. +/// Not every variant has a [`Reason`]. These variants have one: +/// [`Context`](Error::Context), [`Plan`](Error::Plan), +/// [`Source`](Error::Source), [`Record`](Error::Record), +/// [`Predicate`](Error::Predicate), and [`Value`](Error::Value). The reason +/// is in the message, in [`reason`](Self::reason), and in the payload +/// (`reason`). +/// +/// The other variants have payload fields of their own: +/// +/// - [`Term`](Error::Term) names the index that was asked for (`index`). +/// - [`UntypedIndex`](Error::UntypedIndex) names the field (`field`). +/// - `Target` and `Cipher` have the payload of the error they wrap. +/// - `Internal` has no payload. +/// +/// A binding reads `reason` when it is present. A binding must not require +/// it. #[derive(Debug, thiserror::Error, miette::Diagnostic)] #[non_exhaustive] pub enum Error { @@ -208,18 +214,24 @@ pub enum Error { at: usize, }, - /// One value cannot be encrypted on its own, as a single ciphertext - /// ([`value::encrypt`](crate::dynamic::value::encrypt)). The value is - /// an array, an object, a passthrough, a null or `undefined`. Or it is - /// not of the kind declared for it. Or, under the `json` kind, its text - /// is not a JSON document. + /// One value cannot be encrypted as a single ciphertext. Only + /// [`value::encrypt`](crate::dynamic::value::encrypt) and + /// [`value::encrypt_with_context`](crate::dynamic::value::encrypt_with_context) + /// return this error. The cause is one of these: /// - /// The refusal names no field, because there is no record. It says - /// which kind of value was found, and never the value. + /// - The value is an array, an object, a passthrough, a null, or + /// `undefined`. + /// - The value is of another kind than the declared kind, with no exact + /// conversion to the declared kind. + /// - The text of the value is not a JSON document, when the declared + /// kind is `json`. + /// + /// The error names no field, because there is no record. The reason names + /// the kind of value that was found. The error never contains the value. #[error("the value cannot be encrypted as one ciphertext: {}", value_text(*reason))] #[diagnostic( code(stack_encrypt::dynamic_value), - help("One ciphertext holds one value that is present: text, a number, a boolean, bytes, a date, a timestamp, a decimal, a UUID or a JSON document. Encrypt a list one value at a time, and store an absent value as a database NULL.") + help("One ciphertext contains one value that is present. That value is text, a number, a boolean, bytes, a date, a timestamp, a decimal, a UUID, or a JSON document. To encrypt a list, encrypt each value separately. Store an absent value as a database NULL.") )] Value { /// What was wrong with the value. @@ -258,25 +270,22 @@ fn in_field_text(field: &Option) -> String { .unwrap_or_default() } -/// What a single-value refusal says for `reason`. +/// The text for `reason` in the message of [`Error::Value`]. /// -/// Two reasons have phrases written for a record's field: a value of -/// another type, and `undefined`. A single value has no field, so each is -/// reworded here. Every other reason says what was found, and reads the -/// same for one value. +/// The display text of two reasons mentions a field of a record: a value of +/// another type, and `undefined`. A single value has no field, so this +/// function has its own text for those two reasons. The display text of +/// every other reason names what was found, and suits one value as it is. fn value_text(reason: Reason) -> String { match reason { - Reason::FieldType => { - "it is not of the kind declared for it, and does not convert to that kind exactly" - .to_owned() - } + Reason::FieldType => "it does not convert exactly to the declared kind".to_owned(), Reason::Undefined => "it is undefined".to_owned(), found => found.to_string(), } } impl Error { - /// A single-value refusal. + /// An error for one value that cannot be encrypted as a single ciphertext. pub(crate) fn bad_value(reason: Reason) -> Self { Self::Value { reason } } @@ -370,7 +379,7 @@ impl Error { } } - /// What was wrong, for a context, plan, source, record, predicate or + /// What was wrong, for a context, plan, source, record, predicate, or /// single-value error. pub fn reason(&self) -> Option { match self { @@ -573,14 +582,15 @@ reasons! { /// A passthrough value cannot be stored as a frame: it nests deeper, /// or holds text, bytes or a key longer, than a frame carries. Unframeable => "unframeable", "a passthrough value nests deeper, or holds a longer value, than a frame carries"; - /// An array sits where one value must be: a single ciphertext holds - /// one scalar ([`value::encrypt`](crate::dynamic::value::encrypt)). + /// An array was given where one value is required. A single ciphertext + /// contains one scalar + /// ([`value::encrypt`](crate::dynamic::value::encrypt)). Array => "array", "an array where one value must be"; - /// An object sits where one value must be: a single ciphertext - /// holds one scalar. + /// An object was given where one value is required. A single ciphertext + /// contains one scalar. Object => "object", "an object where one value must be"; - /// A null, plain or typed, sits where one value must be: a single - /// ciphertext holds a value that is present. + /// A null was given where one value is required. The null can be plain + /// or typed. A single ciphertext contains a value that is present. Null => "null", "a null where one value must be"; /// A stored field is not a map of outputs. OutputsNotMap => "outputs_not_map", "a stored field is not a map of outputs"; diff --git a/packages/stack-encrypt/src/scalar.rs b/packages/stack-encrypt/src/scalar.rs index 6dcc48dc2..0dd71af53 100644 --- a/packages/stack-encrypt/src/scalar.rs +++ b/packages/stack-encrypt/src/scalar.rs @@ -112,48 +112,57 @@ pub trait OpaqueEncode: sealed::Encode + Zeroize + Send + 'static {} /// A plaintext type that one opaque [`Ciphertext`] decrypts to. /// -/// A `Ciphertext` holds one scalar. So `OpaqueDecode` is implemented for -/// every type that one scalar builds, Vitamin C's [`ScalarTarget`], that -/// also implements [`Zeroize`]: +/// A `Ciphertext` contains one scalar. So `OpaqueDecode` is implemented for +/// every type that is built from one scalar and that implements [`Zeroize`]. +/// Vitamin C names a type that is built from one scalar a [`ScalarTarget`]. +/// The `OpaqueDecode` types are: /// -/// - each scalar: `bool`, the integers, the floats, `String`, `Vec` and -/// `[u8; N]`, and the date, timestamp, decimal and UUID -/// [values](crate::value) +/// - each scalar: `bool`, the integers, the floats, `String`, `Vec`, and +/// `[u8; N]` +/// - the date, timestamp, decimal, and UUID [values](crate::value) /// - [`JsonPlaintext`](crate::json::JsonPlaintext), a JSON document /// - a [`Protected`](vitaminc_protected::Protected) of one, such as /// `Protected` -/// - an `Option` of one, such as `Option`, which reads a sealed null -/// as `None` +/// - an `Option` of one, such as `Option`. An encrypted null decrypts +/// as `None`. /// - a newtype that derives [`Decrypt`](crate::Decrypt) over one, such as /// `struct Email(String)` -/// - an `OwnedFrame`, the value as a frame, for a caller that learns the -/// value's kind only when the code runs +/// - an `OwnedFrame`: the value written as bytes, for a caller that only +/// learns the kind of the value when the code runs /// /// [`OpaqueBlob`](crate::OpaqueBlob) is an `OpaqueDecode` type too. The /// trait is sealed, as `OpaqueEncode` is. /// -/// A target that needs a container does not compile: a `Vec` of anything -/// but bytes, a map, or a struct that derives `Decrypt`. Each of them reads -/// a tree of leaves, which is a -/// [`StackCipherText`](crate::StackCipherText). Decrypt one with -/// [`KeysetCipher::decrypt_tree`]. A column of ciphertexts is a -/// `Vec`, which decrypts into a `Vec` through -/// [`DecryptFrom`]. The [crate docs on collections](crate#collections) -/// explain how. +/// A target that needs a container does not compile: +/// +/// - a `Vec` of anything but bytes +/// - a map +/// - a struct that derives `Decrypt` with named fields +/// +/// Each of those targets reads a tree of leaves. A leaf is one encrypted +/// scalar. A tree of leaves is a +/// [`StackCipherText`](crate::StackCipherText), and +/// [`KeysetCipher::decrypt_tree`] decrypts it. +/// +/// A column of ciphertexts is a `Vec`. A `Vec` +/// decrypts into a `Vec` through [`DecryptFrom`]. The +/// [crate docs on collections](crate#collections) explain how. /// /// ```compile_fail,E0277 /// # fn example(keyset: &stack_encrypt::KeysetCipher<'_, K>, ciphertext: stack_encrypt::Ciphertext) { -/// // A ciphertext holds one scalar, never a sequence. +/// // A ciphertext contains one scalar, never a sequence. /// let _ = keyset.decrypt::>(ciphertext); /// # } /// ``` /// -/// A type of your own is an `OpaqueDecode` type when one scalar builds it -/// and it implements `Zeroize`. You write no marker for that, and you -/// cannot: `ScalarTarget` follows from how the type decrypts. A newtype -/// that derives `Decrypt` over a scalar works as it is, and so does a type -/// that implements Vitamin C's `FromScalar`. The derive is Vitamin C's, so -/// your crate needs `vitaminc-aead` as a dependency to use it. +/// A type of your own is an `OpaqueDecode` type when it is built from one +/// scalar and implements `Zeroize`. You cannot implement `ScalarTarget` for +/// it: a type is a `ScalarTarget` because of how it decrypts. A newtype that +/// derives `Decrypt` over a scalar needs no extra code. Neither does a type +/// that implements Vitamin C's `FromScalar`. +/// +/// The derive is Vitamin C's, so your crate needs `vitaminc-aead` as a +/// dependency to use it. /// /// ``` /// # async fn example() -> Result<(), stack_encrypt::Error> { diff --git a/packages/stack-encrypt/tests/common/conformance.rs b/packages/stack-encrypt/tests/common/conformance.rs index 12b3921a0..d5218ecd4 100644 --- a/packages/stack-encrypt/tests/common/conformance.rs +++ b/packages/stack-encrypt/tests/common/conformance.rs @@ -202,9 +202,10 @@ fn parse_timestamp(text: &str) -> i128 { ((days * 86_400 + hour * 3_600 + minute * 60 + second) * 1_000_000_000) + nanos } -/// The sixteen bytes of a UUID from its canonical text: lowercase hex in -/// groups of 8, 4, 4, 4 and 12 digits, with `-` between them. Any other -/// spelling (uppercase, braces, no hyphens) is a corpus error. +/// The sixteen bytes of a UUID, from its canonical text. The canonical text +/// is lowercase hex in groups of 8, 4, 4, 4, and 12 digits, with `-` between +/// the groups. Any other spelling is a corpus error: uppercase, braces, or +/// no hyphens. fn parse_uuid(text: &str) -> [u8; 16] { let groups: Vec<&str> = text.split('-').collect(); let lengths: Vec = groups.iter().map(|group| group.len()).collect(); diff --git a/packages/stack-encrypt/tests/common/leaves.rs b/packages/stack-encrypt/tests/common/leaves.rs index 8f005ea25..41a4a276d 100644 --- a/packages/stack-encrypt/tests/common/leaves.rs +++ b/packages/stack-encrypt/tests/common/leaves.rs @@ -1,10 +1,13 @@ -//! Opening a sealed leaf to the plaintext sealed in it. +//! Read the plaintext of a sealed leaf. //! -//! A sealed leaf carries a random AES-GCM nonce, so two ciphertexts of one -//! value never have the same bytes. What a test can compare is the -//! plaintext each leaf was sealed with. [`kept_cipher`] is a cipher over -//! [`DeterministicSource`] that keeps each data key it generates, and -//! [`reveal`] opens leaves with those keys and the engine's leaf AAD. +//! A sealed leaf is one encrypted scalar inside a ciphertext. Each sealed +//! leaf has a random AES-GCM nonce, so two ciphertexts of one value never +//! have the same bytes. A test can compare the plaintext that each leaf was +//! sealed with. +//! +//! [`kept_cipher`] is a cipher over [`DeterministicSource`] that keeps each +//! data key it generates. [`reveal`] opens leaves with those keys, and with +//! the additional authenticated data (AAD) that the engine uses for a leaf. use std::borrow::Cow; use std::cell::RefCell; @@ -24,11 +27,12 @@ use vitaminc_protected::{Buffer, Controlled as _, Protected}; use super::{hex, DeterministicSource}; -/// The data keys a [`KeptKeys`] source generated, by IV. +/// The data keys that a [`KeptKeys`] source generated, by IV. pub type Kept = Mutex, [u8; 32]>>; -/// [`DeterministicSource`], keeping each data key it generates by its IV, -/// so a test can open the leaves sealed under them without the engine. +/// [`DeterministicSource`], with each data key it generates kept by its IV. +/// A test can then open the leaves sealed under those keys without the +/// engine. pub struct KeptKeys { inner: DeterministicSource, keys: Arc, @@ -91,10 +95,17 @@ pub async fn kept_cipher(seed: [u8; 32]) -> (StackCipher, Arc) { (cipher, keys) } -/// A vitaminc cipher that opens a stored leaf with its kept key, under the -/// AAD the engine binds a leaf to (`stack-encrypt/leaf`, the format version, -/// the keyset, the AAD of the leaf's place and the key tag, as a PAE), and -/// keeps each plaintext it opened, in walk order. +/// A vitaminc cipher that opens a stored leaf with its kept key, and keeps +/// each plaintext it opened, in walk order. +/// +/// The cipher opens the leaf under the AAD that the engine binds a leaf to. +/// That AAD is a pre-authentication encoding (PAE) of five parts: +/// +/// - the text `stack-encrypt/leaf` +/// - the format version +/// - the keyset +/// - the AAD of the leaf's place +/// - the key tag struct Reveal<'k> { keys: &'k HashMap, [u8; 32]>, opened: RefCell>, @@ -130,8 +141,9 @@ impl Cipher for Reveal<'_> { } /// The plaintext of every leaf of `tree`, sealed under `context`, in walk -/// order: a scalar's tagged bytes, a typed null's padded bytes, and an empty -/// container's marker as the empty string. +/// order. The plaintext of a scalar is its tagged bytes. The plaintext of a +/// typed null is its padded bytes. The plaintext of an empty container is +/// its marker, shown as the empty string. pub fn reveal<'c>( keys: &Kept, tree: StackCipherText, @@ -158,27 +170,28 @@ pub fn reveal<'c>( reveal.opened.into_inner() } -/// Everything of a single ciphertext that does not depend on its leaf's -/// nonce. Two ciphertexts of one value, sealed under the same data key and -/// context, have the same parts and different bytes. +/// Every part of a single ciphertext that does not depend on the nonce of +/// its leaf. Two ciphertexts of one value, sealed under the same data key +/// and context, have the same parts and different bytes. #[derive(Debug, PartialEq, Eq)] pub struct Parts { - /// The ciphertext's bytes before the leaf's AEAD output, in hex: the - /// format version, the keyset, the data key's IV, and its tag with the - /// tag's length. + /// The bytes of the ciphertext before the output of the leaf's + /// authenticated encryption (AEAD), in hex. Those bytes are the format + /// version, the keyset, the IV of the data key, and the key tag with its + /// length. pub header: String, /// The length of the whole ciphertext in bytes. pub len: usize, - /// The plaintext the leaf was sealed with, in hex: its tag and payload. + /// The plaintext that the leaf was sealed with, in hex: its tag and payload. pub leaf: String, } -/// The parts of `ciphertext`, sealed under `context`, opened with the keys -/// `keys` kept. +/// The parts of `ciphertext`, a ciphertext sealed under `context`. The kept +/// keys in `keys` open its leaf. pub fn parts<'c>(keys: &Kept, ciphertext: Ciphertext, context: impl IntoContext<'c>) -> Parts { let bytes = ciphertext.to_bytes(); - // The leaf's AEAD output is the last part of the bytes: its nonce, the - // encrypted plaintext and the authentication tag. + // The AEAD output of the leaf is the last part of the bytes: the nonce, + // the encrypted plaintext, and the authentication tag. let (_, _, _, sealed) = SealedValue::from(ciphertext.clone()).into_parts(); let header = hex(&bytes[..bytes.len() - sealed.len()]); let leaf = SealedValue::from(ciphertext); diff --git a/packages/stack-encrypt/tests/scalar.rs b/packages/stack-encrypt/tests/scalar.rs index d5ebf3942..6a9f66df9 100644 --- a/packages/stack-encrypt/tests/scalar.rs +++ b/packages/stack-encrypt/tests/scalar.rs @@ -113,9 +113,10 @@ async fn a_scalar_decrypts_straight_into_a_protected() { #[tokio::test] async fn a_ciphertext_opens_as_a_nullable_target() { - // A `Ciphertext` holds one scalar, so its target is one a scalar builds. - // A sequence does not compile (`tests/ui/scalar_decrypt_into_a_container.rs`). - // A nullable target does: it reads a value as present, and a sealed null + // A `Ciphertext` contains one scalar, so its target must be built from one + // scalar. A sequence does not compile + // (`tests/ui/scalar_decrypt_into_a_container.rs`). A nullable target + // compiles. That target reads a value as present, and an encrypted null // as absent. let cipher = common::stack_cipher().await; let keyset = cipher.default_keyset(); diff --git a/packages/stack-encrypt/tests/single_value.rs b/packages/stack-encrypt/tests/single_value.rs index 6c383f5f6..1ab891b29 100644 --- a/packages/stack-encrypt/tests/single_value.rs +++ b/packages/stack-encrypt/tests/single_value.rs @@ -1,17 +1,26 @@ -//! One value as one ciphertext through the run-time interface -//! (`dynamic::value`), held to the typed one (`keyset.encrypt`, -//! `keyset.decrypt`). +//! Tests that the run-time interface (`dynamic::value`) and the typed +//! interface (`keyset.encrypt`, `keyset.decrypt`) agree on one value as one +//! ciphertext. //! -//! A sealed leaf carries a random AES-GCM nonce, so two ciphertexts of one -//! value never have the same bytes. What the two interfaces must agree on -//! is everything else: the bytes before the leaf's AEAD output (the format -//! version, the keyset, and the data key's IV and tag), the ciphertext's -//! length, and the plaintext the leaf was sealed with. The tests here seal -//! each value through both interfaces, each over a fresh deterministic key -//! source of one seed, and compare those parts. They also open each -//! interface's ciphertext through the other. -// The typed `Uuid` case needs the `uuid` feature, which `dynamic` does not -// turn on. +//! In these tests, "seal" means encrypt and authenticate a value. "Open" +//! means decrypt a ciphertext and check it. A leaf is the one sealed scalar +//! inside a ciphertext. +//! +//! Each sealed leaf has a random AES-GCM nonce, so two ciphertexts of one +//! value never have the same bytes. The two interfaces must agree on every +//! other part: +//! +//! - the bytes before the output of the leaf's authenticated encryption: +//! the format version, the keyset, and the IV and tag of the data key +//! - the length of the ciphertext +//! - the plaintext that the leaf was sealed with +//! +//! The tests seal each value through both interfaces, and compare those +//! parts. Each interface gets a new deterministic key source with the same +//! seed. The tests also open the ciphertext of each interface through the +//! other interface. +// The typed `Uuid` case needs the `uuid` feature. The `dynamic` feature +// does not turn `uuid` on. #![cfg(all(feature = "dynamic", feature = "uuid"))] mod common; @@ -33,17 +42,17 @@ use vitaminc_aead::plaintext::{FixedType, Int, Logical, Physical, Raw, Width}; const SEED: [u8; 32] = *b"stack-encrypt single value v1 "; -/// A context a test seals under, beside the empty one. +/// A context that a test seals under, other than the empty context. fn column() -> ContextPiece<'static> { ("users", "value").into_context().into_owned() } -/// The empty context, which `keyset.encrypt` and `value::encrypt` use. +/// The empty context. `keyset.encrypt` and `value::encrypt` use it. fn no_context() -> ContextPiece<'static> { ().into_context() } -/// `value` sealed by the typed call, over a fresh key source of the seed. +/// `value` sealed by the typed call, over a new key source of the seed. async fn typed(value: S, context: &ContextPiece<'static>) -> (Ciphertext, Parts) { let (cipher, keys) = kept_cipher(SEED).await; let sealed = cipher @@ -54,7 +63,7 @@ async fn typed(value: S, context: &ContextPiece<'static>) -> (C (sealed.clone(), parts(&keys, sealed, context.clone())) } -/// `value` sealed by the run-time call, over a fresh key source of the seed. +/// `value` sealed by the run-time call, over a new key source of the seed. async fn run_time( value: &OwnedFrame, kind: Option, @@ -73,10 +82,10 @@ async fn run_time( (sealed.clone(), parts(&keys, sealed, context.clone())) } -/// The run-time call and the typed call seal the same ciphertext for one -/// value, and each opens the other's. `typed_value` builds the typed value, -/// `frame_of` the frame a binding hands over, and `stored` the frame the -/// value opens as. +/// The run-time call and the typed call seal the same parts for one value, +/// and each call opens the ciphertext of the other. `typed_value` builds the +/// typed value. `frame_of` builds the frame that a binding passes. `stored` +/// builds the frame that the value opens as. async fn assert_same_ciphertext( name: &str, typed_value: impl Fn() -> S, @@ -156,8 +165,8 @@ fn uuid_value() -> UuidValue { mod the_run_time_ciphertext_is_the_typed_one { use super::*; - /// A value of a Rust type whose frame is of the same kind, with the - /// kind declared and with none. + /// A value of a Rust type whose frame is of the same kind. The test + /// runs with the kind declared and with no declared kind. macro_rules! same { ($name:literal, $kind:expr, $ty:ty, $value:expr) => {{ let stored = frame($value); @@ -199,8 +208,8 @@ mod the_run_time_ciphertext_is_the_typed_one { } /// No Rust type spells a lone `u8`: a `Vec` is a byte string. So - /// the run-time leaf is compared with the leaf the cipher seals for the - /// same scalar walked as a tree. + /// the test compares the run-time leaf with another leaf: the one that + /// the cipher seals for the same scalar walked as a tree. #[tokio::test] async fn for_an_unsigned_8_bit_integer() { let context = column(); @@ -224,8 +233,9 @@ mod the_run_time_ciphertext_is_the_typed_one { } } - /// A number of another width or kind seals as the declared kind's - /// value, which is the ciphertext the typed call makes for that value. + /// A number of another width or kind seals as the value of the + /// declared kind. The typed call makes the same ciphertext parts for + /// that value. #[tokio::test] async fn for_a_number_converted_to_its_declared_kind() { assert_same_ciphertext( @@ -266,13 +276,14 @@ mod the_run_time_ciphertext_is_the_typed_one { .await; } - /// A document's JSON text, in a text leaf or a bytes leaf, seals as - /// the typed call seals the document: as its compact JSON text. + /// A document arrives as JSON text, as a text value or a bytes value. + /// `encrypt` seals it as the typed call seals the document: as its + /// compact JSON text. #[tokio::test] async fn for_a_json_document() { let text = r#"{ "b": [1, 2.5, null], "a": "é" }"#; let document = || JsonPlaintext::parse(text).expect("a document"); - // What a `String` reads back: the text the document was sealed as. + // What a `String` reads back: the text that the document was sealed as. let sealed_text = frame(r#"{"a":"é","b":[1,2.5,null]}"#); for (name, crossing) in [ ("json as text", frame(text)), @@ -293,8 +304,9 @@ mod the_run_time_ciphertext_is_the_typed_one { proptest! { #![proptest_config(ProptestConfig::with_cases(48))] - /// For any scalar, any declared kind that is the scalar's own, and - /// any context, the run-time ciphertext is the typed one. + /// For any scalar, any context, and the scalar's own kind as the + /// declared kind, the run-time ciphertext has the parts of the typed + /// ciphertext. #[test] fn for_any_generated_scalar( scalar in any_scalar(), @@ -323,7 +335,7 @@ mod the_run_time_ciphertext_is_the_typed_one { } } - /// One generated scalar, of a kind a Rust type spells. + /// One generated scalar, of a kind that a Rust type spells. #[derive(Debug, Clone)] enum Scalar { Bool(bool), @@ -381,7 +393,7 @@ mod the_run_time_ciphertext_is_the_typed_one { } } -/// A frame the hand writes: a passthrough of the text `clear`. +/// A frame written by hand: a passthrough of the text `clear`. fn passthrough() -> OwnedFrame { let mut bytes = vec![PASSTHROUGH]; bytes.extend_from_slice(frame("clear").frame().as_bytes()); @@ -396,8 +408,8 @@ fn undefined() -> OwnedFrame { frame(Raw(Some(Logical::Undefined), Physical::Null)) } -/// The refusal `value::encrypt` makes for `value` under `kind`, with a -/// check that it made no key request. +/// The refusal that `value::encrypt` makes for `value` under `kind`. Also +/// checks that the call made no key request. async fn refused(value: &OwnedFrame, kind: Option) -> dynamic::Error { let (cipher, generates, retrieves) = common::counting_cipher().await; let keyset = cipher.default_keyset(); @@ -428,8 +440,8 @@ async fn refused(value: &OwnedFrame, kind: Option) -> dynamic::Error single } -/// A single-value refusal: its own variant and code, the reason, and a -/// message about one value, with no record, plan or field in it. +/// A single-value refusal has its own variant and code, the reason, and a +/// message about one value. The message mentions no record, plan, or field. fn assert_value_refusal(error: &dynamic::Error, reason: Reason, what: &str) { use stack_encrypt::ErrorPayload as _; assert!( @@ -451,13 +463,11 @@ fn assert_value_refusal(error: &dynamic::Error, reason: Reason, what: &str) { Some(reason.as_str()), "{what}: the payload carries the reason" ); - // Two reasons have phrases written for a record's field. One value has - // no field, so its refusal words them for a value. + // The display text of two reasons mentions a field of a record. One + // value has no field, so `Error::Value` has its own text for those + // reasons. let found = match reason { - Reason::FieldType => { - "it is not of the kind declared for it, and does not convert to that kind exactly" - .to_owned() - } + Reason::FieldType => "it does not convert exactly to the declared kind".to_owned(), Reason::Undefined => "it is undefined".to_owned(), found => found.to_string(), }; @@ -493,8 +503,8 @@ mod encrypt_refuses_before_any_key_request { ("a typed null", typed_null(), Reason::Null), ]; for (what, value, reason) in &cases { - // With no declared kind, and with a kind of each shape: what - // was found is reported, whatever was declared. + // With no declared kind, and with a kind of each shape. The refusal + // reports what was found, whatever kind was declared. for kind in [ None, Some(ValueKind::Int64), @@ -508,8 +518,8 @@ mod encrypt_refuses_before_any_key_request { } } - /// `undefined` is most often a property name spelt wrong, and no typed - /// call could read it back. So it is refused with a declared kind and + /// `undefined` is most often a misspelt property name. No typed call + /// could read it back. So `encrypt` refuses it with a declared kind and /// with none. #[tokio::test] async fn undefined_whatever_kind_is_declared() { @@ -571,7 +581,8 @@ mod encrypt_refuses_before_any_key_request { } } - /// A refusal says what kind of value was found, and nothing of it. + /// A refusal names the kind of value that was found, and contains no + /// part of the value. #[tokio::test] async fn without_any_of_the_value_in_the_error() { let secret = "sk_live_4242424242"; @@ -600,16 +611,16 @@ mod encrypt_refuses_before_any_key_request { mod encrypt_with_no_declared_kind { use super::*; - /// A scalar of a logical type this build does not know: the frame and - /// the leaf carry its type id, and no kind names it. + /// A scalar of a logical type that this build does not define. The frame + /// and the leaf record the id of the type, and no kind names it. fn unknown_logical() -> OwnedFrame { let unknown = Logical::from_wire(200, 9).expect("an id no build knows yet"); frame(Raw(Some(unknown), Physical::Int(Int::I32(7)))) } - /// The leaf format carries a logical type it does not know, so a value - /// of a newer type survives an older build. The value is one scalar, - /// and it is sealed as it arrived. + /// The leaf format records a logical type that this build does not + /// define. So an older build can store a value of a newer type. The + /// value is one scalar. `encrypt` seals it as it arrived. #[tokio::test] async fn seals_a_scalar_of_an_unknown_logical_type_as_it_arrived() { let cipher = common::stack_cipher().await; @@ -629,7 +640,7 @@ mod encrypt_with_no_declared_kind { "the value opens with its type id" ); - // It opens as no declared kind, and as no Rust type. + // The ciphertext opens as no declared kind, and as no Rust type. let as_int = value::decrypt(&keyset, sealed.clone(), Some(ValueKind::Int32)).await; assert!( matches!(as_int, Err(Error::OpenedType { expected: "int32" })), @@ -654,9 +665,10 @@ mod encrypt_with_no_declared_kind { } } - /// A known logical type over a value it does not admit never reaches - /// `encrypt`: no frame holds one. The frame writer refuses to write it, - /// and the frame reader refuses bytes that spell it. + /// A known logical type over a value that the type does not admit never + /// reaches `encrypt`, because no frame can contain one. The frame + /// writer refuses to write it. The frame reader refuses bytes that spell + /// it. #[test] fn a_logical_type_over_a_value_it_does_not_admit_is_not_a_frame() { let short_uuid = Raw(Some(Logical::Uuid), Physical::Bytes(&[7; 15])); @@ -664,8 +676,8 @@ mod encrypt_with_no_declared_kind { OwnedFrame::of(short_uuid).is_err(), "the writer must refuse a UUID of fifteen bytes" ); - // A real UUID's frame, with one byte taken off the payload and off - // the length. + // The frame of a real UUID, with one byte removed from the payload and + // from the length. let uuid = frame(Raw(Some(Logical::Uuid), Physical::Bytes(&[7; 16]))); let mut bytes = uuid.frame().as_bytes().to_vec(); let length = bytes.len() - 16 - 4; @@ -745,7 +757,7 @@ mod encrypt_with_a_context { ); } - /// The call shows the context it will use, as the typed call does. + /// The call shows the context that it will use, as the typed call does. #[tokio::test] async fn runs_under_the_context_the_typed_call_runs_under() { let cipher = common::stack_cipher().await; @@ -770,8 +782,8 @@ mod encrypt_with_a_context { } /// The run-time interface has no batch call. A binding makes one call for -/// each value and merges them with `Pending::all`, which sends one key -/// request. +/// each value, and merges the calls with `Pending::all`. The merged call +/// sends one key request. mod many_values_merged_with_pending_all { use super::*; @@ -779,7 +791,8 @@ mod many_values_merged_with_pending_all { async fn seal_and_open_in_one_key_request_each_and_keep_their_order() { let (cipher, generates, retrieves) = common::counting_cipher().await; let keyset = cipher.default_keyset(); - // Each value has its own declared kind, and the last its own context. + // Each value has its own declared kind. The last value also has its own + // context. let values = [frame(1.0f64), frame("two"), frame(true), frame(4i64)]; let kinds = [ Some(ValueKind::UInt32), @@ -843,7 +856,7 @@ mod many_values_merged_with_pending_all { ); } - // The value sealed under a context opens only under it. + // A value sealed under a context opens only under that context. let without = value::decrypt(&keyset, sealed[3].clone(), kinds[3]).await; assert!( matches!(without, Err(Error::Aead)), @@ -936,8 +949,8 @@ mod decrypt { .expect("a uint64 opens as uint64"); assert_eq!(opened.frame(), frame(34u64).frame(), "the sealed value"); - // An integer of another width is another kind: decrypt converts - // nothing, as a record's typed field converts nothing when it opens. + // An integer of another width is another kind. `decrypt` converts + // nothing, as a typed field of a record converts nothing when it opens. let narrower = value::decrypt(&keyset, sealed, Some(ValueKind::UInt32)).await; assert!( matches!(narrower, Err(Error::OpenedType { expected: "uint32" })), @@ -945,8 +958,8 @@ mod decrypt { ); } - /// A refusal names the kind that was expected. It never says what the - /// value opened as. + /// A refusal names the kind that was expected. A refusal never says + /// what the value opened as. #[tokio::test] async fn refuses_another_kind_without_saying_what_the_value_is() { let cipher = common::stack_cipher().await; @@ -1052,7 +1065,7 @@ mod decrypt { mod decrypt_a_json_document { use super::*; - /// The frame a `json` value opens as: its JSON text in a bytes leaf. + /// The frame that a `json` value opens as: its JSON text as a bytes value. fn document(text: &str) -> OwnedFrame { frame(text.as_bytes().to_vec()) } @@ -1081,7 +1094,7 @@ mod decrypt_a_json_document { "the frame a record's json field opens as" ); - // With no declared kind the leaf comes back as it was sealed: text. + // With no declared kind, the leaf comes back as it was sealed: as text. let as_sealed = value::decrypt(&keyset, sealed, None) .await .expect("it opens"); @@ -1133,7 +1146,8 @@ mod decrypt_a_json_document { keyset.encrypt(String::from("{not json")).await, ), ("an integer", keyset.encrypt(7i64).await), - // The typed document reads a text leaf alone, and so does this. + // The typed document reads only a text leaf. `decrypt` as `json` does the + // same. ( "JSON text in a bytes leaf", keyset.encrypt(b"{}".to_vec()).await, @@ -1149,9 +1163,9 @@ mod decrypt_a_json_document { } } - /// `json` is a declared kind, and a document is stored as text. So a - /// string and a document share one stored form, and a kind check - /// cannot tell them apart. + /// `json` is a declared kind, and the engine stores a document as text. + /// So a string and a document have one stored form. A kind check cannot + /// distinguish them. #[tokio::test] async fn opens_a_string_that_holds_json_text_and_returns_it_as_the_engine_writes_it() { let cipher = common::stack_cipher().await; diff --git a/packages/stack-encrypt/tests/single_value_conformance.rs b/packages/stack-encrypt/tests/single_value_conformance.rs index 0816f6eac..5ce813f20 100644 --- a/packages/stack-encrypt/tests/single_value_conformance.rs +++ b/packages/stack-encrypt/tests/single_value_conformance.rs @@ -1,8 +1,11 @@ -//! The shared single-value profile: one value as one ciphertext through the -//! run-time interface, with what it seals held to the typed interface and -//! to frozen artifacts. See conformance/stack-encrypt/single-value-contract.md. -// The typed `Uuid` reference needs the `uuid` feature, which `dynamic` does -// not turn on. +//! The runner for the shared single-value conformance profile. +//! +//! The profile encrypts one value as one ciphertext through the run-time +//! interface. The runner compares each result with the typed interface and +//! with the frozen artifacts. See +//! `conformance/stack-encrypt/single-value-contract.md`. +// The typed `Uuid` reference needs the `uuid` feature. The `dynamic` +// feature does not turn `uuid` on. #![cfg(all(feature = "dynamic", feature = "uuid"))] mod common; @@ -29,8 +32,9 @@ use vitaminc_aead::plaintext::{FixedType, Width}; const PROFILE: &str = "single-value-v1"; -/// The values an input of type `shape` names: what `{type, text}` cannot -/// spell. A name outside this list is a corpus error. +/// The values that an input of type `shape` can name. The `{type, text}` +/// form cannot spell these values. A name outside this list is a corpus +/// error. const SHAPES: [&str; 5] = [ "array", "empty_array", @@ -54,18 +58,19 @@ struct Corpus { #[serde(deny_unknown_fields)] struct Case { id: String, - /// The declared kind's name, or empty for none. + /// The name of the declared kind, or empty for none. kind: String, - /// The context's parts, or empty for the empty context. + /// The parts of the context, or empty for the empty context. context: Vec, input: Input, - /// The value the ciphertext holds, where it is not the input: a number - /// converted to the declared kind, or a document's compact JSON text. + /// The value in the ciphertext, where it differs from the input. That is + /// a number converted to the declared kind, or the compact JSON text of a + /// document. stored: Option, - /// Kinds the ciphertext must refuse to open as. + /// Kinds that the ciphertext must not decrypt as. refused_as: Option>, - /// Kinds the ciphertext must open as, beside the declared one, each - /// with the value it opens to. + /// Kinds that the ciphertext must decrypt as, other than the declared + /// kind. Each has the value that the ciphertext decrypts to. opens_as: Option>, expected_error: Option, } @@ -86,7 +91,7 @@ struct Batch { kinds: Vec, context: Vec, inputs: Vec, - /// The values the ciphertexts hold, where they are not the inputs. + /// The values in the ciphertexts, where they differ from the inputs. stored: Option>, expected_error: Option, } @@ -110,10 +115,10 @@ struct Artifacts { #[derive(Deserialize, Serialize)] #[serde(deny_unknown_fields)] struct Artifact { - /// The input's transport frame. + /// The frame of the input: the value written as bytes. frame: String, - /// The plaintext the leaf is sealed with: its tag and payload. Absent - /// for a refused case. + /// The plaintext that the leaf is sealed with: its tag and payload. + /// Absent for a refused case. #[serde(skip_serializing_if = "Option::is_none")] leaf: Option, /// A ciphertext of the value, frozen. Absent for a refused case. @@ -125,7 +130,7 @@ fn root() -> PathBuf { PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../conformance/stack-encrypt/v1") } -/// The value an input of type `shape` names. +/// The value that an input of type `shape` names. fn shape(name: &str) -> OwnedFrame { assert!( SHAPES.contains(&name), @@ -144,8 +149,8 @@ fn shape(name: &str) -> OwnedFrame { } } -/// The frame an input names: a shape, or a value in the corpus's -/// `{type, text}` form. +/// The frame that an input names: a shape, or a value in the +/// `{type, text}` form of the corpus. fn input(input: &Input) -> OwnedFrame { match input.kind.as_str() { "shape" => shape(&input.text), @@ -157,7 +162,7 @@ fn declared(kind: &str) -> Option { (!kind.is_empty()).then(|| kind.parse().expect("a kind's name")) } -/// A case's context, as a binding hands one over: a frame of its parts. +/// The context of a case, as a binding passes one: a frame of its parts. fn piece(parts: &[String]) -> ContextPiece<'static> { let frame = recipher_frame::serde::to_vec(&parts).expect("a context frames"); dynamic::context(frame.as_protected_ref()) @@ -165,8 +170,8 @@ fn piece(parts: &[String]) -> ContextPiece<'static> { .into_inner() } -/// The run-time encrypt: the form with no context for an empty context, -/// and the form with one otherwise. +/// The run-time encrypt. An empty context uses the form with no context. Any +/// other context uses the form with a context. fn seal<'a, K: 'static>( keyset: &'a KeysetCipher<'_, K>, value: Frame<'_>, @@ -180,9 +185,10 @@ fn seal<'a, K: 'static>( } } -/// A batch, as a binding seals one: one single-value call for each value, -/// each with its own declared kind, merged into one key request. A refused -/// value is the batch's refusal, and nothing is merged. +/// A batch, as a binding encrypts one. The binding makes one single-value +/// call for each value, each with its own declared kind. The binding then +/// merges the calls into one key request. A refused value refuses the whole +/// batch. No call is merged. fn seal_all<'a, K: 'static>( keyset: &'a KeysetCipher<'_, K>, values: &[OwnedFrame], @@ -210,8 +216,9 @@ fn open<'a, K: 'static>( } } -/// A batch, as a binding opens one: one single-value call for each -/// ciphertext, each with its own declared kind, merged into one key request. +/// A batch, as a binding decrypts one. The binding makes one single-value +/// call for each ciphertext, each with its own declared kind. The binding +/// then merges the calls into one key request. fn open_all<'a, K: 'static>( keyset: &'a KeysetCipher<'_, K>, ciphertexts: Vec, @@ -226,8 +233,8 @@ fn open_all<'a, K: 'static>( Pending::all(keyset, calls) } -/// The context `ciphertext`'s leaf is sealed under, for opening the leaf -/// with a kept key. +/// The context that the leaf of `ciphertext` is sealed under. Opening the +/// leaf with a kept key needs this context. fn sealed_under(context: &[String]) -> ContextPiece<'static> { if context.is_empty() { ().into_context() @@ -236,9 +243,9 @@ fn sealed_under(context: &[String]) -> ContextPiece<'static> { } } -/// The Rust types the typed interface spells a kind with. `$run` is handed -/// the type for `name`, or the match is `None` for a kind no Rust type -/// spells: a lone 8-bit unsigned integer. +/// The Rust type that the typed interface uses for each kind. `$run` +/// receives the type for `name`. The match is `None` for the one kind that +/// no Rust type spells: a lone 8-bit unsigned integer. macro_rules! with_rust_type { ($name:expr, $run:ident) => { match $name { @@ -267,8 +274,8 @@ macro_rules! with_rust_type { }; } -/// The typed call's ciphertext of the value `stored` holds, as the Rust -/// type `name` names. +/// The ciphertext that the typed call makes for the value in `stored`, as +/// the Rust type that `name` names. async fn typed_seal( keyset: &KeysetCipher<'_, K>, name: &str, @@ -294,8 +301,8 @@ where with_rust_type!(name, seal_as) } -/// The value the typed call opens `ciphertext` to, as the Rust type `name` -/// names, written as a frame. +/// The value that the typed call decrypts `ciphertext` to, as the Rust type +/// that `name` names. The value is written as a frame. async fn typed_open( keyset: &KeysetCipher<'_, K>, name: &str, @@ -363,8 +370,8 @@ fn is_forbidden(result: &Result) -> bool { ) } -/// One accepted case: what the run-time call seals is what the typed call -/// seals and what the artifact froze, and every reader opens it. +/// One accepted case. The run-time call must seal what the typed call seals +/// and what the artifact froze. Every reader must open the result. async fn accepted( seed: [u8; 32], case: &Case, @@ -387,8 +394,8 @@ async fn accepted( .unwrap_or_else(|error| panic!("{id}: the value does not seal: {error}")); let fresh_parts = parts(&keys, fresh.clone(), sealed_under(context)); - // The typed call, over a fresh source of the same seed, so that its - // data key is the one the run-time call was given. + // The typed call, over a new source of the same seed. The typed call + // then gets the data key that the run-time call was given. let typed_name = if case.kind == "json" { "json" } else { @@ -407,8 +414,8 @@ async fn accepted( artifact.leaf = Some(fresh_parts.leaf.clone()); artifact.ciphertext = Some(hex(&typed.unwrap_or_else(|| fresh.clone()).to_bytes())); // An update keeps the frozen ciphertext of a case whose leaf has not - // changed. So a ciphertext stays frozen from one update to the next, - // and the checks below hold the kept one to today's engine. + // changed. So a ciphertext stays frozen from one update to the next. The + // checks below test the kept ciphertext against the current engine. if let Some(kept) = kept.filter(|kept| kept.leaf == artifact.leaf && kept.ciphertext.is_some()) { artifact.ciphertext.clone_from(&kept.ciphertext); @@ -431,7 +438,7 @@ async fn accepted( "{id}: the frozen ciphertext differs from a fresh one in a part that is not the nonce" ); - // Under the `json` kind a document opens as its text in a bytes leaf. + // With the `json` kind, a document decrypts as its text in a bytes value. let opened_as_declared = if case.kind == "json" { frame(stored_input.text.as_bytes().to_vec()) } else { diff --git a/packages/stack-encrypt/tests/ui/pass/scalar_decrypt_targets.rs b/packages/stack-encrypt/tests/ui/pass/scalar_decrypt_targets.rs index 53a284781..b3caed3b7 100644 --- a/packages/stack-encrypt/tests/ui/pass/scalar_decrypt_targets.rs +++ b/packages/stack-encrypt/tests/ui/pass/scalar_decrypt_targets.rs @@ -1,9 +1,14 @@ -//! The targets one `Ciphertext` decrypts into, which must compile: every -//! scalar, a `Protected` of one, a nullable one, a JSON document, the date, -//! timestamp, decimal and UUID values, a derived newtype of one with no -//! marker written for it, an opaque blob and a frame. +//! The targets that one `Ciphertext` decrypts into. Each must compile: +//! +//! - every scalar +//! - a `Protected` of a scalar, and a nullable scalar +//! - a JSON document +//! - the date, timestamp, decimal, and UUID values +//! - a derived newtype of a scalar, with no marker impl written for it +//! - an opaque blob, and a frame +//! //! `tests/ui/scalar_decrypt_into_a_container.rs` pins the targets that must -//! not. +//! not compile. use stack_encrypt::dynamic::frame::OwnedFrame; use stack_encrypt::json::JsonPlaintext; use stack_encrypt::value::{Date, Decimal, Timestamp, Uuid}; @@ -14,12 +19,12 @@ use stack_encrypt::{ use stack_kms::FakeDataKeySource; /// A newtype that derives `Decrypt` over a scalar decrypts from one -/// ciphertext as it is. Nothing else is written for it. +/// ciphertext with no extra code. #[derive(Decrypt, zeroize::Zeroize)] struct Email(String); -/// The same over an integer, over another newtype, and over a nullable -/// scalar. +/// The same is true for a newtype of an integer, of another newtype, and of +/// a nullable scalar. #[derive(Decrypt, zeroize::Zeroize)] struct UserId(u64); #[derive(Decrypt, zeroize::Zeroize)] @@ -27,7 +32,8 @@ struct PrimaryEmail(Email); #[derive(Decrypt, zeroize::Zeroize)] struct Nickname(Option); -/// A whole value stored as one blob keeps its own way in. +/// A whole value stored as one blob decrypts through `OpaqueBlob`. +/// `OpaqueBlob` has its own impl of `OpaqueDecode`. #[derive(Default, serde::Deserialize, zeroize::Zeroize)] struct Profile { name: String, @@ -86,7 +92,8 @@ async fn calls( let _ = OwnedFrame::decrypt_from(ciphertext.clone(), cipher).await?; let _ = Email::decrypt_from(ciphertext.clone(), cipher).await?; let _: UserId = keyset.decrypt(ciphertext.clone()).await?; - // A column of ciphertexts is a `Vec` of them, one scalar each. + // A column of ciphertexts is a `Vec`, with one scalar in + // each ciphertext. let _ = Vec::::decrypt_from(vec![ciphertext], keyset).await?; Ok(()) } diff --git a/packages/stack-encrypt/tests/ui/scalar_decrypt_into_a_container.rs b/packages/stack-encrypt/tests/ui/scalar_decrypt_into_a_container.rs index 4ae5843d8..a26885e7a 100644 --- a/packages/stack-encrypt/tests/ui/scalar_decrypt_into_a_container.rs +++ b/packages/stack-encrypt/tests/ui/scalar_decrypt_into_a_container.rs @@ -1,8 +1,8 @@ -//! A `Ciphertext` holds one scalar, so it decrypts only into a target that -//! one scalar builds. A sequence, a map, a derived struct, a derived -//! newtype of a sequence and a protected sequence each need a container, -//! and do not compile. -//! `tests/ui/pass/scalar_decrypt_targets.rs` pins the targets that do. +//! A `Ciphertext` contains one scalar. So its target must be built from one +//! scalar. A target that needs a container does not compile. These tests +//! cover a sequence, a map, a derived struct, a derived newtype of a +//! sequence, and a protected sequence. +//! `tests/ui/pass/scalar_decrypt_targets.rs` pins the targets that compile. use std::collections::{BTreeMap, HashMap}; use stack_encrypt::{Ciphertext, Decrypt, DecryptFrom, KeysetCipher, Protected}; diff --git a/packages/stack-encrypt/tests/ui/scalar_decrypt_into_a_container.stderr b/packages/stack-encrypt/tests/ui/scalar_decrypt_into_a_container.stderr index c3ab7b7f8..b5d0730be 100644 --- a/packages/stack-encrypt/tests/ui/scalar_decrypt_into_a_container.stderr +++ b/packages/stack-encrypt/tests/ui/scalar_decrypt_into_a_container.stderr @@ -1,15 +1,16 @@ -error[E0277]: one ciphertext holds one value, and this decrypt target is not built from one value +error[E0277]: this target cannot be decrypted from one ciphertext --> tests/ui/scalar_decrypt_into_a_container.rs:19:30 | 19 | let _ = keyset.decrypt::>(ciphertext.clone()); - | ------- ^^^^^^^^^^^ this target cannot be decrypted from one ciphertext + | ------- ^^^^^^^^^^^ one ciphertext contains one value, and this target needs more | | | required by a bound introduced by this call | = help: the trait `TakesScalar` is not implemented for `vitaminc_aead::typed::List` - = note: `vitaminc_aead::typed::List` is the target's sink, and it does not read a single scalar - = note: a single ciphertext decrypts into a scalar such as `String`, `i64` or `Vec`, an `Option` or a `Protected` of one, or a newtype that derives `Decrypt` over one - = note: to decrypt many values, decrypt a `Vec`, which opens each ciphertext into one element; to decrypt a sequence, a map or a struct that was encrypted as a tree, use `decrypt_tree` + = note: `vitaminc_aead::typed::List` is the sink that builds this target, and that sink does not build its value from one scalar + = note: one ciphertext decrypts into a scalar such as `String`, `i64`, or `Vec`, or into an `Option`, a `Protected`, or a derived newtype of a scalar + = note: to decrypt many values, decrypt a `Vec`: each ciphertext becomes one element + = note: to decrypt a sequence, a map, or a struct that was encrypted as a tree, use `decrypt_tree` = help: the following other types implement trait `TakesScalar`: Optional OwnedFrameSink @@ -28,18 +29,19 @@ note: required by a bound in `stack_encrypt::scalar::>: | pub fn decrypt(&self, ciphertext: Ciphertext) -> Pending<'_, P, K> { | ^^^^^^^^^^^^ required by this bound in `stack_encrypt::scalar::>::decrypt` -error[E0277]: one ciphertext holds one value, and this decrypt target is not built from one value +error[E0277]: this target cannot be decrypted from one ciphertext --> tests/ui/scalar_decrypt_into_a_container.rs:20:30 | 20 | let _ = keyset.decrypt::>(ciphertext.clone()); - | ------- ^^^^^^^^^^^^^^^^^^^^^ this target cannot be decrypted from one ciphertext + | ------- ^^^^^^^^^^^^^^^^^^^^^ one ciphertext contains one value, and this target needs more | | | required by a bound introduced by this call | = help: the trait `TakesScalar` is not implemented for `Dict>` - = note: `Dict>` is the target's sink, and it does not read a single scalar - = note: a single ciphertext decrypts into a scalar such as `String`, `i64` or `Vec`, an `Option` or a `Protected` of one, or a newtype that derives `Decrypt` over one - = note: to decrypt many values, decrypt a `Vec`, which opens each ciphertext into one element; to decrypt a sequence, a map or a struct that was encrypted as a tree, use `decrypt_tree` + = note: `Dict>` is the sink that builds this target, and that sink does not build its value from one scalar + = note: one ciphertext decrypts into a scalar such as `String`, `i64`, or `Vec`, or into an `Option`, a `Protected`, or a derived newtype of a scalar + = note: to decrypt many values, decrypt a `Vec`: each ciphertext becomes one element + = note: to decrypt a sequence, a map, or a struct that was encrypted as a tree, use `decrypt_tree` = help: the following other types implement trait `TakesScalar`: Optional OwnedFrameSink @@ -84,11 +86,11 @@ note: required by a bound in `stack_encrypt::scalar::>: | pub fn decrypt(&self, ciphertext: Ciphertext) -> Pending<'_, P, K> { | ^^^^^^^^^^^^ required by this bound in `stack_encrypt::scalar::>::decrypt` -error[E0277]: one ciphertext holds one value, and this decrypt target is not built from one value +error[E0277]: this target cannot be decrypted from one ciphertext --> tests/ui/scalar_decrypt_into_a_container.rs:21:30 | 21 | let _ = keyset.decrypt::(ciphertext.clone()); - | ------- ^^^^^^^ this target cannot be decrypted from one ciphertext + | ------- ^^^^^^^ one ciphertext contains one value, and this target needs more | | | required by a bound introduced by this call | @@ -97,9 +99,10 @@ help: the trait `TakesScalar` is not implemented for `__AccountDecryptSink` | 10 | #[derive(Decrypt, zeroize::Zeroize)] | ^^^^^^^ - = note: `__AccountDecryptSink` is the target's sink, and it does not read a single scalar - = note: a single ciphertext decrypts into a scalar such as `String`, `i64` or `Vec`, an `Option` or a `Protected` of one, or a newtype that derives `Decrypt` over one - = note: to decrypt many values, decrypt a `Vec`, which opens each ciphertext into one element; to decrypt a sequence, a map or a struct that was encrypted as a tree, use `decrypt_tree` + = note: `__AccountDecryptSink` is the sink that builds this target, and that sink does not build its value from one scalar + = note: one ciphertext decrypts into a scalar such as `String`, `i64`, or `Vec`, or into an `Option`, a `Protected`, or a derived newtype of a scalar + = note: to decrypt many values, decrypt a `Vec`: each ciphertext becomes one element + = note: to decrypt a sequence, a map, or a struct that was encrypted as a tree, use `decrypt_tree` = help: the following other types implement trait `TakesScalar`: Optional OwnedFrameSink @@ -117,18 +120,19 @@ note: required by a bound in `stack_encrypt::scalar::>: | ^^^^^^^^^^^^ required by this bound in `stack_encrypt::scalar::>::decrypt` = note: this error originates in the derive macro `Decrypt` (in Nightly builds, run with -Z macro-backtrace for more info) -error[E0277]: one ciphertext holds one value, and this decrypt target is not built from one value +error[E0277]: this target cannot be decrypted from one ciphertext --> tests/ui/scalar_decrypt_into_a_container.rs:22:30 | 22 | let _ = keyset.decrypt::(ciphertext.clone()); - | ------- ^^^^ this target cannot be decrypted from one ciphertext + | ------- ^^^^ one ciphertext contains one value, and this target needs more | | | required by a bound introduced by this call | = help: the trait `TakesScalar` is not implemented for `vitaminc_aead::typed::List` - = note: `vitaminc_aead::typed::List` is the target's sink, and it does not read a single scalar - = note: a single ciphertext decrypts into a scalar such as `String`, `i64` or `Vec`, an `Option` or a `Protected` of one, or a newtype that derives `Decrypt` over one - = note: to decrypt many values, decrypt a `Vec`, which opens each ciphertext into one element; to decrypt a sequence, a map or a struct that was encrypted as a tree, use `decrypt_tree` + = note: `vitaminc_aead::typed::List` is the sink that builds this target, and that sink does not build its value from one scalar + = note: one ciphertext decrypts into a scalar such as `String`, `i64`, or `Vec`, or into an `Option`, a `Protected`, or a derived newtype of a scalar + = note: to decrypt many values, decrypt a `Vec`: each ciphertext becomes one element + = note: to decrypt a sequence, a map, or a struct that was encrypted as a tree, use `decrypt_tree` = help: the following other types implement trait `TakesScalar`: Optional OwnedFrameSink @@ -148,18 +152,19 @@ note: required by a bound in `stack_encrypt::scalar::>: | pub fn decrypt(&self, ciphertext: Ciphertext) -> Pending<'_, P, K> { | ^^^^^^^^^^^^ required by this bound in `stack_encrypt::scalar::>::decrypt` -error[E0277]: one ciphertext holds one value, and this decrypt target is not built from one value +error[E0277]: this target cannot be decrypted from one ciphertext --> tests/ui/scalar_decrypt_into_a_container.rs:23:30 | 23 | let _ = keyset.decrypt::>>(ciphertext.clone()); - | ------- ^^^^^^^^^^^^^^^^^^^ this target cannot be decrypted from one ciphertext + | ------- ^^^^^^^^^^^^^^^^^^^ one ciphertext contains one value, and this target needs more | | | required by a bound introduced by this call | = help: the trait `TakesScalar` is not implemented for `ProtectedList` - = note: `ProtectedList` is the target's sink, and it does not read a single scalar - = note: a single ciphertext decrypts into a scalar such as `String`, `i64` or `Vec`, an `Option` or a `Protected` of one, or a newtype that derives `Decrypt` over one - = note: to decrypt many values, decrypt a `Vec`, which opens each ciphertext into one element; to decrypt a sequence, a map or a struct that was encrypted as a tree, use `decrypt_tree` + = note: `ProtectedList` is the sink that builds this target, and that sink does not build its value from one scalar + = note: one ciphertext decrypts into a scalar such as `String`, `i64`, or `Vec`, or into an `Option`, a `Protected`, or a derived newtype of a scalar + = note: to decrypt many values, decrypt a `Vec`: each ciphertext becomes one element + = note: to decrypt a sequence, a map, or a struct that was encrypted as a tree, use `decrypt_tree` = help: the following other types implement trait `TakesScalar`: Optional OwnedFrameSink @@ -178,18 +183,19 @@ note: required by a bound in `stack_encrypt::scalar::>: | pub fn decrypt(&self, ciphertext: Ciphertext) -> Pending<'_, P, K> { | ^^^^^^^^^^^^ required by this bound in `stack_encrypt::scalar::>::decrypt` -error[E0277]: one ciphertext holds one value, and this decrypt target is not built from one value +error[E0277]: this target cannot be decrypted from one ciphertext --> tests/ui/scalar_decrypt_into_a_container.rs:24:43 | 24 | let _ = keyset.decrypt_with_context::>(ciphertext.clone(), "users/tags"); - | -------------------- ^^^^^^^^^^^^^^^^^^^^^^^ this target cannot be decrypted from one ciphertext + | -------------------- ^^^^^^^^^^^^^^^^^^^^^^^ one ciphertext contains one value, and this target needs more | | | required by a bound introduced by this call | = help: the trait `TakesScalar` is not implemented for `Dict>` - = note: `Dict>` is the target's sink, and it does not read a single scalar - = note: a single ciphertext decrypts into a scalar such as `String`, `i64` or `Vec`, an `Option` or a `Protected` of one, or a newtype that derives `Decrypt` over one - = note: to decrypt many values, decrypt a `Vec`, which opens each ciphertext into one element; to decrypt a sequence, a map or a struct that was encrypted as a tree, use `decrypt_tree` + = note: `Dict>` is the sink that builds this target, and that sink does not build its value from one scalar + = note: one ciphertext decrypts into a scalar such as `String`, `i64`, or `Vec`, or into an `Option`, a `Protected`, or a derived newtype of a scalar + = note: to decrypt many values, decrypt a `Vec`: each ciphertext becomes one element + = note: to decrypt a sequence, a map, or a struct that was encrypted as a tree, use `decrypt_tree` = help: the following other types implement trait `TakesScalar`: Optional OwnedFrameSink @@ -234,16 +240,17 @@ note: required by a bound in `stack_encrypt::scalar::>: | pub fn decrypt_with_context<'c, P: OpaqueDecode>( | ^^^^^^^^^^^^ required by this bound in `stack_encrypt::scalar::>::decrypt_with_context` -error[E0277]: one ciphertext holds one value, and this decrypt target is not built from one value +error[E0277]: this target cannot be decrypted from one ciphertext --> tests/ui/scalar_decrypt_into_a_container.rs:25:13 | 25 | let _ = Vec::::decrypt_from(ciphertext, keyset); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ this target cannot be decrypted from one ciphertext + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ one ciphertext contains one value, and this target needs more | = help: the trait `TakesScalar` is not implemented for `vitaminc_aead::typed::List` - = note: `vitaminc_aead::typed::List` is the target's sink, and it does not read a single scalar - = note: a single ciphertext decrypts into a scalar such as `String`, `i64` or `Vec`, an `Option` or a `Protected` of one, or a newtype that derives `Decrypt` over one - = note: to decrypt many values, decrypt a `Vec`, which opens each ciphertext into one element; to decrypt a sequence, a map or a struct that was encrypted as a tree, use `decrypt_tree` + = note: `vitaminc_aead::typed::List` is the sink that builds this target, and that sink does not build its value from one scalar + = note: one ciphertext decrypts into a scalar such as `String`, `i64`, or `Vec`, or into an `Option`, a `Protected`, or a derived newtype of a scalar + = note: to decrypt many values, decrypt a `Vec`: each ciphertext becomes one element + = note: to decrypt a sequence, a map, or a struct that was encrypted as a tree, use `decrypt_tree` = help: the following other types implement trait `TakesScalar`: Optional OwnedFrameSink diff --git a/packages/vitaminc-aead/CHANGELOG.md b/packages/vitaminc-aead/CHANGELOG.md index ab5b256bb..b1cc53cc0 100644 --- a/packages/vitaminc-aead/CHANGELOG.md +++ b/packages/vitaminc-aead/CHANGELOG.md @@ -16,17 +16,21 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ### Added -- `ScalarTarget` (also `typed::ScalarTarget`): a marker for a decrypt target that one scalar builds. - It is the decrypt-side counterpart of `Scalar`. - A caller that opens exactly one leaf bounds its target on it, so a target that needs a sequence or a map does not compile. - No one implements it by hand, and no one can: a target is a `ScalarTarget` when its sink is marked `TakesScalar`. - So every `FromScalar` type is one, and so are an `Option` of one, a `Protected` of a scalar or of an `Option` of one, `OwnedFrame`, a fieldless enum that derives `Decrypt`, and a newtype that derives `Decrypt` over one. - A `Vec` other than `Vec`, a map, a derived struct with named fields, and a newtype of one of those are not. - Its `#[diagnostic::on_unimplemented]` message says that one ciphertext holds one value, and what to decrypt instead. - Nothing in this crate bounds on it, so no existing code changes. -- `TakesScalar` (also `typed::TakesScalar`): a marker for a sink that one scalar satisfies. - It is implemented for `ScalarSink`, `ScalarProtected` and `OwnedFrameSink`, and for `Optional`, `ProtectedOptional`, `Wrapped` and `Wrap` over a sink that carries it. - A sink written by hand opts in with an empty impl, which makes its target a `ScalarTarget`. +- `ScalarTarget` (also `typed::ScalarTarget`): a trait for a decrypt target that is built from one scalar. + `ScalarTarget` is the decrypt-side counterpart of `Scalar`. + Code that decrypts exactly one leaf bounds its target on `ScalarTarget`, so a target that needs a sequence or a map does not compile. + No one can implement `ScalarTarget` directly: a target has it when its sink implements `TakesScalar`. + So every `FromScalar` type is a `ScalarTarget`, and a fieldless enum that derives `Decrypt` is one too. + An `Option` of a `ScalarTarget`, a newtype that derives `Decrypt` over one, and `OwnedFrame` are also `ScalarTarget`s. + So is a `Protected` of a scalar, or of an `Option` of a scalar. + A `Vec` other than `Vec`, a map, a derived struct with named fields, and a newtype of one of those are not `ScalarTarget`s. + The `#[diagnostic::on_unimplemented]` message of the trait says that one ciphertext contains one value, and names what to decrypt instead. + Nothing in this crate bounds on `ScalarTarget`, so no existing code changes. +- `TakesScalar` (also `typed::TakesScalar`): a trait for a sink that builds its value from one scalar. + `ScalarSink`, `ScalarProtected`, and `OwnedFrameSink` implement it. + `Optional`, `ProtectedOptional`, `Wrapped`, and `Wrap` implement it over a sink that implements it. + A hand-written sink opts in with an empty impl. + That impl makes the target of the sink a `ScalarTarget`. - `plaintext::ValueKind`: what a value is, without the value, with the text name a schema spells it with (`"int32"`, `"timestamp"`, `"object"`, `"json"`, …). It covers every scalar, an array, an object and a JSON document. `ValueKind::Uuid` (`"uuid"`) is a UUID: `Logical::Uuid` over sixteen bytes. Its zero is sixteen zero bytes, its null is a typed null as long as a UUID leaf, and it holds only a UUID. diff --git a/packages/vitaminc-aead/src/frame/owned.rs b/packages/vitaminc-aead/src/frame/owned.rs index 19c11bff0..8f0494a47 100644 --- a/packages/vitaminc-aead/src/frame/owned.rs +++ b/packages/vitaminc-aead/src/frame/owned.rs @@ -170,8 +170,8 @@ impl From for DecodeError { /// written. pub struct OwnedFrameSink(()); -/// One scalar always builds a frame: the frame of that scalar, or of the -/// null. So an [`OwnedFrame`] is a target one leaf builds. +/// One scalar always builds a frame: the frame of that scalar, or the null +/// frame. So one leaf can be decrypted into an [`OwnedFrame`]. impl TakesScalar for OwnedFrameSink {} /// A container an [`OwnedFrameSink`] is opening: a sequence or a map diff --git a/packages/vitaminc-aead/src/typed.rs b/packages/vitaminc-aead/src/typed.rs index ead64f4ce..fd9452127 100644 --- a/packages/vitaminc-aead/src/typed.rs +++ b/packages/vitaminc-aead/src/typed.rs @@ -15,11 +15,14 @@ //! kind, and never reads it as a zero. `HashMap` and `BTreeMap` //! read a map, each value through `T`'s sink. //! -//! [`ScalarTarget`] marks a target that one scalar builds: the scalar -//! targets, an `Option`, a `Protected` or a derived newtype of one, and an -//! [`OwnedFrame`](crate::OwnedFrame). A caller that opens exactly one leaf -//! bounds on it, so a target that needs a container does not compile. No -//! one implements it: a target is one when its sink is marked +//! [`ScalarTarget`] is implemented for each target that is built from one +//! scalar. Those are the scalar targets and +//! [`OwnedFrame`](crate::OwnedFrame). An `Option`, a `Protected`, and a +//! derived newtype of a scalar target are also built from one scalar. +//! +//! Code that decrypts exactly one leaf bounds its target on `ScalarTarget`. +//! A target that needs a container then does not compile. No one implements +//! `ScalarTarget` directly: a target has it when its sink implements //! [`TakesScalar`]. //! //! `Protected` is a target for every `T` that implements @@ -272,36 +275,47 @@ impl Decrypt for T { } } -/// A target that one scalar builds. +/// A decrypt target that is built from one scalar. +/// +/// `ScalarTarget` is the decrypt-side counterpart of +/// [`Scalar`](crate::Scalar). A leaf is one encrypted scalar or one +/// encrypted null. A leaf is never a sequence or a map. So code that +/// decrypts exactly one leaf bounds its target on this trait. A target that +/// needs a sequence or a map then fails to compile. +/// +/// With a bound on [`Decrypt`] alone, such a target would compile. The code +/// would then decrypt the leaf and return an error afterwards. +/// +/// # How a target gets this trait /// -/// The decrypt-side counterpart of [`Scalar`](crate::Scalar). A sealed leaf -/// holds one scalar or one null, and never a sequence or a map. A caller -/// that opens exactly one leaf bounds its target on this trait. A target -/// that only a container builds then fails to compile, where a bound on -/// [`Decrypt`] alone would let it open the leaf and refuse it afterwards. +/// You cannot implement this trait yourself. A sink is the builder that a +/// target names in [`Decrypt::Sink`]. The decrypt code passes each decrypted +/// value to the sink, and the sink builds the target. A target is a +/// `ScalarTarget` when its sink implements [`TakesScalar`]. /// -/// You do not implement this trait, and you cannot. A target is a -/// `ScalarTarget` when its sink is one that a scalar satisfies: when -/// [`Decrypt::Sink`] implements [`TakesScalar`]. So these targets are -/// `ScalarTarget`s, with no code of their own: +/// So these targets are `ScalarTarget`s with no code of their own: /// -/// - Every [`FromScalar`] type: `bool`, the integers (except `u8`), the -/// floats, `String`, `Vec`, `[u8; N]`, this crate's date, timestamp, -/// decimal and UUID values, the jiff, `rust_decimal` and uuid types behind -/// their features, a fieldless enum that derives `Decrypt`, and any type -/// of your own that implements `FromScalar`. +/// - Every [`FromScalar`] type, such as `bool`, the integers except `u8`, +/// the floats, `String`, `Vec`, and `[u8; N]`. +/// - The other `FromScalar` types of this crate: the date, timestamp, +/// decimal, and UUID values. The jiff, `rust_decimal`, and uuid types +/// behind their features are `FromScalar` types too. +/// - A fieldless enum that derives `Decrypt`, and any type of your own that +/// implements `FromScalar`. /// - A newtype that derives `Decrypt` over a `ScalarTarget`, such as /// `struct Email(String)`. /// - `Option` of a `ScalarTarget`. A null leaf builds `None`. -/// - `Protected` of a `FromScalar` type that can be wiped, and of an -/// `Option` of one. -/// - [`OwnedFrame`](crate::OwnedFrame). One leaf always builds a frame that -/// holds one scalar. +/// - `Protected` of a `FromScalar` type that can be wiped, and +/// `Protected>` of such a type. +/// - [`OwnedFrame`](crate::OwnedFrame). One leaf always builds a frame of +/// one scalar. /// -/// These targets are not, because each needs a container: a `Vec` other -/// than `Vec`, a `HashMap` or a `BTreeMap`, a struct that derives -/// `Decrypt` with named fields, and a newtype or an `Option` of one of -/// those. +/// These targets are not `ScalarTarget`s, because each needs a container: +/// +/// - A `Vec` other than `Vec`. +/// - A `HashMap` or a `BTreeMap`. +/// - A struct that derives `Decrypt` with named fields. +/// - A newtype or an `Option` of one of those. /// /// ``` /// use vitaminc_aead::{Decrypt, Encrypt, OwnedFrame, ScalarTarget}; @@ -318,7 +332,7 @@ impl Decrypt for T { /// let _ = opens_one_leaf::>(); /// let _ = opens_one_leaf::(); /// -/// // A derived newtype of a scalar is one too, as it is. +/// // A derived newtype of a scalar is a `ScalarTarget` with no extra code. /// #[derive(Decrypt, Debug, PartialEq)] /// struct Email(String); /// @@ -335,58 +349,70 @@ impl Decrypt for T { /// opens_one_leaf::>(); /// ``` /// -/// A target with a sink written by hand becomes a `ScalarTarget` by marking -/// that sink. See [`TakesScalar`]. +/// A target with a hand-written sink is a `ScalarTarget` when that sink +/// implements [`TakesScalar`]. #[diagnostic::on_unimplemented( - message = "one ciphertext holds one value, and `{Self}` is not built from one value", - label = "this target cannot be decrypted from one ciphertext", - note = "a single ciphertext decrypts into a scalar such as `String`, `i64` or `Vec`, an `Option` or a `Protected` of one, or a newtype that derives `Decrypt` over one", - note = "to decrypt many values, decrypt a `Vec`, which opens each ciphertext into one element; to decrypt a sequence, a map or a struct that was encrypted as a tree, use `decrypt_tree`" + message = "`{Self}` cannot be decrypted from one ciphertext", + label = "one ciphertext contains one value, and this target needs more", + note = "one ciphertext decrypts into a scalar such as `String`, `i64`, or `Vec`, or into an `Option`, a `Protected`, or a derived newtype of a scalar", + note = "to decrypt many values, decrypt a `Vec`: each ciphertext becomes one element", + note = "to decrypt a sequence, a map, or a struct that was encrypted as a tree, use `decrypt_tree`" )] pub trait ScalarTarget: Decrypt + sealed::SinkTakesScalar {} -/// The one way to be a [`ScalarTarget`]: a sink that a scalar satisfies. +/// The only impl of [`ScalarTarget`]: for a target whose sink implements +/// [`TakesScalar`]. impl ScalarTarget for T where T::Sink: TakesScalar {} mod sealed { use super::{Decrypt, TakesScalar}; - /// What closes [`ScalarTarget`](super::ScalarTarget) to an impl - /// written by hand. + /// Stops code outside this crate from implementing + /// [`ScalarTarget`](super::ScalarTarget). + /// + /// The blanket impl of `ScalarTarget` does not stop that alone. Take a + /// crate that defines a type and the sink of that type, where the sink + /// does not implement `TakesScalar`. The compiler can prove that the + /// blanket impl does not apply to that type. So the compiler accepts a + /// second impl of `ScalarTarget` for the type. The sink that + /// `#[derive(Decrypt)]` generates for a struct with named fields is such + /// a sink. /// - /// The blanket impl of `ScalarTarget` does not close it alone. The - /// compiler accepts a second impl for a type whose sink is defined in - /// the same crate as that impl, such as the sink `#[derive(Decrypt)]` - /// generates for a struct with named fields: it can see that the sink - /// is not marked, so the two impls do not overlap. This trait cannot - /// be named outside this module, and it holds only for a target whose - /// sink is marked. So such an impl is refused. + /// `SinkTakesScalar` is a supertrait of `ScalarTarget`. Code outside this + /// module cannot name `SinkTakesScalar`, so that code cannot implement + /// it. The only impl is for a target whose sink implements `TakesScalar`. + /// So the compiler rejects the second impl of `ScalarTarget`. pub trait SinkTakesScalar {} impl SinkTakesScalar for T where T::Sink: TakesScalar {} } -/// A sink that one scalar satisfies: given one scalar, it can build its -/// value. +/// A sink that builds its value from one scalar. +/// +/// A target is a [`ScalarTarget`] when its sink implements this trait. These +/// sinks of this crate implement it, because each reads a scalar: +/// +/// - [`ScalarSink`] and [`ScalarProtected`]. +/// - [`Optional`] and [`ProtectedOptional`] over a sink that implements it. +/// - [`Wrapped`] and [`Wrap`] over a sink that implements it. +/// - [`OwnedFrameSink`](crate::frame::OwnedFrameSink). /// -/// This marker is what makes a target a [`ScalarTarget`]. Every sink of -/// this crate that reads a scalar carries it: [`ScalarSink`] and -/// [`ScalarProtected`], [`Optional`] and [`ProtectedOptional`] over such a -/// sink, [`Wrapped`] and [`Wrap`] over such a sink, and -/// [`OwnedFrameSink`](crate::frame::OwnedFrameSink). The sinks that need a -/// container do not: [`List`], [`Dict`], the protected list, and the sink -/// `#[derive(Decrypt)]` generates for a struct with named fields. +/// These sinks do not implement it, because each needs a container: +/// [`List`], [`Dict`], and the protected list. The sink that +/// `#[derive(Decrypt)]` generates for a struct with named fields does not +/// implement it either. /// -/// So a target built from these sinks needs nothing more. A derived -/// newtype's sink is [`Wrapped`] over its inner type's sink, and is marked -/// exactly when the inner sink is. +/// So a target whose sink is in the first list needs no extra code. The sink +/// of a derived newtype is [`Wrapped`] over the sink of the inner type. That +/// sink implements `TakesScalar` exactly when the inner sink does. /// /// # A sink written by hand /// /// Implement this trait only for a sink of your own whose /// [`scalar`](Sink::scalar) method can succeed. The compiler does not check -/// that: a sink that carries the marker and refuses every scalar compiles, -/// and then refuses every leaf it is given. +/// that. A sink that implements this trait and returns an error for every +/// scalar still compiles. Decrypting into the target of that sink then fails +/// for every leaf. /// /// ``` /// use vitaminc_aead::typed::{Never, TakesScalar}; @@ -435,7 +461,8 @@ mod sealed { /// } /// } /// -/// // One scalar satisfies the sink, so `Flag` is a `ScalarTarget`. +/// // The sink builds a `Flag` from one scalar, so `Flag` is a +/// // `ScalarTarget`. /// impl TakesScalar for FlagSink {} /// /// fn opens_one_leaf() -> T::Sink { @@ -445,11 +472,12 @@ mod sealed { /// # Ok::<(), DecodeError>(()) /// ``` #[diagnostic::on_unimplemented( - message = "one ciphertext holds one value, and this decrypt target is not built from one value", - label = "this target cannot be decrypted from one ciphertext", - note = "`{Self}` is the target's sink, and it does not read a single scalar", - note = "a single ciphertext decrypts into a scalar such as `String`, `i64` or `Vec`, an `Option` or a `Protected` of one, or a newtype that derives `Decrypt` over one", - note = "to decrypt many values, decrypt a `Vec`, which opens each ciphertext into one element; to decrypt a sequence, a map or a struct that was encrypted as a tree, use `decrypt_tree`" + message = "this target cannot be decrypted from one ciphertext", + label = "one ciphertext contains one value, and this target needs more", + note = "`{Self}` is the sink that builds this target, and that sink does not build its value from one scalar", + note = "one ciphertext decrypts into a scalar such as `String`, `i64`, or `Vec`, or into an `Option`, a `Protected`, or a derived newtype of a scalar", + note = "to decrypt many values, decrypt a `Vec`: each ciphertext becomes one element", + note = "to decrypt a sequence, a map, or a struct that was encrypted as a tree, use `decrypt_tree`" )] pub trait TakesScalar: Sink {} @@ -1002,9 +1030,10 @@ impl, W: Rewrap> Sink for Wrapped { } } -/// The inner sink's scalar, rewrapped: a scalar satisfies the wrapper -/// exactly when it satisfies the sink inside. So a derived newtype of a -/// scalar target is a scalar target. +/// `Wrapped` passes a scalar to the inner sink and rewraps the result. So +/// `Wrapped` builds its value from one scalar exactly when the inner sink +/// does. That is why a derived newtype of a scalar target is a scalar +/// target. impl + TakesScalar, W: Rewrap> TakesScalar for Wrapped {} /// A container sink whose `end` passes its result through `W`. @@ -1259,8 +1288,8 @@ impl Decrypt for Option { } } -/// A null builds `None`, and any other scalar builds `Some` of what `T`'s -/// sink builds. +/// A null builds `None`. Any other scalar builds `Some` of the value that +/// the sink of `T` builds. impl TakesScalar for Optional where T::Sink: TakesScalar {} /// A type that can be decrypted straight into `Protected`: it names @@ -1433,8 +1462,8 @@ impl DecryptProtected for Option { /// The sink for `Protected>`. pub struct ProtectedOptional(T::ProtectedSink); -/// A null builds a protected `None`, and any other scalar builds a -/// protected `Some` of what `T`'s protected sink builds. +/// A null builds a protected `None`. Any other scalar builds a protected +/// `Some` of the value that the protected sink of `T` builds. impl TakesScalar for ProtectedOptional where T::ProtectedSink: TakesScalar {} impl Sink for ProtectedOptional { @@ -1516,8 +1545,9 @@ where } } -/// The inner sink's scalar, moved into `Protected`: a scalar satisfies the -/// wrapper exactly when it satisfies the sink inside. +/// `Wrap` passes a scalar to the inner sink and moves the result into +/// `Protected`. So `Wrap` builds its value from one scalar exactly when the +/// inner sink does. impl TakesScalar for Wrap where S: Sink + TakesScalar, diff --git a/packages/vitaminc-aead/tests/scalar_target.rs b/packages/vitaminc-aead/tests/scalar_target.rs index a84ac8d04..b5553a41c 100644 --- a/packages/vitaminc-aead/tests/scalar_target.rs +++ b/packages/vitaminc-aead/tests/scalar_target.rs @@ -1,14 +1,18 @@ -//! `ScalarTarget`, the decrypt-side marker for a target that one scalar -//! builds: the counterpart of `Scalar`. +//! Tests of `ScalarTarget`: the trait of a decrypt target that is built from +//! one scalar. `ScalarTarget` is the decrypt-side counterpart of `Scalar`. //! -//! No target implements the marker itself: a target carries it when its -//! sink is one a scalar satisfies (`TakesScalar`). The marker is only worth -//! having if it agrees with the sinks. So for every kind of target that -//! carries it, these tests walk one scalar into the target's sink and check -//! what it builds. The compile-fail half lives in `tests/ui/scalar_target/`: -//! a sequence, a map, a derived struct, a newtype of a sequence and a -//! protected sequence do not carry the marker, and no one can give it to -//! them by hand. +//! No target implements `ScalarTarget` itself. A target has it when its sink +//! implements `TakesScalar`: when the sink builds its value from one scalar. +//! +//! The trait is only useful if it agrees with what the sinks do. So these +//! tests take every kind of target that has the trait. Each test passes one +//! scalar to the sink of the target, and checks what the sink builds. +//! +//! The compile-fail tests are in `tests/ui/scalar_target/`. Those tests +//! check that a target that needs a container does not have the trait. The +//! targets are a sequence, a map, a derived struct, a newtype of a sequence, +//! and a protected sequence. The same tests check that no one can implement +//! the trait for such a target directly. use vitaminc_aead::plaintext::Raw; use vitaminc_aead::{ @@ -17,15 +21,16 @@ use vitaminc_aead::{ }; use vitaminc_protected::{Controlled, Protected}; -/// What a caller that opens exactly one leaf asks for: the target says one -/// scalar builds it, and the scalar `source` does. +/// The bound that code asks for when it decrypts exactly one leaf. The bound +/// says that one scalar builds the target. This function then checks that +/// the scalar `source` builds it. fn built_by_one_scalar(source: impl Encrypt) -> T { source .visit(T::sink()) .expect("one scalar builds a scalar target") } -/// A null, as a leaf holds one. +/// A null, as a leaf contains one. fn null() -> Raw<'static> { Raw(None, Physical::Null) } @@ -125,7 +130,8 @@ fn an_owned_frame_is_built_by_any_scalar_and_by_a_null() { ); } -/// A scalar target written by hand gets the marker from `FromScalar`. +/// A hand-written scalar target has the trait because it implements +/// `FromScalar`. #[test] fn a_hand_written_scalar_target_carries_the_marker() { #[derive(Debug, PartialEq)] @@ -144,8 +150,9 @@ fn a_hand_written_scalar_target_carries_the_marker() { ); } -/// A derived newtype reads what its inner type reads. Its sink wraps the -/// inner type's sink, so it is a scalar target with no code of its own. +/// A derived newtype reads what its inner type reads. The sink of the +/// newtype wraps the sink of the inner type. So the newtype is a scalar +/// target with no code of its own. #[test] fn a_derived_newtype_of_a_scalar_target_is_one_as_it_is() { #[derive(Decrypt, Debug, PartialEq)] @@ -187,9 +194,10 @@ fn a_derived_newtype_of_a_scalar_target_is_one_as_it_is() { ); } -/// A newtype decrypts into `Protected` once its author says how. `Wrap` -/// moves what the newtype's own sink builds into the wrapper, and a scalar -/// satisfies it when it satisfies that sink. +/// A newtype decrypts into `Protected` when its author implements +/// `DecryptProtected` for it. `Wrap` moves the value that the newtype's own +/// sink builds into `Protected`. `Wrap` builds its value from one scalar +/// when that sink does. #[test] fn a_protected_newtype_is_a_scalar_target_through_wrap() { use vitaminc_aead::typed::Wrap; @@ -212,8 +220,8 @@ fn a_protected_newtype_is_a_scalar_target_through_wrap() { ); } -/// A target with a sink of its own is a scalar target once that sink is -/// marked as one a scalar satisfies. +/// A target with a sink of its own is a scalar target when that sink +/// implements `TakesScalar`. #[test] fn a_hand_written_sink_opts_in_by_its_marker() { use vitaminc_aead::typed::{Never, TakesScalar}; @@ -261,8 +269,8 @@ fn a_hand_written_sink_opts_in_by_its_marker() { ); } -/// A derived fieldless enum reads an int leaf through `FromScalar`, so it -/// carries the marker with no impl of its own. +/// A derived fieldless enum reads an int leaf through `FromScalar`. So the +/// enum is a scalar target with no impl of its own. #[test] fn a_derived_fieldless_enum_carries_the_marker() { #[derive(Encrypt, Decrypt, Debug, PartialEq, Clone, Copy)] @@ -325,8 +333,8 @@ fn the_uuid_targets_are_built_by_one_scalar() { assert_eq!(wiped.to_uuid(), id, "this crate's Uuid"); } -// `trybuild` launches rustc and inspects the filesystem, neither of which can -// run inside Miri's isolated interpreter. +// `trybuild` starts rustc and reads the filesystem. Neither can run inside +// Miri's isolated interpreter. #[cfg(not(miri))] #[test] fn containers_are_not_scalar_targets() { diff --git a/packages/vitaminc-aead/tests/ui/scalar_target/derived_newtype_of_a_container.rs b/packages/vitaminc-aead/tests/ui/scalar_target/derived_newtype_of_a_container.rs index aeef7ead7..37507ff0b 100644 --- a/packages/vitaminc-aead/tests/ui/scalar_target/derived_newtype_of_a_container.rs +++ b/packages/vitaminc-aead/tests/ui/scalar_target/derived_newtype_of_a_container.rs @@ -1,5 +1,5 @@ -//! A derived newtype reads what its inner type reads. Over a sequence it -//! needs a sequence, so one scalar does not build it. +//! A derived newtype reads what its inner type reads. A newtype of a +//! sequence needs a sequence, so one scalar does not build it. use vitaminc_aead::{Decrypt, ScalarTarget}; diff --git a/packages/vitaminc-aead/tests/ui/scalar_target/derived_newtype_of_a_container.stderr b/packages/vitaminc-aead/tests/ui/scalar_target/derived_newtype_of_a_container.stderr index d0881d12d..78370e4e7 100644 --- a/packages/vitaminc-aead/tests/ui/scalar_target/derived_newtype_of_a_container.stderr +++ b/packages/vitaminc-aead/tests/ui/scalar_target/derived_newtype_of_a_container.stderr @@ -1,13 +1,14 @@ -error[E0277]: one ciphertext holds one value, and this decrypt target is not built from one value +error[E0277]: this target cannot be decrypted from one ciphertext --> tests/ui/scalar_target/derived_newtype_of_a_container.rs:12:22 | 12 | opens_one_leaf::(); - | ^^^^ this target cannot be decrypted from one ciphertext + | ^^^^ one ciphertext contains one value, and this target needs more | = help: the trait `TakesScalar` is not implemented for `vitaminc_aead::typed::List` - = note: `vitaminc_aead::typed::List` is the target's sink, and it does not read a single scalar - = note: a single ciphertext decrypts into a scalar such as `String`, `i64` or `Vec`, an `Option` or a `Protected` of one, or a newtype that derives `Decrypt` over one - = note: to decrypt many values, decrypt a `Vec`, which opens each ciphertext into one element; to decrypt a sequence, a map or a struct that was encrypted as a tree, use `decrypt_tree` + = note: `vitaminc_aead::typed::List` is the sink that builds this target, and that sink does not build its value from one scalar + = note: one ciphertext decrypts into a scalar such as `String`, `i64`, or `Vec`, or into an `Option`, a `Protected`, or a derived newtype of a scalar + = note: to decrypt many values, decrypt a `Vec`: each ciphertext becomes one element + = note: to decrypt a sequence, a map, or a struct that was encrypted as a tree, use `decrypt_tree` = help: the following other types implement trait `TakesScalar`: Optional OwnedFrameSink diff --git a/packages/vitaminc-aead/tests/ui/scalar_target/derived_struct_needs_a_map.rs b/packages/vitaminc-aead/tests/ui/scalar_target/derived_struct_needs_a_map.rs index ac9d32892..30740c98a 100644 --- a/packages/vitaminc-aead/tests/ui/scalar_target/derived_struct_needs_a_map.rs +++ b/packages/vitaminc-aead/tests/ui/scalar_target/derived_struct_needs_a_map.rs @@ -1,5 +1,5 @@ -//! A derived struct reads a map, one leaf per field, so one scalar does -//! not build it, even with a single field. +//! A derived struct reads a map with one leaf for each field. So one scalar +//! does not build it, even when the struct has a single field. use vitaminc_aead::{Decrypt, ScalarTarget}; diff --git a/packages/vitaminc-aead/tests/ui/scalar_target/derived_struct_needs_a_map.stderr b/packages/vitaminc-aead/tests/ui/scalar_target/derived_struct_needs_a_map.stderr index c99f50987..2b7499032 100644 --- a/packages/vitaminc-aead/tests/ui/scalar_target/derived_struct_needs_a_map.stderr +++ b/packages/vitaminc-aead/tests/ui/scalar_target/derived_struct_needs_a_map.stderr @@ -1,17 +1,18 @@ -error[E0277]: one ciphertext holds one value, and this decrypt target is not built from one value +error[E0277]: this target cannot be decrypted from one ciphertext --> tests/ui/scalar_target/derived_struct_needs_a_map.rs:14:22 | 14 | opens_one_leaf::(); - | ^^^^^^^ this target cannot be decrypted from one ciphertext + | ^^^^^^^ one ciphertext contains one value, and this target needs more | help: the trait `TakesScalar` is not implemented for `__AccountDecryptSink` --> tests/ui/scalar_target/derived_struct_needs_a_map.rs:6:10 | 6 | #[derive(Decrypt)] | ^^^^^^^ - = note: `__AccountDecryptSink` is the target's sink, and it does not read a single scalar - = note: a single ciphertext decrypts into a scalar such as `String`, `i64` or `Vec`, an `Option` or a `Protected` of one, or a newtype that derives `Decrypt` over one - = note: to decrypt many values, decrypt a `Vec`, which opens each ciphertext into one element; to decrypt a sequence, a map or a struct that was encrypted as a tree, use `decrypt_tree` + = note: `__AccountDecryptSink` is the sink that builds this target, and that sink does not build its value from one scalar + = note: one ciphertext decrypts into a scalar such as `String`, `i64`, or `Vec`, or into an `Option`, a `Protected`, or a derived newtype of a scalar + = note: to decrypt many values, decrypt a `Vec`: each ciphertext becomes one element + = note: to decrypt a sequence, a map, or a struct that was encrypted as a tree, use `decrypt_tree` = help: the following other types implement trait `TakesScalar`: Optional OwnedFrameSink diff --git a/packages/vitaminc-aead/tests/ui/scalar_target/hand_written_impl_for_a_derived_struct.rs b/packages/vitaminc-aead/tests/ui/scalar_target/hand_written_impl_for_a_derived_struct.rs index b42c7e69d..6e162e0cf 100644 --- a/packages/vitaminc-aead/tests/ui/scalar_target/hand_written_impl_for_a_derived_struct.rs +++ b/packages/vitaminc-aead/tests/ui/scalar_target/hand_written_impl_for_a_derived_struct.rs @@ -1,6 +1,7 @@ -//! No one implements `ScalarTarget` by hand. A derived struct's sink is -//! generated beside the struct, and it is not marked, because it reads a -//! map. An impl written for the struct is refused for that reason. +//! No one implements `ScalarTarget` directly. The sink of a derived struct +//! is generated beside the struct. That sink reads a map, so it does not +//! implement `TakesScalar`. So the compiler rejects an impl of +//! `ScalarTarget` for the struct. use vitaminc_aead::{Decrypt, ScalarTarget}; diff --git a/packages/vitaminc-aead/tests/ui/scalar_target/hand_written_impl_for_a_derived_struct.stderr b/packages/vitaminc-aead/tests/ui/scalar_target/hand_written_impl_for_a_derived_struct.stderr index 387953dc3..df12d40db 100644 --- a/packages/vitaminc-aead/tests/ui/scalar_target/hand_written_impl_for_a_derived_struct.stderr +++ b/packages/vitaminc-aead/tests/ui/scalar_target/hand_written_impl_for_a_derived_struct.stderr @@ -1,17 +1,18 @@ -error[E0277]: one ciphertext holds one value, and this decrypt target is not built from one value - --> tests/ui/scalar_target/hand_written_impl_for_a_derived_struct.rs:12:23 +error[E0277]: this target cannot be decrypted from one ciphertext + --> tests/ui/scalar_target/hand_written_impl_for_a_derived_struct.rs:13:23 | -12 | impl ScalarTarget for Account {} - | ^^^^^^^ this target cannot be decrypted from one ciphertext +13 | impl ScalarTarget for Account {} + | ^^^^^^^ one ciphertext contains one value, and this target needs more | help: the trait `TakesScalar` is not implemented for `__AccountDecryptSink` - --> tests/ui/scalar_target/hand_written_impl_for_a_derived_struct.rs:7:10 + --> tests/ui/scalar_target/hand_written_impl_for_a_derived_struct.rs:8:10 | - 7 | #[derive(Decrypt)] + 8 | #[derive(Decrypt)] | ^^^^^^^ - = note: `__AccountDecryptSink` is the target's sink, and it does not read a single scalar - = note: a single ciphertext decrypts into a scalar such as `String`, `i64` or `Vec`, an `Option` or a `Protected` of one, or a newtype that derives `Decrypt` over one - = note: to decrypt many values, decrypt a `Vec`, which opens each ciphertext into one element; to decrypt a sequence, a map or a struct that was encrypted as a tree, use `decrypt_tree` + = note: `__AccountDecryptSink` is the sink that builds this target, and that sink does not build its value from one scalar + = note: one ciphertext decrypts into a scalar such as `String`, `i64`, or `Vec`, or into an `Option`, a `Protected`, or a derived newtype of a scalar + = note: to decrypt many values, decrypt a `Vec`: each ciphertext becomes one element + = note: to decrypt a sequence, a map, or a struct that was encrypted as a tree, use `decrypt_tree` = help: the following other types implement trait `TakesScalar`: Optional OwnedFrameSink diff --git a/packages/vitaminc-aead/tests/ui/scalar_target/hand_written_impl_for_a_newtype.rs b/packages/vitaminc-aead/tests/ui/scalar_target/hand_written_impl_for_a_newtype.rs index 72d88c0f8..c81d5de90 100644 --- a/packages/vitaminc-aead/tests/ui/scalar_target/hand_written_impl_for_a_newtype.rs +++ b/packages/vitaminc-aead/tests/ui/scalar_target/hand_written_impl_for_a_newtype.rs @@ -1,6 +1,7 @@ -//! No one implements `ScalarTarget` by hand. A target is one when its sink -//! is marked. A derived newtype's sink is this crate's, so an impl written -//! for a newtype of a sequence conflicts with the one impl there is. +//! No one implements `ScalarTarget` directly. A target is a `ScalarTarget` +//! when its sink implements `TakesScalar`. The sink of a derived newtype is +//! defined in vitaminc-aead. So an impl of `ScalarTarget` for a newtype of a +//! sequence conflicts with the blanket impl. use vitaminc_aead::{Decrypt, ScalarTarget}; diff --git a/packages/vitaminc-aead/tests/ui/scalar_target/hand_written_impl_for_a_newtype.stderr b/packages/vitaminc-aead/tests/ui/scalar_target/hand_written_impl_for_a_newtype.stderr index 27eb7bfbf..9b29f712a 100644 --- a/packages/vitaminc-aead/tests/ui/scalar_target/hand_written_impl_for_a_newtype.stderr +++ b/packages/vitaminc-aead/tests/ui/scalar_target/hand_written_impl_for_a_newtype.stderr @@ -1,7 +1,7 @@ error[E0119]: conflicting implementations of trait `ScalarTarget` for type `Tags` - --> tests/ui/scalar_target/hand_written_impl_for_a_newtype.rs:10:1 + --> tests/ui/scalar_target/hand_written_impl_for_a_newtype.rs:11:1 | -10 | impl ScalarTarget for Tags {} +11 | impl ScalarTarget for Tags {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^ | = note: conflicting implementation in crate `vitaminc_aead`: diff --git a/packages/vitaminc-aead/tests/ui/scalar_target/map_needs_a_map.rs b/packages/vitaminc-aead/tests/ui/scalar_target/map_needs_a_map.rs index 38963bdf4..05add3dde 100644 --- a/packages/vitaminc-aead/tests/ui/scalar_target/map_needs_a_map.rs +++ b/packages/vitaminc-aead/tests/ui/scalar_target/map_needs_a_map.rs @@ -1,5 +1,5 @@ -//! A map target reads a map, one leaf per value, so one scalar does not -//! build it. +//! A map target reads a map with one leaf for each value. So one scalar does +//! not build it. use std::collections::{BTreeMap, HashMap}; diff --git a/packages/vitaminc-aead/tests/ui/scalar_target/map_needs_a_map.stderr b/packages/vitaminc-aead/tests/ui/scalar_target/map_needs_a_map.stderr index 46d8737fd..c3764cd4a 100644 --- a/packages/vitaminc-aead/tests/ui/scalar_target/map_needs_a_map.stderr +++ b/packages/vitaminc-aead/tests/ui/scalar_target/map_needs_a_map.stderr @@ -1,13 +1,14 @@ -error[E0277]: one ciphertext holds one value, and this decrypt target is not built from one value +error[E0277]: this target cannot be decrypted from one ciphertext --> tests/ui/scalar_target/map_needs_a_map.rs:11:22 | 11 | opens_one_leaf::>(); - | ^^^^^^^^^^^^^^^^^^^^ this target cannot be decrypted from one ciphertext + | ^^^^^^^^^^^^^^^^^^^^ one ciphertext contains one value, and this target needs more | = help: the trait `TakesScalar` is not implemented for `Dict>` - = note: `Dict>` is the target's sink, and it does not read a single scalar - = note: a single ciphertext decrypts into a scalar such as `String`, `i64` or `Vec`, an `Option` or a `Protected` of one, or a newtype that derives `Decrypt` over one - = note: to decrypt many values, decrypt a `Vec`, which opens each ciphertext into one element; to decrypt a sequence, a map or a struct that was encrypted as a tree, use `decrypt_tree` + = note: `Dict>` is the sink that builds this target, and that sink does not build its value from one scalar + = note: one ciphertext decrypts into a scalar such as `String`, `i64`, or `Vec`, or into an `Option`, a `Protected`, or a derived newtype of a scalar + = note: to decrypt many values, decrypt a `Vec`: each ciphertext becomes one element + = note: to decrypt a sequence, a map, or a struct that was encrypted as a tree, use `decrypt_tree` = help: the following other types implement trait `TakesScalar`: Optional OwnedFrameSink @@ -23,16 +24,17 @@ note: required by a bound in `opens_one_leaf` 8 | fn opens_one_leaf() {} | ^^^^^^^^^^^^ required by this bound in `opens_one_leaf` -error[E0277]: one ciphertext holds one value, and this decrypt target is not built from one value +error[E0277]: this target cannot be decrypted from one ciphertext --> tests/ui/scalar_target/map_needs_a_map.rs:12:22 | 12 | opens_one_leaf::>(); - | ^^^^^^^^^^^^^^^^^^^^^ this target cannot be decrypted from one ciphertext + | ^^^^^^^^^^^^^^^^^^^^^ one ciphertext contains one value, and this target needs more | = help: the trait `TakesScalar` is not implemented for `Dict>` - = note: `Dict>` is the target's sink, and it does not read a single scalar - = note: a single ciphertext decrypts into a scalar such as `String`, `i64` or `Vec`, an `Option` or a `Protected` of one, or a newtype that derives `Decrypt` over one - = note: to decrypt many values, decrypt a `Vec`, which opens each ciphertext into one element; to decrypt a sequence, a map or a struct that was encrypted as a tree, use `decrypt_tree` + = note: `Dict>` is the sink that builds this target, and that sink does not build its value from one scalar + = note: one ciphertext decrypts into a scalar such as `String`, `i64`, or `Vec`, or into an `Option`, a `Protected`, or a derived newtype of a scalar + = note: to decrypt many values, decrypt a `Vec`: each ciphertext becomes one element + = note: to decrypt a sequence, a map, or a struct that was encrypted as a tree, use `decrypt_tree` = help: the following other types implement trait `TakesScalar`: Optional OwnedFrameSink diff --git a/packages/vitaminc-aead/tests/ui/scalar_target/vec_needs_a_sequence.rs b/packages/vitaminc-aead/tests/ui/scalar_target/vec_needs_a_sequence.rs index fb93438d5..421196fe4 100644 --- a/packages/vitaminc-aead/tests/ui/scalar_target/vec_needs_a_sequence.rs +++ b/packages/vitaminc-aead/tests/ui/scalar_target/vec_needs_a_sequence.rs @@ -1,6 +1,6 @@ -//! A `Vec` of a scalar target reads a sequence, one leaf per element, -//! so one scalar does not build it. (`Vec` is the byte leaf, and one -//! scalar does build it.) +//! A `Vec` of a scalar target reads a sequence with one leaf for each +//! element. So one scalar does not build it. `Vec` is different: it is +//! the bytes scalar, so one scalar builds it. use vitaminc_aead::ScalarTarget; diff --git a/packages/vitaminc-aead/tests/ui/scalar_target/vec_needs_a_sequence.stderr b/packages/vitaminc-aead/tests/ui/scalar_target/vec_needs_a_sequence.stderr index 3beadeaf5..849322662 100644 --- a/packages/vitaminc-aead/tests/ui/scalar_target/vec_needs_a_sequence.stderr +++ b/packages/vitaminc-aead/tests/ui/scalar_target/vec_needs_a_sequence.stderr @@ -1,13 +1,14 @@ -error[E0277]: one ciphertext holds one value, and this decrypt target is not built from one value +error[E0277]: this target cannot be decrypted from one ciphertext --> tests/ui/scalar_target/vec_needs_a_sequence.rs:11:22 | 11 | opens_one_leaf::>(); - | ^^^^^^^^^^^ this target cannot be decrypted from one ciphertext + | ^^^^^^^^^^^ one ciphertext contains one value, and this target needs more | = help: the trait `TakesScalar` is not implemented for `vitaminc_aead::typed::List` - = note: `vitaminc_aead::typed::List` is the target's sink, and it does not read a single scalar - = note: a single ciphertext decrypts into a scalar such as `String`, `i64` or `Vec`, an `Option` or a `Protected` of one, or a newtype that derives `Decrypt` over one - = note: to decrypt many values, decrypt a `Vec`, which opens each ciphertext into one element; to decrypt a sequence, a map or a struct that was encrypted as a tree, use `decrypt_tree` + = note: `vitaminc_aead::typed::List` is the sink that builds this target, and that sink does not build its value from one scalar + = note: one ciphertext decrypts into a scalar such as `String`, `i64`, or `Vec`, or into an `Option`, a `Protected`, or a derived newtype of a scalar + = note: to decrypt many values, decrypt a `Vec`: each ciphertext becomes one element + = note: to decrypt a sequence, a map, or a struct that was encrypted as a tree, use `decrypt_tree` = help: the following other types implement trait `TakesScalar`: Optional OwnedFrameSink diff --git a/packages/vitaminc-aead/tests/ui/scalar_target/wrapped_container_is_not_a_scalar_target.rs b/packages/vitaminc-aead/tests/ui/scalar_target/wrapped_container_is_not_a_scalar_target.rs index 908e97fd7..69b1d8e60 100644 --- a/packages/vitaminc-aead/tests/ui/scalar_target/wrapped_container_is_not_a_scalar_target.rs +++ b/packages/vitaminc-aead/tests/ui/scalar_target/wrapped_container_is_not_a_scalar_target.rs @@ -1,7 +1,7 @@ -//! `Option` and `Protected` pass the marker through only when what they -//! wrap carries it. A `Vec` reads a sequence, so neither an `Option` -//! of it, a `Protected` of it nor a `Protected` of an `Option` of it is -//! built by one scalar. +//! `Option` and `Protected` are scalar targets only when the type they wrap +//! is one. A `Vec` reads a sequence. So one scalar does not build an +//! `Option` of it, a `Protected` of it, or a `Protected` of an `Option` of +//! it. use vitaminc_aead::ScalarTarget; use vitaminc_protected::Protected; diff --git a/packages/vitaminc-aead/tests/ui/scalar_target/wrapped_container_is_not_a_scalar_target.stderr b/packages/vitaminc-aead/tests/ui/scalar_target/wrapped_container_is_not_a_scalar_target.stderr index b102239f6..9c7ea4a70 100644 --- a/packages/vitaminc-aead/tests/ui/scalar_target/wrapped_container_is_not_a_scalar_target.stderr +++ b/packages/vitaminc-aead/tests/ui/scalar_target/wrapped_container_is_not_a_scalar_target.stderr @@ -1,13 +1,14 @@ -error[E0277]: one ciphertext holds one value, and this decrypt target is not built from one value +error[E0277]: this target cannot be decrypted from one ciphertext --> tests/ui/scalar_target/wrapped_container_is_not_a_scalar_target.rs:12:22 | 12 | opens_one_leaf::>>(); - | ^^^^^^^^^^^^^^^^ this target cannot be decrypted from one ciphertext + | ^^^^^^^^^^^^^^^^ one ciphertext contains one value, and this target needs more | = help: the trait `TakesScalar` is not implemented for `vitaminc_aead::typed::List` - = note: `vitaminc_aead::typed::List` is the target's sink, and it does not read a single scalar - = note: a single ciphertext decrypts into a scalar such as `String`, `i64` or `Vec`, an `Option` or a `Protected` of one, or a newtype that derives `Decrypt` over one - = note: to decrypt many values, decrypt a `Vec`, which opens each ciphertext into one element; to decrypt a sequence, a map or a struct that was encrypted as a tree, use `decrypt_tree` + = note: `vitaminc_aead::typed::List` is the sink that builds this target, and that sink does not build its value from one scalar + = note: one ciphertext decrypts into a scalar such as `String`, `i64`, or `Vec`, or into an `Option`, a `Protected`, or a derived newtype of a scalar + = note: to decrypt many values, decrypt a `Vec`: each ciphertext becomes one element + = note: to decrypt a sequence, a map, or a struct that was encrypted as a tree, use `decrypt_tree` = help: the following other types implement trait `TakesScalar`: Optional OwnedFrameSink @@ -24,16 +25,17 @@ note: required by a bound in `opens_one_leaf` 9 | fn opens_one_leaf() {} | ^^^^^^^^^^^^ required by this bound in `opens_one_leaf` -error[E0277]: one ciphertext holds one value, and this decrypt target is not built from one value +error[E0277]: this target cannot be decrypted from one ciphertext --> tests/ui/scalar_target/wrapped_container_is_not_a_scalar_target.rs:13:22 | 13 | opens_one_leaf::>>(); - | ^^^^^^^^^^^^^^^^^^^ this target cannot be decrypted from one ciphertext + | ^^^^^^^^^^^^^^^^^^^ one ciphertext contains one value, and this target needs more | = help: the trait `TakesScalar` is not implemented for `ProtectedList` - = note: `ProtectedList` is the target's sink, and it does not read a single scalar - = note: a single ciphertext decrypts into a scalar such as `String`, `i64` or `Vec`, an `Option` or a `Protected` of one, or a newtype that derives `Decrypt` over one - = note: to decrypt many values, decrypt a `Vec`, which opens each ciphertext into one element; to decrypt a sequence, a map or a struct that was encrypted as a tree, use `decrypt_tree` + = note: `ProtectedList` is the sink that builds this target, and that sink does not build its value from one scalar + = note: one ciphertext decrypts into a scalar such as `String`, `i64`, or `Vec`, or into an `Option`, a `Protected`, or a derived newtype of a scalar + = note: to decrypt many values, decrypt a `Vec`: each ciphertext becomes one element + = note: to decrypt a sequence, a map, or a struct that was encrypted as a tree, use `decrypt_tree` = help: the following other types implement trait `TakesScalar`: Optional OwnedFrameSink @@ -49,16 +51,17 @@ note: required by a bound in `opens_one_leaf` 9 | fn opens_one_leaf() {} | ^^^^^^^^^^^^ required by this bound in `opens_one_leaf` -error[E0277]: one ciphertext holds one value, and this decrypt target is not built from one value +error[E0277]: this target cannot be decrypted from one ciphertext --> tests/ui/scalar_target/wrapped_container_is_not_a_scalar_target.rs:14:22 | 14 | opens_one_leaf::>>>(); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ this target cannot be decrypted from one ciphertext + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ one ciphertext contains one value, and this target needs more | = help: the trait `TakesScalar` is not implemented for `ProtectedList` - = note: `ProtectedList` is the target's sink, and it does not read a single scalar - = note: a single ciphertext decrypts into a scalar such as `String`, `i64` or `Vec`, an `Option` or a `Protected` of one, or a newtype that derives `Decrypt` over one - = note: to decrypt many values, decrypt a `Vec`, which opens each ciphertext into one element; to decrypt a sequence, a map or a struct that was encrypted as a tree, use `decrypt_tree` + = note: `ProtectedList` is the sink that builds this target, and that sink does not build its value from one scalar + = note: one ciphertext decrypts into a scalar such as `String`, `i64`, or `Vec`, or into an `Option`, a `Protected`, or a derived newtype of a scalar + = note: to decrypt many values, decrypt a `Vec`: each ciphertext becomes one element + = note: to decrypt a sequence, a map, or a struct that was encrypted as a tree, use `decrypt_tree` = help: the following other types implement trait `TakesScalar`: Optional OwnedFrameSink From fe7640c0dbd0d022dad33f247144d68a987ea711 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sat, 28 Nov 2026 20:05:14 +1100 Subject: [PATCH 16/19] fix(stack-encrypt): report a refused decrypt target in the crate's terms The compile error for `keyset.decrypt::>` named Vitamin C internals. The error said that `TakesScalar` is not implemented for `vitaminc_aead::typed::List`, and listed the other sinks. A user of Stack Encrypt wrote `Vec`, and has never used a sink. The blanket impl of `OpaqueDecode` now has `#[diagnostic::do_not_recommend]`. The compiler then reports the refused type against `OpaqueDecode`, and stops there. `OpaqueDecode` has a message of its own. The error reads "`Vec` cannot be decrypted from one `Ciphertext`", and its notes say: - what one `Ciphertext` decrypts into - that the type must also be `Zeroize`, `Send`, and `'static` - what to use for a `Vec`, for a sequence, a map, or a struct, and for a whole `Deserialize` value The attribute hides which bound failed. So the notes list every bound, and none of them says that the type is a container. A new compile-fail test pins the error for a derived newtype of a `String` with no `Zeroize` impl. Vitamin C's own messages change to match. The blanket impls of `ScalarTarget` and of its sealed supertrait have the same attribute. A caller with a `T: ScalarTarget` bound now gets "`Vec` is not built from one scalar", with the target named. A hand-written impl gets "`ScalarTarget` cannot be implemented for `Account`". These messages no longer mention `Ciphertext` or `decrypt_tree`, because those are Stack Encrypt's names. The same message now covers `OpaqueBlob` when `T` lacks `Default` or `Zeroize`, so its last note names those two bounds. --- packages/stack-encrypt/CHANGELOG.md | 5 +- packages/stack-encrypt/src/scalar.rs | 23 ++ ...paque_blob_decrypt_requires_default.stderr | 13 +- .../ui/opaque_blob_requires_zeroize.stderr | 13 +- .../tests/ui/owned_collection_elements.stderr | 29 +- .../ui/scalar_decrypt_into_a_container.stderr | 321 ++++++------------ .../scalar_decrypt_target_requires_zeroize.rs | 13 + ...lar_decrypt_target_requires_zeroize.stderr | 27 ++ packages/vitaminc-aead/CHANGELOG.md | 2 +- packages/vitaminc-aead/src/typed.rs | 40 ++- .../derived_newtype_of_a_container.stderr | 27 +- .../derived_struct_needs_a_map.stderr | 29 +- ...d_written_impl_for_a_derived_struct.stderr | 27 +- .../ui/scalar_target/map_needs_a_map.stderr | 44 +-- .../scalar_target/vec_needs_a_sequence.stderr | 22 +- ...ed_container_is_not_a_scalar_target.stderr | 68 +--- 16 files changed, 305 insertions(+), 398 deletions(-) create mode 100644 packages/stack-encrypt/tests/ui/scalar_decrypt_target_requires_zeroize.rs create mode 100644 packages/stack-encrypt/tests/ui/scalar_decrypt_target_requires_zeroize.stderr diff --git a/packages/stack-encrypt/CHANGELOG.md b/packages/stack-encrypt/CHANGELOG.md index 64c000068..d9614ab1d 100644 --- a/packages/stack-encrypt/CHANGELOG.md +++ b/packages/stack-encrypt/CHANGELOG.md @@ -597,8 +597,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 implement `ScalarTarget` directly. A type is a `ScalarTarget` when it is built from one scalar. The compiler derives that from how the type decrypts. - - The compile error says that one ciphertext contains one value, and - names what to decrypt instead. + - The compile error names the type that you wrote, such as + `Vec`. The error says what one `Ciphertext` decrypts into, and + what to use for the other types. - A sequence, a map, or a struct is stored as a tree of encrypted scalars: a `StackCipherText`. Decrypt one with `keyset.decrypt_tree`. - A column of ciphertexts is a `Vec`. A `Vec` diff --git a/packages/stack-encrypt/src/scalar.rs b/packages/stack-encrypt/src/scalar.rs index 0dd71af53..4ed66a8e1 100644 --- a/packages/stack-encrypt/src/scalar.rs +++ b/packages/stack-encrypt/src/scalar.rs @@ -192,6 +192,24 @@ pub trait OpaqueEncode: sealed::Encode + Zeroize + Send + 'static {} /// owned value, and nothing wipes it when it is dropped: `Zeroize` is the /// bound, not a drop guard. Decrypt into a `Protected` to have it wiped on /// drop. A decrypted `OpaqueBlob` also wipes its value on drop. +#[diagnostic::on_unimplemented( + message = "`{Self}` cannot be decrypted from one `Ciphertext`", + label = "one `Ciphertext` decrypts into one owned value", + note = "one value is a `String`, a `bool`, a float, a `Vec`, or an integer other than \ + `u8`. An `Option` or a `Protected` of one of these is one value too. So is a newtype \ + that derives `Decrypt` over one of these.", + note = "the type must also implement `Zeroize`, so that a decrypted value can be wiped when \ + a later decrypt in the same call fails.", + note = "the type must also be `Send` and `'static`. A type that borrows data is not \ + `'static`.", + note = "to decrypt a `Vec` into a `Vec`, with one element from each \ + `Ciphertext`, use `DecryptFrom`.", + note = "to decrypt a sequence, a map, or a struct that derives `Decrypt`, use \ + `keyset.decrypt_tree`. `keyset.encrypt_tree` makes the tree of ciphertexts that it \ + reads.", + note = "to decrypt a whole `Deserialize` value from one `Ciphertext`, decrypt into \ + `OpaqueBlob`. `T` must also implement `Default` and `Zeroize`." +)] pub trait OpaqueDecode: sealed::Decode + Zeroize + Send + 'static {} // An owned `S` is sealed through a borrow of it. `&S` is one of Vitamin C's @@ -226,6 +244,11 @@ impl sealed::Decode for P { crate::target::core::open_opaque(CipherText::Single(leaf), cipher, context) } } +// `do_not_recommend` makes the compiler report a refused type against +// `OpaqueDecode`. The message of `OpaqueDecode` says what one `Ciphertext` +// decrypts into, and what to use instead. Without the attribute, the +// compiler reports the bound below that failed, in Vitamin C's terms. +#[diagnostic::do_not_recommend] impl OpaqueDecode for P {} /// One opaque ciphertext, with no exposed structural node variants. diff --git a/packages/stack-encrypt/tests/ui/opaque_blob_decrypt_requires_default.stderr b/packages/stack-encrypt/tests/ui/opaque_blob_decrypt_requires_default.stderr index 9121fd18c..9dceb5ba8 100644 --- a/packages/stack-encrypt/tests/ui/opaque_blob_decrypt_requires_default.stderr +++ b/packages/stack-encrypt/tests/ui/opaque_blob_decrypt_requires_default.stderr @@ -1,9 +1,16 @@ -error[E0277]: the trait bound `OpaqueBlob: OpaqueDecode` is not satisfied +error[E0277]: `OpaqueBlob` cannot be decrypted from one `Ciphertext` --> tests/ui/opaque_blob_decrypt_requires_default.rs:16:50 | 16 | let _refused: OpaqueBlob = keyset.decrypt(ct).await.unwrap(); - | ^^^^^^^ the trait `OpaqueDecode` is not implemented for `OpaqueBlob` - | + | ^^^^^^^ one `Ciphertext` decrypts into one owned value + | + = help: the trait `OpaqueDecode` is not implemented for `OpaqueBlob` + = note: one value is a `String`, a `bool`, a float, a `Vec`, or an integer other than `u8`. An `Option` or a `Protected` of one of these is one value too. So is a newtype that derives `Decrypt` over one of these. + = note: the type must also implement `Zeroize`, so that a decrypted value can be wiped when a later decrypt in the same call fails. + = note: the type must also be `Send` and `'static`. A type that borrows data is not `'static`. + = note: to decrypt a `Vec` into a `Vec`, with one element from each `Ciphertext`, use `DecryptFrom`. + = note: to decrypt a sequence, a map, or a struct that derives `Decrypt`, use `keyset.decrypt_tree`. `keyset.encrypt_tree` makes the tree of ciphertexts that it reads. + = note: to decrypt a whole `Deserialize` value from one `Ciphertext`, decrypt into `OpaqueBlob`. `T` must also implement `Default` and `Zeroize`. help: the trait `OpaqueDecode` is implemented for `OpaqueBlob` --> src/blob.rs | diff --git a/packages/stack-encrypt/tests/ui/opaque_blob_requires_zeroize.stderr b/packages/stack-encrypt/tests/ui/opaque_blob_requires_zeroize.stderr index ad432f03d..260defdb1 100644 --- a/packages/stack-encrypt/tests/ui/opaque_blob_requires_zeroize.stderr +++ b/packages/stack-encrypt/tests/ui/opaque_blob_requires_zeroize.stderr @@ -157,12 +157,19 @@ note: required by a bound in `OpaqueBlob` | pub struct OpaqueBlob(Zeroizing); | ^^^^^^^ required by this bound in `OpaqueBlob` -error[E0277]: the trait bound `OpaqueBlob: OpaqueDecode` is not satisfied +error[E0277]: `OpaqueBlob` cannot be decrypted from one `Ciphertext` --> tests/ui/opaque_blob_requires_zeroize.rs:18:48 | 18 | let _refused: OpaqueBlob = keyset.decrypt(ct).await.unwrap(); - | ^^^^^^^ the trait `OpaqueDecode` is not implemented for `OpaqueBlob` - | + | ^^^^^^^ one `Ciphertext` decrypts into one owned value + | + = help: the trait `OpaqueDecode` is not implemented for `OpaqueBlob` + = note: one value is a `String`, a `bool`, a float, a `Vec`, or an integer other than `u8`. An `Option` or a `Protected` of one of these is one value too. So is a newtype that derives `Decrypt` over one of these. + = note: the type must also implement `Zeroize`, so that a decrypted value can be wiped when a later decrypt in the same call fails. + = note: the type must also be `Send` and `'static`. A type that borrows data is not `'static`. + = note: to decrypt a `Vec` into a `Vec`, with one element from each `Ciphertext`, use `DecryptFrom`. + = note: to decrypt a sequence, a map, or a struct that derives `Decrypt`, use `keyset.decrypt_tree`. `keyset.encrypt_tree` makes the tree of ciphertexts that it reads. + = note: to decrypt a whole `Deserialize` value from one `Ciphertext`, decrypt into `OpaqueBlob`. `T` must also implement `Default` and `Zeroize`. help: the trait `OpaqueDecode` is implemented for `OpaqueBlob` --> src/blob.rs | diff --git a/packages/stack-encrypt/tests/ui/owned_collection_elements.stderr b/packages/stack-encrypt/tests/ui/owned_collection_elements.stderr index bf2021ce1..5c294f59e 100644 --- a/packages/stack-encrypt/tests/ui/owned_collection_elements.stderr +++ b/packages/stack-encrypt/tests/ui/owned_collection_elements.stderr @@ -86,25 +86,24 @@ help: the following other types implement trait `Scalar` = note: required for `stack_encrypt::Ciphertext` to implement `EncryptTarget>` = note: this error originates in the macro `scalar` (in Nightly builds, run with -Z macro-backtrace for more info) -error[E0277]: the trait bound `u8: vitaminc_aead::typed::FromScalar` is not satisfied +error[E0277]: `u8` cannot be decrypted from one `Ciphertext` --> tests/ui/owned_collection_elements.rs:15:13 | 15 | let _ = Vec::::decrypt_from(column, keyset); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `vitaminc_aead::typed::FromScalar` is not implemented for `u8` + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ one `Ciphertext` decrypts into one owned value | - = help: the following other types implement trait `vitaminc_aead::typed::FromScalar`: - f32 - f64 - i128 - i16 - i32 - i64 - i8 - u128 - and $N others - = note: required for `u8` to implement `Decrypt` - = note: required for `u8` to implement `ScalarTarget` - = note: required for `u8` to implement `OpaqueDecode` + = help: the trait `OpaqueDecode` is not implemented for `u8` + = note: one value is a `String`, a `bool`, a float, a `Vec`, or an integer other than `u8`. An `Option` or a `Protected` of one of these is one value too. So is a newtype that derives `Decrypt` over one of these. + = note: the type must also implement `Zeroize`, so that a decrypted value can be wiped when a later decrypt in the same call fails. + = note: the type must also be `Send` and `'static`. A type that borrows data is not `'static`. + = note: to decrypt a `Vec` into a `Vec`, with one element from each `Ciphertext`, use `DecryptFrom`. + = note: to decrypt a sequence, a map, or a struct that derives `Decrypt`, use `keyset.decrypt_tree`. `keyset.encrypt_tree` makes the tree of ciphertexts that it reads. + = note: to decrypt a whole `Deserialize` value from one `Ciphertext`, decrypt into `OpaqueBlob`. `T` must also implement `Default` and `Zeroize`. +help: the trait `OpaqueDecode` is implemented for `OpaqueBlob` + --> src/blob.rs + | + | impl OpaqueDecode for OpaqueBlob {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ = note: required for `stack_encrypt::Ciphertext` to implement `DecryptSource` = note: 1 redundant requirement hidden = note: required for `Vec` to implement `DecryptSource>` diff --git a/packages/stack-encrypt/tests/ui/scalar_decrypt_into_a_container.stderr b/packages/stack-encrypt/tests/ui/scalar_decrypt_into_a_container.stderr index b5d0730be..a721b61cc 100644 --- a/packages/stack-encrypt/tests/ui/scalar_decrypt_into_a_container.stderr +++ b/packages/stack-encrypt/tests/ui/scalar_decrypt_into_a_container.stderr @@ -1,266 +1,171 @@ -error[E0277]: this target cannot be decrypted from one ciphertext +error[E0277]: `Vec` cannot be decrypted from one `Ciphertext` --> tests/ui/scalar_decrypt_into_a_container.rs:19:30 | 19 | let _ = keyset.decrypt::>(ciphertext.clone()); - | ------- ^^^^^^^^^^^ one ciphertext contains one value, and this target needs more - | | - | required by a bound introduced by this call - | - = help: the trait `TakesScalar` is not implemented for `vitaminc_aead::typed::List` - = note: `vitaminc_aead::typed::List` is the sink that builds this target, and that sink does not build its value from one scalar - = note: one ciphertext decrypts into a scalar such as `String`, `i64`, or `Vec`, or into an `Option`, a `Protected`, or a derived newtype of a scalar - = note: to decrypt many values, decrypt a `Vec`: each ciphertext becomes one element - = note: to decrypt a sequence, a map, or a struct that was encrypted as a tree, use `decrypt_tree` - = help: the following other types implement trait `TakesScalar`: - Optional - OwnedFrameSink - ProtectedOptional - ScalarProtected - ScalarSink - Wrap - Wrapped - = note: there are multiple different versions of crate `vitaminc_aead` in the dependency graph - = help: you can use `cargo tree` to explore your dependency tree - = note: required for `Vec` to implement `ScalarTarget` - = note: required for `Vec` to implement `OpaqueDecode` -note: required by a bound in `stack_encrypt::scalar::>::decrypt` - --> src/scalar.rs - | - | pub fn decrypt(&self, ciphertext: Ciphertext) -> Pending<'_, P, K> { - | ^^^^^^^^^^^^ required by this bound in `stack_encrypt::scalar::>::decrypt` - -error[E0277]: this target cannot be decrypted from one ciphertext - --> tests/ui/scalar_decrypt_into_a_container.rs:20:30 - | -20 | let _ = keyset.decrypt::>(ciphertext.clone()); - | ------- ^^^^^^^^^^^^^^^^^^^^^ one ciphertext contains one value, and this target needs more - | | - | required by a bound introduced by this call - | - = help: the trait `TakesScalar` is not implemented for `Dict>` - = note: `Dict>` is the sink that builds this target, and that sink does not build its value from one scalar - = note: one ciphertext decrypts into a scalar such as `String`, `i64`, or `Vec`, or into an `Option`, a `Protected`, or a derived newtype of a scalar - = note: to decrypt many values, decrypt a `Vec`: each ciphertext becomes one element - = note: to decrypt a sequence, a map, or a struct that was encrypted as a tree, use `decrypt_tree` - = help: the following other types implement trait `TakesScalar`: - Optional - OwnedFrameSink - ProtectedOptional - ScalarProtected - ScalarSink - Wrap - Wrapped - = note: there are multiple different versions of crate `vitaminc_aead` in the dependency graph - = help: you can use `cargo tree` to explore your dependency tree - = note: required for `BTreeMap` to implement `ScalarTarget` - = note: required for `BTreeMap` to implement `OpaqueDecode` + | ^^^^^^^^^^^ one `Ciphertext` decrypts into one owned value + | + = help: the trait `OpaqueDecode` is not implemented for `Vec` + = note: one value is a `String`, a `bool`, a float, a `Vec`, or an integer other than `u8`. An `Option` or a `Protected` of one of these is one value too. So is a newtype that derives `Decrypt` over one of these. + = note: the type must also implement `Zeroize`, so that a decrypted value can be wiped when a later decrypt in the same call fails. + = note: the type must also be `Send` and `'static`. A type that borrows data is not `'static`. + = note: to decrypt a `Vec` into a `Vec`, with one element from each `Ciphertext`, use `DecryptFrom`. + = note: to decrypt a sequence, a map, or a struct that derives `Decrypt`, use `keyset.decrypt_tree`. `keyset.encrypt_tree` makes the tree of ciphertexts that it reads. + = note: to decrypt a whole `Deserialize` value from one `Ciphertext`, decrypt into `OpaqueBlob`. `T` must also implement `Default` and `Zeroize`. +help: the trait `OpaqueDecode` is implemented for `OpaqueBlob` + --> src/blob.rs + | + | impl OpaqueDecode for OpaqueBlob {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ note: required by a bound in `stack_encrypt::scalar::>::decrypt` --> src/scalar.rs | | pub fn decrypt(&self, ciphertext: Ciphertext) -> Pending<'_, P, K> { | ^^^^^^^^^^^^ required by this bound in `stack_encrypt::scalar::>::decrypt` -error[E0277]: the trait bound `BTreeMap: OpaqueDecode` is not satisfied +error[E0277]: `BTreeMap` cannot be decrypted from one `Ciphertext` --> tests/ui/scalar_decrypt_into_a_container.rs:20:30 | 20 | let _ = keyset.decrypt::>(ciphertext.clone()); - | ------- ^^^^^^^^^^^^^^^^^^^^^ the trait `DefaultIsZeroes` is not implemented for `BTreeMap` - | | - | required by a bound introduced by this call - | - = help: the following other types implement trait `DefaultIsZeroes`: - () - PhantomPinned - bool - char - f32 - f64 - i128 - i16 - and $N others - = note: required for `BTreeMap` to implement `Zeroize` - = note: required for `BTreeMap` to implement `OpaqueDecode` + | ^^^^^^^^^^^^^^^^^^^^^ one `Ciphertext` decrypts into one owned value + | + = help: the trait `OpaqueDecode` is not implemented for `BTreeMap` + = note: one value is a `String`, a `bool`, a float, a `Vec`, or an integer other than `u8`. An `Option` or a `Protected` of one of these is one value too. So is a newtype that derives `Decrypt` over one of these. + = note: the type must also implement `Zeroize`, so that a decrypted value can be wiped when a later decrypt in the same call fails. + = note: the type must also be `Send` and `'static`. A type that borrows data is not `'static`. + = note: to decrypt a `Vec` into a `Vec`, with one element from each `Ciphertext`, use `DecryptFrom`. + = note: to decrypt a sequence, a map, or a struct that derives `Decrypt`, use `keyset.decrypt_tree`. `keyset.encrypt_tree` makes the tree of ciphertexts that it reads. + = note: to decrypt a whole `Deserialize` value from one `Ciphertext`, decrypt into `OpaqueBlob`. `T` must also implement `Default` and `Zeroize`. +help: the trait `OpaqueDecode` is implemented for `OpaqueBlob` + --> src/blob.rs + | + | impl OpaqueDecode for OpaqueBlob {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ note: required by a bound in `stack_encrypt::scalar::>::decrypt` --> src/scalar.rs | | pub fn decrypt(&self, ciphertext: Ciphertext) -> Pending<'_, P, K> { | ^^^^^^^^^^^^ required by this bound in `stack_encrypt::scalar::>::decrypt` -error[E0277]: this target cannot be decrypted from one ciphertext +error[E0277]: `Account` cannot be decrypted from one `Ciphertext` --> tests/ui/scalar_decrypt_into_a_container.rs:21:30 | 21 | let _ = keyset.decrypt::(ciphertext.clone()); - | ------- ^^^^^^^ one ciphertext contains one value, and this target needs more - | | - | required by a bound introduced by this call - | -help: the trait `TakesScalar` is not implemented for `__AccountDecryptSink` - --> tests/ui/scalar_decrypt_into_a_container.rs:10:10 - | -10 | #[derive(Decrypt, zeroize::Zeroize)] - | ^^^^^^^ - = note: `__AccountDecryptSink` is the sink that builds this target, and that sink does not build its value from one scalar - = note: one ciphertext decrypts into a scalar such as `String`, `i64`, or `Vec`, or into an `Option`, a `Protected`, or a derived newtype of a scalar - = note: to decrypt many values, decrypt a `Vec`: each ciphertext becomes one element - = note: to decrypt a sequence, a map, or a struct that was encrypted as a tree, use `decrypt_tree` - = help: the following other types implement trait `TakesScalar`: - Optional - OwnedFrameSink - ProtectedOptional - ScalarProtected - ScalarSink - Wrap - Wrapped - = note: required for `Account` to implement `ScalarTarget` - = note: required for `Account` to implement `OpaqueDecode` + | ^^^^^^^ one `Ciphertext` decrypts into one owned value + | +help: the trait `OpaqueDecode` is not implemented for `Account` + --> tests/ui/scalar_decrypt_into_a_container.rs:11:1 + | +11 | struct Account { + | ^^^^^^^^^^^^^^ + = note: one value is a `String`, a `bool`, a float, a `Vec`, or an integer other than `u8`. An `Option` or a `Protected` of one of these is one value too. So is a newtype that derives `Decrypt` over one of these. + = note: the type must also implement `Zeroize`, so that a decrypted value can be wiped when a later decrypt in the same call fails. + = note: the type must also be `Send` and `'static`. A type that borrows data is not `'static`. + = note: to decrypt a `Vec` into a `Vec`, with one element from each `Ciphertext`, use `DecryptFrom`. + = note: to decrypt a sequence, a map, or a struct that derives `Decrypt`, use `keyset.decrypt_tree`. `keyset.encrypt_tree` makes the tree of ciphertexts that it reads. + = note: to decrypt a whole `Deserialize` value from one `Ciphertext`, decrypt into `OpaqueBlob`. `T` must also implement `Default` and `Zeroize`. +help: the trait `OpaqueDecode` is implemented for `OpaqueBlob` + --> src/blob.rs + | + | impl OpaqueDecode for OpaqueBlob {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ note: required by a bound in `stack_encrypt::scalar::>::decrypt` --> src/scalar.rs | | pub fn decrypt(&self, ciphertext: Ciphertext) -> Pending<'_, P, K> { | ^^^^^^^^^^^^ required by this bound in `stack_encrypt::scalar::>::decrypt` - = note: this error originates in the derive macro `Decrypt` (in Nightly builds, run with -Z macro-backtrace for more info) -error[E0277]: this target cannot be decrypted from one ciphertext +error[E0277]: `Tags` cannot be decrypted from one `Ciphertext` --> tests/ui/scalar_decrypt_into_a_container.rs:22:30 | 22 | let _ = keyset.decrypt::(ciphertext.clone()); - | ------- ^^^^ one ciphertext contains one value, and this target needs more - | | - | required by a bound introduced by this call - | - = help: the trait `TakesScalar` is not implemented for `vitaminc_aead::typed::List` - = note: `vitaminc_aead::typed::List` is the sink that builds this target, and that sink does not build its value from one scalar - = note: one ciphertext decrypts into a scalar such as `String`, `i64`, or `Vec`, or into an `Option`, a `Protected`, or a derived newtype of a scalar - = note: to decrypt many values, decrypt a `Vec`: each ciphertext becomes one element - = note: to decrypt a sequence, a map, or a struct that was encrypted as a tree, use `decrypt_tree` - = help: the following other types implement trait `TakesScalar`: - Optional - OwnedFrameSink - ProtectedOptional - ScalarProtected - ScalarSink - Wrap - Wrapped - = note: there are multiple different versions of crate `vitaminc_aead` in the dependency graph - = help: you can use `cargo tree` to explore your dependency tree - = note: required for `Wrapped, __TagsDecryptWrap>` to implement `TakesScalar` - = note: required for `Tags` to implement `ScalarTarget` - = note: required for `Tags` to implement `OpaqueDecode` + | ^^^^ one `Ciphertext` decrypts into one owned value + | +help: the trait `OpaqueDecode` is not implemented for `Tags` + --> tests/ui/scalar_decrypt_into_a_container.rs:16:1 + | +16 | struct Tags(Vec); + | ^^^^^^^^^^^ + = note: one value is a `String`, a `bool`, a float, a `Vec`, or an integer other than `u8`. An `Option` or a `Protected` of one of these is one value too. So is a newtype that derives `Decrypt` over one of these. + = note: the type must also implement `Zeroize`, so that a decrypted value can be wiped when a later decrypt in the same call fails. + = note: the type must also be `Send` and `'static`. A type that borrows data is not `'static`. + = note: to decrypt a `Vec` into a `Vec`, with one element from each `Ciphertext`, use `DecryptFrom`. + = note: to decrypt a sequence, a map, or a struct that derives `Decrypt`, use `keyset.decrypt_tree`. `keyset.encrypt_tree` makes the tree of ciphertexts that it reads. + = note: to decrypt a whole `Deserialize` value from one `Ciphertext`, decrypt into `OpaqueBlob`. `T` must also implement `Default` and `Zeroize`. +help: the trait `OpaqueDecode` is implemented for `OpaqueBlob` + --> src/blob.rs + | + | impl OpaqueDecode for OpaqueBlob {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ note: required by a bound in `stack_encrypt::scalar::>::decrypt` --> src/scalar.rs | | pub fn decrypt(&self, ciphertext: Ciphertext) -> Pending<'_, P, K> { | ^^^^^^^^^^^^ required by this bound in `stack_encrypt::scalar::>::decrypt` -error[E0277]: this target cannot be decrypted from one ciphertext +error[E0277]: `Protected>` cannot be decrypted from one `Ciphertext` --> tests/ui/scalar_decrypt_into_a_container.rs:23:30 | 23 | let _ = keyset.decrypt::>>(ciphertext.clone()); - | ------- ^^^^^^^^^^^^^^^^^^^ one ciphertext contains one value, and this target needs more - | | - | required by a bound introduced by this call - | - = help: the trait `TakesScalar` is not implemented for `ProtectedList` - = note: `ProtectedList` is the sink that builds this target, and that sink does not build its value from one scalar - = note: one ciphertext decrypts into a scalar such as `String`, `i64`, or `Vec`, or into an `Option`, a `Protected`, or a derived newtype of a scalar - = note: to decrypt many values, decrypt a `Vec`: each ciphertext becomes one element - = note: to decrypt a sequence, a map, or a struct that was encrypted as a tree, use `decrypt_tree` - = help: the following other types implement trait `TakesScalar`: - Optional - OwnedFrameSink - ProtectedOptional - ScalarProtected - ScalarSink - Wrap - Wrapped - = note: there are multiple different versions of crate `vitaminc_aead` in the dependency graph - = help: you can use `cargo tree` to explore your dependency tree - = note: required for `Protected>` to implement `ScalarTarget` - = note: required for `Protected>` to implement `OpaqueDecode` + | ^^^^^^^^^^^^^^^^^^^ one `Ciphertext` decrypts into one owned value + | + = help: the trait `OpaqueDecode` is not implemented for `Protected>` + = note: one value is a `String`, a `bool`, a float, a `Vec`, or an integer other than `u8`. An `Option` or a `Protected` of one of these is one value too. So is a newtype that derives `Decrypt` over one of these. + = note: the type must also implement `Zeroize`, so that a decrypted value can be wiped when a later decrypt in the same call fails. + = note: the type must also be `Send` and `'static`. A type that borrows data is not `'static`. + = note: to decrypt a `Vec` into a `Vec`, with one element from each `Ciphertext`, use `DecryptFrom`. + = note: to decrypt a sequence, a map, or a struct that derives `Decrypt`, use `keyset.decrypt_tree`. `keyset.encrypt_tree` makes the tree of ciphertexts that it reads. + = note: to decrypt a whole `Deserialize` value from one `Ciphertext`, decrypt into `OpaqueBlob`. `T` must also implement `Default` and `Zeroize`. +help: the trait `OpaqueDecode` is implemented for `OpaqueBlob` + --> src/blob.rs + | + | impl OpaqueDecode for OpaqueBlob {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ note: required by a bound in `stack_encrypt::scalar::>::decrypt` --> src/scalar.rs | | pub fn decrypt(&self, ciphertext: Ciphertext) -> Pending<'_, P, K> { | ^^^^^^^^^^^^ required by this bound in `stack_encrypt::scalar::>::decrypt` -error[E0277]: this target cannot be decrypted from one ciphertext - --> tests/ui/scalar_decrypt_into_a_container.rs:24:43 - | -24 | let _ = keyset.decrypt_with_context::>(ciphertext.clone(), "users/tags"); - | -------------------- ^^^^^^^^^^^^^^^^^^^^^^^ one ciphertext contains one value, and this target needs more - | | - | required by a bound introduced by this call - | - = help: the trait `TakesScalar` is not implemented for `Dict>` - = note: `Dict>` is the sink that builds this target, and that sink does not build its value from one scalar - = note: one ciphertext decrypts into a scalar such as `String`, `i64`, or `Vec`, or into an `Option`, a `Protected`, or a derived newtype of a scalar - = note: to decrypt many values, decrypt a `Vec`: each ciphertext becomes one element - = note: to decrypt a sequence, a map, or a struct that was encrypted as a tree, use `decrypt_tree` - = help: the following other types implement trait `TakesScalar`: - Optional - OwnedFrameSink - ProtectedOptional - ScalarProtected - ScalarSink - Wrap - Wrapped - = note: there are multiple different versions of crate `vitaminc_aead` in the dependency graph - = help: you can use `cargo tree` to explore your dependency tree - = note: required for `HashMap` to implement `ScalarTarget` - = note: required for `HashMap` to implement `OpaqueDecode` -note: required by a bound in `stack_encrypt::scalar::>::decrypt_with_context` - --> src/scalar.rs - | - | pub fn decrypt_with_context<'c, P: OpaqueDecode>( - | ^^^^^^^^^^^^ required by this bound in `stack_encrypt::scalar::>::decrypt_with_context` - -error[E0277]: the trait bound `HashMap: OpaqueDecode` is not satisfied +error[E0277]: `HashMap` cannot be decrypted from one `Ciphertext` --> tests/ui/scalar_decrypt_into_a_container.rs:24:43 | 24 | let _ = keyset.decrypt_with_context::>(ciphertext.clone(), "users/tags"); - | -------------------- ^^^^^^^^^^^^^^^^^^^^^^^ the trait `DefaultIsZeroes` is not implemented for `HashMap` - | | - | required by a bound introduced by this call - | - = help: the following other types implement trait `DefaultIsZeroes`: - () - PhantomPinned - bool - char - f32 - f64 - i128 - i16 - and $N others - = note: required for `HashMap` to implement `Zeroize` - = note: required for `HashMap` to implement `OpaqueDecode` + | ^^^^^^^^^^^^^^^^^^^^^^^ one `Ciphertext` decrypts into one owned value + | + = help: the trait `OpaqueDecode` is not implemented for `HashMap` + = note: one value is a `String`, a `bool`, a float, a `Vec`, or an integer other than `u8`. An `Option` or a `Protected` of one of these is one value too. So is a newtype that derives `Decrypt` over one of these. + = note: the type must also implement `Zeroize`, so that a decrypted value can be wiped when a later decrypt in the same call fails. + = note: the type must also be `Send` and `'static`. A type that borrows data is not `'static`. + = note: to decrypt a `Vec` into a `Vec`, with one element from each `Ciphertext`, use `DecryptFrom`. + = note: to decrypt a sequence, a map, or a struct that derives `Decrypt`, use `keyset.decrypt_tree`. `keyset.encrypt_tree` makes the tree of ciphertexts that it reads. + = note: to decrypt a whole `Deserialize` value from one `Ciphertext`, decrypt into `OpaqueBlob`. `T` must also implement `Default` and `Zeroize`. +help: the trait `OpaqueDecode` is implemented for `OpaqueBlob` + --> src/blob.rs + | + | impl OpaqueDecode for OpaqueBlob {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ note: required by a bound in `stack_encrypt::scalar::>::decrypt_with_context` --> src/scalar.rs | | pub fn decrypt_with_context<'c, P: OpaqueDecode>( | ^^^^^^^^^^^^ required by this bound in `stack_encrypt::scalar::>::decrypt_with_context` -error[E0277]: this target cannot be decrypted from one ciphertext +error[E0277]: `Vec` cannot be decrypted from one `Ciphertext` --> tests/ui/scalar_decrypt_into_a_container.rs:25:13 | 25 | let _ = Vec::::decrypt_from(ciphertext, keyset); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ one ciphertext contains one value, and this target needs more - | - = help: the trait `TakesScalar` is not implemented for `vitaminc_aead::typed::List` - = note: `vitaminc_aead::typed::List` is the sink that builds this target, and that sink does not build its value from one scalar - = note: one ciphertext decrypts into a scalar such as `String`, `i64`, or `Vec`, or into an `Option`, a `Protected`, or a derived newtype of a scalar - = note: to decrypt many values, decrypt a `Vec`: each ciphertext becomes one element - = note: to decrypt a sequence, a map, or a struct that was encrypted as a tree, use `decrypt_tree` - = help: the following other types implement trait `TakesScalar`: - Optional - OwnedFrameSink - ProtectedOptional - ScalarProtected - ScalarSink - Wrap - Wrapped - = note: there are multiple different versions of crate `vitaminc_aead` in the dependency graph - = help: you can use `cargo tree` to explore your dependency tree - = note: required for `Vec` to implement `ScalarTarget` - = note: required for `Vec` to implement `OpaqueDecode` + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ one `Ciphertext` decrypts into one owned value + | + = help: the trait `OpaqueDecode` is not implemented for `Vec` + = note: one value is a `String`, a `bool`, a float, a `Vec`, or an integer other than `u8`. An `Option` or a `Protected` of one of these is one value too. So is a newtype that derives `Decrypt` over one of these. + = note: the type must also implement `Zeroize`, so that a decrypted value can be wiped when a later decrypt in the same call fails. + = note: the type must also be `Send` and `'static`. A type that borrows data is not `'static`. + = note: to decrypt a `Vec` into a `Vec`, with one element from each `Ciphertext`, use `DecryptFrom`. + = note: to decrypt a sequence, a map, or a struct that derives `Decrypt`, use `keyset.decrypt_tree`. `keyset.encrypt_tree` makes the tree of ciphertexts that it reads. + = note: to decrypt a whole `Deserialize` value from one `Ciphertext`, decrypt into `OpaqueBlob`. `T` must also implement `Default` and `Zeroize`. +help: the trait `OpaqueDecode` is implemented for `OpaqueBlob` + --> src/blob.rs + | + | impl OpaqueDecode for OpaqueBlob {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ = note: required for `stack_encrypt::Ciphertext` to implement `DecryptSource>` diff --git a/packages/stack-encrypt/tests/ui/scalar_decrypt_target_requires_zeroize.rs b/packages/stack-encrypt/tests/ui/scalar_decrypt_target_requires_zeroize.rs new file mode 100644 index 000000000..dbd3aef7b --- /dev/null +++ b/packages/stack-encrypt/tests/ui/scalar_decrypt_target_requires_zeroize.rs @@ -0,0 +1,13 @@ +//! One scalar builds a newtype that derives `Decrypt` over a `String`. A +//! `Ciphertext` still does not decrypt into the newtype, because the newtype +//! does not implement `Zeroize`. +use stack_encrypt::{Ciphertext, Decrypt, KeysetCipher}; + +#[derive(Decrypt)] +struct Email(String); + +fn refused(keyset: &KeysetCipher<'_, K>, ciphertext: Ciphertext) { + let _ = keyset.decrypt::(ciphertext); +} + +fn main() {} diff --git a/packages/stack-encrypt/tests/ui/scalar_decrypt_target_requires_zeroize.stderr b/packages/stack-encrypt/tests/ui/scalar_decrypt_target_requires_zeroize.stderr new file mode 100644 index 000000000..927435a39 --- /dev/null +++ b/packages/stack-encrypt/tests/ui/scalar_decrypt_target_requires_zeroize.stderr @@ -0,0 +1,27 @@ +error[E0277]: `Email` cannot be decrypted from one `Ciphertext` + --> tests/ui/scalar_decrypt_target_requires_zeroize.rs:10:30 + | +10 | let _ = keyset.decrypt::(ciphertext); + | ^^^^^ one `Ciphertext` decrypts into one owned value + | +help: the trait `OpaqueDecode` is not implemented for `Email` + --> tests/ui/scalar_decrypt_target_requires_zeroize.rs:7:1 + | + 7 | struct Email(String); + | ^^^^^^^^^^^^ + = note: one value is a `String`, a `bool`, a float, a `Vec`, or an integer other than `u8`. An `Option` or a `Protected` of one of these is one value too. So is a newtype that derives `Decrypt` over one of these. + = note: the type must also implement `Zeroize`, so that a decrypted value can be wiped when a later decrypt in the same call fails. + = note: the type must also be `Send` and `'static`. A type that borrows data is not `'static`. + = note: to decrypt a `Vec` into a `Vec`, with one element from each `Ciphertext`, use `DecryptFrom`. + = note: to decrypt a sequence, a map, or a struct that derives `Decrypt`, use `keyset.decrypt_tree`. `keyset.encrypt_tree` makes the tree of ciphertexts that it reads. + = note: to decrypt a whole `Deserialize` value from one `Ciphertext`, decrypt into `OpaqueBlob`. `T` must also implement `Default` and `Zeroize`. +help: the trait `OpaqueDecode` is implemented for `OpaqueBlob` + --> src/blob.rs + | + | impl OpaqueDecode for OpaqueBlob {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +note: required by a bound in `stack_encrypt::scalar::>::decrypt` + --> src/scalar.rs + | + | pub fn decrypt(&self, ciphertext: Ciphertext) -> Pending<'_, P, K> { + | ^^^^^^^^^^^^ required by this bound in `stack_encrypt::scalar::>::decrypt` diff --git a/packages/vitaminc-aead/CHANGELOG.md b/packages/vitaminc-aead/CHANGELOG.md index b1cc53cc0..ea8dbaa63 100644 --- a/packages/vitaminc-aead/CHANGELOG.md +++ b/packages/vitaminc-aead/CHANGELOG.md @@ -24,7 +24,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). An `Option` of a `ScalarTarget`, a newtype that derives `Decrypt` over one, and `OwnedFrame` are also `ScalarTarget`s. So is a `Protected` of a scalar, or of an `Option` of a scalar. A `Vec` other than `Vec`, a map, a derived struct with named fields, and a newtype of one of those are not `ScalarTarget`s. - The `#[diagnostic::on_unimplemented]` message of the trait says that one ciphertext contains one value, and names what to decrypt instead. + The compile error for a target that is not a `ScalarTarget` names the target, and says what a scalar target is. Nothing in this crate bounds on `ScalarTarget`, so no existing code changes. - `TakesScalar` (also `typed::TakesScalar`): a trait for a sink that builds its value from one scalar. `ScalarSink`, `ScalarProtected`, and `OwnedFrameSink` implement it. diff --git a/packages/vitaminc-aead/src/typed.rs b/packages/vitaminc-aead/src/typed.rs index fd9452127..b48e4884d 100644 --- a/packages/vitaminc-aead/src/typed.rs +++ b/packages/vitaminc-aead/src/typed.rs @@ -352,16 +352,24 @@ impl Decrypt for T { /// A target with a hand-written sink is a `ScalarTarget` when that sink /// implements [`TakesScalar`]. #[diagnostic::on_unimplemented( - message = "`{Self}` cannot be decrypted from one ciphertext", - label = "one ciphertext contains one value, and this target needs more", - note = "one ciphertext decrypts into a scalar such as `String`, `i64`, or `Vec`, or into an `Option`, a `Protected`, or a derived newtype of a scalar", - note = "to decrypt many values, decrypt a `Vec`: each ciphertext becomes one element", - note = "to decrypt a sequence, a map, or a struct that was encrypted as a tree, use `decrypt_tree`" + message = "`{Self}` is not built from one scalar", + label = "this decrypt target is not a `ScalarTarget`", + note = "a scalar target is a `FromScalar` type, such as `String`, `i64`, or `Vec`. An \ + `Option` or a `Protected` of one is a scalar target too. So is a newtype that \ + derives `Decrypt` over one.", + note = "a sequence, a map, and a struct with named fields each need a container. So none of \ + them is a scalar target.", + note = "a target with a hand-written sink is a scalar target when that sink implements \ + `TakesScalar`." )] pub trait ScalarTarget: Decrypt + sealed::SinkTakesScalar {} /// The only impl of [`ScalarTarget`]: for a target whose sink implements /// [`TakesScalar`]. +// `do_not_recommend` makes the compiler report a refused target against +// `ScalarTarget`, and name the target. Without the attribute, the compiler +// reports the bound on the sink, and names the sink. +#[diagnostic::do_not_recommend] impl ScalarTarget for T where T::Sink: TakesScalar {} mod sealed { @@ -382,8 +390,18 @@ mod sealed { /// module cannot name `SinkTakesScalar`, so that code cannot implement /// it. The only impl is for a target whose sink implements `TakesScalar`. /// So the compiler rejects the second impl of `ScalarTarget`. + #[diagnostic::on_unimplemented( + message = "`ScalarTarget` cannot be implemented for `{Self}`", + label = "the sink of this target does not implement `TakesScalar`", + note = "a target is a `ScalarTarget` when its sink, `Decrypt::Sink`, implements \ + `TakesScalar`. No other impl is accepted." + )] pub trait SinkTakesScalar {} + // `do_not_recommend` makes the compiler report a refused impl of + // `ScalarTarget` against `SinkTakesScalar`. The message above then says + // why the impl is refused. + #[diagnostic::do_not_recommend] impl SinkTakesScalar for T where T::Sink: TakesScalar {} } @@ -472,12 +490,12 @@ mod sealed { /// # Ok::<(), DecodeError>(()) /// ``` #[diagnostic::on_unimplemented( - message = "this target cannot be decrypted from one ciphertext", - label = "one ciphertext contains one value, and this target needs more", - note = "`{Self}` is the sink that builds this target, and that sink does not build its value from one scalar", - note = "one ciphertext decrypts into a scalar such as `String`, `i64`, or `Vec`, or into an `Option`, a `Protected`, or a derived newtype of a scalar", - note = "to decrypt many values, decrypt a `Vec`: each ciphertext becomes one element", - note = "to decrypt a sequence, a map, or a struct that was encrypted as a tree, use `decrypt_tree`" + message = "`{Self}` does not build its value from one scalar", + label = "this sink does not implement `TakesScalar`", + note = "the sinks of this crate that read one scalar implement `TakesScalar`. The sinks that \ + need a sequence or a map do not.", + note = "implement `TakesScalar` for a sink of your own only when its `scalar` method can \ + succeed." )] pub trait TakesScalar: Sink {} diff --git a/packages/vitaminc-aead/tests/ui/scalar_target/derived_newtype_of_a_container.stderr b/packages/vitaminc-aead/tests/ui/scalar_target/derived_newtype_of_a_container.stderr index 78370e4e7..392a7de21 100644 --- a/packages/vitaminc-aead/tests/ui/scalar_target/derived_newtype_of_a_container.stderr +++ b/packages/vitaminc-aead/tests/ui/scalar_target/derived_newtype_of_a_container.stderr @@ -1,24 +1,17 @@ -error[E0277]: this target cannot be decrypted from one ciphertext +error[E0277]: `Tags` is not built from one scalar --> tests/ui/scalar_target/derived_newtype_of_a_container.rs:12:22 | 12 | opens_one_leaf::(); - | ^^^^ one ciphertext contains one value, and this target needs more + | ^^^^ this decrypt target is not a `ScalarTarget` | - = help: the trait `TakesScalar` is not implemented for `vitaminc_aead::typed::List` - = note: `vitaminc_aead::typed::List` is the sink that builds this target, and that sink does not build its value from one scalar - = note: one ciphertext decrypts into a scalar such as `String`, `i64`, or `Vec`, or into an `Option`, a `Protected`, or a derived newtype of a scalar - = note: to decrypt many values, decrypt a `Vec`: each ciphertext becomes one element - = note: to decrypt a sequence, a map, or a struct that was encrypted as a tree, use `decrypt_tree` - = help: the following other types implement trait `TakesScalar`: - Optional - OwnedFrameSink - ProtectedOptional - ScalarProtected - ScalarSink - Wrap - Wrapped - = note: required for `Wrapped, __TagsDecryptWrap>` to implement `TakesScalar` - = note: required for `Tags` to implement `ScalarTarget` +help: the trait `ScalarTarget` is not implemented for `Tags` + --> tests/ui/scalar_target/derived_newtype_of_a_container.rs:7:1 + | + 7 | struct Tags(Vec); + | ^^^^^^^^^^^ + = note: a scalar target is a `FromScalar` type, such as `String`, `i64`, or `Vec`. An `Option` or a `Protected` of one is a scalar target too. So is a newtype that derives `Decrypt` over one. + = note: a sequence, a map, and a struct with named fields each need a container. So none of them is a scalar target. + = note: a target with a hand-written sink is a scalar target when that sink implements `TakesScalar`. note: required by a bound in `opens_one_leaf` --> tests/ui/scalar_target/derived_newtype_of_a_container.rs:9:22 | diff --git a/packages/vitaminc-aead/tests/ui/scalar_target/derived_struct_needs_a_map.stderr b/packages/vitaminc-aead/tests/ui/scalar_target/derived_struct_needs_a_map.stderr index 2b7499032..e9d66e3da 100644 --- a/packages/vitaminc-aead/tests/ui/scalar_target/derived_struct_needs_a_map.stderr +++ b/packages/vitaminc-aead/tests/ui/scalar_target/derived_struct_needs_a_map.stderr @@ -1,30 +1,19 @@ -error[E0277]: this target cannot be decrypted from one ciphertext +error[E0277]: `Account` is not built from one scalar --> tests/ui/scalar_target/derived_struct_needs_a_map.rs:14:22 | 14 | opens_one_leaf::(); - | ^^^^^^^ one ciphertext contains one value, and this target needs more + | ^^^^^^^ this decrypt target is not a `ScalarTarget` | -help: the trait `TakesScalar` is not implemented for `__AccountDecryptSink` - --> tests/ui/scalar_target/derived_struct_needs_a_map.rs:6:10 +help: the trait `ScalarTarget` is not implemented for `Account` + --> tests/ui/scalar_target/derived_struct_needs_a_map.rs:7:1 | - 6 | #[derive(Decrypt)] - | ^^^^^^^ - = note: `__AccountDecryptSink` is the sink that builds this target, and that sink does not build its value from one scalar - = note: one ciphertext decrypts into a scalar such as `String`, `i64`, or `Vec`, or into an `Option`, a `Protected`, or a derived newtype of a scalar - = note: to decrypt many values, decrypt a `Vec`: each ciphertext becomes one element - = note: to decrypt a sequence, a map, or a struct that was encrypted as a tree, use `decrypt_tree` - = help: the following other types implement trait `TakesScalar`: - Optional - OwnedFrameSink - ProtectedOptional - ScalarProtected - ScalarSink - Wrap - Wrapped - = note: required for `Account` to implement `ScalarTarget` + 7 | struct Account { + | ^^^^^^^^^^^^^^ + = note: a scalar target is a `FromScalar` type, such as `String`, `i64`, or `Vec`. An `Option` or a `Protected` of one is a scalar target too. So is a newtype that derives `Decrypt` over one. + = note: a sequence, a map, and a struct with named fields each need a container. So none of them is a scalar target. + = note: a target with a hand-written sink is a scalar target when that sink implements `TakesScalar`. note: required by a bound in `opens_one_leaf` --> tests/ui/scalar_target/derived_struct_needs_a_map.rs:11:22 | 11 | fn opens_one_leaf() {} | ^^^^^^^^^^^^ required by this bound in `opens_one_leaf` - = note: this error originates in the derive macro `Decrypt` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/packages/vitaminc-aead/tests/ui/scalar_target/hand_written_impl_for_a_derived_struct.stderr b/packages/vitaminc-aead/tests/ui/scalar_target/hand_written_impl_for_a_derived_struct.stderr index df12d40db..6235cd78a 100644 --- a/packages/vitaminc-aead/tests/ui/scalar_target/hand_written_impl_for_a_derived_struct.stderr +++ b/packages/vitaminc-aead/tests/ui/scalar_target/hand_written_impl_for_a_derived_struct.stderr @@ -1,27 +1,15 @@ -error[E0277]: this target cannot be decrypted from one ciphertext +error[E0277]: `ScalarTarget` cannot be implemented for `Account` --> tests/ui/scalar_target/hand_written_impl_for_a_derived_struct.rs:13:23 | 13 | impl ScalarTarget for Account {} - | ^^^^^^^ one ciphertext contains one value, and this target needs more + | ^^^^^^^ the sink of this target does not implement `TakesScalar` | -help: the trait `TakesScalar` is not implemented for `__AccountDecryptSink` - --> tests/ui/scalar_target/hand_written_impl_for_a_derived_struct.rs:8:10 +help: the trait `typed::sealed::SinkTakesScalar` is not implemented for `Account` + --> tests/ui/scalar_target/hand_written_impl_for_a_derived_struct.rs:9:1 | - 8 | #[derive(Decrypt)] - | ^^^^^^^ - = note: `__AccountDecryptSink` is the sink that builds this target, and that sink does not build its value from one scalar - = note: one ciphertext decrypts into a scalar such as `String`, `i64`, or `Vec`, or into an `Option`, a `Protected`, or a derived newtype of a scalar - = note: to decrypt many values, decrypt a `Vec`: each ciphertext becomes one element - = note: to decrypt a sequence, a map, or a struct that was encrypted as a tree, use `decrypt_tree` - = help: the following other types implement trait `TakesScalar`: - Optional - OwnedFrameSink - ProtectedOptional - ScalarProtected - ScalarSink - Wrap - Wrapped - = note: required for `Account` to implement `typed::sealed::SinkTakesScalar` + 9 | struct Account { + | ^^^^^^^^^^^^^^ + = note: a target is a `ScalarTarget` when its sink, `Decrypt::Sink`, implements `TakesScalar`. No other impl is accepted. note: required by a bound in `ScalarTarget` --> src/typed.rs | @@ -30,4 +18,3 @@ note: required by a bound in `ScalarTarget` = note: `ScalarTarget` is a "sealed trait", because to implement it you also need to implement `vitaminc_aead::typed::sealed::SinkTakesScalar`, which is not accessible; this is usually done to force you to use one of the provided types that already implement it = help: the following type implements the trait: T - = note: this error originates in the derive macro `Decrypt` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/packages/vitaminc-aead/tests/ui/scalar_target/map_needs_a_map.stderr b/packages/vitaminc-aead/tests/ui/scalar_target/map_needs_a_map.stderr index c3764cd4a..af0e5f3f3 100644 --- a/packages/vitaminc-aead/tests/ui/scalar_target/map_needs_a_map.stderr +++ b/packages/vitaminc-aead/tests/ui/scalar_target/map_needs_a_map.stderr @@ -1,49 +1,29 @@ -error[E0277]: this target cannot be decrypted from one ciphertext +error[E0277]: `HashMap` is not built from one scalar --> tests/ui/scalar_target/map_needs_a_map.rs:11:22 | 11 | opens_one_leaf::>(); - | ^^^^^^^^^^^^^^^^^^^^ one ciphertext contains one value, and this target needs more + | ^^^^^^^^^^^^^^^^^^^^ this decrypt target is not a `ScalarTarget` | - = help: the trait `TakesScalar` is not implemented for `Dict>` - = note: `Dict>` is the sink that builds this target, and that sink does not build its value from one scalar - = note: one ciphertext decrypts into a scalar such as `String`, `i64`, or `Vec`, or into an `Option`, a `Protected`, or a derived newtype of a scalar - = note: to decrypt many values, decrypt a `Vec`: each ciphertext becomes one element - = note: to decrypt a sequence, a map, or a struct that was encrypted as a tree, use `decrypt_tree` - = help: the following other types implement trait `TakesScalar`: - Optional - OwnedFrameSink - ProtectedOptional - ScalarProtected - ScalarSink - Wrap - Wrapped - = note: required for `HashMap` to implement `ScalarTarget` + = help: the trait `ScalarTarget` is not implemented for `HashMap` + = note: a scalar target is a `FromScalar` type, such as `String`, `i64`, or `Vec`. An `Option` or a `Protected` of one is a scalar target too. So is a newtype that derives `Decrypt` over one. + = note: a sequence, a map, and a struct with named fields each need a container. So none of them is a scalar target. + = note: a target with a hand-written sink is a scalar target when that sink implements `TakesScalar`. note: required by a bound in `opens_one_leaf` --> tests/ui/scalar_target/map_needs_a_map.rs:8:22 | 8 | fn opens_one_leaf() {} | ^^^^^^^^^^^^ required by this bound in `opens_one_leaf` -error[E0277]: this target cannot be decrypted from one ciphertext +error[E0277]: `BTreeMap` is not built from one scalar --> tests/ui/scalar_target/map_needs_a_map.rs:12:22 | 12 | opens_one_leaf::>(); - | ^^^^^^^^^^^^^^^^^^^^^ one ciphertext contains one value, and this target needs more + | ^^^^^^^^^^^^^^^^^^^^^ this decrypt target is not a `ScalarTarget` | - = help: the trait `TakesScalar` is not implemented for `Dict>` - = note: `Dict>` is the sink that builds this target, and that sink does not build its value from one scalar - = note: one ciphertext decrypts into a scalar such as `String`, `i64`, or `Vec`, or into an `Option`, a `Protected`, or a derived newtype of a scalar - = note: to decrypt many values, decrypt a `Vec`: each ciphertext becomes one element - = note: to decrypt a sequence, a map, or a struct that was encrypted as a tree, use `decrypt_tree` - = help: the following other types implement trait `TakesScalar`: - Optional - OwnedFrameSink - ProtectedOptional - ScalarProtected - ScalarSink - Wrap - Wrapped - = note: required for `BTreeMap` to implement `ScalarTarget` + = help: the trait `ScalarTarget` is not implemented for `BTreeMap` + = note: a scalar target is a `FromScalar` type, such as `String`, `i64`, or `Vec`. An `Option` or a `Protected` of one is a scalar target too. So is a newtype that derives `Decrypt` over one. + = note: a sequence, a map, and a struct with named fields each need a container. So none of them is a scalar target. + = note: a target with a hand-written sink is a scalar target when that sink implements `TakesScalar`. note: required by a bound in `opens_one_leaf` --> tests/ui/scalar_target/map_needs_a_map.rs:8:22 | diff --git a/packages/vitaminc-aead/tests/ui/scalar_target/vec_needs_a_sequence.stderr b/packages/vitaminc-aead/tests/ui/scalar_target/vec_needs_a_sequence.stderr index 849322662..f26994858 100644 --- a/packages/vitaminc-aead/tests/ui/scalar_target/vec_needs_a_sequence.stderr +++ b/packages/vitaminc-aead/tests/ui/scalar_target/vec_needs_a_sequence.stderr @@ -1,23 +1,13 @@ -error[E0277]: this target cannot be decrypted from one ciphertext +error[E0277]: `Vec` is not built from one scalar --> tests/ui/scalar_target/vec_needs_a_sequence.rs:11:22 | 11 | opens_one_leaf::>(); - | ^^^^^^^^^^^ one ciphertext contains one value, and this target needs more + | ^^^^^^^^^^^ this decrypt target is not a `ScalarTarget` | - = help: the trait `TakesScalar` is not implemented for `vitaminc_aead::typed::List` - = note: `vitaminc_aead::typed::List` is the sink that builds this target, and that sink does not build its value from one scalar - = note: one ciphertext decrypts into a scalar such as `String`, `i64`, or `Vec`, or into an `Option`, a `Protected`, or a derived newtype of a scalar - = note: to decrypt many values, decrypt a `Vec`: each ciphertext becomes one element - = note: to decrypt a sequence, a map, or a struct that was encrypted as a tree, use `decrypt_tree` - = help: the following other types implement trait `TakesScalar`: - Optional - OwnedFrameSink - ProtectedOptional - ScalarProtected - ScalarSink - Wrap - Wrapped - = note: required for `Vec` to implement `ScalarTarget` + = help: the trait `ScalarTarget` is not implemented for `Vec` + = note: a scalar target is a `FromScalar` type, such as `String`, `i64`, or `Vec`. An `Option` or a `Protected` of one is a scalar target too. So is a newtype that derives `Decrypt` over one. + = note: a sequence, a map, and a struct with named fields each need a container. So none of them is a scalar target. + = note: a target with a hand-written sink is a scalar target when that sink implements `TakesScalar`. note: required by a bound in `opens_one_leaf` --> tests/ui/scalar_target/vec_needs_a_sequence.rs:7:22 | diff --git a/packages/vitaminc-aead/tests/ui/scalar_target/wrapped_container_is_not_a_scalar_target.stderr b/packages/vitaminc-aead/tests/ui/scalar_target/wrapped_container_is_not_a_scalar_target.stderr index 9c7ea4a70..f2c493d8d 100644 --- a/packages/vitaminc-aead/tests/ui/scalar_target/wrapped_container_is_not_a_scalar_target.stderr +++ b/packages/vitaminc-aead/tests/ui/scalar_target/wrapped_container_is_not_a_scalar_target.stderr @@ -1,77 +1,45 @@ -error[E0277]: this target cannot be decrypted from one ciphertext +error[E0277]: `Option>` is not built from one scalar --> tests/ui/scalar_target/wrapped_container_is_not_a_scalar_target.rs:12:22 | 12 | opens_one_leaf::>>(); - | ^^^^^^^^^^^^^^^^ one ciphertext contains one value, and this target needs more + | ^^^^^^^^^^^^^^^^ this decrypt target is not a `ScalarTarget` | - = help: the trait `TakesScalar` is not implemented for `vitaminc_aead::typed::List` - = note: `vitaminc_aead::typed::List` is the sink that builds this target, and that sink does not build its value from one scalar - = note: one ciphertext decrypts into a scalar such as `String`, `i64`, or `Vec`, or into an `Option`, a `Protected`, or a derived newtype of a scalar - = note: to decrypt many values, decrypt a `Vec`: each ciphertext becomes one element - = note: to decrypt a sequence, a map, or a struct that was encrypted as a tree, use `decrypt_tree` - = help: the following other types implement trait `TakesScalar`: - Optional - OwnedFrameSink - ProtectedOptional - ScalarProtected - ScalarSink - Wrap - Wrapped - = note: required for `Optional>` to implement `TakesScalar` - = note: required for `Option>` to implement `ScalarTarget` + = help: the trait `ScalarTarget` is not implemented for `Option>` + = note: a scalar target is a `FromScalar` type, such as `String`, `i64`, or `Vec`. An `Option` or a `Protected` of one is a scalar target too. So is a newtype that derives `Decrypt` over one. + = note: a sequence, a map, and a struct with named fields each need a container. So none of them is a scalar target. + = note: a target with a hand-written sink is a scalar target when that sink implements `TakesScalar`. note: required by a bound in `opens_one_leaf` --> tests/ui/scalar_target/wrapped_container_is_not_a_scalar_target.rs:9:22 | 9 | fn opens_one_leaf() {} | ^^^^^^^^^^^^ required by this bound in `opens_one_leaf` -error[E0277]: this target cannot be decrypted from one ciphertext +error[E0277]: `Protected>` is not built from one scalar --> tests/ui/scalar_target/wrapped_container_is_not_a_scalar_target.rs:13:22 | 13 | opens_one_leaf::>>(); - | ^^^^^^^^^^^^^^^^^^^ one ciphertext contains one value, and this target needs more + | ^^^^^^^^^^^^^^^^^^^ this decrypt target is not a `ScalarTarget` | - = help: the trait `TakesScalar` is not implemented for `ProtectedList` - = note: `ProtectedList` is the sink that builds this target, and that sink does not build its value from one scalar - = note: one ciphertext decrypts into a scalar such as `String`, `i64`, or `Vec`, or into an `Option`, a `Protected`, or a derived newtype of a scalar - = note: to decrypt many values, decrypt a `Vec`: each ciphertext becomes one element - = note: to decrypt a sequence, a map, or a struct that was encrypted as a tree, use `decrypt_tree` - = help: the following other types implement trait `TakesScalar`: - Optional - OwnedFrameSink - ProtectedOptional - ScalarProtected - ScalarSink - Wrap - Wrapped - = note: required for `Protected>` to implement `ScalarTarget` + = help: the trait `ScalarTarget` is not implemented for `Protected>` + = note: a scalar target is a `FromScalar` type, such as `String`, `i64`, or `Vec`. An `Option` or a `Protected` of one is a scalar target too. So is a newtype that derives `Decrypt` over one. + = note: a sequence, a map, and a struct with named fields each need a container. So none of them is a scalar target. + = note: a target with a hand-written sink is a scalar target when that sink implements `TakesScalar`. note: required by a bound in `opens_one_leaf` --> tests/ui/scalar_target/wrapped_container_is_not_a_scalar_target.rs:9:22 | 9 | fn opens_one_leaf() {} | ^^^^^^^^^^^^ required by this bound in `opens_one_leaf` -error[E0277]: this target cannot be decrypted from one ciphertext +error[E0277]: `Protected>>` is not built from one scalar --> tests/ui/scalar_target/wrapped_container_is_not_a_scalar_target.rs:14:22 | 14 | opens_one_leaf::>>>(); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ one ciphertext contains one value, and this target needs more + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ this decrypt target is not a `ScalarTarget` | - = help: the trait `TakesScalar` is not implemented for `ProtectedList` - = note: `ProtectedList` is the sink that builds this target, and that sink does not build its value from one scalar - = note: one ciphertext decrypts into a scalar such as `String`, `i64`, or `Vec`, or into an `Option`, a `Protected`, or a derived newtype of a scalar - = note: to decrypt many values, decrypt a `Vec`: each ciphertext becomes one element - = note: to decrypt a sequence, a map, or a struct that was encrypted as a tree, use `decrypt_tree` - = help: the following other types implement trait `TakesScalar`: - Optional - OwnedFrameSink - ProtectedOptional - ScalarProtected - ScalarSink - Wrap - Wrapped - = note: required for `ProtectedOptional>` to implement `TakesScalar` - = note: required for `Protected>>` to implement `ScalarTarget` + = help: the trait `ScalarTarget` is not implemented for `Protected>>` + = note: a scalar target is a `FromScalar` type, such as `String`, `i64`, or `Vec`. An `Option` or a `Protected` of one is a scalar target too. So is a newtype that derives `Decrypt` over one. + = note: a sequence, a map, and a struct with named fields each need a container. So none of them is a scalar target. + = note: a target with a hand-written sink is a scalar target when that sink implements `TakesScalar`. note: required by a bound in `opens_one_leaf` --> tests/ui/scalar_target/wrapped_container_is_not_a_scalar_target.rs:9:22 | From 2e6b6018c026728f88154ffa5b1ba6c14dd61ffe Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sat, 28 Nov 2026 20:08:09 +1100 Subject: [PATCH 17/19] fix(stack-encrypt): say which integers one ciphertext decrypts into The note on a refused decrypt target said "an integer other than u8". usize and isize are refused too, so the note now says "a fixed-width integer other than u8", as the encrypt side's note does. --- packages/stack-encrypt/src/scalar.rs | 6 +++--- .../ui/opaque_blob_decrypt_requires_default.stderr | 2 +- .../tests/ui/opaque_blob_requires_zeroize.stderr | 2 +- .../tests/ui/owned_collection_elements.stderr | 2 +- .../ui/scalar_decrypt_into_a_container.stderr | 14 +++++++------- .../scalar_decrypt_target_requires_zeroize.stderr | 2 +- 6 files changed, 14 insertions(+), 14 deletions(-) diff --git a/packages/stack-encrypt/src/scalar.rs b/packages/stack-encrypt/src/scalar.rs index 4ed66a8e1..58915e797 100644 --- a/packages/stack-encrypt/src/scalar.rs +++ b/packages/stack-encrypt/src/scalar.rs @@ -195,9 +195,9 @@ pub trait OpaqueEncode: sealed::Encode + Zeroize + Send + 'static {} #[diagnostic::on_unimplemented( message = "`{Self}` cannot be decrypted from one `Ciphertext`", label = "one `Ciphertext` decrypts into one owned value", - note = "one value is a `String`, a `bool`, a float, a `Vec`, or an integer other than \ - `u8`. An `Option` or a `Protected` of one of these is one value too. So is a newtype \ - that derives `Decrypt` over one of these.", + note = "one value is a `String`, a `bool`, a float, a `Vec`, or a fixed-width integer \ + other than `u8`. An `Option` or a `Protected` of one of these is one value too. So is \ + a newtype that derives `Decrypt` over one of these.", note = "the type must also implement `Zeroize`, so that a decrypted value can be wiped when \ a later decrypt in the same call fails.", note = "the type must also be `Send` and `'static`. A type that borrows data is not \ diff --git a/packages/stack-encrypt/tests/ui/opaque_blob_decrypt_requires_default.stderr b/packages/stack-encrypt/tests/ui/opaque_blob_decrypt_requires_default.stderr index 9dceb5ba8..0c065f867 100644 --- a/packages/stack-encrypt/tests/ui/opaque_blob_decrypt_requires_default.stderr +++ b/packages/stack-encrypt/tests/ui/opaque_blob_decrypt_requires_default.stderr @@ -5,7 +5,7 @@ error[E0277]: `OpaqueBlob` cannot be decrypted from one `Ciphertext` | ^^^^^^^ one `Ciphertext` decrypts into one owned value | = help: the trait `OpaqueDecode` is not implemented for `OpaqueBlob` - = note: one value is a `String`, a `bool`, a float, a `Vec`, or an integer other than `u8`. An `Option` or a `Protected` of one of these is one value too. So is a newtype that derives `Decrypt` over one of these. + = note: one value is a `String`, a `bool`, a float, a `Vec`, or a fixed-width integer other than `u8`. An `Option` or a `Protected` of one of these is one value too. So is a newtype that derives `Decrypt` over one of these. = note: the type must also implement `Zeroize`, so that a decrypted value can be wiped when a later decrypt in the same call fails. = note: the type must also be `Send` and `'static`. A type that borrows data is not `'static`. = note: to decrypt a `Vec` into a `Vec`, with one element from each `Ciphertext`, use `DecryptFrom`. diff --git a/packages/stack-encrypt/tests/ui/opaque_blob_requires_zeroize.stderr b/packages/stack-encrypt/tests/ui/opaque_blob_requires_zeroize.stderr index 260defdb1..a24ba97e3 100644 --- a/packages/stack-encrypt/tests/ui/opaque_blob_requires_zeroize.stderr +++ b/packages/stack-encrypt/tests/ui/opaque_blob_requires_zeroize.stderr @@ -164,7 +164,7 @@ error[E0277]: `OpaqueBlob` cannot be decrypted from one `Ciphertext` | ^^^^^^^ one `Ciphertext` decrypts into one owned value | = help: the trait `OpaqueDecode` is not implemented for `OpaqueBlob` - = note: one value is a `String`, a `bool`, a float, a `Vec`, or an integer other than `u8`. An `Option` or a `Protected` of one of these is one value too. So is a newtype that derives `Decrypt` over one of these. + = note: one value is a `String`, a `bool`, a float, a `Vec`, or a fixed-width integer other than `u8`. An `Option` or a `Protected` of one of these is one value too. So is a newtype that derives `Decrypt` over one of these. = note: the type must also implement `Zeroize`, so that a decrypted value can be wiped when a later decrypt in the same call fails. = note: the type must also be `Send` and `'static`. A type that borrows data is not `'static`. = note: to decrypt a `Vec` into a `Vec`, with one element from each `Ciphertext`, use `DecryptFrom`. diff --git a/packages/stack-encrypt/tests/ui/owned_collection_elements.stderr b/packages/stack-encrypt/tests/ui/owned_collection_elements.stderr index 5c294f59e..eeddc4676 100644 --- a/packages/stack-encrypt/tests/ui/owned_collection_elements.stderr +++ b/packages/stack-encrypt/tests/ui/owned_collection_elements.stderr @@ -93,7 +93,7 @@ error[E0277]: `u8` cannot be decrypted from one `Ciphertext` | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ one `Ciphertext` decrypts into one owned value | = help: the trait `OpaqueDecode` is not implemented for `u8` - = note: one value is a `String`, a `bool`, a float, a `Vec`, or an integer other than `u8`. An `Option` or a `Protected` of one of these is one value too. So is a newtype that derives `Decrypt` over one of these. + = note: one value is a `String`, a `bool`, a float, a `Vec`, or a fixed-width integer other than `u8`. An `Option` or a `Protected` of one of these is one value too. So is a newtype that derives `Decrypt` over one of these. = note: the type must also implement `Zeroize`, so that a decrypted value can be wiped when a later decrypt in the same call fails. = note: the type must also be `Send` and `'static`. A type that borrows data is not `'static`. = note: to decrypt a `Vec` into a `Vec`, with one element from each `Ciphertext`, use `DecryptFrom`. diff --git a/packages/stack-encrypt/tests/ui/scalar_decrypt_into_a_container.stderr b/packages/stack-encrypt/tests/ui/scalar_decrypt_into_a_container.stderr index a721b61cc..de76f8a9d 100644 --- a/packages/stack-encrypt/tests/ui/scalar_decrypt_into_a_container.stderr +++ b/packages/stack-encrypt/tests/ui/scalar_decrypt_into_a_container.stderr @@ -5,7 +5,7 @@ error[E0277]: `Vec` cannot be decrypted from one `Ciphertex | ^^^^^^^^^^^ one `Ciphertext` decrypts into one owned value | = help: the trait `OpaqueDecode` is not implemented for `Vec` - = note: one value is a `String`, a `bool`, a float, a `Vec`, or an integer other than `u8`. An `Option` or a `Protected` of one of these is one value too. So is a newtype that derives `Decrypt` over one of these. + = note: one value is a `String`, a `bool`, a float, a `Vec`, or a fixed-width integer other than `u8`. An `Option` or a `Protected` of one of these is one value too. So is a newtype that derives `Decrypt` over one of these. = note: the type must also implement `Zeroize`, so that a decrypted value can be wiped when a later decrypt in the same call fails. = note: the type must also be `Send` and `'static`. A type that borrows data is not `'static`. = note: to decrypt a `Vec` into a `Vec`, with one element from each `Ciphertext`, use `DecryptFrom`. @@ -29,7 +29,7 @@ error[E0277]: `BTreeMap` cannot be decrypted from one | ^^^^^^^^^^^^^^^^^^^^^ one `Ciphertext` decrypts into one owned value | = help: the trait `OpaqueDecode` is not implemented for `BTreeMap` - = note: one value is a `String`, a `bool`, a float, a `Vec`, or an integer other than `u8`. An `Option` or a `Protected` of one of these is one value too. So is a newtype that derives `Decrypt` over one of these. + = note: one value is a `String`, a `bool`, a float, a `Vec`, or a fixed-width integer other than `u8`. An `Option` or a `Protected` of one of these is one value too. So is a newtype that derives `Decrypt` over one of these. = note: the type must also implement `Zeroize`, so that a decrypted value can be wiped when a later decrypt in the same call fails. = note: the type must also be `Send` and `'static`. A type that borrows data is not `'static`. = note: to decrypt a `Vec` into a `Vec`, with one element from each `Ciphertext`, use `DecryptFrom`. @@ -57,7 +57,7 @@ help: the trait `OpaqueDecode` is not implemented for `Account` | 11 | struct Account { | ^^^^^^^^^^^^^^ - = note: one value is a `String`, a `bool`, a float, a `Vec`, or an integer other than `u8`. An `Option` or a `Protected` of one of these is one value too. So is a newtype that derives `Decrypt` over one of these. + = note: one value is a `String`, a `bool`, a float, a `Vec`, or a fixed-width integer other than `u8`. An `Option` or a `Protected` of one of these is one value too. So is a newtype that derives `Decrypt` over one of these. = note: the type must also implement `Zeroize`, so that a decrypted value can be wiped when a later decrypt in the same call fails. = note: the type must also be `Send` and `'static`. A type that borrows data is not `'static`. = note: to decrypt a `Vec` into a `Vec`, with one element from each `Ciphertext`, use `DecryptFrom`. @@ -85,7 +85,7 @@ help: the trait `OpaqueDecode` is not implemented for `Tags` | 16 | struct Tags(Vec); | ^^^^^^^^^^^ - = note: one value is a `String`, a `bool`, a float, a `Vec`, or an integer other than `u8`. An `Option` or a `Protected` of one of these is one value too. So is a newtype that derives `Decrypt` over one of these. + = note: one value is a `String`, a `bool`, a float, a `Vec`, or a fixed-width integer other than `u8`. An `Option` or a `Protected` of one of these is one value too. So is a newtype that derives `Decrypt` over one of these. = note: the type must also implement `Zeroize`, so that a decrypted value can be wiped when a later decrypt in the same call fails. = note: the type must also be `Send` and `'static`. A type that borrows data is not `'static`. = note: to decrypt a `Vec` into a `Vec`, with one element from each `Ciphertext`, use `DecryptFrom`. @@ -109,7 +109,7 @@ error[E0277]: `Protected>` cannot be decrypted from one `Ciphertext` | ^^^^^^^^^^^^^^^^^^^ one `Ciphertext` decrypts into one owned value | = help: the trait `OpaqueDecode` is not implemented for `Protected>` - = note: one value is a `String`, a `bool`, a float, a `Vec`, or an integer other than `u8`. An `Option` or a `Protected` of one of these is one value too. So is a newtype that derives `Decrypt` over one of these. + = note: one value is a `String`, a `bool`, a float, a `Vec`, or a fixed-width integer other than `u8`. An `Option` or a `Protected` of one of these is one value too. So is a newtype that derives `Decrypt` over one of these. = note: the type must also implement `Zeroize`, so that a decrypted value can be wiped when a later decrypt in the same call fails. = note: the type must also be `Send` and `'static`. A type that borrows data is not `'static`. = note: to decrypt a `Vec` into a `Vec`, with one element from each `Ciphertext`, use `DecryptFrom`. @@ -133,7 +133,7 @@ error[E0277]: `HashMap` cannot be decr | ^^^^^^^^^^^^^^^^^^^^^^^ one `Ciphertext` decrypts into one owned value | = help: the trait `OpaqueDecode` is not implemented for `HashMap` - = note: one value is a `String`, a `bool`, a float, a `Vec`, or an integer other than `u8`. An `Option` or a `Protected` of one of these is one value too. So is a newtype that derives `Decrypt` over one of these. + = note: one value is a `String`, a `bool`, a float, a `Vec`, or a fixed-width integer other than `u8`. An `Option` or a `Protected` of one of these is one value too. So is a newtype that derives `Decrypt` over one of these. = note: the type must also implement `Zeroize`, so that a decrypted value can be wiped when a later decrypt in the same call fails. = note: the type must also be `Send` and `'static`. A type that borrows data is not `'static`. = note: to decrypt a `Vec` into a `Vec`, with one element from each `Ciphertext`, use `DecryptFrom`. @@ -157,7 +157,7 @@ error[E0277]: `Vec` cannot be decrypted from one `Ciphertext` | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ one `Ciphertext` decrypts into one owned value | = help: the trait `OpaqueDecode` is not implemented for `Vec` - = note: one value is a `String`, a `bool`, a float, a `Vec`, or an integer other than `u8`. An `Option` or a `Protected` of one of these is one value too. So is a newtype that derives `Decrypt` over one of these. + = note: one value is a `String`, a `bool`, a float, a `Vec`, or a fixed-width integer other than `u8`. An `Option` or a `Protected` of one of these is one value too. So is a newtype that derives `Decrypt` over one of these. = note: the type must also implement `Zeroize`, so that a decrypted value can be wiped when a later decrypt in the same call fails. = note: the type must also be `Send` and `'static`. A type that borrows data is not `'static`. = note: to decrypt a `Vec` into a `Vec`, with one element from each `Ciphertext`, use `DecryptFrom`. diff --git a/packages/stack-encrypt/tests/ui/scalar_decrypt_target_requires_zeroize.stderr b/packages/stack-encrypt/tests/ui/scalar_decrypt_target_requires_zeroize.stderr index 927435a39..eb40dce00 100644 --- a/packages/stack-encrypt/tests/ui/scalar_decrypt_target_requires_zeroize.stderr +++ b/packages/stack-encrypt/tests/ui/scalar_decrypt_target_requires_zeroize.stderr @@ -9,7 +9,7 @@ help: the trait `OpaqueDecode` is not implemented for `Email` | 7 | struct Email(String); | ^^^^^^^^^^^^ - = note: one value is a `String`, a `bool`, a float, a `Vec`, or an integer other than `u8`. An `Option` or a `Protected` of one of these is one value too. So is a newtype that derives `Decrypt` over one of these. + = note: one value is a `String`, a `bool`, a float, a `Vec`, or a fixed-width integer other than `u8`. An `Option` or a `Protected` of one of these is one value too. So is a newtype that derives `Decrypt` over one of these. = note: the type must also implement `Zeroize`, so that a decrypted value can be wiped when a later decrypt in the same call fails. = note: the type must also be `Send` and `'static`. A type that borrows data is not `'static`. = note: to decrypt a `Vec` into a `Vec`, with one element from each `Ciphertext`, use `DecryptFrom`. From 25e344aff82959898ce6c60dcf1a93a5b4e5e4c4 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sat, 28 Nov 2026 20:52:07 +1100 Subject: [PATCH 18/19] fix(stack-encrypt): correct which decrypt targets the docs say exist A second review found three statements about decrypt targets that were wrong or incomplete. The first note of the compile error for `OpaqueDecode` read as a full list of the accepted types. The note left out several of them. A user who wrote `keyset.decrypt::` saw the note, and nothing told them to use `value::Uuid`. The note now says that its list is partial, and names the docs of `OpaqueDecode` for the full list. A new note names `value::Date`, `value::Timestamp`, `value::Decimal`, and `value::Uuid`. The same note says why the jiff, rust_decimal, and uuid types are refused: each is built from one scalar, but none implements `Zeroize`. The docs and the changelog said that every integer is a target. `u8`, `usize`, and `isize` are not. The text now says "the fixed-width integers other than `u8`". The docs and the changelog said that a type of your own needs one scalar and `Zeroize`. The blanket impl also needs `Send` and `'static`. The text now lists every bound, and says that a `'static` type borrows no data. The compile-fail test for a target with no `Zeroize` now also covers `uuid::Uuid`. --- packages/stack-encrypt/CHANGELOG.md | 16 +++---- packages/stack-encrypt/src/scalar.rs | 41 +++++++++++------- ...paque_blob_decrypt_requires_default.stderr | 6 ++- .../ui/opaque_blob_requires_zeroize.stderr | 6 ++- .../tests/ui/owned_collection_elements.stderr | 6 ++- .../ui/scalar_decrypt_into_a_container.stderr | 42 ++++++++++++------- .../scalar_decrypt_target_requires_zeroize.rs | 6 ++- ...lar_decrypt_target_requires_zeroize.stderr | 40 +++++++++++++++--- packages/vitaminc-aead/src/typed.rs | 4 +- 9 files changed, 116 insertions(+), 51 deletions(-) diff --git a/packages/stack-encrypt/CHANGELOG.md b/packages/stack-encrypt/CHANGELOG.md index d9614ab1d..886d0e02d 100644 --- a/packages/stack-encrypt/CHANGELOG.md +++ b/packages/stack-encrypt/CHANGELOG.md @@ -578,9 +578,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 `T::decrypt_from(ciphertext, ..)`, and a `Ciphertext` field of a derived record. - Still accepted: - - every scalar: `bool`, the integers, the floats, `String`, `Vec`, - `[u8; N]`, `value::Date`, `value::Timestamp`, `value::Decimal`, and - `value::Uuid` + - every scalar: `bool`, the fixed-width integers other than `u8`, the + floats, `String`, `Vec`, `[u8; N]`, `value::Date`, + `value::Timestamp`, `value::Decimal`, and `value::Uuid` - `JsonPlaintext` - a `Protected` or an `Option` of a scalar - `OwnedFrame` @@ -593,10 +593,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - a `HashMap` or a `BTreeMap` - a struct that derives `Decrypt` with named fields - a newtype, a `Protected`, or an `Option` of one of those - - You write no code to make a type of your own a target. You cannot - implement `ScalarTarget` directly. A type is a `ScalarTarget` when it - is built from one scalar. The compiler derives that from how the type - decrypts. + - A type of your own is accepted when it is built from one scalar. The + type must also implement `Zeroize` and `Send`, and be `'static`. A + `'static` type borrows no data. + - You cannot implement `ScalarTarget` directly. A type is a + `ScalarTarget` when it is built from one scalar. The compiler derives + that from how the type decrypts. - The compile error names the type that you wrote, such as `Vec`. The error says what one `Ciphertext` decrypts into, and what to use for the other types. diff --git a/packages/stack-encrypt/src/scalar.rs b/packages/stack-encrypt/src/scalar.rs index 58915e797..54dab925a 100644 --- a/packages/stack-encrypt/src/scalar.rs +++ b/packages/stack-encrypt/src/scalar.rs @@ -113,12 +113,17 @@ pub trait OpaqueEncode: sealed::Encode + Zeroize + Send + 'static {} /// A plaintext type that one opaque [`Ciphertext`] decrypts to. /// /// A `Ciphertext` contains one scalar. So `OpaqueDecode` is implemented for -/// every type that is built from one scalar and that implements [`Zeroize`]. -/// Vitamin C names a type that is built from one scalar a [`ScalarTarget`]. +/// every type that meets two conditions: +/// +/// - The type is built from one scalar. Vitamin C names such a type a +/// [`ScalarTarget`]. +/// - The type implements [`Zeroize`] and `Send`, and is `'static`. A +/// `'static` type borrows no data. +/// /// The `OpaqueDecode` types are: /// -/// - each scalar: `bool`, the integers, the floats, `String`, `Vec`, and -/// `[u8; N]` +/// - each scalar: `bool`, the fixed-width integers other than `u8`, the +/// floats, `String`, `Vec`, and `[u8; N]` /// - the date, timestamp, decimal, and UUID [values](crate::value) /// - [`JsonPlaintext`](crate::json::JsonPlaintext), a JSON document /// - a [`Protected`](vitaminc_protected::Protected) of one, such as @@ -155,11 +160,14 @@ pub trait OpaqueEncode: sealed::Encode + Zeroize + Send + 'static {} /// # } /// ``` /// -/// A type of your own is an `OpaqueDecode` type when it is built from one -/// scalar and implements `Zeroize`. You cannot implement `ScalarTarget` for -/// it: a type is a `ScalarTarget` because of how it decrypts. A newtype that -/// derives `Decrypt` over a scalar needs no extra code. Neither does a type -/// that implements Vitamin C's `FromScalar`. +/// A type of your own is an `OpaqueDecode` type when it meets the same two +/// conditions. You cannot implement `ScalarTarget` for it: a type is a +/// `ScalarTarget` because of how it decrypts. A newtype that derives +/// `Decrypt` over a scalar meets the first condition with no extra code. So +/// does a type that implements Vitamin C's `FromScalar`. +/// +/// For the second condition, derive or implement `Zeroize`. A type that +/// borrows data is not `'static`, so it is refused. /// /// The derive is Vitamin C's, so your crate needs `vitaminc-aead` as a /// dependency to use it. @@ -195,13 +203,18 @@ pub trait OpaqueEncode: sealed::Encode + Zeroize + Send + 'static {} #[diagnostic::on_unimplemented( message = "`{Self}` cannot be decrypted from one `Ciphertext`", label = "one `Ciphertext` decrypts into one owned value", - note = "one value is a `String`, a `bool`, a float, a `Vec`, or a fixed-width integer \ - other than `u8`. An `Option` or a `Protected` of one of these is one value too. So is \ - a newtype that derives `Decrypt` over one of these.", + note = "one value is a scalar, such as a `String`, a `bool`, a float, a `Vec`, or a \ + fixed-width integer other than `u8`. The docs of `OpaqueDecode` list every type \ + that is accepted.", + note = "an `Option` or a `Protected` of a scalar is one value too. So is a newtype that \ + derives `Decrypt` over a scalar.", + note = "for a date, a timestamp, a decimal, or a UUID, use `value::Date`, \ + `value::Timestamp`, `value::Decimal`, or `value::Uuid`. A `uuid::Uuid`, a \ + `rust_decimal::Decimal`, and the jiff types do not implement `Zeroize`.", note = "the type must also implement `Zeroize`, so that a decrypted value can be wiped when \ a later decrypt in the same call fails.", - note = "the type must also be `Send` and `'static`. A type that borrows data is not \ - `'static`.", + note = "the type must also be `Send` and `'static`. A `'static` type borrows no \ + data.", note = "to decrypt a `Vec` into a `Vec`, with one element from each \ `Ciphertext`, use `DecryptFrom`.", note = "to decrypt a sequence, a map, or a struct that derives `Decrypt`, use \ diff --git a/packages/stack-encrypt/tests/ui/opaque_blob_decrypt_requires_default.stderr b/packages/stack-encrypt/tests/ui/opaque_blob_decrypt_requires_default.stderr index 0c065f867..568c19603 100644 --- a/packages/stack-encrypt/tests/ui/opaque_blob_decrypt_requires_default.stderr +++ b/packages/stack-encrypt/tests/ui/opaque_blob_decrypt_requires_default.stderr @@ -5,9 +5,11 @@ error[E0277]: `OpaqueBlob` cannot be decrypted from one `Ciphertext` | ^^^^^^^ one `Ciphertext` decrypts into one owned value | = help: the trait `OpaqueDecode` is not implemented for `OpaqueBlob` - = note: one value is a `String`, a `bool`, a float, a `Vec`, or a fixed-width integer other than `u8`. An `Option` or a `Protected` of one of these is one value too. So is a newtype that derives `Decrypt` over one of these. + = note: one value is a scalar, such as a `String`, a `bool`, a float, a `Vec`, or a fixed-width integer other than `u8`. The docs of `OpaqueDecode` list every type that is accepted. + = note: an `Option` or a `Protected` of a scalar is one value too. So is a newtype that derives `Decrypt` over a scalar. + = note: for a date, a timestamp, a decimal, or a UUID, use `value::Date`, `value::Timestamp`, `value::Decimal`, or `value::Uuid`. A `uuid::Uuid`, a `rust_decimal::Decimal`, and the jiff types do not implement `Zeroize`. = note: the type must also implement `Zeroize`, so that a decrypted value can be wiped when a later decrypt in the same call fails. - = note: the type must also be `Send` and `'static`. A type that borrows data is not `'static`. + = note: the type must also be `Send` and `'static`. A `'static` type borrows no data. = note: to decrypt a `Vec` into a `Vec`, with one element from each `Ciphertext`, use `DecryptFrom`. = note: to decrypt a sequence, a map, or a struct that derives `Decrypt`, use `keyset.decrypt_tree`. `keyset.encrypt_tree` makes the tree of ciphertexts that it reads. = note: to decrypt a whole `Deserialize` value from one `Ciphertext`, decrypt into `OpaqueBlob`. `T` must also implement `Default` and `Zeroize`. diff --git a/packages/stack-encrypt/tests/ui/opaque_blob_requires_zeroize.stderr b/packages/stack-encrypt/tests/ui/opaque_blob_requires_zeroize.stderr index a24ba97e3..06cfc11f6 100644 --- a/packages/stack-encrypt/tests/ui/opaque_blob_requires_zeroize.stderr +++ b/packages/stack-encrypt/tests/ui/opaque_blob_requires_zeroize.stderr @@ -164,9 +164,11 @@ error[E0277]: `OpaqueBlob` cannot be decrypted from one `Ciphertext` | ^^^^^^^ one `Ciphertext` decrypts into one owned value | = help: the trait `OpaqueDecode` is not implemented for `OpaqueBlob` - = note: one value is a `String`, a `bool`, a float, a `Vec`, or a fixed-width integer other than `u8`. An `Option` or a `Protected` of one of these is one value too. So is a newtype that derives `Decrypt` over one of these. + = note: one value is a scalar, such as a `String`, a `bool`, a float, a `Vec`, or a fixed-width integer other than `u8`. The docs of `OpaqueDecode` list every type that is accepted. + = note: an `Option` or a `Protected` of a scalar is one value too. So is a newtype that derives `Decrypt` over a scalar. + = note: for a date, a timestamp, a decimal, or a UUID, use `value::Date`, `value::Timestamp`, `value::Decimal`, or `value::Uuid`. A `uuid::Uuid`, a `rust_decimal::Decimal`, and the jiff types do not implement `Zeroize`. = note: the type must also implement `Zeroize`, so that a decrypted value can be wiped when a later decrypt in the same call fails. - = note: the type must also be `Send` and `'static`. A type that borrows data is not `'static`. + = note: the type must also be `Send` and `'static`. A `'static` type borrows no data. = note: to decrypt a `Vec` into a `Vec`, with one element from each `Ciphertext`, use `DecryptFrom`. = note: to decrypt a sequence, a map, or a struct that derives `Decrypt`, use `keyset.decrypt_tree`. `keyset.encrypt_tree` makes the tree of ciphertexts that it reads. = note: to decrypt a whole `Deserialize` value from one `Ciphertext`, decrypt into `OpaqueBlob`. `T` must also implement `Default` and `Zeroize`. diff --git a/packages/stack-encrypt/tests/ui/owned_collection_elements.stderr b/packages/stack-encrypt/tests/ui/owned_collection_elements.stderr index eeddc4676..632b71be3 100644 --- a/packages/stack-encrypt/tests/ui/owned_collection_elements.stderr +++ b/packages/stack-encrypt/tests/ui/owned_collection_elements.stderr @@ -93,9 +93,11 @@ error[E0277]: `u8` cannot be decrypted from one `Ciphertext` | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ one `Ciphertext` decrypts into one owned value | = help: the trait `OpaqueDecode` is not implemented for `u8` - = note: one value is a `String`, a `bool`, a float, a `Vec`, or a fixed-width integer other than `u8`. An `Option` or a `Protected` of one of these is one value too. So is a newtype that derives `Decrypt` over one of these. + = note: one value is a scalar, such as a `String`, a `bool`, a float, a `Vec`, or a fixed-width integer other than `u8`. The docs of `OpaqueDecode` list every type that is accepted. + = note: an `Option` or a `Protected` of a scalar is one value too. So is a newtype that derives `Decrypt` over a scalar. + = note: for a date, a timestamp, a decimal, or a UUID, use `value::Date`, `value::Timestamp`, `value::Decimal`, or `value::Uuid`. A `uuid::Uuid`, a `rust_decimal::Decimal`, and the jiff types do not implement `Zeroize`. = note: the type must also implement `Zeroize`, so that a decrypted value can be wiped when a later decrypt in the same call fails. - = note: the type must also be `Send` and `'static`. A type that borrows data is not `'static`. + = note: the type must also be `Send` and `'static`. A `'static` type borrows no data. = note: to decrypt a `Vec` into a `Vec`, with one element from each `Ciphertext`, use `DecryptFrom`. = note: to decrypt a sequence, a map, or a struct that derives `Decrypt`, use `keyset.decrypt_tree`. `keyset.encrypt_tree` makes the tree of ciphertexts that it reads. = note: to decrypt a whole `Deserialize` value from one `Ciphertext`, decrypt into `OpaqueBlob`. `T` must also implement `Default` and `Zeroize`. diff --git a/packages/stack-encrypt/tests/ui/scalar_decrypt_into_a_container.stderr b/packages/stack-encrypt/tests/ui/scalar_decrypt_into_a_container.stderr index de76f8a9d..317aea2d8 100644 --- a/packages/stack-encrypt/tests/ui/scalar_decrypt_into_a_container.stderr +++ b/packages/stack-encrypt/tests/ui/scalar_decrypt_into_a_container.stderr @@ -5,9 +5,11 @@ error[E0277]: `Vec` cannot be decrypted from one `Ciphertex | ^^^^^^^^^^^ one `Ciphertext` decrypts into one owned value | = help: the trait `OpaqueDecode` is not implemented for `Vec` - = note: one value is a `String`, a `bool`, a float, a `Vec`, or a fixed-width integer other than `u8`. An `Option` or a `Protected` of one of these is one value too. So is a newtype that derives `Decrypt` over one of these. + = note: one value is a scalar, such as a `String`, a `bool`, a float, a `Vec`, or a fixed-width integer other than `u8`. The docs of `OpaqueDecode` list every type that is accepted. + = note: an `Option` or a `Protected` of a scalar is one value too. So is a newtype that derives `Decrypt` over a scalar. + = note: for a date, a timestamp, a decimal, or a UUID, use `value::Date`, `value::Timestamp`, `value::Decimal`, or `value::Uuid`. A `uuid::Uuid`, a `rust_decimal::Decimal`, and the jiff types do not implement `Zeroize`. = note: the type must also implement `Zeroize`, so that a decrypted value can be wiped when a later decrypt in the same call fails. - = note: the type must also be `Send` and `'static`. A type that borrows data is not `'static`. + = note: the type must also be `Send` and `'static`. A `'static` type borrows no data. = note: to decrypt a `Vec` into a `Vec`, with one element from each `Ciphertext`, use `DecryptFrom`. = note: to decrypt a sequence, a map, or a struct that derives `Decrypt`, use `keyset.decrypt_tree`. `keyset.encrypt_tree` makes the tree of ciphertexts that it reads. = note: to decrypt a whole `Deserialize` value from one `Ciphertext`, decrypt into `OpaqueBlob`. `T` must also implement `Default` and `Zeroize`. @@ -29,9 +31,11 @@ error[E0277]: `BTreeMap` cannot be decrypted from one | ^^^^^^^^^^^^^^^^^^^^^ one `Ciphertext` decrypts into one owned value | = help: the trait `OpaqueDecode` is not implemented for `BTreeMap` - = note: one value is a `String`, a `bool`, a float, a `Vec`, or a fixed-width integer other than `u8`. An `Option` or a `Protected` of one of these is one value too. So is a newtype that derives `Decrypt` over one of these. + = note: one value is a scalar, such as a `String`, a `bool`, a float, a `Vec`, or a fixed-width integer other than `u8`. The docs of `OpaqueDecode` list every type that is accepted. + = note: an `Option` or a `Protected` of a scalar is one value too. So is a newtype that derives `Decrypt` over a scalar. + = note: for a date, a timestamp, a decimal, or a UUID, use `value::Date`, `value::Timestamp`, `value::Decimal`, or `value::Uuid`. A `uuid::Uuid`, a `rust_decimal::Decimal`, and the jiff types do not implement `Zeroize`. = note: the type must also implement `Zeroize`, so that a decrypted value can be wiped when a later decrypt in the same call fails. - = note: the type must also be `Send` and `'static`. A type that borrows data is not `'static`. + = note: the type must also be `Send` and `'static`. A `'static` type borrows no data. = note: to decrypt a `Vec` into a `Vec`, with one element from each `Ciphertext`, use `DecryptFrom`. = note: to decrypt a sequence, a map, or a struct that derives `Decrypt`, use `keyset.decrypt_tree`. `keyset.encrypt_tree` makes the tree of ciphertexts that it reads. = note: to decrypt a whole `Deserialize` value from one `Ciphertext`, decrypt into `OpaqueBlob`. `T` must also implement `Default` and `Zeroize`. @@ -57,9 +61,11 @@ help: the trait `OpaqueDecode` is not implemented for `Account` | 11 | struct Account { | ^^^^^^^^^^^^^^ - = note: one value is a `String`, a `bool`, a float, a `Vec`, or a fixed-width integer other than `u8`. An `Option` or a `Protected` of one of these is one value too. So is a newtype that derives `Decrypt` over one of these. + = note: one value is a scalar, such as a `String`, a `bool`, a float, a `Vec`, or a fixed-width integer other than `u8`. The docs of `OpaqueDecode` list every type that is accepted. + = note: an `Option` or a `Protected` of a scalar is one value too. So is a newtype that derives `Decrypt` over a scalar. + = note: for a date, a timestamp, a decimal, or a UUID, use `value::Date`, `value::Timestamp`, `value::Decimal`, or `value::Uuid`. A `uuid::Uuid`, a `rust_decimal::Decimal`, and the jiff types do not implement `Zeroize`. = note: the type must also implement `Zeroize`, so that a decrypted value can be wiped when a later decrypt in the same call fails. - = note: the type must also be `Send` and `'static`. A type that borrows data is not `'static`. + = note: the type must also be `Send` and `'static`. A `'static` type borrows no data. = note: to decrypt a `Vec` into a `Vec`, with one element from each `Ciphertext`, use `DecryptFrom`. = note: to decrypt a sequence, a map, or a struct that derives `Decrypt`, use `keyset.decrypt_tree`. `keyset.encrypt_tree` makes the tree of ciphertexts that it reads. = note: to decrypt a whole `Deserialize` value from one `Ciphertext`, decrypt into `OpaqueBlob`. `T` must also implement `Default` and `Zeroize`. @@ -85,9 +91,11 @@ help: the trait `OpaqueDecode` is not implemented for `Tags` | 16 | struct Tags(Vec); | ^^^^^^^^^^^ - = note: one value is a `String`, a `bool`, a float, a `Vec`, or a fixed-width integer other than `u8`. An `Option` or a `Protected` of one of these is one value too. So is a newtype that derives `Decrypt` over one of these. + = note: one value is a scalar, such as a `String`, a `bool`, a float, a `Vec`, or a fixed-width integer other than `u8`. The docs of `OpaqueDecode` list every type that is accepted. + = note: an `Option` or a `Protected` of a scalar is one value too. So is a newtype that derives `Decrypt` over a scalar. + = note: for a date, a timestamp, a decimal, or a UUID, use `value::Date`, `value::Timestamp`, `value::Decimal`, or `value::Uuid`. A `uuid::Uuid`, a `rust_decimal::Decimal`, and the jiff types do not implement `Zeroize`. = note: the type must also implement `Zeroize`, so that a decrypted value can be wiped when a later decrypt in the same call fails. - = note: the type must also be `Send` and `'static`. A type that borrows data is not `'static`. + = note: the type must also be `Send` and `'static`. A `'static` type borrows no data. = note: to decrypt a `Vec` into a `Vec`, with one element from each `Ciphertext`, use `DecryptFrom`. = note: to decrypt a sequence, a map, or a struct that derives `Decrypt`, use `keyset.decrypt_tree`. `keyset.encrypt_tree` makes the tree of ciphertexts that it reads. = note: to decrypt a whole `Deserialize` value from one `Ciphertext`, decrypt into `OpaqueBlob`. `T` must also implement `Default` and `Zeroize`. @@ -109,9 +117,11 @@ error[E0277]: `Protected>` cannot be decrypted from one `Ciphertext` | ^^^^^^^^^^^^^^^^^^^ one `Ciphertext` decrypts into one owned value | = help: the trait `OpaqueDecode` is not implemented for `Protected>` - = note: one value is a `String`, a `bool`, a float, a `Vec`, or a fixed-width integer other than `u8`. An `Option` or a `Protected` of one of these is one value too. So is a newtype that derives `Decrypt` over one of these. + = note: one value is a scalar, such as a `String`, a `bool`, a float, a `Vec`, or a fixed-width integer other than `u8`. The docs of `OpaqueDecode` list every type that is accepted. + = note: an `Option` or a `Protected` of a scalar is one value too. So is a newtype that derives `Decrypt` over a scalar. + = note: for a date, a timestamp, a decimal, or a UUID, use `value::Date`, `value::Timestamp`, `value::Decimal`, or `value::Uuid`. A `uuid::Uuid`, a `rust_decimal::Decimal`, and the jiff types do not implement `Zeroize`. = note: the type must also implement `Zeroize`, so that a decrypted value can be wiped when a later decrypt in the same call fails. - = note: the type must also be `Send` and `'static`. A type that borrows data is not `'static`. + = note: the type must also be `Send` and `'static`. A `'static` type borrows no data. = note: to decrypt a `Vec` into a `Vec`, with one element from each `Ciphertext`, use `DecryptFrom`. = note: to decrypt a sequence, a map, or a struct that derives `Decrypt`, use `keyset.decrypt_tree`. `keyset.encrypt_tree` makes the tree of ciphertexts that it reads. = note: to decrypt a whole `Deserialize` value from one `Ciphertext`, decrypt into `OpaqueBlob`. `T` must also implement `Default` and `Zeroize`. @@ -133,9 +143,11 @@ error[E0277]: `HashMap` cannot be decr | ^^^^^^^^^^^^^^^^^^^^^^^ one `Ciphertext` decrypts into one owned value | = help: the trait `OpaqueDecode` is not implemented for `HashMap` - = note: one value is a `String`, a `bool`, a float, a `Vec`, or a fixed-width integer other than `u8`. An `Option` or a `Protected` of one of these is one value too. So is a newtype that derives `Decrypt` over one of these. + = note: one value is a scalar, such as a `String`, a `bool`, a float, a `Vec`, or a fixed-width integer other than `u8`. The docs of `OpaqueDecode` list every type that is accepted. + = note: an `Option` or a `Protected` of a scalar is one value too. So is a newtype that derives `Decrypt` over a scalar. + = note: for a date, a timestamp, a decimal, or a UUID, use `value::Date`, `value::Timestamp`, `value::Decimal`, or `value::Uuid`. A `uuid::Uuid`, a `rust_decimal::Decimal`, and the jiff types do not implement `Zeroize`. = note: the type must also implement `Zeroize`, so that a decrypted value can be wiped when a later decrypt in the same call fails. - = note: the type must also be `Send` and `'static`. A type that borrows data is not `'static`. + = note: the type must also be `Send` and `'static`. A `'static` type borrows no data. = note: to decrypt a `Vec` into a `Vec`, with one element from each `Ciphertext`, use `DecryptFrom`. = note: to decrypt a sequence, a map, or a struct that derives `Decrypt`, use `keyset.decrypt_tree`. `keyset.encrypt_tree` makes the tree of ciphertexts that it reads. = note: to decrypt a whole `Deserialize` value from one `Ciphertext`, decrypt into `OpaqueBlob`. `T` must also implement `Default` and `Zeroize`. @@ -157,9 +169,11 @@ error[E0277]: `Vec` cannot be decrypted from one `Ciphertext` | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ one `Ciphertext` decrypts into one owned value | = help: the trait `OpaqueDecode` is not implemented for `Vec` - = note: one value is a `String`, a `bool`, a float, a `Vec`, or a fixed-width integer other than `u8`. An `Option` or a `Protected` of one of these is one value too. So is a newtype that derives `Decrypt` over one of these. + = note: one value is a scalar, such as a `String`, a `bool`, a float, a `Vec`, or a fixed-width integer other than `u8`. The docs of `OpaqueDecode` list every type that is accepted. + = note: an `Option` or a `Protected` of a scalar is one value too. So is a newtype that derives `Decrypt` over a scalar. + = note: for a date, a timestamp, a decimal, or a UUID, use `value::Date`, `value::Timestamp`, `value::Decimal`, or `value::Uuid`. A `uuid::Uuid`, a `rust_decimal::Decimal`, and the jiff types do not implement `Zeroize`. = note: the type must also implement `Zeroize`, so that a decrypted value can be wiped when a later decrypt in the same call fails. - = note: the type must also be `Send` and `'static`. A type that borrows data is not `'static`. + = note: the type must also be `Send` and `'static`. A `'static` type borrows no data. = note: to decrypt a `Vec` into a `Vec`, with one element from each `Ciphertext`, use `DecryptFrom`. = note: to decrypt a sequence, a map, or a struct that derives `Decrypt`, use `keyset.decrypt_tree`. `keyset.encrypt_tree` makes the tree of ciphertexts that it reads. = note: to decrypt a whole `Deserialize` value from one `Ciphertext`, decrypt into `OpaqueBlob`. `T` must also implement `Default` and `Zeroize`. diff --git a/packages/stack-encrypt/tests/ui/scalar_decrypt_target_requires_zeroize.rs b/packages/stack-encrypt/tests/ui/scalar_decrypt_target_requires_zeroize.rs index dbd3aef7b..a1569f532 100644 --- a/packages/stack-encrypt/tests/ui/scalar_decrypt_target_requires_zeroize.rs +++ b/packages/stack-encrypt/tests/ui/scalar_decrypt_target_requires_zeroize.rs @@ -1,13 +1,15 @@ //! One scalar builds a newtype that derives `Decrypt` over a `String`. A //! `Ciphertext` still does not decrypt into the newtype, because the newtype -//! does not implement `Zeroize`. +//! does not implement `Zeroize`. The same is true of a `uuid::Uuid`: the +//! error points to `value::Uuid`. use stack_encrypt::{Ciphertext, Decrypt, KeysetCipher}; #[derive(Decrypt)] struct Email(String); fn refused(keyset: &KeysetCipher<'_, K>, ciphertext: Ciphertext) { - let _ = keyset.decrypt::(ciphertext); + let _ = keyset.decrypt::(ciphertext.clone()); + let _ = keyset.decrypt::(ciphertext); } fn main() {} diff --git a/packages/stack-encrypt/tests/ui/scalar_decrypt_target_requires_zeroize.stderr b/packages/stack-encrypt/tests/ui/scalar_decrypt_target_requires_zeroize.stderr index eb40dce00..c177655b2 100644 --- a/packages/stack-encrypt/tests/ui/scalar_decrypt_target_requires_zeroize.stderr +++ b/packages/stack-encrypt/tests/ui/scalar_decrypt_target_requires_zeroize.stderr @@ -1,17 +1,45 @@ error[E0277]: `Email` cannot be decrypted from one `Ciphertext` - --> tests/ui/scalar_decrypt_target_requires_zeroize.rs:10:30 + --> tests/ui/scalar_decrypt_target_requires_zeroize.rs:11:30 | -10 | let _ = keyset.decrypt::(ciphertext); +11 | let _ = keyset.decrypt::(ciphertext.clone()); | ^^^^^ one `Ciphertext` decrypts into one owned value | help: the trait `OpaqueDecode` is not implemented for `Email` - --> tests/ui/scalar_decrypt_target_requires_zeroize.rs:7:1 + --> tests/ui/scalar_decrypt_target_requires_zeroize.rs:8:1 | - 7 | struct Email(String); + 8 | struct Email(String); | ^^^^^^^^^^^^ - = note: one value is a `String`, a `bool`, a float, a `Vec`, or a fixed-width integer other than `u8`. An `Option` or a `Protected` of one of these is one value too. So is a newtype that derives `Decrypt` over one of these. + = note: one value is a scalar, such as a `String`, a `bool`, a float, a `Vec`, or a fixed-width integer other than `u8`. The docs of `OpaqueDecode` list every type that is accepted. + = note: an `Option` or a `Protected` of a scalar is one value too. So is a newtype that derives `Decrypt` over a scalar. + = note: for a date, a timestamp, a decimal, or a UUID, use `value::Date`, `value::Timestamp`, `value::Decimal`, or `value::Uuid`. A `uuid::Uuid`, a `rust_decimal::Decimal`, and the jiff types do not implement `Zeroize`. = note: the type must also implement `Zeroize`, so that a decrypted value can be wiped when a later decrypt in the same call fails. - = note: the type must also be `Send` and `'static`. A type that borrows data is not `'static`. + = note: the type must also be `Send` and `'static`. A `'static` type borrows no data. + = note: to decrypt a `Vec` into a `Vec`, with one element from each `Ciphertext`, use `DecryptFrom`. + = note: to decrypt a sequence, a map, or a struct that derives `Decrypt`, use `keyset.decrypt_tree`. `keyset.encrypt_tree` makes the tree of ciphertexts that it reads. + = note: to decrypt a whole `Deserialize` value from one `Ciphertext`, decrypt into `OpaqueBlob`. `T` must also implement `Default` and `Zeroize`. +help: the trait `OpaqueDecode` is implemented for `OpaqueBlob` + --> src/blob.rs + | + | impl OpaqueDecode for OpaqueBlob {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +note: required by a bound in `stack_encrypt::scalar::>::decrypt` + --> src/scalar.rs + | + | pub fn decrypt(&self, ciphertext: Ciphertext) -> Pending<'_, P, K> { + | ^^^^^^^^^^^^ required by this bound in `stack_encrypt::scalar::>::decrypt` + +error[E0277]: `uuid::Uuid` cannot be decrypted from one `Ciphertext` + --> tests/ui/scalar_decrypt_target_requires_zeroize.rs:12:30 + | +12 | let _ = keyset.decrypt::(ciphertext); + | ^^^^^^^^^^ one `Ciphertext` decrypts into one owned value + | + = help: the trait `OpaqueDecode` is not implemented for `uuid::Uuid` + = note: one value is a scalar, such as a `String`, a `bool`, a float, a `Vec`, or a fixed-width integer other than `u8`. The docs of `OpaqueDecode` list every type that is accepted. + = note: an `Option` or a `Protected` of a scalar is one value too. So is a newtype that derives `Decrypt` over a scalar. + = note: for a date, a timestamp, a decimal, or a UUID, use `value::Date`, `value::Timestamp`, `value::Decimal`, or `value::Uuid`. A `uuid::Uuid`, a `rust_decimal::Decimal`, and the jiff types do not implement `Zeroize`. + = note: the type must also implement `Zeroize`, so that a decrypted value can be wiped when a later decrypt in the same call fails. + = note: the type must also be `Send` and `'static`. A `'static` type borrows no data. = note: to decrypt a `Vec` into a `Vec`, with one element from each `Ciphertext`, use `DecryptFrom`. = note: to decrypt a sequence, a map, or a struct that derives `Decrypt`, use `keyset.decrypt_tree`. `keyset.encrypt_tree` makes the tree of ciphertexts that it reads. = note: to decrypt a whole `Deserialize` value from one `Ciphertext`, decrypt into `OpaqueBlob`. `T` must also implement `Default` and `Zeroize`. diff --git a/packages/vitaminc-aead/src/typed.rs b/packages/vitaminc-aead/src/typed.rs index b48e4884d..4ac8ae934 100644 --- a/packages/vitaminc-aead/src/typed.rs +++ b/packages/vitaminc-aead/src/typed.rs @@ -295,8 +295,8 @@ impl Decrypt for T { /// /// So these targets are `ScalarTarget`s with no code of their own: /// -/// - Every [`FromScalar`] type, such as `bool`, the integers except `u8`, -/// the floats, `String`, `Vec`, and `[u8; N]`. +/// - Every [`FromScalar`] type, such as `bool`, the fixed-width integers +/// except `u8`, the floats, `String`, `Vec`, and `[u8; N]`. /// - The other `FromScalar` types of this crate: the date, timestamp, /// decimal, and UUID values. The jiff, `rust_decimal`, and uuid types /// behind their features are `FromScalar` types too. From dacd89cc79349f764ead0bd727a48c632cec2d72 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sun, 29 Nov 2026 13:19:37 +1100 Subject: [PATCH 19/19] feat(stack-encrypt)!: name the kind of a refused single value A refusal from `dynamic::value::encrypt` now names the kind of the value to encrypt, as a `dynamic::Found`. The record errors already name a kind in this way, and one rule for both is simpler for a language SDK. - `Error::Value` has a new field, `found`. The kind is in `found()`, in the payload field `found`, and in the message. - An array, an object, a null, a passthrough, and `undefined` share the new reason `not_a_scalar`. The reasons `array`, `object`, and `null` are removed. Nothing else used them. - The kind is always the kind of the input. A refused decrypt still names only the kind that was expected. - Each refused case of `single-value-v1` checks `found` as well as `code` and `reason`. --- .../stack-encrypt/single-value-contract.md | 33 ++++-- .../v1/single-value-v1.cases.json | 99 ++++++++++------ languages/golang/encrypt/guest/src/status.rs | 8 +- packages/stack-encrypt/CHANGELOG.md | 20 ++-- .../docs/language-integration.md | 17 +-- packages/stack-encrypt/src/codes.rs | 15 ++- packages/stack-encrypt/src/dynamic/value.rs | 69 ++++++------ packages/stack-encrypt/src/refusal.rs | 96 ++++++++++------ packages/stack-encrypt/tests/single_value.rs | 106 +++++++++++------- .../tests/single_value_conformance.rs | 8 ++ 10 files changed, 300 insertions(+), 171 deletions(-) diff --git a/conformance/stack-encrypt/single-value-contract.md b/conformance/stack-encrypt/single-value-contract.md index 7cab722de..0ebb0a0d0 100644 --- a/conformance/stack-encrypt/single-value-contract.md +++ b/conformance/stack-encrypt/single-value-contract.md @@ -47,7 +47,7 @@ a list of `cases`, and a list of `batches`. Each case has these keys: | `stored` | The value in the ciphertext, where it differs from the input | | `opens_as` | Kinds that the ciphertext must open as, other than the declared kind. Each entry has the `value` that the ciphertext opens to. | | `refused_as` | Kinds that the ciphertext must not open as | -| `expected_error` | For a refused case, the `code` and `reason` of the refusal | +| `expected_error` | For a refused case, the `code`, the `reason`, and the `found` kind of the refusal | A context of two parts is a pair. For example, `["conformance", "value"]` is the Rust context `("conformance", "value")`. For an empty list, a runner calls @@ -164,21 +164,33 @@ them. Three groups of cases pin the consequences: ### A refused case A case with `expected_error` is a refused case. The run-time encrypt refuses -the value before any key request, with the diagnostic `code` and `reason` of -the case. The code of every such refusal is `stack_encrypt::dynamic_value`. A -single value has its own refusal, with no record, plan, or field in it. +the value before any key request, with the diagnostic `code`, `reason`, and +`found` of the case. The code of every such refusal is +`stack_encrypt::dynamic_value`. A single value has its own refusal, with no +record, plan, or field in it. + +`found` is the kind of the value to encrypt, as the payload field `found` +names it. Every refusal of a single value names that kind. The name is a +kind name such as `array`, `string`, or `int64`, or one of `null`, +`undefined`, `passthrough`, and `unknown`. The kind is the kind of the +input. A refusal never names the kind of a decrypted value. The cases cover these values: - An array, an object, a passthrough, a plain null, and a typed null. Each is - tested with no declared kind and with one. The reason names what was found: - `array`, `object`, `passthrough`, or `null`. + tested with no declared kind and with one. The reason is `not_a_scalar`. + `found` is `array`, `object`, `passthrough`, or `null`. A typed null is a + `null`. - JavaScript's `undefined`, with a declared kind and with none. The reason is - `undefined`. + `not_a_scalar`. `found` is `undefined`. - A value of another kind that does not convert exactly. The reason is - `field_type`. + `field_type`. `found` is the kind of the input. - Text that is not a JSON document, with the kind `json`. The reason is - `json_syntax`, `json_duplicate_key`, or `json_integer_range`. + `json_syntax`, `json_duplicate_key`, or `json_integer_range`. `found` is + `string` or `bytes`. + +A runner checks all three of `code`, `reason`, and `found`. `reason` says +which rule the value breaks, and `found` says what the value is. The engine refuses `undefined` with any declared kind. An `undefined` value is most often a misspelt property name. No typed call could read it back. @@ -208,7 +220,8 @@ A runner seals and opens each entry as a binding does: `stored` where the batch has one, and the inputs otherwise. - An empty batch makes no key request. - In a batch with `expected_error`, the single-value call refuses one of the - values with that `code` and `reason`. The batch then makes no key request. + values with that `code`, `reason`, and `found`. The batch then makes no + key request. The counts of key requests are native observations: the Rust runner counts them on its key source. diff --git a/conformance/stack-encrypt/v1/single-value-v1.cases.json b/conformance/stack-encrypt/v1/single-value-v1.cases.json index 2dc39594a..26e3372d3 100644 --- a/conformance/stack-encrypt/v1/single-value-v1.cases.json +++ b/conformance/stack-encrypt/v1/single-value-v1.cases.json @@ -456,7 +456,8 @@ }, "expected_error": { "code": "stack_encrypt::dynamic_value", - "reason": "array" + "reason": "not_a_scalar", + "found": "array" } }, { @@ -469,7 +470,8 @@ }, "expected_error": { "code": "stack_encrypt::dynamic_value", - "reason": "array" + "reason": "not_a_scalar", + "found": "array" } }, { @@ -482,7 +484,8 @@ }, "expected_error": { "code": "stack_encrypt::dynamic_value", - "reason": "array" + "reason": "not_a_scalar", + "found": "array" } }, { @@ -495,7 +498,8 @@ }, "expected_error": { "code": "stack_encrypt::dynamic_value", - "reason": "array" + "reason": "not_a_scalar", + "found": "array" } }, { @@ -508,7 +512,8 @@ }, "expected_error": { "code": "stack_encrypt::dynamic_value", - "reason": "object" + "reason": "not_a_scalar", + "found": "object" } }, { @@ -521,7 +526,8 @@ }, "expected_error": { "code": "stack_encrypt::dynamic_value", - "reason": "object" + "reason": "not_a_scalar", + "found": "object" } }, { @@ -534,7 +540,8 @@ }, "expected_error": { "code": "stack_encrypt::dynamic_value", - "reason": "object" + "reason": "not_a_scalar", + "found": "object" } }, { @@ -547,7 +554,8 @@ }, "expected_error": { "code": "stack_encrypt::dynamic_value", - "reason": "passthrough" + "reason": "not_a_scalar", + "found": "passthrough" } }, { @@ -560,7 +568,8 @@ }, "expected_error": { "code": "stack_encrypt::dynamic_value", - "reason": "passthrough" + "reason": "not_a_scalar", + "found": "passthrough" } }, { @@ -573,7 +582,8 @@ }, "expected_error": { "code": "stack_encrypt::dynamic_value", - "reason": "null" + "reason": "not_a_scalar", + "found": "null" } }, { @@ -586,7 +596,8 @@ }, "expected_error": { "code": "stack_encrypt::dynamic_value", - "reason": "null" + "reason": "not_a_scalar", + "found": "null" } }, { @@ -599,7 +610,8 @@ }, "expected_error": { "code": "stack_encrypt::dynamic_value", - "reason": "null" + "reason": "not_a_scalar", + "found": "null" } }, { @@ -612,7 +624,8 @@ }, "expected_error": { "code": "stack_encrypt::dynamic_value", - "reason": "null" + "reason": "not_a_scalar", + "found": "null" } }, { @@ -625,7 +638,8 @@ }, "expected_error": { "code": "stack_encrypt::dynamic_value", - "reason": "null" + "reason": "not_a_scalar", + "found": "null" } }, { @@ -638,7 +652,8 @@ }, "expected_error": { "code": "stack_encrypt::dynamic_value", - "reason": "null" + "reason": "not_a_scalar", + "found": "null" } }, { @@ -651,7 +666,8 @@ }, "expected_error": { "code": "stack_encrypt::dynamic_value", - "reason": "undefined" + "reason": "not_a_scalar", + "found": "undefined" } }, { @@ -664,7 +680,8 @@ }, "expected_error": { "code": "stack_encrypt::dynamic_value", - "reason": "undefined" + "reason": "not_a_scalar", + "found": "undefined" } }, { @@ -677,7 +694,8 @@ }, "expected_error": { "code": "stack_encrypt::dynamic_value", - "reason": "undefined" + "reason": "not_a_scalar", + "found": "undefined" } }, { @@ -690,7 +708,8 @@ }, "expected_error": { "code": "stack_encrypt::dynamic_value", - "reason": "field_type" + "reason": "field_type", + "found": "string" } }, { @@ -703,7 +722,8 @@ }, "expected_error": { "code": "stack_encrypt::dynamic_value", - "reason": "field_type" + "reason": "field_type", + "found": "float64" } }, { @@ -716,7 +736,8 @@ }, "expected_error": { "code": "stack_encrypt::dynamic_value", - "reason": "field_type" + "reason": "field_type", + "found": "int64" } }, { @@ -729,7 +750,8 @@ }, "expected_error": { "code": "stack_encrypt::dynamic_value", - "reason": "field_type" + "reason": "field_type", + "found": "int32" } }, { @@ -742,7 +764,8 @@ }, "expected_error": { "code": "stack_encrypt::dynamic_value", - "reason": "field_type" + "reason": "field_type", + "found": "float64" } }, { @@ -755,7 +778,8 @@ }, "expected_error": { "code": "stack_encrypt::dynamic_value", - "reason": "field_type" + "reason": "field_type", + "found": "int64" } }, { @@ -768,7 +792,8 @@ }, "expected_error": { "code": "stack_encrypt::dynamic_value", - "reason": "field_type" + "reason": "field_type", + "found": "string" } }, { @@ -781,7 +806,8 @@ }, "expected_error": { "code": "stack_encrypt::dynamic_value", - "reason": "field_type" + "reason": "field_type", + "found": "string" } }, { @@ -794,7 +820,8 @@ }, "expected_error": { "code": "stack_encrypt::dynamic_value", - "reason": "field_type" + "reason": "field_type", + "found": "int64" } }, { @@ -807,7 +834,8 @@ }, "expected_error": { "code": "stack_encrypt::dynamic_value", - "reason": "field_type" + "reason": "field_type", + "found": "int64" } }, { @@ -820,7 +848,8 @@ }, "expected_error": { "code": "stack_encrypt::dynamic_value", - "reason": "json_syntax" + "reason": "json_syntax", + "found": "string" } }, { @@ -833,7 +862,8 @@ }, "expected_error": { "code": "stack_encrypt::dynamic_value", - "reason": "json_duplicate_key" + "reason": "json_duplicate_key", + "found": "string" } }, { @@ -846,7 +876,8 @@ }, "expected_error": { "code": "stack_encrypt::dynamic_value", - "reason": "json_integer_range" + "reason": "json_integer_range", + "found": "bytes" } } ], @@ -981,7 +1012,8 @@ ], "expected_error": { "code": "stack_encrypt::dynamic_value", - "reason": "null" + "reason": "not_a_scalar", + "found": "null" } }, { @@ -1000,7 +1032,8 @@ ], "expected_error": { "code": "stack_encrypt::dynamic_value", - "reason": "field_type" + "reason": "field_type", + "found": "string" } } ] diff --git a/languages/golang/encrypt/guest/src/status.rs b/languages/golang/encrypt/guest/src/status.rs index 8990db893..258d39793 100644 --- a/languages/golang/encrypt/guest/src/status.rs +++ b/languages/golang/encrypt/guest/src/status.rs @@ -194,7 +194,8 @@ pub fn status_for_dynamic(error: &stack_encrypt::dynamic::Error) -> u32 { | Error::Source { .. } | Error::SourceFailed { .. } // One value that a single ciphertext cannot contain: an array, an - // object, a null, or a value of another kind than the one declared. + // object, a null, a passthrough, `undefined`, or a value of another + // kind than the one declared. | Error::Value { .. } | Error::Record { .. } // A `match` predicate refused at an offset in its text: a construct @@ -547,7 +548,7 @@ mod tests { #[test] fn dynamic_input_errors_are_encoding_and_a_library_bug_is_internal() { - use stack_encrypt::dynamic::{Error, Reason}; + use stack_encrypt::dynamic::{Error, Found, Reason}; use stack_encrypt::sem::MatchOptions; use stack_encrypt::target::IndexSpec; let age = || Some("age".to_string()); @@ -600,7 +601,8 @@ mod tests { ( "a refused single value", Error::Value { - reason: Reason::Null, + reason: Reason::NotAScalar, + found: Found::Null, }, ), ( diff --git a/packages/stack-encrypt/CHANGELOG.md b/packages/stack-encrypt/CHANGELOG.md index 182db65e8..3d07b4e66 100644 --- a/packages/stack-encrypt/CHANGELOG.md +++ b/packages/stack-encrypt/CHANGELOG.md @@ -52,16 +52,20 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 as the engine writes it. - A ciphertext contains one scalar. `encrypt` refuses an array, an object, a passthrough, and a null before it requests any key. The null - can be plain or typed. + can be plain or typed. `encrypt` also refuses JavaScript's `undefined`, + with a declared kind and with none. An `undefined` value is most often + a misspelt property name. No typed call could read it back. - The refusal is a new variant, `dynamic::Error::Value`, with the code `stack_encrypt::dynamic_value`. The error names no field, and its - message is about one value. The reason is `Reason::Passthrough`, or one - of three new reasons: `Reason::Array`, `Reason::Object`, and - `Reason::Null`. - - `encrypt` refuses JavaScript's `undefined` with `Reason::Undefined`, - with a declared kind and with none. An `undefined` value is most often - a misspelt property name. No typed call could read it back. A value of - another kind is `Reason::FieldType`. + message is about one value. + - The reason of each of those refusals is the new `Reason::NotAScalar` + (`not_a_scalar`). A value of another kind is `Reason::FieldType`. + - Every `Error::Value` names the kind of the value to encrypt as a + `dynamic::Found`. The kind is in `Error::found()`, in the payload field + `found`, and in the message, such as + `the value to encrypt is an array, not a scalar`. The error never + contains the value, and a refused decrypt never names the kind of the + decrypted value. - Two ciphertexts of one value never have the same bytes, because each encrypted scalar has a random nonce. The two interfaces agree on every other part: the keyset, the data key, the length, and the plaintext of diff --git a/packages/stack-encrypt/docs/language-integration.md b/packages/stack-encrypt/docs/language-integration.md index acd8196f9..064f5c2b0 100644 --- a/packages/stack-encrypt/docs/language-integration.md +++ b/packages/stack-encrypt/docs/language-integration.md @@ -196,14 +196,17 @@ makes one call for each value, and merges the calls with Each value keeps its own declared kind. A ciphertext contains one scalar. The engine refuses an array, an object, a -passthrough, and a null before it requests any key. The refusal is +passthrough, and a null before it requests any key. The engine also refuses +JavaScript's `undefined`, with any declared kind. The refusal is [`crate::dynamic::Error::Value`], with the code -`stack_encrypt::dynamic_value`. The reason of the refusal names what was -found: `array`, `object`, `passthrough`, or `null`. An SDK stores an absent -value as a database `NULL`. - -The engine also refuses JavaScript's `undefined`, with any declared kind. -The reason is `undefined`. +`stack_encrypt::dynamic_value` and the reason `not_a_scalar`. An SDK stores +an absent value as a database `NULL`. + +Every refusal of a single value names the kind of the value to encrypt, in +the payload field `found`. Examples are `array`, `null`, `undefined`, and +`string`. An SDK reports `found` as it reports the kind in a record's +`not_an_object` error. The kind is the kind of the input. A refused decrypt +never names the kind of the decrypted value. `json` is a declared kind, and the engine stores a document as text. So a `string` and a document have one stored form. A check of the stored kind diff --git a/packages/stack-encrypt/src/codes.rs b/packages/stack-encrypt/src/codes.rs index 34457c5aa..3a5648e0b 100644 --- a/packages/stack-encrypt/src/codes.rs +++ b/packages/stack-encrypt/src/codes.rs @@ -205,7 +205,7 @@ mod tests { #[cfg(feature = "dynamic")] fn dynamic_variants() -> Vec { - use crate::dynamic::{Error, Reason, TargetError, ValueKind}; + use crate::dynamic::{Error, Found, Reason, TargetError, ValueKind}; use crate::target::IndexSpec; let name = || "email".to_string(); let target = || "TextEq".to_string(); @@ -219,7 +219,7 @@ mod tests { Error::Plan { .. } => Error::bad_plan(Reason::NoFields), Error::UntypedIndex { .. } => Error::UntypedIndex { field: name() }, Error::Source { .. } => Error::bad_source(Reason::FieldMissing), - Error::Value { .. } => Error::bad_value(Reason::Null), + Error::Value { .. } => Error::bad_value(Reason::NotAScalar, Found::Null), Error::SourceFailed { .. } => Error::SourceFailed { field: Some(name()), row: None, @@ -610,6 +610,17 @@ mod tests { }), json!({ "field": "email", "reason": "source_failed", "row": 0 }), ), + ( + // One value names no field, even after `in_field`. + Box::new( + Error::bad_value( + Reason::NotAScalar, + crate::dynamic::Found::Kind(ValueKind::Array), + ) + .in_field("email"), + ), + json!({ "reason": "not_a_scalar", "found": "array" }), + ), ( Box::new(Error::UntypedIndex { field: name() }), json!({ "field": "email" }), diff --git a/packages/stack-encrypt/src/dynamic/value.rs b/packages/stack-encrypt/src/dynamic/value.rs index 988290130..2938b6342 100644 --- a/packages/stack-encrypt/src/dynamic/value.rs +++ b/packages/stack-encrypt/src/dynamic/value.rs @@ -123,8 +123,9 @@ //! [`decrypt`] returns it only when no kind is declared. //! - With a declared kind, [`encrypt`] refuses such a scalar. //! -//! A refusal names the kind of value that was found. A refusal never -//! contains the value. +//! A refusal names the kind of the value to encrypt as a [`Found`]. A +//! refusal never contains the value. A refused decrypt never names the kind +//! of the decrypted value, because that kind is part of the plaintext. //! //! [`KeysetCipher::encrypt`]: crate::KeysetCipher::encrypt //! [`KeysetCipher::decrypt`]: crate::KeysetCipher::decrypt @@ -135,7 +136,7 @@ use vitaminc_aead::{Encrypt, IntoContext}; use super::kind::convert; use super::term::OneScalar; -use super::{read_json, Error, JsonValueError, Reason, ValueKind}; +use super::{read_json, Error, Found, JsonValueError, Reason, ValueKind}; use crate::json::inputs::json_reason; use crate::json::JsonPlaintext; use crate::target::core::encrypt_opaque; @@ -241,18 +242,18 @@ use crate::{Ciphertext, ContextPiece, DecryptFrom, KeysetCipher}; /// `encrypt` returns [`Error::Value`] before it requests any key. The reason /// in the error is one of these: /// -/// - [`Reason::Array`], [`Reason::Object`], [`Reason::Passthrough`], or -/// [`Reason::Null`] for a value that is not one scalar. A typed null is a -/// null. -/// - [`Reason::Undefined`] for JavaScript's `undefined`, with a declared -/// kind or with none. +/// - [`Reason::NotAScalar`] for an array, an object, a null, a passthrough, +/// or JavaScript's `undefined`, with a declared kind or with none. A typed +/// null is a null. /// - [`Reason::FieldType`] for a value of another kind that does not convert /// exactly to the declared kind. /// - [`Reason::JsonSyntax`], [`Reason::JsonDuplicateKey`], or /// [`Reason::JsonIntegerRange`] for text that is not a JSON document, when /// the declared kind is [`ValueKind::Json`]. /// -/// The error names no field and contains no part of the value. When the +/// [`Error::found`] returns the kind of the value, such as +/// [`Found::Null`] or `Found::Kind(ValueKind::Array)`. The error names no +/// field and contains no part of the value. When the /// pending call fails, the error is the engine's [`Error`](crate::Error), as /// it is for [`KeysetCipher::encrypt`]. /// @@ -470,24 +471,25 @@ pub fn decrypt_with_context<'a, 'c, K: 'static>( /// /// # Errors /// -/// [`Error::Value`]. The reason names what was found: an array, an object, a -/// null, a passthrough, or `undefined`. +/// [`Error::Value`] with [`Reason::NotAScalar`], for an array, an object, a +/// null, a passthrough, or `undefined`. The error names the kind of the +/// value. fn one_scalar(value: Frame<'_>) -> Result<(), Error> { - let found = match value.kind() { - Some(ValueKind::Array) => Reason::Array, - Some(ValueKind::Object) => Reason::Object, - Some(_) => return Ok(()), + let scalar = match value.kind() { + Some(ValueKind::Array | ValueKind::Object) => false, + Some(_) => true, // A value of no kind is a null, a passthrough, `undefined`, or a - // scalar of a logical type that this build does not define. - None if value.is_null() => Reason::Null, - None if value.has_passthrough() => Reason::Passthrough, - None if is_undefined(value) => Reason::Undefined, - // The leaf format records a logical type that this build does not - // define. So an older build can store a value of a newer type. Such + // scalar of a logical type that this build does not define. The + // leaf format records a logical type that this build does not + // define, so an older build can store a value of a newer type. Such // a value is one scalar. `seal` stores it as it arrived. - None => return Ok(()), + None => !(value.is_null() || value.has_passthrough() || is_undefined(value)), }; - Err(Error::bad_value(found)) + if scalar { + Ok(()) + } else { + Err(Error::bad_value(Reason::NotAScalar, Found::of_frame(value))) + } } /// Whether `value` is JavaScript's `undefined`. @@ -513,7 +515,7 @@ fn seal<'a, K: 'static>( None => encrypt_opaque(value, keyset, context), Some(ValueKind::Json) => { // A document arrives as text or bytes, so nothing is converted. - let document = read_json(value).map_err(not_a_document)?; + let document = read_json(value).map_err(|error| not_a_document(error, value))?; // The document is encrypted through a borrow. The document is // wiped when it is dropped here, as the typed call's owned // document is. @@ -521,7 +523,7 @@ fn seal<'a, K: 'static>( } // The conversion also refuses a value that is not of the declared // kind. A converted value is wiped when it is dropped. - Some(kind) => match convert(kind, value).map_err(of_one_value)? { + Some(kind) => match convert(kind, value).map_err(|error| of_one_value(error, value))? { Some(converted) => encrypt_opaque(converted.frame(), keyset, context), None => encrypt_opaque(value, keyset, context), }, @@ -530,21 +532,22 @@ fn seal<'a, K: 'static>( } /// Turn a refusal that the shared conversion made for a record field into -/// the refusal of one value. The reason stays the same. No field is named. -fn of_one_value(error: Error) -> Error { +/// the refusal of `value`. The reason stays the same. No field is named. +fn of_one_value(error: Error, value: Frame<'_>) -> Error { match error.reason() { - Some(reason) => Error::bad_value(reason), + Some(reason) => Error::bad_value(reason, Found::of_frame(value)), None => error, } } -/// The refusal of a value that is not a document, when the declared kind is -/// `json`. -fn not_a_document(error: JsonValueError) -> Error { - Error::bad_value(match error { +/// The refusal of `value` for the declared kind `json`, when `value` is not +/// a document. +fn not_a_document(error: JsonValueError, value: Frame<'_>) -> Error { + let reason = match error { JsonValueError::NotText => Reason::FieldType, JsonValueError::Text(error) => json_reason(error), - }) + }; + Error::bad_value(reason, Found::of_frame(value)) } /// The error for a value that was stored as another kind than the declared diff --git a/packages/stack-encrypt/src/refusal.rs b/packages/stack-encrypt/src/refusal.rs index ac9421aa6..ed4bc34c5 100644 --- a/packages/stack-encrypt/src/refusal.rs +++ b/packages/stack-encrypt/src/refusal.rs @@ -61,9 +61,11 @@ use crate::target::IndexSpec; /// Some operations take an object: a plan, a record to encrypt, or a /// stored record to decrypt. When the caller passes another kind of value, /// the error names that kind as a [`Found`]. For example, the error says -/// that the record is a null or an array. The error never includes the -/// value. The kind is in the message, in [`found`](Self::found), and in the -/// payload field `found`. +/// that the record is a null or an array. An error about one value to +/// encrypt as a single ciphertext ([`Value`](Error::Value)) always names +/// the kind of that value. The error never includes the value. The kind is +/// in the message, in [`found`](Self::found), and in the payload field +/// `found`. /// /// An error names a kind only when the engine can read that kind without /// decrypting anything. There are two such kinds: @@ -361,16 +363,24 @@ pub enum Error { /// - The text of the value is not a JSON document, when the declared /// kind is `json`. /// - /// The error names no field, because there is no record. The reason names - /// the kind of value that was found. The error never contains the value. - #[error("the value cannot be encrypted as one ciphertext: {}", value_text(*reason))] + /// The error names no field, because there is no record. The error + /// names the kind of the value to encrypt as a [`Found`]. The kind is in + /// the message, in [`found`](Self::found), and in the payload field + /// `found`. The error never contains the value. + /// + /// The kind is always the kind of the value that the caller sent. A + /// refused decrypt is not this error, and never names the kind of the + /// decrypted value. + #[error("{}", value_text(*reason, *found))] #[diagnostic( code(stack_encrypt::dynamic_value), - help("One ciphertext contains one value that is present. That value is text, a number, a boolean, bytes, a date, a timestamp, a decimal, a UUID, or a JSON document. To encrypt a list, encrypt each value separately. Store an absent value as a database NULL.") + help("One ciphertext contains one scalar that is present. A scalar is text, a number, a boolean, bytes, a date, a timestamp, a decimal, a UUID, or a JSON document. To encrypt a list, encrypt each value separately. Store an absent value as a database NULL.") )] Value { /// What was wrong with the value. reason: Reason, + /// The kind of the value to encrypt. + found: Found, }, /// An invariant this module maintains did not hold — a slot count that @@ -405,17 +415,31 @@ fn in_field_text(field: &Option) -> String { .unwrap_or_default() } -/// The text for `reason` in the message of [`Error::Value`]. +/// The message of an [`Error::Value`]. +/// +/// The message is one sentence that starts with the kind of the value to +/// encrypt. There are three forms: /// -/// The display text of two reasons mentions a field of a record: a value of -/// another type, and `undefined`. A single value has no field, so this -/// function has its own text for those two reasons. The display text of -/// every other reason names what was found, and suits one value as it is. -fn value_text(reason: Reason) -> String { +/// - For [`Reason::NotAScalar`], the message says that the value is not a +/// scalar. An example is `the value to encrypt is an array, not a scalar`. +/// - For [`Reason::FieldType`], the message says that the value does not +/// convert to the declared kind. A record's message for that reason names +/// a field, and one value has no field. +/// - For every other reason, the message ends with the reason. For +/// example, the message can end with `a JSON object names a member +/// twice`. +fn value_text(reason: Reason, found: Found) -> String { match reason { - Reason::FieldType => "it does not convert exactly to the declared kind".to_owned(), - Reason::Undefined => "it is undefined".to_owned(), - found => found.to_string(), + Reason::NotAScalar => format!("the value to encrypt is {found}, not a scalar"), + Reason::FieldType => format!( + "the value to encrypt is {found}, and does not convert exactly to the declared kind" + ), + Reason::JsonSyntax | Reason::JsonDuplicateKey | Reason::JsonIntegerRange => format!( + "the value to encrypt is {found}, and its text is not a JSON document: {reason}" + ), + reason => { + format!("the value to encrypt is {found}, and cannot be encrypted: {reason}") + } } } @@ -585,9 +609,10 @@ fn misfit_text( } impl Error { - /// An error for one value that cannot be encrypted as a single ciphertext. - pub(crate) fn bad_value(reason: Reason) -> Self { - Self::Value { reason } + /// An error for one value that cannot be encrypted as a single + /// ciphertext. `found` is the kind of that value. + pub(crate) fn bad_value(reason: Reason, found: Found) -> Self { + Self::Value { reason, found } } /// A context error with no field named yet. @@ -695,7 +720,7 @@ impl Error { | Self::Source { reason, .. } | Self::Record { reason, .. } | Self::Predicate { reason, .. } - | Self::Value { reason } => Some(*reason), + | Self::Value { reason, .. } => Some(*reason), Self::SourceFailed { .. } => Some(Reason::SourceFailed), #[cfg(feature = "dynamic")] Self::Target(_) => None, @@ -726,18 +751,23 @@ impl Error { } } - /// The kind of value that the caller passed where the operation takes - /// an object. + /// The kind of value that the caller passed, where the operation does + /// not take that kind. + /// + /// - For [`Reason::NotAnObject`], the value is a plan, a field spec, a + /// record source, a stored record, or a row of a batch. + /// - For [`Reason::JsonVarsNotObject`], the value is the vars of a + /// `match` query. + /// - For [`Error::Value`], the value is the one value to encrypt. Every + /// `Value` error names its kind. /// - /// For [`Reason::NotAnObject`], the value is a plan, a field spec, a - /// record source, a stored record, or a row of a batch. For - /// [`Reason::JsonVarsNotObject`], the value is the vars of a `match` - /// query. `None` for every other error. + /// `None` for every other error. pub fn found(&self) -> Option { match self { Self::Plan { found, .. } | Self::Source { found, .. } | Self::Record { found, .. } => { *found } + Self::Value { found, .. } => Some(*found), _ => None, } } @@ -935,16 +965,12 @@ reasons! { /// A passthrough value cannot be stored as a frame: it nests deeper, /// or holds text, bytes or a key longer, than a frame carries. Unframeable => "unframeable", "a passthrough value nests deeper, or holds a longer value, than a frame carries"; - /// An array was given where one value is required. A single ciphertext - /// contains one scalar + /// A value to encrypt as one ciphertext is not a scalar that is + /// present. The value is an array, an object, a null, a + /// passthrough, or `undefined`. The null can be plain or typed. + /// [`Error::found`] returns the kind of the value /// ([`value::encrypt`](crate::dynamic::value::encrypt)). - Array => "array", "an array where one value must be"; - /// An object was given where one value is required. A single ciphertext - /// contains one scalar. - Object => "object", "an object where one value must be"; - /// A null was given where one value is required. The null can be plain - /// or typed. A single ciphertext contains a value that is present. - Null => "null", "a null where one value must be"; + NotAScalar => "not_a_scalar", "the value is not a scalar, and one ciphertext contains one scalar"; /// A stored field is not a map of outputs. OutputsNotMap => "outputs_not_map", "a stored field is not a map of outputs"; /// A stored sealed field has no `"c"` node. diff --git a/packages/stack-encrypt/tests/single_value.rs b/packages/stack-encrypt/tests/single_value.rs index 1ab891b29..1a38f94ff 100644 --- a/packages/stack-encrypt/tests/single_value.rs +++ b/packages/stack-encrypt/tests/single_value.rs @@ -32,7 +32,7 @@ use common::leaves::{kept_cipher, parts, Parts}; use miette::Diagnostic as _; use proptest::prelude::*; use serde_json::json; -use stack_encrypt::dynamic::{self, frame::OwnedFrame, value, Reason, ValueKind}; +use stack_encrypt::dynamic::{self, frame::OwnedFrame, value, Found, Reason, ValueKind}; use stack_encrypt::json::JsonPlaintext; use stack_encrypt::kms::IdentifiedBy; use stack_encrypt::value::{Date, Decimal, Timestamp, Uuid as UuidValue}; @@ -423,9 +423,9 @@ async fn refused(value: &OwnedFrame, kind: Option) -> dynamic::Error Ok(_) => panic!("the form with a context took what the form without refused"), }; assert_eq!( - with_context.reason(), - single.reason(), - "the form with a context refuses for the same reason" + (with_context.reason(), with_context.found()), + (single.reason(), single.found()), + "the form with a context refuses for the same reason, and names the same kind" ); assert_eq!( generates.load(Ordering::SeqCst), @@ -440,9 +440,10 @@ async fn refused(value: &OwnedFrame, kind: Option) -> dynamic::Error single } -/// A single-value refusal has its own variant and code, the reason, and a -/// message about one value. The message mentions no record, plan, or field. -fn assert_value_refusal(error: &dynamic::Error, reason: Reason, what: &str) { +/// A single-value refusal has its own variant and code, the reason, the kind +/// of the value to encrypt, and a message about one value. The message +/// mentions no record, plan, or field. +fn assert_value_refusal(error: &dynamic::Error, reason: Reason, found: Found, what: &str) { use stack_encrypt::ErrorPayload as _; assert!( matches!(error, dynamic::Error::Value { .. }), @@ -463,18 +464,26 @@ fn assert_value_refusal(error: &dynamic::Error, reason: Reason, what: &str) { Some(reason.as_str()), "{what}: the payload carries the reason" ); - // The display text of two reasons mentions a field of a record. One - // value has no field, so `Error::Value` has its own text for those - // reasons. - let found = match reason { - Reason::FieldType => "it does not convert exactly to the declared kind".to_owned(), - Reason::Undefined => "it is undefined".to_owned(), - found => found.to_string(), + assert_eq!(error.found(), Some(found), "{what}: the kind found"); + assert_eq!( + error + .payload() + .get("found") + .and_then(|value| value.as_str()), + Some(found.as_str()), + "{what}: the payload carries the kind found" + ); + // The message starts with the kind of the value. A record's message + // for a value of another type names a field, and one value has none. + let rest = match reason { + Reason::NotAScalar => ", not a scalar".to_owned(), + Reason::FieldType => ", and does not convert exactly to the declared kind".to_owned(), + reason => format!(", and its text is not a JSON document: {reason}"), }; let message = error.to_string(); assert_eq!( message, - format!("the value cannot be encrypted as one ciphertext: {found}"), + format!("the value to encrypt is {found}{rest}"), "{what}: the message is about one value" ); for word in ["field", "record", "plan"] { @@ -490,21 +499,22 @@ mod encrypt_refuses_before_any_key_request { #[tokio::test] async fn a_value_that_is_not_one_scalar() { + let array = Found::Kind(ValueKind::Array); let cases = [ - ("an array", frame(vec!["a", "b"]), Reason::Array), - ("an empty array", frame(Vec::::new()), Reason::Array), + ("an array", frame(vec!["a", "b"]), array), + ("an empty array", frame(Vec::::new()), array), ( "an object", frame(std::collections::BTreeMap::from([("a", 1u32)])), - Reason::Object, + Found::Kind(ValueKind::Object), ), - ("a passthrough", passthrough(), Reason::Passthrough), - ("a plain null", OwnedFrame::null(), Reason::Null), - ("a typed null", typed_null(), Reason::Null), + ("a passthrough", passthrough(), Found::Passthrough), + ("a plain null", OwnedFrame::null(), Found::Null), + ("a typed null", typed_null(), Found::Null), ]; - for (what, value, reason) in &cases { + for (what, value, found) in &cases { // With no declared kind, and with a kind of each shape. The refusal - // reports what was found, whatever kind was declared. + // names the kind of the value, whatever kind was declared. for kind in [ None, Some(ValueKind::Int64), @@ -513,7 +523,12 @@ mod encrypt_refuses_before_any_key_request { Some(ValueKind::Json), ] { let error = refused(value, kind).await; - assert_value_refusal(&error, *reason, &format!("{what} under {kind:?}")); + assert_value_refusal( + &error, + Reason::NotAScalar, + *found, + &format!("{what} under {kind:?}"), + ); } } } @@ -533,7 +548,8 @@ mod encrypt_refuses_before_any_key_request { let error = refused(&undefined(), kind).await; assert_value_refusal( &error, - Reason::Undefined, + Reason::NotAScalar, + Found::Undefined, &format!("undefined under {kind:?}"), ); } @@ -541,20 +557,21 @@ mod encrypt_refuses_before_any_key_request { #[tokio::test] async fn a_value_that_is_not_of_the_declared_kind() { + use ValueKind::*; let cases = [ - ("text as int64", frame("34"), ValueKind::Int64), - ("a fraction as uint64", frame(34.5f64), ValueKind::UInt64), - ("300 as int8", frame(300i64), ValueKind::Int8), - ("an integer as string", frame(34i64), ValueKind::String), - ("an integer as date", frame(0i32), ValueKind::Date), - ("a scalar as array", frame(34i64), ValueKind::Array), - ("a scalar as object", frame("a"), ValueKind::Object), - ("an integer as json", frame(1i64), ValueKind::Json), - ("a boolean as json", frame(true), ValueKind::Json), + ("text as int64", frame("34"), Int64, String), + ("a fraction as uint64", frame(34.5f64), UInt64, Float64), + ("300 as int8", frame(300i64), Int8, Int64), + ("an integer as string", frame(34i64), String, Int64), + ("an integer as date", frame(0i32), Date, Int32), + ("a scalar as array", frame(34i64), Array, Int64), + ("a scalar as object", frame("a"), Object, String), + ("an integer as json", frame(1i64), Json, Int64), + ("a boolean as json", frame(true), Json, Bool), ]; - for (what, value, kind) in &cases { + for (what, value, kind, given) in &cases { let error = refused(value, Some(*kind)).await; - assert_value_refusal(&error, Reason::FieldType, what); + assert_value_refusal(&error, Reason::FieldType, Found::Kind(*given), what); } } @@ -574,14 +591,17 @@ mod encrypt_refuses_before_any_key_request { ), ]; for (what, text, reason) in cases { - for crossing in [frame(text), frame(text.as_bytes().to_vec())] { + for (crossing, given) in [ + (frame(text), ValueKind::String), + (frame(text.as_bytes().to_vec()), ValueKind::Bytes), + ] { let error = refused(&crossing, Some(ValueKind::Json)).await; - assert_value_refusal(&error, reason, what); + assert_value_refusal(&error, reason, Found::Kind(given), what); } } } - /// A refusal names the kind of value that was found, and contains no + /// A refusal names the kind of the value to encrypt, and contains no /// part of the value. #[tokio::test] async fn without_any_of_the_value_in_the_error() { @@ -660,6 +680,7 @@ mod encrypt_with_no_declared_kind { assert_value_refusal( &error, Reason::FieldType, + Found::Unknown, &format!("an unknown logical type as {kind}"), ); } @@ -877,7 +898,12 @@ mod many_values_merged_with_pending_all { Err(error) => error, Ok(_) => panic!("a batch holding a null was taken"), }; - assert_value_refusal(&error, Reason::Null, "the first refused value"); + assert_value_refusal( + &error, + Reason::NotAScalar, + Found::Null, + "the first refused value", + ); assert_eq!( generates.load(Ordering::SeqCst), 0, diff --git a/packages/stack-encrypt/tests/single_value_conformance.rs b/packages/stack-encrypt/tests/single_value_conformance.rs index 5ce813f20..2db20a990 100644 --- a/packages/stack-encrypt/tests/single_value_conformance.rs +++ b/packages/stack-encrypt/tests/single_value_conformance.rs @@ -101,6 +101,9 @@ struct Batch { struct ExpectedError { code: String, reason: String, + /// The kind of the value to encrypt, as the payload field `found` names + /// it. + found: String, } #[derive(Deserialize, Serialize)] @@ -358,6 +361,11 @@ fn assert_refusal(id: &str, error: &dynamic::Error, expected: &ExpectedError) { Some(expected.reason.as_str()), "{id}: the reason" ); + assert_eq!( + error.found().map(|found| found.as_str()), + Some(expected.found.as_str()), + "{id}: the kind of the value" + ); assert_eq!(error.field(), None, "{id}: a single value names no field"); }