Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
15 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 60 additions & 0 deletions packages/stack-encrypt/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<usize> = 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<usize> = 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
Expand Down Expand Up @@ -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::<String>` 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<String>)`
and `struct Nickname(Option<String>)`. `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
Expand Down
225 changes: 214 additions & 11 deletions packages/stack-encrypt/src/scalar.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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`].
Expand All @@ -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::<String>` opens what an `Email` encrypted. The derive
/// comes from Vitamin C, so your crate needs `vitaminc-aead` as a

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

minor The hand-written path these docs and the doctests at L234-235 and L267-268 describe needs vitaminc_aead::Scalar and vitaminc_aead::plaintext::depth, and stack-encrypt re-exports neither (src/lib.rs:779-782). #2013 covers the derive's paths, not these. Re-export Scalar and depth from stack_encrypt and point the docs and CHANGELOG (L1293, L1301) at them.

Source: mattpocock-skills:code-review (spec) · claude-opus-5-5


Generated by Claude Code

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not in this PR. A hand-written Encrypt impl also needs vitaminc_aead::plaintext::Sink, so re-exporting Scalar and depth would not complete that path: the user's crate would still list vitaminc-aead.

The whole surface belongs in one change, so I have added the hand-written path to #2013, which already covers the derive's paths.

/// 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<String>)`, still derives `Encrypt`. So it can be a field
/// of a struct. `keyset.encrypt` refuses it, as it refuses a `Vec<String>`.
///
/// 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<K: 'static>(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::<stack_encrypt::kms::FakeDataKeySource>;
/// ```
///
/// 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<usize> = 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<T>`](crate::OpaqueBlob) is an `OpaqueEncode` type too. It
/// encodes a whole `Serialize` value as one storage blob first.
Expand Down Expand Up @@ -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<T>`. A scalar is a value such \
as a `String`, a `bool`, a float, a `Vec<u8>`, 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>`, `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.
Expand Down Expand Up @@ -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<S: crate::EncryptRef> 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<usize> = depth::SCALAR;
/// fn visit<S: Sink>(self, sink: S) -> Result<S::Ok, S::Error> {
/// 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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: this doctest does not prove why the build fails.

rustdoc checks the error code of a compile_fail test only on nightly. This repository pins stable, so any compile error in the snippet keeps the test green. A rename of depth::container or FakeDataKeySource would do that with the const check removed.

Fix: add a positive control. The same snippet with DEPTH = depth::SCALAR must compile as a passing doctest.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in c3f2cf7. The docs now have two doctests, one after the other. The first passes: a hand-written leaf with DEPTH = depth::SCALAR. The second is the compile_fail one, and it differs from the first only in DEPTH. So a compile error from anything else would fail the first test.

/// 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<usize> = depth::container(depth::SCALAR);
/// fn visit<S: Sink>(self, sink: S) -> Result<S::Ok, S::Error> {
/// 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<S> 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 {

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Important: a hand-written one-value type that leaves DEPTH at its default no longer builds.

This check asserts depth::is_scalar(<&S>::DEPTH), and is_scalar(None) is false. Encrypt::DEPTH defaults to None, and its docs say a hand-written impl may leave it at None.

Reproduced: a type with impl Encrypt for &Token (no DEPTH) and impl Scalar for &Token {} compiled with keyset.encrypt before this PR. Now cargo build fails with E0080. cargo check still passes.

The CHANGELOG lists the check under Fixed and describes only the container case.

Fix, one of:

  • keep the check strict, move the entry to Breaking, and say that a hand-written Scalar type must set DEPTH = depth::SCALAR;
  • accept None, and refuse only a depth above 0. This is weaker: a false marker that leaves DEPTH unset passes.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in c3f2cf7 and 45ea2c5. The check stays strict, because a Scalar marker on a type whose DEPTH says "depends on the value" contradicts itself.

  • The assertion message now names the fix: "Set const DEPTH: Option<usize> = depth::SCALAR; in the Encrypt impl of its borrow."
  • The OpaqueEncode docs and the Scalar docs say the same.
  • The stack-encrypt CHANGELOG lists it under Breaking, with the line to add. The old bullet under Fixed is gone.

Every hand-written Scalar impl in this repository already sets DEPTH, so none needed a change. I re-ran the reproduction: it still fails the build, now with the new message.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

minor The new message misdirects for a derived newtype over a hand-written type. With impl Encrypt for &Inner (no DEPTH) and impl Scalar for &Inner {}, #[derive(Encrypt, Zeroize)] struct Outer(Inner) inherits both, and keyset.encrypt(Outer(..)) fails with E0080 telling the user to set DEPTH in Outer's borrow impl, which the macro wrote (scalar.rs:304-306; reproduced). Say that for a derived newtype the impl to fix is the innermost hand-written type's.

Source: code-review · claude-opus-5-5


Generated by Claude Code

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reproduced and fixed in 52c2a01. A const panic cannot name a type on stable Rust, so the message says where to look:

a type marked Scalar must encrypt as one value. Set const DEPTH: Option<usize> = 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.

The OpaqueEncode docs and the Breaking entry say the same.

assert!(
vitaminc_aead::plaintext::depth::is_scalar(<S as crate::EncryptRef>::REF_DEPTH),
"a type marked `Scalar` must encrypt as one value. Set \
`const DEPTH: Option<usize> = 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<S> 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<P: ScalarTarget + Zeroize + Send + 'static> sealed::Decode for P {
fn open<'a, K: 'static>(
Expand Down
Loading
Loading