From 5329ca3c3afbe5dd3f1a327d9a9ae7aa758d37bb Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Tue, 24 Nov 2026 11:55:06 +1100 Subject: [PATCH 1/3] chore(agents): add the vitaminc skill for agents working on the repo The vitaminc skill maps each task that touches a secret to the vitaminc type for it, with working recipes. It was not installed here, so agents writing Rust in this repository hand-rolled what vitaminc already has. It is a copy from cipherstash/vitaminc at 5dbbafaa1, beside the misuse-resistance copy, in .claude/skills/ so it does not ship to customers. AGENTS.md says when to read it, and adds two rules the skill does not state yet: derive OpaqueDebug for a type that holds a secret, and reuse an engine or vitaminc type before wrapping it. --- .claude/skills/misuse-resistance/SKILL.md | 2 +- .claude/skills/vitaminc/RECIPES.md | 287 ++++++++++++++++++++++ .claude/skills/vitaminc/SKILL.md | 67 +++++ AGENTS.md | 17 ++ 4 files changed, 372 insertions(+), 1 deletion(-) create mode 100644 .claude/skills/vitaminc/RECIPES.md create mode 100644 .claude/skills/vitaminc/SKILL.md diff --git a/.claude/skills/misuse-resistance/SKILL.md b/.claude/skills/misuse-resistance/SKILL.md index bdcd3e992..22a88f4d5 100644 --- a/.claude/skills/misuse-resistance/SKILL.md +++ b/.claude/skills/misuse-resistance/SKILL.md @@ -70,4 +70,4 @@ Done when every public item in scope has been checked against every rule, with i For Rust techniques at each rung (newtypes, typestate, sealed traits, const generics, withheld traits, compile-fail tests, the assumptions behind "if it compiles, it is secure"), read [RUST.md](RUST.md). -In Rust, the vitaminc crates provide ready-made types for rules 3, 4 and 5: secret wrappers, randomness, encryption, key wrapping and keyed hashing. Reach for them before writing your own. The `vitaminc` skill shows how to use them. That skill is in the vitaminc repository, at `.claude/skills/vitaminc/`. It is not installed here. +In Rust, the vitaminc crates provide ready-made types for rules 3, 4 and 5: secret wrappers, randomness, encryption, key wrapping and keyed hashing. Reach for them before writing your own. The `vitaminc` skill shows how to use them. It is installed here, at `.claude/skills/vitaminc/`. diff --git a/.claude/skills/vitaminc/RECIPES.md b/.claude/skills/vitaminc/RECIPES.md new file mode 100644 index 000000000..5701ae62f --- /dev/null +++ b/.claude/skills/vitaminc/RECIPES.md @@ -0,0 +1,287 @@ +# vitaminc recipes + +One recipe per task. Each is complete, compiles, and is the production path: copy it as written. Imports use the individual crates; with the facade crate, `vitaminc_protected::X` is `vitaminc::protected::X`, and so on. + +## Hold a secret + +Wrap the secret the moment it exists, and keep it wrapped until the last call that needs it. + +```rust +use std::env::VarError; +use vitaminc_protected::{Controlled, Protected}; +use zeroize::Zeroize; + +/// Says that the token could not be read, and nothing about its value. +#[derive(Debug)] +pub struct TokenUnavailable; + +/// Read a token from the environment straight into a `Protected`. `VarError` +/// holds the raw value when it is not Unicode, so it is wiped here and never returned. +fn api_token() -> Result, TokenUnavailable> { + Protected::generate_ok(|| match std::env::var("API_TOKEN") { + Ok(token) => Ok(token), + Err(VarError::NotPresent) => Err(TokenUnavailable), + Err(VarError::NotUnicode(raw)) => { + raw.into_encoded_bytes().zeroize(); + Err(TokenUnavailable) + } + }) +} + +/// Transform without unwrapping. The closure owns the bare value, so it returns +/// it (here as bytes, in the same allocation) rather than dropping it unwiped. +fn token_bytes(token: Protected) -> Protected> { + token.map(String::into_bytes) +} + +/// To read a value without taking it, borrow it. The wrapper keeps ownership +/// and still wipes the token when it is dropped. +fn token_len(token: &Protected) -> usize { + token.risky_ref().len() +} + +/// At the boundary to an API that takes a plain `&str`, borrow with `risky_ref`. +/// Keep the borrow inside one call, never store it. +fn send(token: &Protected, client: impl Fn(&str)) { + client(token.risky_ref()); +} +``` + +## Compare secrets + +`Protected` has no `PartialEq`. Compare through `Equatable`, which is constant-time. + +```rust +use vitaminc_protected::{Equatable, Protected}; + +fn tag_matches( + presented: &Equatable>, + expected: &Equatable>, +) -> bool { + presented == expected +} + +let a: Equatable> = Equatable::new([7; 32]); +let b: Equatable> = Equatable::new([7; 32]); +assert!(tag_matches(&a, &b)); +``` + +## Generate random values + +```rust +use vitaminc_protected::Protected; +use vitaminc_random::{Generatable, RandomError, SafeRand}; + +fn random_secret() -> Result, RandomError> { + let mut rng = SafeRand::from_entropy()?; + Protected::random(&mut rng) +} + +/// A uniform index in `0..len`, for choosing from a list. `next_below` panics on a +/// zero bound, since `0..0` has nothing to draw, so an empty list is refused here. +fn random_index(rng: &mut SafeRand, len: u32) -> Option { + (len > 0).then(|| rng.next_below(len)) +} +``` + +Derive `Generatable` to generate a whole struct of random fields: + +```rust +use vitaminc_protected::Protected; +use vitaminc_random::{Generatable, RandomError, SafeRand}; + +#[derive(Generatable)] +struct SessionSecrets { + signing: Protected<[u8; 32]>, + encryption: Protected<[u8; 32]>, +} + +fn new_session() -> Result { + SessionSecrets::random(&mut SafeRand::from_entropy()?) +} +``` + +## Generate a password + +Use the `vitaminc-password` types. Each draws its characters uniformly and holds them wrapped. The length is a const generic, and a length below the type's minimum fails compilation. `generate` gives the minimum length; `random` with a `SafeRand` gives any longer one. + +```rust +use vitaminc_password::{AlphaNumericPassword, RandomError}; +use vitaminc_protected::Protected; +use vitaminc_random::{Generatable, SafeRand}; + +/// 22 letters and digits, about 131 bits. +fn new_password() -> Result, RandomError> { + Ok(AlphaNumericPassword::generate()?.into_protected_string()) +} + +/// A longer password, for a service account. +fn new_service_password(rng: &mut SafeRand) -> Result, RandomError> { + Ok(AlphaNumericPassword::<32>::random(rng)?.into_protected_string()) +} +``` + +## Encrypt a value or a struct + +Build the cipher at startup from a key that outlives the process (see "Wrap a data key" below), and pass it to every call. `Aes256Cipher` is not `Sync`, so build one per thread or task from the same key rather than sharing one across threads. A key generated inside the function that encrypts is lost when it returns, and so is everything sealed under it. Encrypt under associated data (AAD) naming the record the ciphertext belongs to. Decryption must present the same AAD, so a ciphertext copied onto another record fails to open. Nonces are generated for you. + +Describe the AAD with a type of your own that implements `IntoContext`, as `UserRecord` does below, and pass it at both sites. The write and the read then cannot disagree, and the parts are encoded unambiguously. `encrypt` also accepts a bare `&str`, so `""`, a typo or a value copied from another record compiles; the type is what stops that. + +Each sealed leaf (each encrypted field, each sequence element) draws a random 96-bit nonce, and nothing counts them. Keep the leaves sealed under one key, across every cipher instance and restart, well below 2³², and rotate to a new data key before that (see "Wrap a data key" below). + +```rust +use vitaminc_aead::{ContextPiece, IntoContext}; +use vitaminc_encrypt::{ + decrypt, encrypt, Aes256Cipher, AesCipherText, DecodeError, Decrypt, DecryptError, Encrypt, + EncryptError, Unspecified, +}; + +/// The record a user ciphertext belongs to. The one place its AAD is spelled. +struct UserRecord(u64); + +impl<'a> IntoContext<'a> for UserRecord { + fn into_context(self) -> ContextPiece<'a> { + ("users", self.0).into_context() + } +} + +#[derive(Encrypt, Decrypt)] +struct User { + #[aead(passthrough)] // stored in the clear: only for non-sensitive fields + id: u64, + email: String, + date_of_birth: String, +} + +/// Seal a user for storage. `cipher` is built at startup, one per thread or task. +fn seal_user(cipher: &Aes256Cipher, user: &User) -> Result> { + encrypt(user, cipher, UserRecord(user.id)) +} + +/// Open the record stored under `id`. Take `id` from the lookup, not from the stored +/// value: the passthrough copy is unauthenticated. Under another record's id this fails. +fn open_user( + cipher: &Aes256Cipher, + id: u64, + stored: AesCipherText, +) -> Result> { + decrypt(cipher, stored, UserRecord(id)) +} +``` + +To encrypt a single secret, pass the `Protected` itself. It is walked inside the wrapper and decrypts back into one. The AAD has no id, so a unit type names the one place the value lives: + +```rust +use vitaminc_aead::{ContextPiece, IntoContext}; +use vitaminc_encrypt::{ + decrypt, encrypt, Aes256Cipher, AesCipherText, DecodeError, DecryptError, EncryptError, + Unspecified, +}; +use vitaminc_protected::Protected; + +/// The one stored GitHub integration token. The one place its AAD is spelled. +struct GithubToken; + +impl<'a> IntoContext<'a> for GithubToken { + fn into_context(self) -> ContextPiece<'a> { + ("integrations", "github/token").into_context() + } +} + +fn seal_token(cipher: &Aes256Cipher, token: Protected) -> Result> { + encrypt(token, cipher, GithubToken) +} + +fn open_token( + cipher: &Aes256Cipher, + stored: AesCipherText, +) -> Result, DecryptError> { + decrypt(cipher, stored, GithubToken) +} +``` + +## Wrap a data key under a key-encryption key + +Generate the data key once, when its owner (a tenant, a table) is created, and store only the wrapped form. At every startup, unwrap it and build the cipher the encrypt recipes take. `kek` is the key-encryption key the service holds for its whole lifetime; it is never generated per call. It is built from 32 bytes held in the secret store, passed straight to `Key::from`. + +Wrap each data key under AAD naming its owner and its version. Under one KEK, a wrapped key copied onto another tenant's record then fails to unwrap rather than opening as that tenant's key. The version is how a tenant rotates: before the leaves sealed under one data key near the nonce budget (see the encrypt recipe), generate version 2, encrypt new values under it, and keep version 1 only to open what it sealed. + +```rust +use vitaminc_aead::{ContextPiece, IntoContext}; +use vitaminc_encrypt::{Aes256Cipher, AesCipherText, Key}; +use vitaminc_random::{Generatable, SafeRand}; + +/// The tenant and version a wrapped data key belongs to. +struct DataKeyOwner<'t> { + tenant_id: &'t str, + version: u32, +} + +impl<'a> IntoContext<'a> for DataKeyOwner<'a> { + fn into_context(self) -> ContextPiece<'a> { + (("tenants/dek", self.tenant_id), self.version).into_context() + } +} + +/// Run at startup, on the root key's bytes fetched from the secret store. `Key` takes a +/// plain array (it has no constructor from `Protected` yet) and wraps it at once: fetch +/// straight into this call, and keep no other copy of the bytes. +fn key_encryption_cipher(root_key: [u8; 32]) -> Result> { + Ok(Aes256Cipher::new(&Key::from(root_key))?) +} + +/// Run once, when the tenant is created. Store the result with the tenant. +fn new_data_key( + kek: &Aes256Cipher, + rng: &mut SafeRand, + owner: DataKeyOwner<'_>, +) -> Result> { + let dek = Key::random(rng)?; + Ok(dek.wrap(kek, owner)?) +} + +/// Run at every startup, on the stored result of `new_data_key` for the same owner. +fn data_cipher( + kek: &Aes256Cipher, + owner: DataKeyOwner<'_>, + wrapped: AesCipherText, +) -> Result> { + let dek = Key::from_wrapped(kek, wrapped, owner)?; + Ok(Aes256Cipher::new(&dek)?) +} +``` + +## Keyed hash, blind index, or equality term + +An unkeyed hash of a low-entropy value (an email, a phone number) is reversible by guessing. Derive a keyed term instead, under a context naming the index and its version; `nonempty!` refuses an empty context at compile time. Writes and queries must use the same input type and context. The key is what makes the terms unguessable, so it is generated once, kept in the secret store, and never written into the source. + +```rust +use vitaminc_hmac::HmacSha256Prf; +use vitaminc_prf::{PrfKeyInit, PrfValue}; +use vitaminc_protected::{nonempty, Protected}; +use vitaminc_random::{Generatable, RandomError, SafeRand}; + +/// Run once, when the index is created. Put the result in the secret store. +fn new_index_key(rng: &mut SafeRand) -> Result, RandomError> { + Protected::random(rng) +} + +/// Run at startup, on the key bytes as the secret store's read returns them, already wrapped. +fn index_key_from_secret_store( + bytes: Protected>, +) -> Result> { + // Rejects keys shorter than the minimum length instead of deriving weak terms. + Ok(HmacSha256Prf::try_from_bytes(bytes)?) +} + +async fn email_term(prf: &HmacSha256Prf, email: &str) -> Result<[u8; 32], Box> { + Ok(email.prf_with_context(prf, nonempty!("users/email/exact/v1")).await?) +} + +// The index's first run: a fresh key, keyed directly. Later runs load it instead. +let mut rng = SafeRand::from_entropy().unwrap(); +let prf = HmacSha256Prf::new(new_index_key(&mut rng).unwrap()); +let a = futures::executor::block_on(email_term(&prf, "ada@example.com")).unwrap(); +let b = futures::executor::block_on(email_term(&prf, "ada@example.com")).unwrap(); +assert_eq!(a, b); +``` diff --git a/.claude/skills/vitaminc/SKILL.md b/.claude/skills/vitaminc/SKILL.md new file mode 100644 index 000000000..800aac904 --- /dev/null +++ b/.claude/skills/vitaminc/SKILL.md @@ -0,0 +1,67 @@ +--- +name: vitaminc +description: Using the vitaminc Rust crates for secrets and cryptography. Use when Rust code holds keys, passwords, tokens or other secrets; generates random values or passwords; encrypts or decrypts values or structs; wraps keys; derives keyed hashes or searchable index terms; or compares secrets. +--- + +# vitaminc + +Internal skill. It lives in `.claude/skills/` on purpose: `skills/` ships to customers inside the `stash` tarball, and this skill must not. + +This skill is a copy. The source is `.claude/skills/vitaminc/` in [cipherstash/vitaminc](https://github.com/cipherstash/vitaminc), at commit `5dbbafaa1` on `main` (24 November 2026). `RECIPES.md` is unchanged. `SKILL.md` differs in this note only. To update the copy, copy the two files again, then restore this note. Propose a change to a rule or a recipe in vitaminc, not here, so the two copies stay the same. + +vitaminc is a suite of Rust crates that replace common cryptography footguns with types. When Rust code touches a secret, use the vitaminc type for the job instead of a raw value or a hand-rolled routine. + +The compiler then checks the code under three assumptions. There is no `unsafe`. Every `risky_*` call is one the project has listed and reviewed. No `#[allow]` disables the lints that enforce this. Outside those assumptions the reviewer is checking again, not the compiler. + +For the reasoning behind these types, and for designing APIs of your own, see the `misuse-resistance` skill. + +## Install + +Use the facade crate with a feature per capability, and import through it (`vitaminc::protected::Protected`): + +```sh +cargo add vitaminc --features protected,random,encrypt,context +``` + +Or add individual crates (`cargo add vitaminc-protected`). All crates release together under one version. Deriving `Encrypt`/`Decrypt` also needs a direct `vitaminc-aead` dependency, because the generated code names that crate. + +## Task map + +| Task | Use | In place of | +|---|---|---| +| Hold a key, token, password or other secret | `Protected` (`protected`) | `String`, `Vec`, `[u8; N]`, `Zeroizing` | +| Hold a key for the whole process | `Locked` (`protected`) | a `static` or lazily initialised byte array | +| Compare secrets or tags | `Equatable>`, `TimingSafeEq` (`protected`) | `==` | +| Hash secret input | `ProtectedDigest` (`protected`) | a digest fed raw secret bytes | +| Require a non-empty label or context | `NonEmpty`, `nonempty!` (`protected`) | `&str` | +| Generate random bytes, keys or structs | `SafeRand` + `Generatable` (`random`) | `rand::thread_rng`, `rand::random` | +| Pick a random index | `SafeRand::next_below` (`random`) | `rng.gen::() % n` | +| Generate a password | `Password`, `AlphaNumericPassword`, `AlphaPassword` + `into_protected_string` (`password`) | `rand`'s `Alphanumeric` sampler, or characters drawn by hand | +| Encrypt a value or struct | `encrypt` / `decrypt`, `Aes256Cipher`, `#[derive(Encrypt, Decrypt)]` (`encrypt`) | an AEAD crate with nonces managed by hand | +| Name what a ciphertext or index term belongs to | a type of your own implementing `IntoContext` (`context`) | a `format!` string built at each call site | +| Wrap a data key under a key-encryption key | `Key::wrap` / `Key::from_wrapped` (`encrypt`) | encrypting key bytes as ordinary data | +| Keyed hash, blind index, equality term | `HmacSha256Prf` + `PrfValue::prf_with_context` (`hmac`, `prf`) | an unkeyed hash, or HMAC with no context | +| HMAC with the key held in AWS KMS | `AwsKmsHmac` (`aws-kms`) | fetching the key into process memory | +| Order-revealing or normalised index terms | `vitaminc-ore`, `vitaminc-normalize` (`ore`, `normalize`) | encoding values for comparison by hand | + +Working code for each common task is in [RECIPES.md](RECIPES.md). Read the recipe before writing the code, and copy it as written. For rows without a recipe, read the crate's docs on docs.rs. + +## Rules + +- **Wrap at the source.** A secret becomes `Protected` the moment it is read or generated (`Protected::generate_ok`, `Protected::random`) and stays wrapped until the last call that needs it. Transform it with `map`, `zip` and `flatten`, which keep the result wrapped. Their closures receive the bare value and own it: return it, or something that still holds it, rather than dropping it inside the closure, where nothing wipes it. To read a value without taking it, borrow with `risky_ref` while the wrapper keeps ownership, and the wrapper still wipes it on drop. +- **Unwrap only at a boundary.** `risky_unwrap` hands the plain value to code outside vitaminc, along with the duty to wipe it and keep it out of logs. Use it only at the call into an external API that must own the value. Prefer `risky_ref` there, kept inside that one call. +- **Errors carry no secret.** An error from the code that reads a secret may hold the value (`std::env::VarError::NotUnicode` holds the raw variable). Map it to an error of your own that says nothing about the value before it can reach a log. +- **Bind every ciphertext to its place.** Pass associated data naming what the ciphertext belongs to as the third argument to `encrypt` and `decrypt`, and spell it as a type: one newtype per kind of record, implementing `IntoContext`, that names the record and carries its id (see the encrypt recipe). The write and the read then cannot disagree, and a ciphertext moved to another record fails to open. `()` is for values that truly belong nowhere. The parameter also accepts a bare `&str`, so `""`, a typo, or a value copied from another record all compile. That is a gap in vitaminc, not a design choice: never pass a string. +- **Name every derivation.** Give `prf_with_context` a context naming the index and its version, checked non-empty at compile time with `nonempty!("users/email/exact/v1")`, and use the same input type and context for writes and for queries. +- **Keys come from a generator, an unwrap or the secret store**: generate a data key once with `Key::random(&mut SafeRand)`, store it wrapped, and load it with `Key::from_wrapped`. The root key-encryption key is the one key built from bytes: fetch its 32 bytes from the secret store at startup and pass them straight to `Key::from`, keeping no other copy. No vitaminc API fetches an AES key from a KMS (`AwsKmsHmac` computes HMACs only), so the secret store is the caller's code. A key written into the source, such as `Key::from([0u8; 32])`, is a test fixture. Rule 3 of `misuse-resistance` says key loading is the library's job, so the caller-written secret store and `Key::from` taking a plain array are both gaps in vitaminc, not design choices. +- **Rotate before the nonce budget runs out.** `Aes256Cipher` draws a random 96-bit nonce for every sealed leaf (each encrypted field and each sequence element), and nothing counts them. Keep the leaves sealed under one key, across every cipher instance and restart, well below 2³² (NIST SP 800-38D). Past that, the chance of a repeated nonce is no longer negligible, and a repeat under AES-GCM exposes plaintext and the authentication key. Give each tenant or table its own data key, version it (`dek/1`, `dek/2`), and wrap a new one before the count gets close. +- **Log the error kind, never the value.** Cipher failures are deliberately the opaque `Unspecified`: a wrong key, a wrong AAD and a tampered ciphertext look the same. + +## Behaviour to know + +- `#[aead(passthrough)]` stores a field in the clear by design: it is neither encrypted nor authenticated, so it can be read, edited or removed in storage while every encrypted field beside it still decrypts. Use it only for non-sensitive fields, treat what it returns as untrusted input, and never let it decide authorization, tenancy or which record to trust. A value that must be readable but tamper-evident belongs in the associated data. +- In an encrypted sequence, each element is bound to the sequence but not to its index, and the element count is not authenticated. If order or completeness matters, put it in the value or the associated data. +- `Aes256Cipher` is not `Sync` (its nonce generator is a `RefCell`). Build one per thread or per task rather than sharing one. +- `Protected` is never `Copy`. Duplicate it with an explicit `clone()`; each clone is wiped when dropped. +- `Locked` is best-effort by default: when the OS refuses to lock memory, the value still exists and `lock_error()` says why. Call `require_locked()`, or set `LockPolicy::Strict` at startup, when locking is mandatory. +- `vitaminc-password` types hold their characters in a `Protected` array and have no `Display`, equality or raw constructor. `into_protected_string` exports a `Protected`, allocated once at full length so no unwiped copy is left behind. `into_unprotected_string` returns a plain `String` that nothing wipes: use it only where an external API must own one. The length is a const generic with a minimum (20, 22 or 23 by alphabet) that fails compilation below it. diff --git a/AGENTS.md b/AGENTS.md index 9065c2333..c5df4dad6 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -870,6 +870,23 @@ ways a rule can be enforced, from "impossible to get wrong" down to ciphertext. The skill is a copy from `cipherstash/vitaminc`. Its first section says which commit it was copied from, and how to update it. +### vitaminc + +Read `.claude/skills/vitaminc/SKILL.md` before you write or review Rust that +holds a key, a token, a plaintext or another secret. That covers the stack-* +crates, the Go guests and every language binding crate. The skill maps each +task to the vitaminc type for it, such as `Protected` in place of a +`String`, and `RECIPES.md` beside it has working code. It is a copy from +`cipherstash/vitaminc`, and its first section says how to update it. + +Two rules the skill does not state yet: + +- A type that holds a secret derives `OpaqueDebug` (`vitaminc-protected`), + as `ValueFrame` in `packages/stack-encrypt/src/dynamic/value_frame.rs` + does. Do not write `impl Debug` by hand to hide a value. +- Use a type the engine or vitaminc already has before you wrap it in a new + one. + ## Designing a language SDK Read [`docs/sdk-design-principles.md`](docs/sdk-design-principles.md) before you From 7e533fb20dc869fd977525cabfc67809f6122bb0 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sun, 29 Nov 2026 02:41:28 +1100 Subject: [PATCH 2/3] docs(agents): say where the vitaminc recipes need changes in this repo The vitaminc recipes are written for vitaminc 0.10 and its individual crates. In this repository they do not compile as written: - protect-ffi pins vitaminc 0.1.0-pre4.2, and that version lacks some items the recipes use. - The Go encrypt guest takes vitaminc only through stack-encrypt. - The root workspace has the facade crate but not vitaminc-random or vitaminc-password. - Two recipes end with statements outside a function. AGENTS.md now lists each change a recipe needs, and leaves the copied files as they are. The OpaqueDebug example now names JsonChildPlaintext. ValueFrame is deleted on next, so the old example would point at nothing after merge. The misuse-resistance copy now takes upstream's last line word for word. That line is true here once the vitaminc skill is installed. The note at the top names commit 5dbbafaa1, the same commit as the vitaminc copy, and says the copy differs in the note only. --- .claude/skills/misuse-resistance/SKILL.md | 4 +-- AGENTS.md | 38 +++++++++++++++++++---- 2 files changed, 34 insertions(+), 8 deletions(-) diff --git a/.claude/skills/misuse-resistance/SKILL.md b/.claude/skills/misuse-resistance/SKILL.md index 22a88f4d5..5d2996021 100644 --- a/.claude/skills/misuse-resistance/SKILL.md +++ b/.claude/skills/misuse-resistance/SKILL.md @@ -7,7 +7,7 @@ description: Misuse-resistant API design for cryptography and sensitive data. Us Internal skill. It lives in `.claude/skills/` on purpose: `skills/` ships to customers inside the `stash` tarball, and this skill must not. -This skill is a copy. The source is `.claude/skills/misuse-resistance/` in [cipherstash/vitaminc](https://github.com/cipherstash/vitaminc), at commit `06861c1b9` on `main` (17 November 2026). `RUST.md` and `EVIDENCE.md` are unchanged. `SKILL.md` differs in this note and in its last section. To update the copy, copy the three files again, then restore this note and the last section. Propose a change to a rule in vitaminc, not here, so the two copies stay the same. +This skill is a copy. The source is `.claude/skills/misuse-resistance/` in [cipherstash/vitaminc](https://github.com/cipherstash/vitaminc), at commit `5dbbafaa1` on `main` (24 November 2026). `RUST.md` and `EVIDENCE.md` are unchanged. `SKILL.md` differs in this note only. To update the copy, copy the three files again, then restore this note. Propose a change to a rule in vitaminc, not here, so the two copies stay the same. A **footgun** is an API whose obvious use is insecure. Most cryptographic failures are footguns fired at the call site: in one study, 83% of crypto CVEs were applications misusing correct libraries. That count covers only CVEs tagged as cryptographic, so library bugs filed under other tags, such as Heartbleed, are outside it. The people firing them, developers and coding agents alike, optimise for code that works, copy examples verbatim, and rate their insecure code as secure. Security therefore has to come from the API itself: the shortest path that works must be the secure path. @@ -70,4 +70,4 @@ Done when every public item in scope has been checked against every rule, with i For Rust techniques at each rung (newtypes, typestate, sealed traits, const generics, withheld traits, compile-fail tests, the assumptions behind "if it compiles, it is secure"), read [RUST.md](RUST.md). -In Rust, the vitaminc crates provide ready-made types for rules 3, 4 and 5: secret wrappers, randomness, encryption, key wrapping and keyed hashing. Reach for them before writing your own. The `vitaminc` skill shows how to use them. It is installed here, at `.claude/skills/vitaminc/`. +In Rust, the `vitaminc` skill provides ready-made types for rules 3, 4 and 5: secret wrappers, randomness, encryption, key wrapping and keyed hashing. Reach for them before writing your own. diff --git a/AGENTS.md b/AGENTS.md index c5df4dad6..f6cd769f8 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -873,16 +873,42 @@ section says which commit it was copied from, and how to update it. ### vitaminc Read `.claude/skills/vitaminc/SKILL.md` before you write or review Rust that -holds a key, a token, a plaintext or another secret. That covers the stack-* -crates, the Go guests and every language binding crate. The skill maps each -task to the vitaminc type for it, such as `Protected` in place of a -`String`, and `RECIPES.md` beside it has working code. It is a copy from +has a key, a token, a plaintext, or another secret. That covers the stack-* +crates, the Go guests, and every language binding crate. The skill maps each +task to its vitaminc type, such as `Protected` in place of a `String`. +`RECIPES.md` beside it has working code. The skill is a copy from `cipherstash/vitaminc`, and its first section says how to update it. +The recipes are written for vitaminc 0.10 and its individual crates. Two +places in this repository differ: + +- **protect-ffi** pins `vitaminc = "=0.1.0-pre4.2"`, in + `languages/typescript/packages/protect-ffi/crates/protect-ffi/Cargo.toml`. + Some recipes use items that version does not have, such as + `SafeRand::next_below`. Do not copy a recipe into protect-ffi until that + pin moves to 0.10. +- **The Go encrypt guest** (`languages/golang/encrypt/guest`) has no vitaminc + dependency of its own. The guest takes vitaminc through `stack-encrypt`'s + re-exports, so it cannot build against a second vitaminc. Do not add one. + +In the root Cargo workspace, a recipe needs these changes before it compiles: + +- The workspace has the `vitaminc` facade crate but no direct + `vitaminc-random` or `vitaminc-password`. Write `vitaminc::random::X` for + `vitaminc_random::X`. +- The password recipe needs the facade's `password` feature. The workspace + does not turn it on. Adding it is a dependency change to review. +- `#[derive(Generatable)]` needs `vitaminc-random` as a direct dependency, + because the code it generates names that crate. +- `futures::executor::block_on` needs the `executor` feature of `futures`. + `stack-encrypt` and `stack-guest-abi` build `futures` without it. +- The "Compare secrets" and "Keyed hash" recipes end with statements outside + any function. Put those lines in a function or a `#[test]`. + Two rules the skill does not state yet: -- A type that holds a secret derives `OpaqueDebug` (`vitaminc-protected`), - as `ValueFrame` in `packages/stack-encrypt/src/dynamic/value_frame.rs` +- A type with a secret in it derives `OpaqueDebug` (`vitaminc-protected`), + as `JsonChildPlaintext` in `packages/stack-encrypt/src/json/plaintext.rs` does. Do not write `impl Debug` by hand to hide a value. - Use a type the engine or vitaminc already has before you wrap it in a new one. From f223efe15f4c54017cac3b7a44084a4c2b90c4dc Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sun, 29 Nov 2026 13:00:42 +1100 Subject: [PATCH 3/3] refactor(stack-kms,stack-encrypt): derive OpaqueDebug in place of hand-written Debug AGENTS.md says a type with a secret in it derives vitaminc's OpaqueDebug. Five types did not: - OpaqueBlob and JsonPlaintext in stack-encrypt wrote Debug by hand. - DataKey, DataKeyWithTag, and the test-support DeterministicSource in stack-kms used the opaque-debug crate. Each now derives OpaqueDebug. The derive masks every field with "***". No field is marked non_sensitive, so no Debug bound is added to T, and the text shows no value, key byte, or seed. The text now starts with the type's full path, as the other derived types' text does. Each type has a test that pins its Debug text. stack-kms no longer depends on opaque-debug. The six Cargo.lock files that list stack-kms drop it. AGENTS.md now says when a hand-written Debug is still right: to show a count or a length. The derive cannot show either. --- AGENTS.md | 8 +++-- Cargo.lock | 1 - languages/golang/encrypt/guest/Cargo.lock | 1 - .../packages/recipher-js/Cargo.lock | 1 - packages/eql/Cargo.lock | 1 - packages/stack-encrypt/CHANGELOG.md | 7 ++++ packages/stack-encrypt/fuzz/Cargo.lock | 1 - packages/stack-encrypt/src/blob.rs | 19 +++++------ packages/stack-encrypt/src/json/plaintext.rs | 16 ++++----- .../stack-encrypt/tests/json_plaintext.rs | 5 ++- packages/stack-encrypt/tests/opaque_blob.rs | 9 +++-- packages/stack-kms/CHANGELOG.md | 5 +++ packages/stack-kms/Cargo.toml | 1 - packages/stack-kms/fuzz/Cargo.lock | 1 - packages/stack-kms/src/key.rs | 34 +++++++++++++++---- packages/stack-kms/src/key_source.rs | 17 ++++++++-- 16 files changed, 85 insertions(+), 42 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 9d5c90339..808976386 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -970,8 +970,12 @@ In the root Cargo workspace, a recipe needs these changes before it compiles: Two rules the skill does not state yet: - A type with a secret in it derives `OpaqueDebug` (`vitaminc-protected`), - as `JsonChildPlaintext` in `packages/stack-encrypt/src/json/plaintext.rs` - does. Do not write `impl Debug` by hand to hide a value. + as `DataKey` in `packages/stack-kms/src/key.rs` and `JsonPlaintext` in + `packages/stack-encrypt/src/json/plaintext.rs` do. Do not write + `impl Debug` by hand to hide a value. The derive masks a field or, with + `#[non_sensitive]`, shows it as it is. Write `Debug` by hand only to show + something the derive cannot, such as a count or a length. That text must + still show no secret. - Use a type the engine or vitaminc already has before you wrap it in a new one. diff --git a/Cargo.lock b/Cargo.lock index 5e06a5f09..92f76e597 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3725,7 +3725,6 @@ dependencies = [ "futures", "lazy_static", "miette", - "opaque-debug", "proptest", "reqwest", "rustls", diff --git a/languages/golang/encrypt/guest/Cargo.lock b/languages/golang/encrypt/guest/Cargo.lock index 5685011cb..f9e6fc4dc 100644 --- a/languages/golang/encrypt/guest/Cargo.lock +++ b/languages/golang/encrypt/guest/Cargo.lock @@ -2344,7 +2344,6 @@ dependencies = [ "blake3", "futures", "miette", - "opaque-debug", "serde", "serde_cbor", "serde_json", diff --git a/languages/typescript/packages/recipher-js/Cargo.lock b/languages/typescript/packages/recipher-js/Cargo.lock index 2f2ed3116..0bf7ce4ff 100644 --- a/languages/typescript/packages/recipher-js/Cargo.lock +++ b/languages/typescript/packages/recipher-js/Cargo.lock @@ -3170,7 +3170,6 @@ dependencies = [ "futures", "lazy_static", "miette", - "opaque-debug", "reqwest", "rustls", "serde", diff --git a/packages/eql/Cargo.lock b/packages/eql/Cargo.lock index 019d803cb..58d74f867 100644 --- a/packages/eql/Cargo.lock +++ b/packages/eql/Cargo.lock @@ -4274,7 +4274,6 @@ dependencies = [ "blake3", "futures", "miette", - "opaque-debug", "serde", "serde_cbor", "serde_json", diff --git a/packages/stack-encrypt/CHANGELOG.md b/packages/stack-encrypt/CHANGELOG.md index ca0482d82..35c019e45 100644 --- a/packages/stack-encrypt/CHANGELOG.md +++ b/packages/stack-encrypt/CHANGELOG.md @@ -1697,6 +1697,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed +- **The `Debug` text of `OpaqueBlob` and `JsonPlaintext` has changed.** + Both types now derive vitaminc's `OpaqueDebug`, as the crate's other + secret types do. The text starts with the type's full path and masks the + value with `"***"`: `stack_encrypt::json::plaintext::JsonPlaintext("***")`, + for example. The text was `OpaqueBlob(***)` and + `JsonPlaintext()`. Neither text shows the value. + - **A write converts a value to its field's type, as a query does.** A data plan's typed field now reads each value it seals by the rules `dynamic::read` reads a query's input by. A number of another width or diff --git a/packages/stack-encrypt/fuzz/Cargo.lock b/packages/stack-encrypt/fuzz/Cargo.lock index b8175032e..cfdf3936a 100644 --- a/packages/stack-encrypt/fuzz/Cargo.lock +++ b/packages/stack-encrypt/fuzz/Cargo.lock @@ -2262,7 +2262,6 @@ dependencies = [ "blake3", "futures", "miette", - "opaque-debug", "serde", "serde_cbor", "serde_json", diff --git a/packages/stack-encrypt/src/blob.rs b/packages/stack-encrypt/src/blob.rs index cd6c8f2b6..c3977a49e 100644 --- a/packages/stack-encrypt/src/blob.rs +++ b/packages/stack-encrypt/src/blob.rs @@ -384,13 +384,11 @@ //! [`Ciphertext`]: crate::Ciphertext //! [`SealedValue`]: crate::SealedValue -use std::fmt; - use recipher_frame::serde::PathSegment; use recipher_frame::storage::{self, ErrorKind}; use serde::de::{DeserializeOwned, Deserializer}; use serde::{Deserialize, Serialize}; -use vitaminc_protected::{AsProtectedRef, Buffer, Controlled, Protected}; +use vitaminc_protected::{AsProtectedRef, Buffer, Controlled, OpaqueDebug, Protected}; use zeroize::{Zeroize, Zeroizing}; use crate::scalar::sealed; @@ -423,7 +421,7 @@ pub const VERSION: u8 = storage::VERSION; /// so that a blob is never written by accident where a `T` was meant. /// /// [`into_inner`]: OpaqueBlob::into_inner -#[derive(Clone, PartialEq, Eq, Default)] +#[derive(Clone, PartialEq, Eq, Default, OpaqueDebug)] pub struct OpaqueBlob(Zeroizing); impl OpaqueBlob { @@ -455,12 +453,6 @@ impl From for OpaqueBlob { } } -impl fmt::Debug for OpaqueBlob { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.write_str("OpaqueBlob(***)") - } -} - impl Zeroize for OpaqueBlob { fn zeroize(&mut self) { self.0.zeroize(); @@ -760,7 +752,12 @@ mod tests { left: "secret".into(), right: 7, }); - assert_eq!(format!("{blob:?}"), "OpaqueBlob(***)"); + let shown = format!("{blob:?}"); + assert_eq!( + shown, + format!("{}(\"***\")", std::any::type_name::>()) + ); + assert!(!shown.contains("secret"), "{shown}"); } #[test] diff --git a/packages/stack-encrypt/src/json/plaintext.rs b/packages/stack-encrypt/src/json/plaintext.rs index f925f8325..00507d7f6 100644 --- a/packages/stack-encrypt/src/json/plaintext.rs +++ b/packages/stack-encrypt/src/json/plaintext.rs @@ -1,7 +1,5 @@ //! A JSON document as a plaintext: [`JsonPlaintext`]. -use std::fmt; - use serde_json::Value; use vitaminc_aead::plaintext::{depth, Error as _, Scalar, SourceError}; use vitaminc_aead::{FixedType, FromScalar, Logical, Physical, Sink}; @@ -164,6 +162,7 @@ use crate::Encrypt; /// [`value`](Self::value) returns. /// /// [`KeysetCipher::encrypt`]: crate::KeysetCipher::encrypt +#[derive(OpaqueDebug)] pub struct JsonPlaintext(Value); impl JsonPlaintext { @@ -225,12 +224,6 @@ impl Drop for JsonPlaintext { impl ZeroizeOnDrop for JsonPlaintext {} -impl fmt::Debug for JsonPlaintext { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.write_str("JsonPlaintext()") - } -} - /// One child of a JSON node, decrypted: its value, and its key or index in /// its parent. Decrypt a [`JsonChild`](super::JsonChild) into this type when /// your app needs to know which child each value is. @@ -613,7 +606,12 @@ mod tests { #[test] fn debug_never_shows_the_document() { let document = JsonPlaintext::from(json!({"secret": "hunter2"})); - assert_eq!(format!("{document:?}"), "JsonPlaintext()"); + let shown = format!("{document:?}"); + assert_eq!( + shown, + r#"stack_encrypt::json::plaintext::JsonPlaintext("***")"# + ); + assert!(!shown.contains("hunter2"), "{shown}"); } mod given_an_opened_child { diff --git a/packages/stack-encrypt/tests/json_plaintext.rs b/packages/stack-encrypt/tests/json_plaintext.rs index 002cc6151..c16fff6dd 100644 --- a/packages/stack-encrypt/tests/json_plaintext.rs +++ b/packages/stack-encrypt/tests/json_plaintext.rs @@ -374,7 +374,10 @@ mod given_a_plaintext_to_clean_up { #[test] fn debug_shows_none_of_the_document() { let shown = format!("{:?}", JsonPlaintext::from(profile())); - assert_eq!(shown, "JsonPlaintext()"); + assert_eq!( + shown, + r#"stack_encrypt::json::plaintext::JsonPlaintext("***")"# + ); } } diff --git a/packages/stack-encrypt/tests/opaque_blob.rs b/packages/stack-encrypt/tests/opaque_blob.rs index eb6fcc655..deac81eb4 100644 --- a/packages/stack-encrypt/tests/opaque_blob.rs +++ b/packages/stack-encrypt/tests/opaque_blob.rs @@ -1296,11 +1296,16 @@ mod given_a_decrypted_blob { #[tokio::test] async fn debug_and_refusals_show_no_plaintext() { let blob = OpaqueBlob::new(ada()); + let shown = format!("{blob:?}"); assert_eq!( - format!("{blob:?}"), - "OpaqueBlob(***)", + shown, + format!("{}(\"***\")", std::any::type_name::>()), "Debug should hide the value" ); + assert!( + !shown.contains("Ada"), + "Debug should hide the value: {shown}" + ); let cipher = common::stack_cipher().await; let keyset = cipher.default_keyset(); diff --git a/packages/stack-kms/CHANGELOG.md b/packages/stack-kms/CHANGELOG.md index be1e491a2..a01c684c2 100644 --- a/packages/stack-kms/CHANGELOG.md +++ b/packages/stack-kms/CHANGELOG.md @@ -31,6 +31,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed +- `DataKey`, `DataKeyWithTag`, and the test-support `DeterministicSource` + now derive vitaminc's `OpaqueDebug`. The `Debug` text names each field + and masks its value with `"***"`, such as + `stack_kms::key::DataKey { iv: "***", key: "***" }`. It was + `DataKey { ... }`. The crate no longer depends on `opaque-debug`. - A batch now yields to the async runtime every 64 keys while it derives data keys. On tokio, the yield reschedules the task. In a wasm guest, it hands control back to the host. The host cannot preempt the guest. diff --git a/packages/stack-kms/Cargo.toml b/packages/stack-kms/Cargo.toml index 1dba0aa22..1d5fc9d03 100644 --- a/packages/stack-kms/Cargo.toml +++ b/packages/stack-kms/Cargo.toml @@ -71,7 +71,6 @@ zeroize = { workspace = true } base16ct = { version = "0.2.0", features = ["alloc"] } base64ct = { version = "1.7", features = ["alloc"] } futures = "0.3.25" -opaque-debug = "0.3.1" serde_cbor = "0.11.2" serdect = { version = "0.3.0", features = ["zeroize"] } sha2 = "0.10.6" diff --git a/packages/stack-kms/fuzz/Cargo.lock b/packages/stack-kms/fuzz/Cargo.lock index d933e388c..12a36701c 100644 --- a/packages/stack-kms/fuzz/Cargo.lock +++ b/packages/stack-kms/fuzz/Cargo.lock @@ -1953,7 +1953,6 @@ dependencies = [ "blake3", "futures", "miette", - "opaque-debug", "serde", "serde_cbor", "serde_json", diff --git a/packages/stack-kms/src/key.rs b/packages/stack-kms/src/key.rs index 713afb80c..5574af8d9 100644 --- a/packages/stack-kms/src/key.rs +++ b/packages/stack-kms/src/key.rs @@ -83,13 +83,12 @@ impl ClientKey { // `key` is secret DEK material, so equality is constant-time: the `TimingSafeEq` // derive provides `ts_eq` *and* `PartialEq`/`Eq` implemented on top of it, so // `==` is safe here — never add a variable-time `derive(PartialEq)`. -#[derive(TimingSafeEq, Zeroize, ZeroizeOnDrop, Clone)] +#[derive(TimingSafeEq, Zeroize, ZeroizeOnDrop, Clone, OpaqueDebug)] #[cfg_attr(test, derive(Default))] pub struct DataKey { pub iv: Iv, pub key: Key, } -opaque_debug::implement!(DataKey); impl DataKey { /// Create a DataKey for a specific [`ClientKey`] given a specific initialisation vector @@ -130,14 +129,13 @@ impl DataKey { // No `PartialEq`/`Eq` on the wrapper: the `tag` is public but `key` is secret. // If key equality is ever needed, compare `a.key == b.key` (constant-time via // `DataKey`'s `TimingSafeEq`-derived `PartialEq`) or `a.key.ts_eq(&b.key)`. -#[derive(Clone)] +#[derive(Clone, OpaqueDebug)] #[cfg_attr(test, derive(Default))] pub struct DataKeyWithTag { pub key: DataKey, pub tag: Vec, pub decryption_policy: Option, } -opaque_debug::implement!(DataKeyWithTag); impl DataKeyWithTag { /// Create a DataKey for a specific [`ClientKey`] given a specific IV, key material and tag @@ -523,10 +521,32 @@ mod tests { #[test] fn test_opaque_debug_datakey() { let key = DataKey { - iv: [0; 16], - key: [0; 32], + iv: [7; 16], + key: [9; 32], }; - assert_eq!(format!("{key:?}"), "DataKey { ... }"); + let shown = format!("{key:?}"); + assert_eq!( + shown, + r#"stack_kms::key::DataKey { iv: "***", key: "***" }"# + ); + assert!(!shown.contains('7') && !shown.contains('9'), "{shown}"); + } + + #[test] + fn test_opaque_debug_datakey_with_tag() { + let key = super::DataKeyWithTag { + key: DataKey { + iv: [7; 16], + key: [9; 32], + }, + tag: vec![5; 4], + decryption_policy: None, + }; + let shown = format!("{key:?}"); + assert_eq!( + shown, + r#"stack_kms::key::DataKeyWithTag { key: "***", tag: "***", decryption_policy: "***" }"# + ); } #[test] diff --git a/packages/stack-kms/src/key_source.rs b/packages/stack-kms/src/key_source.rs index 186f915d3..311b097b6 100644 --- a/packages/stack-kms/src/key_source.rs +++ b/packages/stack-kms/src/key_source.rs @@ -757,6 +757,7 @@ mod deterministic { use sha2::{Digest, Sha256}; use uuid::Uuid; + use vitaminc::protected::OpaqueDebug; use zerokms_protocol::{ IdentifiedBy, UnverifiedContext, ViturRequestError, ViturRequestErrorKind, }; @@ -787,15 +788,15 @@ mod deterministic { /// /// A test double, not a cipher: the derivation is SHA-256 over /// concatenated parts and models nothing of ZeroKMS beyond determinism. + /// + /// `Debug` shows none of the fields: the seed derives every key. + #[derive(OpaqueDebug)] pub struct DeterministicSource { seed: [u8; 32], counter: AtomicU64, index: FakeDataKeySource, } - // Debug without the seed, which derives every key. - opaque_debug::implement!(DeterministicSource); - impl DeterministicSource { /// A source over `seed`. pub fn new(seed: [u8; 32]) -> Self { @@ -999,6 +1000,16 @@ mod tests { /// descriptor the way ZeroKMS does, as a forbidden request, so the Go /// hermetic suite and the live suite assert one error for a wrong /// context. + #[test] + fn deterministic_source_debug_shows_no_field() { + let src = DeterministicSource::new([7u8; 32]); + let shown = format!("{src:?}"); + assert_eq!( + shown, + r#"stack_kms::key_source::deterministic::DeterministicSource { seed: "***", counter: "***", index: "***" }"# + ); + } + #[tokio::test] async fn deterministic_wrong_descriptor_is_forbidden_not_missing() { use zerokms_protocol::ViturRequestErrorKind;