diff --git a/packages/stack-encrypt/CHANGELOG.md b/packages/stack-encrypt/CHANGELOG.md index 7ab0bf090..b9839b813 100644 --- a/packages/stack-encrypt/CHANGELOG.md +++ b/packages/stack-encrypt/CHANGELOG.md @@ -1487,6 +1487,34 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 it needs a `_` arm. To migrate code that names `recipher`, see the stack-kms CHANGELOG. +- **A `Scalar` impl you wrote for a derived newtype or a fieldless enum no + longer compiles** (#2012). `#[derive(Encrypt)]` now implements Vitamin + C's `Scalar` marker for these types. So an `impl Scalar for &Email {}` of + your own conflicts with it. The compiler reports `E0119`, conflicting + implementations. The compiler reports it even when the inner type is not + a `Scalar`. What to do depends on the inner type. + - For a fieldless enum, or for a newtype whose inner type is one value, + such as a `String`, delete your impl. `keyset.encrypt` still encrypts + the type. + - When the inner type is not a `Scalar`, but you know that its value is + one leaf, stop deriving `Encrypt` for the type. Write `Encrypt` for the + type and for its borrow by hand, with + `const DEPTH: Option = depth::SCALAR;`. Then keep your `Scalar` + impl. An example is a newtype over a frame that you check holds one + value. + +- **A `Scalar` type that you write by hand must set its `DEPTH`** (#2012). + `keyset.encrypt` now checks, when the program is built, that the borrow + of the type encrypts as one value. So the `Encrypt` impl that you wrote + for the borrow must contain `const DEPTH: Option = depth::SCALAR;`. + `depth` is `vitaminc_aead::plaintext::depth`. + - An impl that leaves `DEPTH` at its default `None` compiled before. Now + `cargo build` fails with `E0080`, and the message names the line to + add. `cargo check` does not run this check. + - A newtype that derives `Encrypt` copies the `DEPTH` of the type it + wraps. So when the newtype fails this check, fix the type it wraps. + That is the innermost type whose `Encrypt` impl you wrote by hand. + ### Added - **A declaration and a call show the context they use, before any key is @@ -1962,6 +1990,38 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed +- **`keyset.encrypt` encrypts a newtype that derives `Encrypt` over one + value** (#2012). A newtype is a struct with exactly one unnamed field. + `struct Email(String)` with `#[derive(Encrypt, Zeroize)]` now encrypts + with `keyset.encrypt(Email(..))`. You no longer write + `impl Scalar for &Email {}` by hand. Your crate still needs + `vitaminc-aead` as a dependency to use the derive, because the derived + code names `vitaminc_aead` (#2013). + - The newtype encrypts exactly as its inner value does. The leaf has the + same plaintext and the same length. So `keyset.decrypt::` opens + what `Email` encrypted. + - A newtype over a type that contains more than one value still derives + `Encrypt`, for use as a field. Examples are `struct Tags(Vec)` + and `struct Nickname(Option)`. `keyset.encrypt` still refuses + such a newtype when the program compiles. `keyset.encrypt` also + refuses a struct with named fields. + - `keyset.encrypt` also encrypts a fieldless enum that derives + `Encrypt`, as one `u32` value. But `#[derive(Zeroize)]` does not wipe a + fieldless enum: its `zeroize` does nothing. So `keyset.encrypt` cannot + wipe the variant from memory after it encrypts it. To have the variant + wiped, give the enum a `#[default]` variant and implement + `zeroize::DefaultIsZeroes` for it, as the `OpaqueEncode` docs show (see + #2015). + - The compile error for a refused type now says that the type cannot be + encrypted into one `Ciphertext`. The error says what `keyset.encrypt` + needs, and what to use instead: + - `EncryptInto`, for each element of a `Vec` + - `keyset.encrypt_tree`, for an `Option` or a struct + - `OpaqueBlob`, for a whole `Serialize` value + + The error no longer names Vitamin C's `Scalar` trait. When the only + missing condition is `Zeroize`, the error still says so. + - **A query on an EQL type whose twin carries every term is refused for what any of its indexes refuses, before any key is requested** (#1668). `eql_v4.query_text_ord_ore` requires its `hm` and its `ob` together, so diff --git a/packages/stack-encrypt/src/scalar.rs b/packages/stack-encrypt/src/scalar.rs index 54dab925a..886760b28 100644 --- a/packages/stack-encrypt/src/scalar.rs +++ b/packages/stack-encrypt/src/scalar.rs @@ -34,6 +34,15 @@ pub(crate) mod sealed { context: ContextPiece<'static>, ) -> Pending<'a, Self, K>; } + + /// A type whose borrow encrypts as one value. It is implemented for + /// every type whose borrow is a Vitamin C `Scalar`. + /// + /// The trait is a separate bound of [`OpaqueEncode`](super::OpaqueEncode) + /// so that a refusal reports each condition on its own. Its impl has + /// `do_not_recommend`, so the compiler reports a missing `Scalar` as a + /// missing `OneValue`. A missing `Zeroize` is still reported by name. + pub trait OneValue: crate::EncryptRef {} } /// A plaintext type that encrypts as one opaque [`Ciphertext`]. @@ -54,8 +63,92 @@ pub(crate) mod sealed { /// - [`JsonPlaintext`](crate::json::JsonPlaintext), a JSON document, which /// is sealed as its JSON text /// -/// A type of your own meets them if its borrow implements `Scalar` and the -/// type implements `Zeroize`. +/// A newtype is a struct with exactly one unnamed field, such as +/// `struct Email(String)`. A newtype that derives +/// [`Encrypt`](crate::Encrypt) over one of the types above meets both +/// conditions once it implements `Zeroize`. You write no other code: the +/// derive marks the newtype `Scalar` when its inner type is a `Scalar`. +/// +/// The newtype encrypts exactly as its inner value does. So +/// `keyset.decrypt::` opens what an `Email` encrypted. The derive +/// comes from Vitamin C, so your crate needs `vitaminc-aead` as a +/// dependency to use it. +/// +/// ``` +/// # async fn example() -> Result<(), stack_encrypt::Error> { +/// use stack_encrypt::{Encrypt, StackCipher}; +/// use zeroize::Zeroize; +/// +/// #[derive(Encrypt, Zeroize)] +/// struct Email(String); +/// +/// // 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(Email("ada@example.com".into())).await?; +/// let email: String = keyset.decrypt(stored).await?; +/// assert_eq!(email, "ada@example.com"); +/// # Ok(()) +/// # } +/// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(example()).unwrap(); +/// ``` +/// +/// A newtype over a type that contains more than one value, such as +/// `struct Tags(Vec)`, still derives `Encrypt`. So it can be a field +/// of a struct. `keyset.encrypt` refuses it, as it refuses a `Vec`. +/// +/// A fieldless enum that derives `Encrypt` encrypts as one `u32`, so it is +/// one value too. But `#[derive(Zeroize)]` does not wipe a fieldless enum: +/// its `zeroize` does nothing. So `keyset.encrypt` cannot wipe the variant +/// from memory after it encrypts it. To have the variant wiped, give the +/// enum a `#[default]` variant and implement `zeroize::DefaultIsZeroes` for +/// it. Its `zeroize` then overwrites the value with the default variant. +/// +/// ``` +/// use stack_encrypt::{Encrypt, KeysetCipher}; +/// use zeroize::Zeroize; +/// +/// #[derive(Encrypt, Clone, Copy, Default, Debug, PartialEq)] +/// enum Status { +/// #[default] +/// Active, +/// Suspended = 7, +/// } +/// +/// impl zeroize::DefaultIsZeroes for Status {} +/// +/// fn encrypt(keyset: &KeysetCipher<'_, K>) { +/// let _ = keyset.encrypt(Status::Suspended); +/// } +/// +/// let mut status = Status::Suspended; +/// status.zeroize(); +/// assert_eq!(status, Status::Active, "zeroize writes the default variant"); +/// # let _ = encrypt::; +/// ``` +/// +/// You can also write the `Encrypt` impl of a type yourself. Such a type is +/// an `OpaqueEncode` type when you implement `Scalar` for its borrow. +/// +/// A `Scalar` impl states that the borrow encrypts as one value. So the +/// borrow's `Encrypt` impl must set its [`DEPTH`](crate::Encrypt::DEPTH): +/// +/// ```text +/// const DEPTH: Option = depth::SCALAR; +/// ``` +/// +/// `depth` is `vitaminc_aead::plaintext::depth`. The default `DEPTH` is +/// `None`. `None` means that the depth depends on the value. `keyset.encrypt` +/// checks the `DEPTH` when your program is built. A `Scalar` type whose +/// borrow has any other `DEPTH` fails the build. +/// +/// A newtype that derives `Encrypt` copies the `DEPTH` of the type it wraps. +/// So when a derived newtype fails this check, fix the type it wraps. That +/// is the innermost type whose `Encrypt` impl you wrote by hand. /// /// [`OpaqueBlob`](crate::OpaqueBlob) is an `OpaqueEncode` type too. It /// encodes a whole `Serialize` value as one storage blob first. @@ -108,6 +201,22 @@ pub(crate) mod sealed { /// # } /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(example()).unwrap(); /// ``` +#[diagnostic::on_unimplemented( + message = "`{Self}` cannot be encrypted into one `Ciphertext`", + label = "this must be one owned value that can be wiped", + note = "to be encrypted into one `Ciphertext`, a value must meet three conditions.", + note = "first, the value must be one scalar or an `OpaqueBlob`. A scalar is a value such \ + as a `String`, a `bool`, a float, a `Vec`, or a fixed-width integer other than \ + `u8`. A newtype that derives `Encrypt` over a scalar is a scalar too.", + note = "second, the value must be owned. A borrow, such as a `&str`, is not owned.", + note = "third, the type must implement `Zeroize`, so that the value can be wiped after it \ + is encrypted. For an `OpaqueBlob`, `T` must implement `Zeroize` and \ + `Serialize`.", + note = "these calls encrypt a value that is not one scalar. `EncryptInto` encrypts each \ + element of a `Vec` into its own `Ciphertext`. `keyset.encrypt_tree` encrypts an \ + `Option` or a struct into a tree of ciphertexts. `OpaqueBlob` encrypts a whole \ + `Serialize` value into one `Ciphertext`." +)] pub trait OpaqueEncode: sealed::Encode + Zeroize + Send + 'static {} /// A plaintext type that one opaque [`Ciphertext`] decrypts to. @@ -225,28 +334,122 @@ pub trait OpaqueEncode: sealed::Encode + Zeroize + Send + 'static {} )] 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 -// scalars, so the borrow is walked as it is: nothing is copied out of the -// caller's value, and the fixed width of the type is the borrow's own, which -// is what pads an absent value to a present one's length. +// `do_not_recommend` stops the compiler from reporting the `Scalar` bound +// below. A type that is not one value is then reported as a missing +// `OneValue`, under the message of `OpaqueEncode`. +#[diagnostic::do_not_recommend] +impl sealed::OneValue for S where for<'a> &'a S: Scalar {} + +// An owned `S` is sealed through a borrow of it. `EncryptRef::lend` makes +// the borrow. The borrow of a `OneValue` type is one of Vitamin C's +// scalars, so it is walked as it is. Nothing is copied out of the caller's +// value. +// +// The fixed width of the type is the borrow's own. That width pads an +// absent value to the length of a present one. +// +// Anyone can implement `Scalar`. The compiler does not compare an impl with +// the type's `DEPTH`. So `seal` checks that the borrow's `DEPTH` is +// `depth::SCALAR`. +// +// The check is an inline `const`. The compiler evaluates it when it builds +// `seal` for a concrete `S`. So a false `Scalar` impl fails the build, not +// a call. + +/// The `Scalar` impl of a type must agree with the `DEPTH` of its borrow. +/// +/// The first example compiles. Its type sets `DEPTH` to `depth::SCALAR`, and +/// it encrypts as one value. +/// +/// ``` +/// use stack_encrypt::kms::FakeDataKeySource; +/// use stack_encrypt::{Encrypt, EncryptRef, KeysetCipher}; +/// use vitaminc_aead::plaintext::{depth, Sink}; +/// use vitaminc_aead::Scalar; +/// use zeroize::Zeroize; +/// +/// // A type whose borrow encrypts as its one `String`. +/// #[derive(Zeroize)] +/// struct Profile(String); +/// +/// impl Encrypt for &Profile { +/// const DEPTH: Option = depth::SCALAR; +/// fn visit(self, sink: S) -> Result { +/// self.0.visit_ref(sink) +/// } +/// } +/// impl Scalar for &Profile {} +/// +/// fn encrypt(keyset: &KeysetCipher<'_, FakeDataKeySource>) { +/// let _ = keyset.encrypt(Profile("ada".into())); +/// } +/// +/// fn main() { +/// let encrypt: fn(&KeysetCipher<'_, FakeDataKeySource>) = encrypt; +/// let _ = encrypt; +/// } +/// ``` +/// +/// The second example is the same, except for its `DEPTH`. The type states +/// that its borrow encrypts as a map, but it is marked `Scalar`. So the +/// build fails. `cargo build` runs the check, and `cargo check` does not. +/// +/// ```compile_fail,E0080 +/// use stack_encrypt::kms::FakeDataKeySource; +/// use stack_encrypt::{Encrypt, EncryptRef, KeysetCipher}; +/// use vitaminc_aead::plaintext::{depth, Sink}; +/// use vitaminc_aead::Scalar; +/// use zeroize::Zeroize; +/// +/// // A type whose borrow encrypts as its one `String`. +/// #[derive(Zeroize)] +/// struct Profile(String); +/// +/// impl Encrypt for &Profile { +/// const DEPTH: Option = depth::container(depth::SCALAR); +/// fn visit(self, sink: S) -> Result { +/// self.0.visit_ref(sink) +/// } +/// } +/// impl Scalar for &Profile {} +/// +/// fn encrypt(keyset: &KeysetCipher<'_, FakeDataKeySource>) { +/// let _ = keyset.encrypt(Profile("ada".into())); +/// } +/// +/// fn main() { +/// let encrypt: fn(&KeysetCipher<'_, FakeDataKeySource>) = encrypt; +/// let _ = encrypt; +/// } +/// ``` impl sealed::Encode for S where - S: Zeroize + Send + 'static, - for<'a> &'a S: Scalar, + S: sealed::OneValue + Zeroize + Send + 'static, { fn seal<'a, K: 'static>( &self, cipher: &'a KeysetCipher<'_, K>, context: ContextPiece<'static>, ) -> Pending<'a, Ciphertext, K> { - crate::target::core::encrypt_opaque(self, cipher, context).try_map(Ciphertext::from_tree) + const { + assert!( + vitaminc_aead::plaintext::depth::is_scalar(::REF_DEPTH), + "a type marked `Scalar` must encrypt as one value. Set \ + `const DEPTH: Option = depth::SCALAR;` in the `Encrypt` impl that you \ + wrote for its borrow. For a newtype that derives `Encrypt`, set it on the \ + innermost type whose `Encrypt` impl you wrote by hand.", + ) + }; + crate::target::core::encrypt_opaque(self.lend(), cipher, context) + .try_map(Ciphertext::from_tree) } } impl OpaqueEncode for S where - S: Zeroize + Send + 'static, - for<'a> &'a S: Scalar, + S: sealed::OneValue + Zeroize + Send + 'static, { + // The `Scalar` bound is in `OneValue`, so that the compiler reports a + // missing `Zeroize` by name. } impl sealed::Decode for P { fn open<'a, K: 'static>( diff --git a/packages/stack-encrypt/tests/derived_newtype.rs b/packages/stack-encrypt/tests/derived_newtype.rs new file mode 100644 index 000000000..98a8ba22c --- /dev/null +++ b/packages/stack-encrypt/tests/derived_newtype.rs @@ -0,0 +1,332 @@ +//! `keyset.encrypt` encrypts a newtype that derives `Encrypt` exactly as it +//! encrypts the newtype's inner value. It encrypts a fieldless enum that +//! derives `Encrypt` exactly as it encrypts the `u32` of the variant. +//! +//! A leaf is one sealed value. Each leaf has a random nonce, a number used +//! once. So two ciphertexts of one value never have the same bytes. These +//! tests compare what the nonce does not change: +//! +//! - the plaintext of each leaf, opened with the data key that the key +//! source generated for it +//! - the length of the stored bytes +//! +//! The tests also check that each ciphertext decrypts into the inner type. + +mod common; + +use std::borrow::Cow; +use std::cell::RefCell; +use std::collections::HashMap; +use std::sync::{Arc, Mutex}; + +use common::{hex, DeterministicSource}; +use stack_encrypt::{CipherText, Ciphertext, Encrypt, SealedValue, StackCipher}; +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 zeroize::Zeroize; + +#[derive(Encrypt, Zeroize)] +struct Email(String); + +#[derive(Encrypt, Zeroize)] +struct Age(i64); + +#[derive(Encrypt, Zeroize)] +enum Status { + Active, + Suspended = 7, +} + +// A fieldless enum cannot contain itself, so `recursive` changes nothing. +// This test file is built, not only checked, so it runs the build-time +// `DEPTH` check of `keyset.encrypt` on this type. +#[derive(Encrypt, Zeroize)] +#[aead(recursive)] +enum Level { + Low, + High = 3, +} + +const SEED: [u8; 32] = *b"stack-encrypt derived newtype v1"; + +/// The data keys that a [`KeptKeys`] source generated, by initialisation +/// vector (IV). +type Kept = Mutex, [u8; 32]>>; + +/// A [`DeterministicSource`] that also stores each data key it generates, +/// by its IV. A test uses the stored keys to open leaves without the engine. +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 a [`KeptKeys`] source, and the keys that the source stores. +async fn kept_cipher() -> (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 Vitamin C cipher that opens a stored leaf with the data key stored for +/// it, and records each plaintext it opens. +/// +/// The cipher opens the leaf under the associated data (AAD) that the +/// engine seals a leaf under. That AAD is a pre-authentication encoding +/// (PAE) of five parts: +/// +/// - the label `stack-encrypt/leaf` +/// - the format version +/// - the keyset +/// - the AAD of the leaf's place in the value +/// - the key tag +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 `ciphertext`, as hex, opened under `context`. +fn reveal<'c>(keys: &Kept, ciphertext: Ciphertext, context: impl IntoContext<'c>) -> String { + let keys = keys.lock().unwrap(); + let reveal = Reveal { + keys: &keys, + opened: RefCell::default(), + }; + let mut out = Buffer::default(); + vitaminc_aead::decrypt_into( + &reveal, + CipherText::Single(SealedValue::from(ciphertext)), + context.into_context(), + FrameWriter::new(&mut out), + ) + .unwrap_or_else(|_| { + panic!( + "the leaf must open with its stored data key. If every test fails here, \ + the AAD that `Reveal` builds differs from `leaf_aad` in src/cipher.rs" + ) + }); + let mut opened = reveal.opened.into_inner(); + assert_eq!(opened.len(), 1, "a `Ciphertext` holds one leaf"); + opened.remove(0) +} + +#[tokio::test] +async fn a_newtype_over_a_string_seals_the_leaf_a_string_seals() { + let (cipher, keys) = kept_cipher().await; + let keyset = cipher.default_keyset(); + + let wrapped = keyset + .encrypt(Email("ada@example.com".into())) + .await + .expect("a newtype over a string encrypts"); + let bare = keyset + .encrypt(String::from("ada@example.com")) + .await + .expect("a string encrypts"); + + assert_eq!( + wrapped.to_bytes().len(), + bare.to_bytes().len(), + "the newtype's ciphertext is as long as its inner value's" + ); + let opened: String = keyset + .decrypt(wrapped.clone()) + .await + .expect("the newtype's ciphertext decrypts into its inner type"); + assert_eq!( + opened, "ada@example.com", + "the newtype's ciphertext decrypts to its inner value" + ); + assert_eq!( + reveal(&keys, wrapped, ()), + reveal(&keys, bare, ()), + "the newtype's leaf holds the plaintext its inner value's leaf holds" + ); +} + +#[tokio::test] +async fn a_newtype_over_an_integer_seals_the_leaf_an_integer_seals() { + let (cipher, keys) = kept_cipher().await; + let keyset = cipher.default_keyset(); + let context = ("users", "age"); + + let wrapped = keyset + .encrypt_with_context(Age(37), context) + .await + .expect("a newtype over an integer encrypts"); + let bare = keyset + .encrypt_with_context(37i64, context) + .await + .expect("an integer encrypts"); + + assert_eq!( + wrapped.to_bytes().len(), + bare.to_bytes().len(), + "the newtype's ciphertext is as long as its inner value's" + ); + let opened: i64 = keyset + .decrypt_with_context(wrapped.clone(), context) + .await + .expect("the newtype's ciphertext decrypts into its inner type"); + assert_eq!( + opened, 37, + "the newtype's ciphertext decrypts to its inner value" + ); + assert_eq!( + reveal(&keys, wrapped, context), + reveal(&keys, bare, context), + "the newtype's leaf holds the plaintext its inner value's leaf holds" + ); +} + +#[tokio::test] +async fn a_fieldless_enum_seals_the_leaf_its_u32_seals() { + let (cipher, keys) = kept_cipher().await; + let keyset = cipher.default_keyset(); + + for (variant, discriminant) in [(Status::Active, 0u32), (Status::Suspended, 7)] { + let wrapped = keyset + .encrypt(variant) + .await + .expect("a fieldless enum encrypts"); + let bare = keyset + .encrypt(discriminant) + .await + .expect("a `u32` encrypts"); + + assert_eq!( + wrapped.to_bytes().len(), + bare.to_bytes().len(), + "the enum's ciphertext is as long as its `u32`'s" + ); + let opened: u32 = keyset + .decrypt(wrapped.clone()) + .await + .expect("the enum's ciphertext decrypts into a `u32`"); + assert_eq!( + opened, discriminant, + "the enum's ciphertext decrypts to the variant's discriminant" + ); + assert_eq!( + reveal(&keys, wrapped, ()), + reveal(&keys, bare, ()), + "the enum's leaf holds the plaintext its `u32`'s leaf holds" + ); + } +} + +#[tokio::test] +async fn a_fieldless_enum_marked_recursive_is_still_one_value() { + let (cipher, keys) = kept_cipher().await; + let keyset = cipher.default_keyset(); + + for (variant, discriminant) in [(Level::Low, 0u32), (Level::High, 3)] { + let wrapped = keyset + .encrypt(variant) + .await + .expect("a fieldless enum marked `recursive` encrypts"); + let bare = keyset + .encrypt(discriminant) + .await + .expect("a `u32` encrypts"); + + let opened: u32 = keyset + .decrypt(wrapped.clone()) + .await + .expect("the enum's ciphertext decrypts into a `u32`"); + assert_eq!( + opened, discriminant, + "the enum's ciphertext decrypts to the variant's discriminant" + ); + assert_eq!( + reveal(&keys, wrapped, ()), + reveal(&keys, bare, ()), + "the enum's leaf holds the plaintext its `u32`'s leaf holds" + ); + } +} diff --git a/packages/stack-encrypt/tests/ui/opaque_blob_requires_the_wrapper.stderr b/packages/stack-encrypt/tests/ui/opaque_blob_requires_the_wrapper.stderr index 580eb4a3d..9518835d1 100644 --- a/packages/stack-encrypt/tests/ui/opaque_blob_requires_the_wrapper.stderr +++ b/packages/stack-encrypt/tests/ui/opaque_blob_requires_the_wrapper.stderr @@ -1,21 +1,24 @@ -error[E0277]: the trait bound `for<'a> &'a Profile: Scalar` is not satisfied +error[E0277]: `Profile` cannot be encrypted into one `Ciphertext` --> tests/ui/opaque_blob_requires_the_wrapper.rs:16:35 | 16 | let _refused = keyset.encrypt(profile).await.unwrap(); - | ------- ^^^^^^^ the trait `for<'a> Scalar` is not implemented for `&'a Profile` - | | - | required by a bound introduced by this call + | ^^^^^^^ this must be one owned value that can be wiped | - = help: the following other types implement trait `Scalar`: - &&'b T - &'a Protected - &JsonPlaintext - &ProtectedRef<'a, T> - &Raw<'_> - &Vec - &[u8; N] - &[u8] - and $N others +help: the trait `stack_encrypt::scalar::sealed::OneValue` is not implemented for `Profile` + --> tests/ui/opaque_blob_requires_the_wrapper.rs:10:1 + | +10 | struct Profile { + | ^^^^^^^^^^^^^^ + = note: to be encrypted into one `Ciphertext`, a value must meet three conditions. + = note: first, the value must be one scalar or an `OpaqueBlob`. A scalar is a value such as a `String`, a `bool`, a float, a `Vec`, or a fixed-width integer other than `u8`. A newtype that derives `Encrypt` over a scalar is a scalar too. + = note: second, the value must be owned. A borrow, such as a `&str`, is not owned. + = note: third, the type must implement `Zeroize`, so that the value can be wiped after it is encrypted. For an `OpaqueBlob`, `T` must implement `Zeroize` and `Serialize`. + = note: these calls encrypt a value that is not one scalar. `EncryptInto` encrypts each element of a `Vec` into its own `Ciphertext`. `keyset.encrypt_tree` encrypts an `Option` or a struct into a tree of ciphertexts. `OpaqueBlob` encrypts a whole `Serialize` value into one `Ciphertext`. +help: the trait `OpaqueEncode` is implemented for `OpaqueBlob` + --> src/blob.rs + | + | impl OpaqueEncode for OpaqueBlob {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ = note: required for `Profile` to implement `OpaqueEncode` note: required by a bound in `stack_encrypt::scalar::>::encrypt` --> src/scalar.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 06cfc11f6..a11b41235 100644 --- a/packages/stack-encrypt/tests/ui/opaque_blob_requires_zeroize.stderr +++ b/packages/stack-encrypt/tests/ui/opaque_blob_requires_zeroize.stderr @@ -54,14 +54,20 @@ note: required by a bound in `OpaqueBlob` | pub struct OpaqueBlob(Zeroizing); | ^^^^^^^ required by this bound in `OpaqueBlob` -error[E0277]: the trait bound `OpaqueBlob: OpaqueEncode` is not satisfied +error[E0277]: `OpaqueBlob` cannot be encrypted into one `Ciphertext` --> tests/ui/opaque_blob_requires_zeroize.rs:14:35 | 14 | let _refused = keyset.encrypt(OpaqueBlob::new(value)).await.unwrap(); - | ------- ^^^^^^^^^^^^^^^^^^^^^^ the trait `OpaqueEncode` is not implemented for `OpaqueBlob` + | ------- ^^^^^^^^^^^^^^^^^^^^^^ this must be one owned value that can be wiped | | | required by a bound introduced by this call | + = help: the trait `OpaqueEncode` is not implemented for `OpaqueBlob` + = note: to be encrypted into one `Ciphertext`, a value must meet three conditions. + = note: first, the value must be one scalar or an `OpaqueBlob`. A scalar is a value such as a `String`, a `bool`, a float, a `Vec`, or a fixed-width integer other than `u8`. A newtype that derives `Encrypt` over a scalar is a scalar too. + = note: second, the value must be owned. A borrow, such as a `&str`, is not owned. + = note: third, the type must implement `Zeroize`, so that the value can be wiped after it is encrypted. For an `OpaqueBlob`, `T` must implement `Zeroize` and `Serialize`. + = note: these calls encrypt a value that is not one scalar. `EncryptInto` encrypts each element of a `Vec` into its own `Ciphertext`. `keyset.encrypt_tree` encrypts an `Option` or a struct into a tree of ciphertexts. `OpaqueBlob` encrypts a whole `Serialize` value into one `Ciphertext`. help: the trait `OpaqueEncode` 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 632b71be3..2ddbdd95f 100644 --- a/packages/stack-encrypt/tests/ui/owned_collection_elements.stderr +++ b/packages/stack-encrypt/tests/ui/owned_collection_elements.stderr @@ -1,40 +1,46 @@ -error[E0277]: the trait bound `for<'a> &'a u8: Scalar` is not satisfied +error[E0277]: `u8` cannot be encrypted into one `Ciphertext` --> tests/ui/owned_collection_elements.rs:11:26 | 11 | let _ = vec![1u8, 2].encrypt_into::, _>(keyset); - | ^^^^^^^^^^^^ the trait `for<'a> Scalar` is not implemented for `&'a u8` + | ^^^^^^^^^^^^ this must be one owned value that can be wiped | - = help: the following other types implement trait `Scalar`: - &f32 - &f64 - &i128 - &i16 - &i32 - &i64 - &i8 - &u128 - and $N others + = help: the trait `stack_encrypt::scalar::sealed::OneValue` is not implemented for `u8` + = note: to be encrypted into one `Ciphertext`, a value must meet three conditions. + = note: first, the value must be one scalar or an `OpaqueBlob`. A scalar is a value such as a `String`, a `bool`, a float, a `Vec`, or a fixed-width integer other than `u8`. A newtype that derives `Encrypt` over a scalar is a scalar too. + = note: second, the value must be owned. A borrow, such as a `&str`, is not owned. + = note: third, the type must implement `Zeroize`, so that the value can be wiped after it is encrypted. For an `OpaqueBlob`, `T` must implement `Zeroize` and `Serialize`. + = note: these calls encrypt a value that is not one scalar. `EncryptInto` encrypts each element of a `Vec` into its own `Ciphertext`. `keyset.encrypt_tree` encrypts an `Option` or a struct into a tree of ciphertexts. `OpaqueBlob` encrypts a whole `Serialize` value into one `Ciphertext`. +help: the trait `EncryptTarget>` is implemented for `Vec` + --> src/target/collections.rs + | + | / impl> EncryptTarget> for Vec + | | where + | | T::ContextInput: Clone + MaybeSend + 'static, + | |_________________________________________________^ = note: required for `u8` to implement `OpaqueEncode` = note: required for `stack_encrypt::Ciphertext` to implement `EncryptTarget` = note: 1 redundant requirement hidden = note: required for `Vec` to implement `EncryptTarget>` -error[E0277]: the trait bound `for<'a> &'a Option: Scalar` is not satisfied +error[E0277]: `Option` cannot be encrypted into one `Ciphertext` --> tests/ui/owned_collection_elements.rs:12:36 | 12 | let _ = vec![Some(1i32), None].encrypt_into::, _>(keyset); - | ^^^^^^^^^^^^ the trait `for<'a> Scalar` is not implemented for `&'a Option` + | ^^^^^^^^^^^^ this must be one owned value that can be wiped | - = help: the following other types implement trait `Scalar`: - &&'b T - &'a Protected - &JsonPlaintext - &ProtectedRef<'a, T> - &Raw<'_> - &Vec - &[u8; N] - &[u8] - and $N others + = help: the trait `stack_encrypt::scalar::sealed::OneValue` is not implemented for `Option` + = note: to be encrypted into one `Ciphertext`, a value must meet three conditions. + = note: first, the value must be one scalar or an `OpaqueBlob`. A scalar is a value such as a `String`, a `bool`, a float, a `Vec`, or a fixed-width integer other than `u8`. A newtype that derives `Encrypt` over a scalar is a scalar too. + = note: second, the value must be owned. A borrow, such as a `&str`, is not owned. + = note: third, the type must implement `Zeroize`, so that the value can be wiped after it is encrypted. For an `OpaqueBlob`, `T` must implement `Zeroize` and `Serialize`. + = note: these calls encrypt a value that is not one scalar. `EncryptInto` encrypts each element of a `Vec` into its own `Ciphertext`. `keyset.encrypt_tree` encrypts an `Option` or a struct into a tree of ciphertexts. `OpaqueBlob` encrypts a whole `Serialize` value into one `Ciphertext`. +help: the trait `EncryptTarget>` is implemented for `Vec` + --> src/target/collections.rs + | + | / impl> EncryptTarget> for Vec + | | where + | | T::ContextInput: Clone + MaybeSend + 'static, + | |_________________________________________________^ = note: required for `Option` to implement `OpaqueEncode` = note: required for `stack_encrypt::Ciphertext` to implement `EncryptTarget>` = note: 1 redundant requirement hidden @@ -59,32 +65,25 @@ error[E0277]: the trait bound `&str: Zeroize` is not satisfied = note: required for `&str` to implement `Zeroize` = note: required for `Vec` to implement `EncryptTarget>` -error[E0277]: the trait bound `for<'a> &'a Vec: Scalar` is not satisfied +error[E0277]: `Vec` cannot be encrypted into one `Ciphertext` --> tests/ui/owned_collection_elements.rs:14:27 | 14 | let _ = vec![1i32, 2].encrypt_into::(keyset); - | ^^^^^^^^^^^^ the trait `for<'a> Scalar` is not implemented for `&'a Vec` + | ^^^^^^^^^^^^ this must be one owned value that can be wiped | -help: the following other types implement trait `Scalar` - --> $WORKSPACE/packages/vitaminc-aead/src/plaintext/sources.rs + = help: the trait `stack_encrypt::scalar::sealed::OneValue` is not implemented for `Vec` + = note: to be encrypted into one `Ciphertext`, a value must meet three conditions. + = note: first, the value must be one scalar or an `OpaqueBlob`. A scalar is a value such as a `String`, a `bool`, a float, a `Vec`, or a fixed-width integer other than `u8`. A newtype that derives `Encrypt` over a scalar is a scalar too. + = note: second, the value must be owned. A borrow, such as a `&str`, is not owned. + = note: third, the type must implement `Zeroize`, so that the value can be wiped after it is encrypted. For an `OpaqueBlob`, `T` must implement `Zeroize` and `Serialize`. + = note: these calls encrypt a value that is not one scalar. `EncryptInto` encrypts each element of a `Vec` into its own `Ciphertext`. `keyset.encrypt_tree` encrypts an `Option` or a struct into a tree of ciphertexts. `OpaqueBlob` encrypts a whole `Serialize` value into one `Ciphertext`. +help: the trait `EncryptTarget` is implemented for `stack_encrypt::Ciphertext` + --> src/scalar.rs | - | impl Scalar for $ty {} - | ^^^^^^^^^^^^^^^^^^^ - | | - | `&Vec` - | `Vec` -... - | / scalar! { - | | bool, &bool, f32, &f32, f64, &f64, - | | i8, &i8, i16, &i16, i32, &i32, i64, &i64, i128, &i128, - | | u16, &u16, u32, &u32, u64, &u64, u128, &u128, -... | - | | Bytes<'_>, &Bytes<'_>, Raw<'_>, &Raw<'_>, - | | } - | |_- in this macro invocation + | impl EncryptTarget for Ciphertext { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ = note: required for `Vec` to implement `OpaqueEncode` = 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]: `u8` cannot be decrypted from one `Ciphertext` --> tests/ui/owned_collection_elements.rs:15:13 diff --git a/packages/stack-encrypt/tests/ui/pass/derived_newtype_scalar.rs b/packages/stack-encrypt/tests/ui/pass/derived_newtype_scalar.rs new file mode 100644 index 000000000..9f3fb7253 --- /dev/null +++ b/packages/stack-encrypt/tests/ui/pass/derived_newtype_scalar.rs @@ -0,0 +1,69 @@ +//! A newtype that derives `Encrypt` over one value is one value too. The +//! newtypes here have no `Scalar` impl written by hand. +//! +//! - `keyset.encrypt` encrypts the newtype by itself. +//! - `keyset.encrypt` encrypts it inside a `Protected`, and inside another +//! such newtype. +//! - A `Vec` of the newtype encrypts one element at a time. +//! - `keyset.encrypt` encrypts a fieldless enum that derives `Encrypt`, with +//! or without `#[aead(recursive)]`. +//! +//! `tests/ui/scalar_derived_not_one_value.rs` lists the derived types that +//! `keyset.encrypt` refuses. +use stack_encrypt::{Ciphertext, EncryptInto, KeysetCipher, Protected}; +use stack_encrypt::Encrypt; +use stack_kms::FakeDataKeySource; +use zeroize::Zeroize; + +#[derive(Encrypt, Zeroize)] +struct Email(String); + +#[derive(Encrypt, Zeroize)] +struct Age(i64); + +#[derive(Encrypt, Zeroize)] +struct Contact(Email); + +#[derive(Encrypt, Zeroize)] +struct Wrapper(T); + +#[derive(Encrypt, Zeroize)] +enum Status { + Active, + Suspended = 7, +} + +#[derive(Encrypt, Zeroize)] +#[aead(recursive)] +enum Level { + Low, +} + +async fn encrypt(keyset: &KeysetCipher<'_, FakeDataKeySource>) { + let _: Ciphertext = keyset.encrypt(Email("ada@example.com".into())).await.unwrap(); + let _: Ciphertext = keyset.encrypt(Age(37)).await.unwrap(); + let _: Ciphertext = keyset + .encrypt_with_context(Age(37), ("users", "age")) + .await + .unwrap(); + let _: Ciphertext = keyset + .encrypt(Protected::new(Email("ada@example.com".into()))) + .await + .unwrap(); + let _: Ciphertext = keyset + .encrypt(Contact(Email("ada@example.com".into()))) + .await + .unwrap(); + let _: Ciphertext = keyset.encrypt(Wrapper(37i64)).await.unwrap(); + let _: Ciphertext = keyset.encrypt(Status::Active).await.unwrap(); + let _: Ciphertext = keyset.encrypt(Status::Suspended).await.unwrap(); + let _: Ciphertext = keyset.encrypt(Level::Low).await.unwrap(); + let _: Vec = vec![Email("ada@example.com".into()), Email("grace@example.com".into())] + .encrypt_into(keyset) + .await + .unwrap(); +} + +fn main() { + let _ = encrypt; +} diff --git a/packages/stack-encrypt/tests/ui/scalar_collections_and_borrows.stderr b/packages/stack-encrypt/tests/ui/scalar_collections_and_borrows.stderr index 2aaa670ff..b4b22fe40 100644 --- a/packages/stack-encrypt/tests/ui/scalar_collections_and_borrows.stderr +++ b/packages/stack-encrypt/tests/ui/scalar_collections_and_borrows.stderr @@ -1,44 +1,41 @@ -error[E0277]: the trait bound `for<'a> &'a Vec: Scalar` is not satisfied +error[E0277]: `Vec` cannot be encrypted into one `Ciphertext` --> tests/ui/scalar_collections_and_borrows.rs:2:28 | 2 | let _ = keyset.encrypt(vec![1i32, 2]); - | ------- ^^^^^^^^^^^^^ the trait `for<'a> Scalar` is not implemented for `&'a Vec` - | | - | required by a bound introduced by this call + | ^^^^^^^^^^^^^ this must be one owned value that can be wiped | -help: the following other types implement trait `Scalar` - --> $WORKSPACE/packages/vitaminc-aead/src/plaintext/sources.rs + = help: the trait `stack_encrypt::scalar::sealed::OneValue` is not implemented for `Vec` + = note: to be encrypted into one `Ciphertext`, a value must meet three conditions. + = note: first, the value must be one scalar or an `OpaqueBlob`. A scalar is a value such as a `String`, a `bool`, a float, a `Vec`, or a fixed-width integer other than `u8`. A newtype that derives `Encrypt` over a scalar is a scalar too. + = note: second, the value must be owned. A borrow, such as a `&str`, is not owned. + = note: third, the type must implement `Zeroize`, so that the value can be wiped after it is encrypted. For an `OpaqueBlob`, `T` must implement `Zeroize` and `Serialize`. + = note: these calls encrypt a value that is not one scalar. `EncryptInto` encrypts each element of a `Vec` into its own `Ciphertext`. `keyset.encrypt_tree` encrypts an `Option` or a struct into a tree of ciphertexts. `OpaqueBlob` encrypts a whole `Serialize` value into one `Ciphertext`. +help: the trait `OpaqueEncode` is implemented for `OpaqueBlob` + --> src/blob.rs | - | impl Scalar for $ty {} - | ^^^^^^^^^^^^^^^^^^^ - | | - | `&Vec` - | `Vec` -... - | / scalar! { - | | bool, &bool, f32, &f32, f64, &f64, - | | i8, &i8, i16, &i16, i32, &i32, i64, &i64, i128, &i128, - | | u16, &u16, u32, &u32, u64, &u64, u128, &u128, -... | - | | Bytes<'_>, &Bytes<'_>, Raw<'_>, &Raw<'_>, - | | } - | |_- in this macro invocation + | impl OpaqueEncode for OpaqueBlob {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ = note: required for `Vec` to implement `OpaqueEncode` note: required by a bound in `stack_encrypt::scalar::>::encrypt` --> src/scalar.rs | | pub fn encrypt(&self, value: S) -> Pending<'_, Ciphertext, K> { | ^^^^^^^^^^^^ required by this bound in `stack_encrypt::scalar::>::encrypt` - = note: this error originates in the macro `scalar` (in Nightly builds, run with -Z macro-backtrace for more info) -error[E0277]: the trait bound `&str: OpaqueEncode` is not satisfied +error[E0277]: `&str` cannot be encrypted into one `Ciphertext` --> tests/ui/scalar_collections_and_borrows.rs:3:28 | 3 | let _ = keyset.encrypt("borrowed plaintext"); - | ------- ^^^^^^^^^^^^^^^^^^^^ the trait `zeroize::DefaultIsZeroes` is not implemented for `&str` + | ------- ^^^^^^^^^^^^^^^^^^^^ this must be one owned value that can be wiped | | | required by a bound introduced by this call | + = help: the trait `zeroize::DefaultIsZeroes` is not implemented for `&str` + = note: to be encrypted into one `Ciphertext`, a value must meet three conditions. + = note: first, the value must be one scalar or an `OpaqueBlob`. A scalar is a value such as a `String`, a `bool`, a float, a `Vec`, or a fixed-width integer other than `u8`. A newtype that derives `Encrypt` over a scalar is a scalar too. + = note: second, the value must be owned. A borrow, such as a `&str`, is not owned. + = note: third, the type must implement `Zeroize`, so that the value can be wiped after it is encrypted. For an `OpaqueBlob`, `T` must implement `Zeroize` and `Serialize`. + = note: these calls encrypt a value that is not one scalar. `EncryptInto` encrypts each element of a `Vec` into its own `Ciphertext`. `keyset.encrypt_tree` encrypts an `Option` or a struct into a tree of ciphertexts. `OpaqueBlob` encrypts a whole `Serialize` value into one `Ciphertext`. = help: the following other types implement trait `zeroize::DefaultIsZeroes`: () PhantomPinned diff --git a/packages/stack-encrypt/tests/ui/scalar_derived_not_one_value.rs b/packages/stack-encrypt/tests/ui/scalar_derived_not_one_value.rs new file mode 100644 index 000000000..516011717 --- /dev/null +++ b/packages/stack-encrypt/tests/ui/scalar_derived_not_one_value.rs @@ -0,0 +1,29 @@ +//! A derived type that is not one value still derives `Encrypt`. So it can +//! be a field of a struct. `keyset.encrypt` refuses each of these types: +//! +//! - a newtype over a `Vec` +//! - a newtype over an `Option` +//! - a struct with named fields +//! +//! Each error says what `keyset.encrypt` encrypts, and what to use instead. +use stack_encrypt::{Encrypt, KeysetCipher}; +use zeroize::Zeroize; + +#[derive(Encrypt, Zeroize)] +struct Tags(Vec); + +#[derive(Encrypt, Zeroize)] +struct Nickname(Option); + +#[derive(Encrypt, Zeroize)] +struct Profile { + name: String, +} + +fn refused(keyset: &KeysetCipher<'_, K>) { + let _ = keyset.encrypt(Tags(vec!["admin".into()])); + let _ = keyset.encrypt(Nickname(None)); + let _ = keyset.encrypt(Profile { name: "Ada".into() }); +} + +fn main() {} diff --git a/packages/stack-encrypt/tests/ui/scalar_derived_not_one_value.stderr b/packages/stack-encrypt/tests/ui/scalar_derived_not_one_value.stderr new file mode 100644 index 000000000..6e2d4b16d --- /dev/null +++ b/packages/stack-encrypt/tests/ui/scalar_derived_not_one_value.stderr @@ -0,0 +1,83 @@ +error[E0277]: `Tags` cannot be encrypted into one `Ciphertext` + --> tests/ui/scalar_derived_not_one_value.rs:24:28 + | +24 | let _ = keyset.encrypt(Tags(vec!["admin".into()])); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^ this must be one owned value that can be wiped + | +help: the trait `stack_encrypt::scalar::sealed::OneValue` is not implemented for `Tags` + --> tests/ui/scalar_derived_not_one_value.rs:13:1 + | +13 | struct Tags(Vec); + | ^^^^^^^^^^^ + = note: to be encrypted into one `Ciphertext`, a value must meet three conditions. + = note: first, the value must be one scalar or an `OpaqueBlob`. A scalar is a value such as a `String`, a `bool`, a float, a `Vec`, or a fixed-width integer other than `u8`. A newtype that derives `Encrypt` over a scalar is a scalar too. + = note: second, the value must be owned. A borrow, such as a `&str`, is not owned. + = note: third, the type must implement `Zeroize`, so that the value can be wiped after it is encrypted. For an `OpaqueBlob`, `T` must implement `Zeroize` and `Serialize`. + = note: these calls encrypt a value that is not one scalar. `EncryptInto` encrypts each element of a `Vec` into its own `Ciphertext`. `keyset.encrypt_tree` encrypts an `Option` or a struct into a tree of ciphertexts. `OpaqueBlob` encrypts a whole `Serialize` value into one `Ciphertext`. +help: the trait `OpaqueEncode` is implemented for `OpaqueBlob` + --> src/blob.rs + | + | impl OpaqueEncode for OpaqueBlob {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + = note: required for `Tags` to implement `OpaqueEncode` +note: required by a bound in `stack_encrypt::scalar::>::encrypt` + --> src/scalar.rs + | + | pub fn encrypt(&self, value: S) -> Pending<'_, Ciphertext, K> { + | ^^^^^^^^^^^^ required by this bound in `stack_encrypt::scalar::>::encrypt` + +error[E0277]: `Nickname` cannot be encrypted into one `Ciphertext` + --> tests/ui/scalar_derived_not_one_value.rs:25:28 + | +25 | let _ = keyset.encrypt(Nickname(None)); + | ^^^^^^^^^^^^^^ this must be one owned value that can be wiped + | +help: the trait `stack_encrypt::scalar::sealed::OneValue` is not implemented for `Nickname` + --> tests/ui/scalar_derived_not_one_value.rs:16:1 + | +16 | struct Nickname(Option); + | ^^^^^^^^^^^^^^^ + = note: to be encrypted into one `Ciphertext`, a value must meet three conditions. + = note: first, the value must be one scalar or an `OpaqueBlob`. A scalar is a value such as a `String`, a `bool`, a float, a `Vec`, or a fixed-width integer other than `u8`. A newtype that derives `Encrypt` over a scalar is a scalar too. + = note: second, the value must be owned. A borrow, such as a `&str`, is not owned. + = note: third, the type must implement `Zeroize`, so that the value can be wiped after it is encrypted. For an `OpaqueBlob`, `T` must implement `Zeroize` and `Serialize`. + = note: these calls encrypt a value that is not one scalar. `EncryptInto` encrypts each element of a `Vec` into its own `Ciphertext`. `keyset.encrypt_tree` encrypts an `Option` or a struct into a tree of ciphertexts. `OpaqueBlob` encrypts a whole `Serialize` value into one `Ciphertext`. +help: the trait `OpaqueEncode` is implemented for `OpaqueBlob` + --> src/blob.rs + | + | impl OpaqueEncode for OpaqueBlob {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + = note: required for `Nickname` to implement `OpaqueEncode` +note: required by a bound in `stack_encrypt::scalar::>::encrypt` + --> src/scalar.rs + | + | pub fn encrypt(&self, value: S) -> Pending<'_, Ciphertext, K> { + | ^^^^^^^^^^^^ required by this bound in `stack_encrypt::scalar::>::encrypt` + +error[E0277]: `Profile` cannot be encrypted into one `Ciphertext` + --> tests/ui/scalar_derived_not_one_value.rs:26:28 + | +26 | let _ = keyset.encrypt(Profile { name: "Ada".into() }); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ this must be one owned value that can be wiped + | +help: the trait `stack_encrypt::scalar::sealed::OneValue` is not implemented for `Profile` + --> tests/ui/scalar_derived_not_one_value.rs:19:1 + | +19 | struct Profile { + | ^^^^^^^^^^^^^^ + = note: to be encrypted into one `Ciphertext`, a value must meet three conditions. + = note: first, the value must be one scalar or an `OpaqueBlob`. A scalar is a value such as a `String`, a `bool`, a float, a `Vec`, or a fixed-width integer other than `u8`. A newtype that derives `Encrypt` over a scalar is a scalar too. + = note: second, the value must be owned. A borrow, such as a `&str`, is not owned. + = note: third, the type must implement `Zeroize`, so that the value can be wiped after it is encrypted. For an `OpaqueBlob`, `T` must implement `Zeroize` and `Serialize`. + = note: these calls encrypt a value that is not one scalar. `EncryptInto` encrypts each element of a `Vec` into its own `Ciphertext`. `keyset.encrypt_tree` encrypts an `Option` or a struct into a tree of ciphertexts. `OpaqueBlob` encrypts a whole `Serialize` value into one `Ciphertext`. +help: the trait `OpaqueEncode` is implemented for `OpaqueBlob` + --> src/blob.rs + | + | impl OpaqueEncode for OpaqueBlob {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + = note: required for `Profile` to implement `OpaqueEncode` +note: required by a bound in `stack_encrypt::scalar::>::encrypt` + --> src/scalar.rs + | + | pub fn encrypt(&self, value: S) -> Pending<'_, Ciphertext, K> { + | ^^^^^^^^^^^^ required by this bound in `stack_encrypt::scalar::>::encrypt` diff --git a/packages/stack-encrypt/tests/ui/scalar_nullable.stderr b/packages/stack-encrypt/tests/ui/scalar_nullable.stderr index 1be60c369..cac0944af 100644 --- a/packages/stack-encrypt/tests/ui/scalar_nullable.stderr +++ b/packages/stack-encrypt/tests/ui/scalar_nullable.stderr @@ -1,21 +1,20 @@ -error[E0277]: the trait bound `for<'a> &'a Option: Scalar` is not satisfied +error[E0277]: `Option` cannot be encrypted into one `Ciphertext` --> tests/ui/scalar_nullable.rs:2:28 | 2 | let _ = keyset.encrypt(Some(42i32)); - | ------- ^^^^^^^^^^^ the trait `for<'a> Scalar` is not implemented for `&'a Option` - | | - | required by a bound introduced by this call - | - = help: the following other types implement trait `Scalar`: - &&'b T - &'a Protected - &JsonPlaintext - &ProtectedRef<'a, T> - &Raw<'_> - &Vec - &[u8; N] - &[u8] - and $N others + | ^^^^^^^^^^^ this must be one owned value that can be wiped + | + = help: the trait `stack_encrypt::scalar::sealed::OneValue` is not implemented for `Option` + = note: to be encrypted into one `Ciphertext`, a value must meet three conditions. + = note: first, the value must be one scalar or an `OpaqueBlob`. A scalar is a value such as a `String`, a `bool`, a float, a `Vec`, or a fixed-width integer other than `u8`. A newtype that derives `Encrypt` over a scalar is a scalar too. + = note: second, the value must be owned. A borrow, such as a `&str`, is not owned. + = note: third, the type must implement `Zeroize`, so that the value can be wiped after it is encrypted. For an `OpaqueBlob`, `T` must implement `Zeroize` and `Serialize`. + = note: these calls encrypt a value that is not one scalar. `EncryptInto` encrypts each element of a `Vec` into its own `Ciphertext`. `keyset.encrypt_tree` encrypts an `Option` or a struct into a tree of ciphertexts. `OpaqueBlob` encrypts a whole `Serialize` value into one `Ciphertext`. +help: the trait `OpaqueEncode` is implemented for `OpaqueBlob` + --> src/blob.rs + | + | impl OpaqueEncode for OpaqueBlob {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ = note: required for `Option` to implement `OpaqueEncode` note: required by a bound in `stack_encrypt::scalar::>::encrypt` --> src/scalar.rs @@ -23,24 +22,23 @@ note: required by a bound in `stack_encrypt::scalar::>: | pub fn encrypt(&self, value: S) -> Pending<'_, Ciphertext, K> { | ^^^^^^^^^^^^ required by this bound in `stack_encrypt::scalar::>::encrypt` -error[E0277]: the trait bound `for<'a> &'a Option: Scalar` is not satisfied +error[E0277]: `Option` cannot be encrypted into one `Ciphertext` --> tests/ui/scalar_nullable.rs:3:28 | 3 | let _ = keyset.encrypt(None::); - | ------- ^^^^^^^^^^^ the trait `for<'a> Scalar` is not implemented for `&'a Option` - | | - | required by a bound introduced by this call - | - = help: the following other types implement trait `Scalar`: - &&'b T - &'a Protected - &JsonPlaintext - &ProtectedRef<'a, T> - &Raw<'_> - &Vec - &[u8; N] - &[u8] - and $N others + | ^^^^^^^^^^^ this must be one owned value that can be wiped + | + = help: the trait `stack_encrypt::scalar::sealed::OneValue` is not implemented for `Option` + = note: to be encrypted into one `Ciphertext`, a value must meet three conditions. + = note: first, the value must be one scalar or an `OpaqueBlob`. A scalar is a value such as a `String`, a `bool`, a float, a `Vec`, or a fixed-width integer other than `u8`. A newtype that derives `Encrypt` over a scalar is a scalar too. + = note: second, the value must be owned. A borrow, such as a `&str`, is not owned. + = note: third, the type must implement `Zeroize`, so that the value can be wiped after it is encrypted. For an `OpaqueBlob`, `T` must implement `Zeroize` and `Serialize`. + = note: these calls encrypt a value that is not one scalar. `EncryptInto` encrypts each element of a `Vec` into its own `Ciphertext`. `keyset.encrypt_tree` encrypts an `Option` or a struct into a tree of ciphertexts. `OpaqueBlob` encrypts a whole `Serialize` value into one `Ciphertext`. +help: the trait `OpaqueEncode` is implemented for `OpaqueBlob` + --> src/blob.rs + | + | impl OpaqueEncode for OpaqueBlob {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ = note: required for `Option` to implement `OpaqueEncode` note: required by a bound in `stack_encrypt::scalar::>::encrypt` --> src/scalar.rs diff --git a/packages/vitaminc-aead-derive/CHANGELOG.md b/packages/vitaminc-aead-derive/CHANGELOG.md index 9867b81e5..c37269877 100644 --- a/packages/vitaminc-aead-derive/CHANGELOG.md +++ b/packages/vitaminc-aead-derive/CHANGELOG.md @@ -1,3 +1,28 @@ +## [Unreleased] + +### Breaking + +- **Breaking:** `#[derive(Encrypt)]` now implements `Scalar` for a newtype and for a fieldless enum. + A `Scalar` impl you wrote for such a type no longer compiles. + The compiler reports `E0119`, conflicting implementations, even when the inner type is not a `Scalar`. + - For a fieldless enum, or for a newtype whose inner type is a `Scalar`, delete your impl, because the derived impl replaces it. + - When the inner type is not a `Scalar`, but you know that its value is one leaf, stop deriving `Encrypt`. + Write `Encrypt` for the type and for its borrow by hand, with `const DEPTH: Option = depth::SCALAR;`, and keep your `Scalar` impl. + +### Features + +- `#[derive(Encrypt)]` implements `Scalar`, by value and by reference, for a type that encrypts as one leaf. + A newtype is a struct with exactly one unnamed field. + A newtype is a `Scalar` when its inner type is one. + So `struct Email(String)` is a `Scalar`. + A generic `Wrapper` is a `Scalar` when `T` is one. + `struct Tags(Vec)` still derives `Encrypt`, but it is not a `Scalar`. + Neither is `struct Nickname(Option)`. + A fieldless enum is always a `Scalar`, because it is one `u32` leaf. + That is true even when the enum is marked `#[aead(recursive)]`. + Its `DEPTH` is now `depth::SCALAR` in that case too, where it was `None`. + A struct with fields is not a `Scalar`. + A recursive newtype is not a `Scalar` either. ## [0.10.0] - 2026-11-19 diff --git a/packages/vitaminc-aead-derive/docs/attributes.md b/packages/vitaminc-aead-derive/docs/attributes.md index 1289e1a72..5c29bc878 100644 --- a/packages/vitaminc-aead-derive/docs/attributes.md +++ b/packages/vitaminc-aead-derive/docs/attributes.md @@ -110,6 +110,9 @@ struct Odd { # assert!(even.next[0].next.is_empty()); ``` +A fieldless enum has no fields, so it cannot be part of a cycle. The derive +ignores `recursive` on a fieldless enum: the enum is still one `u32` leaf. + A type that contains a recursive type is not checked either, since its depth depends on the recursive part. A generic type is checked once it is used at a concrete type, under `cargo build` rather than `cargo check`. diff --git a/packages/vitaminc-aead-derive/src/encrypt.rs b/packages/vitaminc-aead-derive/src/encrypt.rs index 386f343b8..6ace5eea3 100644 --- a/packages/vitaminc-aead-derive/src/encrypt.rs +++ b/packages/vitaminc-aead-derive/src/encrypt.rs @@ -7,6 +7,11 @@ //! `Vec` does its leftover elements. The impl for `&Name` walks the //! fields by reference and moves nothing; it is what a `Protected` //! walks through, so the struct stays wrapped and is zeroized whole. +//! +//! A leaf is one sealed value. A newtype or a fieldless enum is one leaf. +//! So the derive also implements the `Scalar` marker for it, by value and +//! by reference, as every built-in leaf type has. A newtype is a `Scalar` +//! only when its inner type is one. use proc_macro2::TokenStream; use quote::quote; @@ -22,6 +27,13 @@ pub(crate) fn derive(input: DeriveInput) -> Result { let krate = &attrs.krate; let shape = Shape::parse(&input)?; let name = &input.ident; + // Whether the type has a fixed depth. A type that contains itself has + // none, because its depth depends on the value. The derive detects a type + // that names itself in a field. `#[aead(recursive)]` marks recursion + // through another type. A fieldless enum has no fields, so it + // cannot contain itself, even when it is marked `recursive`. + let fixed_depth = + matches!(shape, Shape::Enum(_)) || !(attrs.recursive || names_itself(name, &shape)); // Bound every type parameter, serde-style: a field of type `Vec` then // picks up `Vec: Encrypt` from the blanket impl in `vitaminc_aead`. @@ -86,8 +98,9 @@ pub(crate) fn derive(input: DeriveInput) -> Result { by_ref: ref_depth, item_check, visit_check, - } = depth(krate, &input, &shape, attrs.recursive); - let (fixed, ref_fixed) = fixed(krate, &input, &shape, attrs.recursive); + } = depth(krate, &input, &shape, fixed_depth); + let (fixed, ref_fixed) = fixed(krate, &shape, fixed_depth); + let scalar = scalar(krate, &input, &shape, fixed_depth, &generics, &ref_generics); Ok(quote! { #[automatically_derived] @@ -118,10 +131,65 @@ pub(crate) fn derive(input: DeriveInput) -> Result { } } + #scalar + #item_check }) } +/// The `Scalar` impls for a type that encrypts as one leaf. Two kinds of +/// type do: a newtype whose inner type is a `Scalar`, and a fieldless enum. +/// A fieldless enum is always one `u32` leaf. A struct with fields is a +/// map, so it gets no impl. A recursive newtype has no fixed depth, so it +/// gets none either. +/// +/// Each impl for a newtype has a bound: the inner type is a `Scalar`. So a +/// newtype over a container, such as `Tags(Vec)`, still derives +/// `Encrypt`. The newtype is not a `Scalar`. +/// +/// The compiler checks a bound that names no generic parameter where the +/// impl is written. A false bound of that kind is an error. So the +/// borrowed impl's bound names the borrow's lifetime `'__r`. The owned +/// impl's bound is inside a `for<'__s>` binder. The compiler then checks +/// each bound only where code asks for the `Scalar` impl. +fn scalar( + krate: &syn::Path, + input: &DeriveInput, + shape: &Shape, + fixed_depth: bool, + generics: &syn::Generics, + ref_generics: &syn::Generics, +) -> TokenStream { + let name = &input.ident; + let (owned, by_ref) = match shape { + Shape::Newtype(field) if fixed_depth => { + let ty = &field.ty; + let mut owned = generics.clone(); + owned + .make_where_clause() + .predicates + .push(parse_quote!(for<'__s> #ty: #krate::Scalar)); + let mut by_ref = ref_generics.clone(); + by_ref + .make_where_clause() + .predicates + .push(parse_quote!(&'__r #ty: #krate::Scalar)); + (owned, by_ref) + } + Shape::Enum(_) => (generics.clone(), ref_generics.clone()), + Shape::Newtype(_) | Shape::Map(_) | Shape::Empty => return TokenStream::new(), + }; + let (impl_generics, ty_generics, where_clause) = owned.split_for_impl(); + let (ref_impl_generics, _, ref_where_clause) = by_ref.split_for_impl(); + quote! { + #[automatically_derived] + impl #impl_generics #krate::Scalar for #name #ty_generics #where_clause {} + + #[automatically_derived] + impl #ref_impl_generics #krate::Scalar for &'__r #name #ty_generics #ref_where_clause {} + } +} + /// The `DEPTH` constants for both impls, and the check that the type fits /// within `MAX_DEPTH`. struct Depth { @@ -141,16 +209,15 @@ struct Depth { /// sink counts nesting. A recursive type has no fixed depth, and naming its /// own `DEPTH` would be a cycle, so it keeps the default `None` and the /// walk checks each value instead. -fn depth(krate: &syn::Path, input: &DeriveInput, shape: &Shape, recursive: bool) -> Depth { +fn depth(krate: &syn::Path, input: &DeriveInput, shape: &Shape, fixed_depth: bool) -> Depth { let name = &input.ident; - let none = Depth { - owned: TokenStream::new(), - by_ref: TokenStream::new(), - item_check: TokenStream::new(), - visit_check: TokenStream::new(), - }; - if recursive || names_itself(name, shape) { - return none; + if !fixed_depth { + return Depth { + owned: TokenStream::new(), + by_ref: TokenStream::new(), + item_check: TokenStream::new(), + visit_check: TokenStream::new(), + }; } let depth = quote!(#krate::plaintext::depth); @@ -235,18 +302,10 @@ fn depth(krate: &syn::Path, input: &DeriveInput, shape: &Shape, recursive: bool) /// value and by reference, as `DEPTH` does). A fieldless enum is always a /// `u32` leaf. A struct is a map, which has none, and a recursive newtype /// keeps the default rather than name its own constant in a cycle. -fn fixed( - krate: &syn::Path, - input: &DeriveInput, - shape: &Shape, - recursive: bool, -) -> (TokenStream, TokenStream) { +fn fixed(krate: &syn::Path, shape: &Shape, fixed_depth: bool) -> (TokenStream, TokenStream) { let decl = |value: TokenStream| quote!(const FIXED: ::core::option::Option<#krate::FixedType> = #value;); match shape { - Shape::Newtype(_) if recursive || names_itself(&input.ident, shape) => { - (TokenStream::new(), TokenStream::new()) - } - Shape::Newtype(field) => { + Shape::Newtype(field) if fixed_depth => { let ty = &field.ty; ( decl(quote!(<#ty as #krate::Encrypt>::FIXED)), @@ -257,7 +316,9 @@ fn fixed( let u32 = decl(quote!(#krate::FixedType::plain(#krate::Width::U32))); (u32.clone(), u32) } - Shape::Map(_) | Shape::Empty => (TokenStream::new(), TokenStream::new()), + Shape::Newtype(_) | Shape::Map(_) | Shape::Empty => { + (TokenStream::new(), TokenStream::new()) + } } } @@ -1130,6 +1191,172 @@ mod tests { assert_contains(&out, quote!(const DEPTH)); } + /// A newtype is a `Scalar` when its inner type is one. The derive + /// implements `Scalar` by value and by reference. Each impl has the + /// inner type's `Scalar` as its bound. + /// + /// The owned bound is inside a + /// binder, and the borrowed bound names the borrow's lifetime. So the + /// compiler does not check either bound where the impl is written. A + /// newtype over a container still derives. + #[test] + fn a_newtype_is_a_scalar_when_its_inner_type_is() { + let out = expand(parse_quote!( + struct Email(String); + )); + assert_contains( + &out, + quote!(impl ::vitaminc_aead::Scalar for Email + where for<'__s> String: ::vitaminc_aead::Scalar {}), + ); + assert_contains( + &out, + quote!( + impl<'__r> ::vitaminc_aead::Scalar for &'__r Email where &'__r String: ::vitaminc_aead::Scalar {} + ), + ); + + let out = expand(parse_quote!( + struct Tags(Vec); + )); + assert_contains( + &out, + quote!(impl ::vitaminc_aead::Scalar for Tags + where for<'__s> Vec: ::vitaminc_aead::Scalar {}), + ); + assert_contains( + &out, + quote!( + impl<'__r> ::vitaminc_aead::Scalar for &'__r Tags where &'__r Vec: ::vitaminc_aead::Scalar {} + ), + ); + } + + /// A generic newtype's `Scalar` impls keep the bounds of its `Encrypt` + /// impls. Each also has the inner type's `Scalar` as a bound. + #[test] + #[rustfmt::skip] + fn a_generic_newtype_is_a_scalar_when_its_parameter_is() { + let out = expand(parse_quote!( + struct Wrapper(T); + )); + assert_contains( + &out, + quote!( + impl ::vitaminc_aead::Scalar for Wrapper where + for<'__s> T: ::vitaminc_aead::Scalar + { + } + ), + ); + assert_contains( + &out, + quote!( + impl<'__r, T> ::vitaminc_aead::Scalar for &'__r Wrapper + where + T: ::vitaminc_aead::EncryptRef, + &'__r T: ::vitaminc_aead::Scalar + { + } + ), + ); + } + + /// A fieldless enum is always one `u32` leaf. So its `Scalar` impls + /// have no bound. + #[test] + fn a_fieldless_enum_is_a_scalar() { + let out = expand(parse_quote! { + enum Status { + Active, + } + }); + assert_contains(&out, quote!(impl ::vitaminc_aead::Scalar for Status {})); + assert_contains( + &out, + quote!( + impl<'__r> ::vitaminc_aead::Scalar for &'__r Status {} + ), + ); + } + + /// A fieldless enum cannot contain itself, so `recursive` changes + /// nothing. The enum still declares a scalar depth and a `u32` fixed + /// type, and it is still a `Scalar`. + #[test] + fn a_recursive_fieldless_enum_is_still_one_leaf() { + let out = expand(parse_quote! { + #[aead(recursive)] + enum Status { + Active, + } + }); + assert_contains( + &out, + quote!( + const DEPTH: ::core::option::Option = + ::vitaminc_aead::plaintext::depth::SCALAR; + ), + ); + assert_contains( + &out, + quote!( + const FIXED: ::core::option::Option<::vitaminc_aead::FixedType> = + ::vitaminc_aead::FixedType::plain(::vitaminc_aead::Width::U32); + ), + ); + assert_contains(&out, quote!(impl ::vitaminc_aead::Scalar for Status {})); + assert_contains( + &out, + quote!( + impl<'__r> ::vitaminc_aead::Scalar for &'__r Status {} + ), + ); + } + + /// A struct with fields and a struct with none each encrypt as a map. A + /// recursive newtype has no fixed depth. So none of them is a `Scalar`. + #[test] + fn a_map_or_a_recursive_type_is_not_a_scalar() { + for input in [ + parse_quote! { + struct User { + name: String, + } + }, + parse_quote!( + struct Pair(String, u32); + ), + parse_quote!( + struct Marker {} + ), + parse_quote!( + struct Wrapped(Vec); + ), + parse_quote!( + #[aead(recursive)] + struct Even(Option>); + ), + ] { + assert_lacks(&expand(input), quote!(::vitaminc_aead::Scalar)); + } + } + + /// The `Scalar` path uses the crate named by the `crate` attribute, as + /// every other path does. + #[test] + fn the_marker_follows_the_crate_attribute() { + let out = expand(parse_quote! { + #[aead(crate = "::vitaminc::aead")] + struct Email(String); + }); + assert_contains(&out, quote!(::vitaminc::aead::Scalar for Email)); + assert!( + !out.contains("vitaminc_aead"), + "expansion still references the default crate path:\n{out}" + ); + } + #[test] fn unknown_attributes_are_rejected() { let err = derive(parse_quote! { diff --git a/packages/vitaminc-aead-derive/src/lib.rs b/packages/vitaminc-aead-derive/src/lib.rs index aef62fdcf..cb5fae977 100644 --- a/packages/vitaminc-aead-derive/src/lib.rs +++ b/packages/vitaminc-aead-derive/src/lib.rs @@ -52,6 +52,8 @@ //! - A **newtype** struct (exactly one unnamed field) is *transparent*: it //! encrypts and decrypts exactly as its inner type, adding nothing to the //! ciphertext. This mirrors serde, and matches how `Protected` behaves. +//! A newtype is also a `Scalar`, one leaf, when its inner type is one. +//! So `Email(String)` is a `Scalar`. `Tags(Vec)` is not. //! - A unit struct — or a struct with no fields — encrypts to the //! authenticated empty-map marker. //! @@ -69,6 +71,33 @@ //! refused. Pin the discriminants with `= n` before storing anything, since //! reordering variants otherwise changes them. Variants take no //! `#[aead(...)]` attributes. +//! A fieldless enum is a `Scalar`, by value and by reference, because it +//! is one leaf. +//! +//! `#[derive(Zeroize)]` from the `zeroize` crate does not wipe a fieldless +//! enum: its `zeroize` does nothing. So a caller that wipes the value after +//! it encrypts it leaves the variant in memory. To have the variant wiped, +//! give the enum a `#[default]` variant and implement +//! `zeroize::DefaultIsZeroes` for it. Its `zeroize` then overwrites the +//! value with the default variant. +//! +//! ```rust +//! use vitaminc_aead::Encrypt; +//! use zeroize::Zeroize; +//! +//! #[derive(Encrypt, Clone, Copy, Default, Debug, PartialEq)] +//! enum Status { +//! #[default] +//! Active, +//! Suspended = 7, +//! } +//! +//! impl zeroize::DefaultIsZeroes for Status {} +//! +//! let mut status = Status::Suspended; +//! status.zeroize(); +//! assert_eq!(status, Status::Active, "zeroize writes the default variant"); +//! ``` //! //! Enums with fields are not supported. Their payload has no agreed layout //! (internally or externally tagged, per-variant AAD), so model the choice diff --git a/packages/vitaminc-aead/CHANGELOG.md b/packages/vitaminc-aead/CHANGELOG.md index 69a8e68c2..8be06db79 100644 --- a/packages/vitaminc-aead/CHANGELOG.md +++ b/packages/vitaminc-aead/CHANGELOG.md @@ -14,6 +14,15 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). A leaf sealed in another unit by an earlier version still decrypts. - Transport frames are unchanged: a frame keeps the unit it was given. +### Breaking + +- **Breaking:** `#[derive(Encrypt)]` now implements `Scalar` for a newtype and for a fieldless enum. + A `Scalar` impl you wrote for such a type now conflicts with the derived impl, even when the inner type is not a `Scalar`. + The compiler reports `E0119`, conflicting implementations. + - For a fieldless enum, or for a newtype whose inner type is a `Scalar`, delete your impl. + - When the inner type is not a `Scalar`, but you know that its value is one leaf, stop deriving `Encrypt`. + Write `Encrypt` for the type and for its borrow by hand, with `const DEPTH: Option = depth::SCALAR;`, and keep your `Scalar` impl. + ### Added - `ScalarTarget` (also `typed::ScalarTarget`): a trait for a decrypt target that is built from one scalar. @@ -56,6 +65,15 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). Code that names `FrameWriter<'_>` is unchanged. The decrypt sink of `OwnedFrame` writes through them, reporting `DecodeError`. - `DecodeError` implements `From`: a scalar its logical type does not admit is `DecodeError::Expected`, a source's failure is `DecodeError::Source`, and any other refusal is `DecodeError::Source` with the writer's error as its source. +- `#[derive(Encrypt)]` implements `Scalar`, by value and by reference, for two kinds of type. + The first is a newtype whose inner type is a `Scalar`. + The second is a fieldless enum. + So `struct Email(String)` needs no `Scalar` impl of its own. + A `Protected` is a `Scalar` too. + `struct Tags(Vec)` still derives `Encrypt`, but it is not a `Scalar`. + The section above, under Breaking, says what to do with a `Scalar` impl you wrote for such a type. +- The `Scalar` docs now say that a hand-written `Scalar` type must set `const DEPTH: Option = depth::SCALAR;`. + A caller that checks `DEPTH` refuses a `Scalar` type whose `DEPTH` is the default `None`. ### Security diff --git a/packages/vitaminc-aead/src/plaintext/mod.rs b/packages/vitaminc-aead/src/plaintext/mod.rs index 146d42523..e61fc69b6 100644 --- a/packages/vitaminc-aead/src/plaintext/mod.rs +++ b/packages/vitaminc-aead/src/plaintext/mod.rs @@ -216,6 +216,32 @@ impl Encrypt for &Lent<'_, T> { /// that bounds on `Scalar` asks for a value that is present, and decides /// for itself how to seal an absent one. /// +/// `#[derive(Encrypt)]` implements `Scalar`, by value and by reference, for +/// a derived type that encrypts as one leaf. So you write no impl for such +/// a type. +/// +/// - A newtype is a struct with exactly one unnamed field. A newtype is a +/// `Scalar` when its inner type is one. So `struct Email(String)` is a +/// `Scalar`. +/// - `struct Tags(Vec)` is not a `Scalar`. Nor is +/// `struct Nickname(Option)`. Both still derive `Encrypt`. +/// - A fieldless enum is always a `Scalar`, because it is one `u32` leaf. +/// - A struct with fields is a map, so it is never a `Scalar`. +/// +/// ``` +/// use vitaminc_aead::{Encrypt, Scalar}; +/// +/// #[derive(Encrypt)] +/// struct Email(String); +/// +/// fn seals_one_leaf(value: S) -> S { +/// value +/// } +/// +/// seals_one_leaf(Email("ada@example.com".into())); +/// seals_one_leaf(&Email("ada@example.com".into())); +/// ``` +/// /// `DEPTH` says the same thing, but stable Rust cannot bound a generic on /// a constant, so a caller that must produce one sealed leaf from any source /// bounds on this trait instead. The trait is open: a hand-written leaf, @@ -253,6 +279,13 @@ impl Encrypt for &Lent<'_, T> { /// seals_one_leaf(Blob(vec![7])); /// ``` /// +/// A hand-written leaf must set `const DEPTH: Option = +/// depth::SCALAR;` in each `Encrypt` impl that is marked `Scalar`, as +/// `Blob` does. The default `DEPTH` is `None`. `None` means that the depth +/// depends on the value. A `Scalar` impl contradicts that default. So a +/// caller that checks `DEPTH`, as `seals_one_leaf` does, refuses the type +/// when the program is built. +/// /// `Vec` is the one exception to the rule that a `Vec` is a sequence: /// it is a byte string, sealed as a single bytes leaf. The same goes for /// `[u8; N]` and `&[u8]`. So `vec![1u8, 2, 3]` is a `Scalar`, while a diff --git a/packages/vitaminc-aead/tests/scalar.rs b/packages/vitaminc-aead/tests/scalar.rs index e7c1e2e22..8f2a0a128 100644 --- a/packages/vitaminc-aead/tests/scalar.rs +++ b/packages/vitaminc-aead/tests/scalar.rs @@ -108,6 +108,49 @@ fn an_empty_text_or_byte_value_is_still_one_leaf() { one_leaf(Protected::new([0u8; 0]).as_protected_ref()); } +/// A derived newtype encrypts as its inner value does. So the derive +/// implements `Scalar` for it, by value and by reference, when the inner +/// type is a `Scalar`. A fieldless enum is one `u32` leaf, so the derive +/// implements `Scalar` for it too. These types have no `Scalar` impl +/// written by hand. +#[derive(Encrypt, zeroize::Zeroize)] +struct Email(String); + +#[derive(Encrypt, zeroize::Zeroize)] +struct Contact(Email); + +#[derive(Encrypt)] +struct Wrapper(T); + +#[derive(Encrypt)] +struct Name<'a>(&'a str); + +#[derive(Encrypt)] +enum Status { + Active, +} + +const _: () = assert!(depth::is_scalar(::DEPTH)); +const _: () = assert!(depth::is_scalar(<&Email as Encrypt>::DEPTH)); +const _: () = assert!(depth::is_scalar( as Encrypt>::DEPTH)); +const _: () = assert!(depth::is_scalar(<&Wrapper as Encrypt>::DEPTH)); + +#[test] +fn a_derived_newtype_over_a_scalar_is_a_scalar() { + one_leaf(Email("ada@example.com".into())); + one_leaf(&Email("ada@example.com".into())); + one_leaf(Contact(Email("ada@example.com".into()))); + one_leaf(&Contact(Email("ada@example.com".into()))); + one_leaf(Wrapper(42i64)); + one_leaf(&Wrapper(vec![1u8, 2])); + one_leaf(Name("ada")); + one_leaf(&Name("ada")); + one_leaf(Protected::new(Email("ada@example.com".into()))); + one_leaf(&Protected::new(Email("ada@example.com".into()))); + one_leaf(Status::Active); + one_leaf(&Status::Active); +} + #[test] fn a_borrow_of_a_scalar_borrow_is_a_scalar() { one_leaf(&&42i32); diff --git a/packages/vitaminc-aead/tests/ui/scalar/derived_newtype_over_a_container.rs b/packages/vitaminc-aead/tests/ui/scalar/derived_newtype_over_a_container.rs new file mode 100644 index 000000000..876c01ac9 --- /dev/null +++ b/packages/vitaminc-aead/tests/ui/scalar/derived_newtype_over_a_container.rs @@ -0,0 +1,24 @@ +//! A derived newtype is a `Scalar` only when its inner type is one. A +//! newtype over a `Vec` encrypts as a sequence. A newtype over an `Option` +//! can be absent. So neither newtype is a `Scalar`, by value or by +//! reference. Both still derive `Encrypt`. + +use vitaminc_aead::{Encrypt, Scalar}; + +#[derive(Encrypt)] +struct Tags(Vec); + +#[derive(Encrypt)] +struct Nickname(Option); + +#[derive(Encrypt)] +struct Wrapper(T); + +fn seals_one_leaf(_: S) {} + +fn main() { + seals_one_leaf(Tags(vec![])); + seals_one_leaf(&Tags(vec![])); + seals_one_leaf(Nickname(None)); + seals_one_leaf(Wrapper(vec![1i32])); +} diff --git a/packages/vitaminc-aead/tests/ui/scalar/derived_newtype_over_a_container.stderr b/packages/vitaminc-aead/tests/ui/scalar/derived_newtype_over_a_container.stderr new file mode 100644 index 000000000..4cefd5a90 --- /dev/null +++ b/packages/vitaminc-aead/tests/ui/scalar/derived_newtype_over_a_container.stderr @@ -0,0 +1,146 @@ +error[E0277]: the trait bound `Vec: vitaminc_aead::Scalar` is not satisfied + --> tests/ui/scalar/derived_newtype_over_a_container.rs:20:20 + | +20 | seals_one_leaf(Tags(vec![])); + | -------------- ^^^^^^^^^^^^ the trait `vitaminc_aead::Scalar` is not implemented for `Vec` + | | + | required by a bound introduced by this call + | +help: the following other types implement trait `vitaminc_aead::Scalar` + --> src/plaintext/sources.rs + | + | impl Scalar for $ty {} + | ^^^^^^^^^^^^^^^^^^^ + | | + | `&Vec` + | `Vec` +... + | / scalar! { + | | bool, &bool, f32, &f32, f64, &f64, + | | i8, &i8, i16, &i16, i32, &i32, i64, &i64, i128, &i128, + | | u16, &u16, u32, &u32, u64, &u64, u128, &u128, +... | + | | Bytes<'_>, &Bytes<'_>, Raw<'_>, &Raw<'_>, + | | } + | |_- in this macro invocation +note: required for `Tags` to implement `vitaminc_aead::Scalar` + --> tests/ui/scalar/derived_newtype_over_a_container.rs:8:10 + | + 8 | #[derive(Encrypt)] + | ^^^^^^^ unsatisfied trait bound introduced in this `derive` macro + 9 | struct Tags(Vec); + | ^^^^ +note: required by a bound in `seals_one_leaf` + --> tests/ui/scalar/derived_newtype_over_a_container.rs:17:22 + | +17 | fn seals_one_leaf(_: S) {} + | ^^^^^^ required by this bound in `seals_one_leaf` + = note: this error originates in the macro `scalar` which comes from the expansion of the derive macro `Encrypt` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0277]: the trait bound `&Vec: vitaminc_aead::Scalar` is not satisfied + --> tests/ui/scalar/derived_newtype_over_a_container.rs:21:21 + | +21 | seals_one_leaf(&Tags(vec![])); + | -------------- ^^^^^^^^^^^^ the trait `vitaminc_aead::Scalar` is not implemented for `&Vec` + | | + | required by a bound introduced by this call + | +help: the following other types implement trait `vitaminc_aead::Scalar` + --> src/plaintext/sources.rs + | + | impl Scalar for $ty {} + | ^^^^^^^^^^^^^^^^^^^ + | | + | `&Vec` + | `Vec` +... + | / scalar! { + | | bool, &bool, f32, &f32, f64, &f64, + | | i8, &i8, i16, &i16, i32, &i32, i64, &i64, i128, &i128, + | | u16, &u16, u32, &u32, u64, &u64, u128, &u128, +... | + | | Bytes<'_>, &Bytes<'_>, Raw<'_>, &Raw<'_>, + | | } + | |_- in this macro invocation +note: required for `&Tags` to implement `vitaminc_aead::Scalar` + --> tests/ui/scalar/derived_newtype_over_a_container.rs:8:10 + | + 8 | #[derive(Encrypt)] + | ^^^^^^^ unsatisfied trait bound introduced in this `derive` macro +note: required by a bound in `seals_one_leaf` + --> tests/ui/scalar/derived_newtype_over_a_container.rs:17:22 + | +17 | fn seals_one_leaf(_: S) {} + | ^^^^^^ required by this bound in `seals_one_leaf` + = note: this error originates in the macro `scalar` which comes from the expansion of the derive macro `Encrypt` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0277]: the trait bound `Option: vitaminc_aead::Scalar` is not satisfied + --> tests/ui/scalar/derived_newtype_over_a_container.rs:22:20 + | +22 | seals_one_leaf(Nickname(None)); + | -------------- ^^^^^^^^^^^^^^ the trait `vitaminc_aead::Scalar` is not implemented for `Option` + | | + | required by a bound introduced by this call + | + = help: the following other types implement trait `vitaminc_aead::Scalar`: + &&'b T + &'__r Nickname + &'__r Tags + &'__r Wrapper + &'a vitaminc_protected::protected::Protected + &Raw<'_> + &Vec + &[u8; N] + and $N others +note: required for `Nickname` to implement `vitaminc_aead::Scalar` + --> tests/ui/scalar/derived_newtype_over_a_container.rs:11:10 + | +11 | #[derive(Encrypt)] + | ^^^^^^^ unsatisfied trait bound introduced in this `derive` macro +12 | struct Nickname(Option); + | ^^^^^^^^ +note: required by a bound in `seals_one_leaf` + --> tests/ui/scalar/derived_newtype_over_a_container.rs:17:22 + | +17 | fn seals_one_leaf(_: S) {} + | ^^^^^^ required by this bound in `seals_one_leaf` + = note: this error originates in the derive macro `Encrypt` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0277]: the trait bound `Vec: vitaminc_aead::Scalar` is not satisfied + --> tests/ui/scalar/derived_newtype_over_a_container.rs:23:28 + | +23 | seals_one_leaf(Wrapper(vec![1i32])); + | -------------- ^^^^^^^^^^ the trait `vitaminc_aead::Scalar` is not implemented for `Vec` + | | + | required by a bound introduced by this call + | +help: the following other types implement trait `vitaminc_aead::Scalar` + --> src/plaintext/sources.rs + | + | impl Scalar for $ty {} + | ^^^^^^^^^^^^^^^^^^^ + | | + | `&Vec` + | `Vec` +... + | / scalar! { + | | bool, &bool, f32, &f32, f64, &f64, + | | i8, &i8, i16, &i16, i32, &i32, i64, &i64, i128, &i128, + | | u16, &u16, u32, &u32, u64, &u64, u128, &u128, +... | + | | Bytes<'_>, &Bytes<'_>, Raw<'_>, &Raw<'_>, + | | } + | |_- in this macro invocation +note: required for `Wrapper>` to implement `vitaminc_aead::Scalar` + --> tests/ui/scalar/derived_newtype_over_a_container.rs:14:10 + | +14 | #[derive(Encrypt)] + | ^^^^^^^ unsatisfied trait bound introduced in this `derive` macro +15 | struct Wrapper(T); + | ^^^^^^^^^^ +note: required by a bound in `seals_one_leaf` + --> tests/ui/scalar/derived_newtype_over_a_container.rs:17:22 + | +17 | fn seals_one_leaf(_: S) {} + | ^^^^^^ required by this bound in `seals_one_leaf` + = note: this error originates in the macro `scalar` which comes from the expansion of the derive macro `Encrypt` (in Nightly builds, run with -Z macro-backtrace for more info)