diff --git a/Cargo.lock b/Cargo.lock index 3f84e775b..a1f237c8b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3465,6 +3465,7 @@ dependencies = [ "rmp-serde", "rust_decimal", "serde", + "serde_derive", "serde_json", "serdect", "sha2 0.11.0", diff --git a/Cargo.toml b/Cargo.toml index 750f78376..73207bd44 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -120,6 +120,10 @@ rustls = { version = "0.23", default-features = false, features = ["std", "tls12 rustls-platform-verifier = "0.6" rustls-webpki = { version = "0.103", default-features = false, features = ["alloc"] } serde = { version = "1.0", features = ["derive"] } +# Named on its own only so a crate can turn on one of its features. +# stack-encrypt turns on `deserialize_in_place`, which every derive in the +# build then writes. +serde_derive = "1.0" serde_json = { version = "1.0.132" } # Constant-time hex (through base16ct) for serde over the order terms. serdect = { version = "0.3", default-features = false, features = ["alloc"] } diff --git a/conformance/stack-encrypt/lifecycle-contract.md b/conformance/stack-encrypt/lifecycle-contract.md index 7c4cef53f..e74af5ce5 100644 --- a/conformance/stack-encrypt/lifecycle-contract.md +++ b/conformance/stack-encrypt/lifecycle-contract.md @@ -12,7 +12,7 @@ process. Python and TypeScript are explicitly not enrolled. |---|---|---| | `lifecycle-ownership-v1` | Actual record operations and owned `Vec` to `Vec` conversions release fulfilment captures exactly once on success, provider failure and unpolled drop; an unpolled encrypt or decrypt makes no key request. Zipped fulfilments do not share key material. An owned `OpaqueBlob` source is wiped before its pending is returned, on success and on an encoding refusal. A decrypted `OpaqueBlob` is wiped once on drop, and the `Zeroizing` its `into_inner` returns is wiped once when it is dropped, not before. | Client keys are consumed/redacted; explicit close and unreachable-client cleanup release guest memory; calls on a closed client fail. GC cleanup is eventual, so callers should close explicitly. | | `lifecycle-cancellation-v1` | Dropping an encrypt future paused in key generation, or a decrypt future paused in key retrieval, drops the provider future and operation captures, for a record operation or an owned collection; subsequent work on the cipher succeeds. Guest ABI abort spends the handle and drops the operation. | Cancellation before a call sends no request; cancellation between steps or during token fetch leaves unrelated operations usable. A guest step that overruns cancellation closes the client. Discarded late output is wiped. | -| `lifecycle-partial-output-v1` | A batch with a valid first row and a later authenticated type mismatch releases its decoded prefix without marked heap residue. Tests check this for the dynamic record path and for the owned `Vec` to `Vec` conversion. For owned collections, drop witnesses are test values that record whether they were wiped. They show that the prefix is wiped, not leaked, after a late failure or an element's panic. The same holds for a column that is a field of a record. For an owned record, a drop witness shows that a field opened before a later field is refused is wiped. Existing context cases reject late authentication failures without returning partial output. An `OpaqueBlob` refused before its first field is built leaves no marked residue; a refusal after some fields are built is the `native-partial-decode-fields` limit below. | Generated and raw batch APIs return no partial rows on failure; interrupted HTTP bodies fail; cancelled output is wiped. SDK conversion diagnostics contain no decrypted values. This does not assert erasure of partially populated caller-owned Go objects. | +| `lifecycle-partial-output-v1` | A batch with a valid first row and a later authenticated type mismatch releases its decoded prefix without marked heap residue. Tests check this for the dynamic record path and for the owned `Vec` to `Vec` conversion. For owned collections, drop witnesses are test values that record whether they were wiped. They show that the prefix is wiped, not leaked, after a late failure or an element's panic. The same holds for a column that is a field of a record. For an owned record, a drop witness shows that a field opened before a later field is refused is wiped. Existing context cases reject late authentication failures without returning partial output. An `OpaqueBlob` refused before its first field is built leaves no marked residue. One refused after some fields are built leaves none either, for a derived struct serde reads in place: the blob is read into a `T::default()` that the refusal wipes. The heap observer checks this for the fields of a struct, the fields of a struct nested in it, and the elements of a sequence stored before the refusal (up to the 1 MiB of elements serde reserves before reading a sequence). A drop witness shows that a field read before a missing field is wiped once. A refusal inside a value serde builds whole is the `native-partial-decode-inside-whole-values` limit below. | Generated and raw batch APIs return no partial rows on failure; interrupted HTTP bodies fail; cancelled output is wiped. SDK conversion diagnostics contain no decrypted values. This does not assert erasure of partially populated caller-owned Go objects. | | `lifecycle-buffer-cleanup-v1` | The existing allocator observer checks selected write/read/JSON parse paths and has a negative control. It also checks an `OpaqueBlob`'s encoded buffer (which regrows while it holds plaintext), its planned leaf and its opened buffer, and for those blob paths that no marked block allocated during the operation is still live at its end (a leak the free-time scan cannot see), with its own negative control. The partial-decode limit is pinned separately and is not enrolled here (see below). One of those paths encrypts an owned `Vec` collection through its guard. Drop witnesses show that an owned collection's source is wiped before its pending request is returned. That includes a refused context, and a context conversion that panics. It also includes the elements after an element whose declaration panics. For an owned record, drop witnesses show that the record wipes the fields it seals, also when the context is refused. When a context is refused, no copy of a sealed plaintext is dropped unwiped. Witnesses check this for a `struct` record, a nested record, a `plaintext` record, a record with a stored context, a column, a `StackCipherText`, a `Vec`, and an `Encrypted`. They also show that the record moves its passthrough fields without copying them, and that a record decrypted into a `Protected` is wiped when the `Protected` is dropped. Guest ABI tests check buffer-registry cleanup, error-buffer release and protected text drop. | Request bodies survive until their owner closes them, then wipe; refused requests wipe; heap growth wipes abandoned backing arrays; guest runtime close releases memory. Post-encryption memory scans are supplementary observations. | | `lifecycle-diagnostics-v1` | Guest errors discard untrusted foreign cause messages; failed/successful exports do not hand over stale diagnostics. | Structured errors remain available after failures; SDK errors and redacted display/logging expose types or fields rather than plaintext values. | | `lifecycle-validation-before-io-v1` | Existing runtime/read/context cases count provider calls. Wrong shape, independently detectable context mismatch and oversized descriptors fail before key I/O; lazy assembly stops after local failure. An `OpaqueBlob` whose `Serialize` refuses requests no key, and an oversized context is refused before the value is encoded; on decrypt the leaf authenticates (one retrieval) before any blob byte is read, and tampering is `Aead` however the bytes would decode. | Host refusals happen before entering the guest, and shared runtime/read cases exercise the uninitialised guest's preflight boundary. Go does not yet expose native provider counters. | @@ -53,16 +53,31 @@ These entries in the index are limitations, not successful requirements: decrypted plaintext can remain in the WASM shadow stack in underlying cipher temporaries. It is not enrolled as passing evidence. The post-encryption scan cannot establish the post-decryption guarantee. -- **`native-partial-decode-fields` — known gap.** - `opaque_blob::a_partial_decode_drops_the_fields_it_built_unwiped` in - `packages/stack-encrypt/tests/heap_hygiene.rs` is a `should_panic` negative - control: a derived `Deserialize` that has built a `String` field of an - `OpaqueBlob` and then refuses a later field drops that field as an - ordinary value, unwiped, because no `T` was constructed to wipe. The opened - buffer the fields were copied from is wiped. This is serde's construction - order, stated in the `blob` module docs; a `T` whose fields wipe on drop - closes it for those fields. It is enrolled as the observation of a limit, - not as passing cleanup evidence. +- **`native-partial-decode-inside-whole-values` — known gap.** + `opaque_blob::given_a_blob_refused_after_fields_are_built::a_refusal_inside_a_sequence_element_drops_what_the_element_built` + in `packages/stack-encrypt/tests/heap_hygiene.rs` is a `should_panic` + negative control, and so is + `opaque_blob::given_a_blob_refused_after_fields_are_built::a_refusal_in_a_struct_the_derive_reads_whole_drops_its_fields`. + An `OpaqueBlob` is read in place, so for most derived structs the + fields are wiped when a later field is refused. serde builds some values + whole and stores them only when they are complete: an element of a + sequence, a map, an `Option`, a `Box`, an enum, a field read with + `deserialize_with`, and a type whose own `Deserialize` impl writes no + `deserialize_in_place`. The derive writes none for a struct marked + `#[serde(transparent)]`, `from` or `try_from`, one with a + `#[serde(flatten)]` field, or one whose every field uses + `deserialize_with`, so such a struct is built whole wherever it appears, + `T` included. A refusal inside any of these drops the parts of it already + built as ordinary values, unwiped. The first control refuses a field of a + sequence's first element after the element's `String` field is built; + the second refuses a later field of a struct a `transparent` wrapper reads + whole. Separately, serde reserves room for at most 1 MiB of a sequence's + elements before reading them, and a longer sequence regrows its buffer + and frees each old one unwiped. The enrollment names each case and the + issue that tracks them (#1754). The opened buffer the parts were copied + from is wiped. The `blob` module docs state this; a part that wipes + itself on drop closes it for that part. It is enrolled as the observation + of a limit, not as passing cleanup evidence. - **`native-heap-observer-exclusions` — limited observation.** `packages/stack-encrypt/tests/heap_hygiene.rs` watches marked frees on the executing thread. Its existing observer excludes a named upstream aws-lc diff --git a/conformance/stack-encrypt/v1/lifecycle-v1.enrollment.json b/conformance/stack-encrypt/v1/lifecycle-v1.enrollment.json index e2c248ada..3abbb42c3 100644 --- a/conformance/stack-encrypt/v1/lifecycle-v1.enrollment.json +++ b/conformance/stack-encrypt/v1/lifecycle-v1.enrollment.json @@ -164,6 +164,8 @@ "a_late_read_type_failure_leaves_no_plaintext_on_the_heap", "a_late_type_failure_in_an_owned_column_leaves_no_plaintext_on_the_heap", "opaque_blob::an_opaque_blob_of_another_shape_leaves_no_plaintext_on_the_heap", + "opaque_blob::given_a_blob_refused_after_fields_are_built::the_fields_built_before_it_are_wiped", + "opaque_blob::given_a_blob_refused_after_fields_are_built::a_nested_field_and_whole_elements_built_before_it_are_wiped", "json_plaintext::text_that_is_not_a_document_leaves_no_plaintext_on_the_heap" ], "collections": [ @@ -174,6 +176,9 @@ "owned-records": [ "a_field_opened_before_a_later_field_is_refused_is_wiped" ], + "opaque": [ + "given_a_decrypted_blob::a_field_read_before_a_refusal_is_wiped" + ], "contexts": ["shared_context_boundaries"], "go": [ "TestContextBoundaries", @@ -326,9 +331,28 @@ "evidence": "packages/stack-encrypt/tests/heap_hygiene.rs" }, { - "id": "native-partial-decode-fields", + "id": "native-partial-decode-inside-whole-values", "status": "known-gap", - "evidence": "packages/stack-encrypt/tests/heap_hygiene.rs::opaque_blob::a_partial_decode_drops_the_fields_it_built_unwiped" + "tracking": "#1754", + "cases": [ + "sequence-element", + "map", + "option", + "box", + "enum", + "deserialize-with-field", + "serde-transparent-struct", + "serde-from-struct", + "serde-try-from-struct", + "serde-flatten-struct", + "all-fields-deserialize-with-struct", + "hand-written-deserialize-without-in-place", + "sequence-regrown-past-1-mib" + ], + "evidence": [ + "packages/stack-encrypt/tests/heap_hygiene.rs::opaque_blob::given_a_blob_refused_after_fields_are_built::a_refusal_inside_a_sequence_element_drops_what_the_element_built", + "packages/stack-encrypt/tests/heap_hygiene.rs::opaque_blob::given_a_blob_refused_after_fields_are_built::a_refusal_in_a_struct_the_derive_reads_whole_drops_its_fields" + ] }, { "id": "caller-owned-host-values", diff --git a/docs/plans/2026-10-24-stack-encrypt-api-plan.md b/docs/plans/2026-10-24-stack-encrypt-api-plan.md index 140ca414f..0b374c370 100644 --- a/docs/plans/2026-10-24-stack-encrypt-api-plan.md +++ b/docs/plans/2026-10-24-stack-encrypt-api-plan.md @@ -2146,8 +2146,18 @@ table. when it is dropped. - **Why.** Plaintext must not stay in freed memory. - **Done already.** Collections wipe the values decoded before a failure. - Cancellation and drop are tested (#1493, #1501). -- **Tracked in.** Issue #1676 is open for the partial Serde decode, which pull request #1503 recorded as a known gap. Issue #1684 is open for the drop-wiping adapter for a single value, such as `Zeroizing`, which needs Vitamin C to implement `FromScalar` for `Zeroizing`. Issue #1458 is open: data keys by reference. Issues #1468 and #1480 are closed. Pull requests #1493, #1501 and #1503 are merged; a decrypted `OpaqueBlob` wipes its value when it is dropped, and its `into_inner` returns a `Zeroizing`. + Cancellation and drop are tested (#1493, #1501). A decrypted + `OpaqueBlob` is read in place into a `T::default()`, so a refusal + wipes the fields of most derived structs that were read before it + (#1676, pull request #1750). Decrypting needs `T: Default`. +- **Tracked in.** Issue #1754 is open for what #1676 left: the + `native-partial-decode-inside-whole-values` known gap. serde still builds + some values whole (an element of a sequence, a map, an `Option`, a `Box`, + an enum, a field read with `deserialize_with`, and a struct marked + `transparent`, `from` or `try_from`, with a `flatten` field, or whose + every field uses `deserialize_with`), and a refusal inside one drops what + it built unwiped; a sequence longer than the 1 MiB serde reserves frees + each regrown buffer unwiped. Issue #1684 is open for the drop-wiping adapter for a single value, such as `Zeroizing`, which needs Vitamin C to implement `FromScalar` for `Zeroizing`. Issue #1458 is open: data keys by reference. Issues #1468 and #1480 are closed. Pull requests #1493, #1501 and #1503 are merged; a decrypted `OpaqueBlob` wipes its value when it is dropped, and its `into_inner` returns a `Zeroizing`. - **Finished when** the conformance profile for the lifecycle covers both cases. ### 4. The query engine diff --git a/languages/golang/encrypt/guest/Cargo.lock b/languages/golang/encrypt/guest/Cargo.lock index ef9930eb5..667834085 100644 --- a/languages/golang/encrypt/guest/Cargo.lock +++ b/languages/golang/encrypt/guest/Cargo.lock @@ -2271,6 +2271,7 @@ dependencies = [ "ore-rs", "rand 0.10.2", "serde", + "serde_derive", "serde_json", "serdect", "sha2 0.11.0", diff --git a/packages/eql/Cargo.lock b/packages/eql/Cargo.lock index e511cddee..3147e395e 100644 --- a/packages/eql/Cargo.lock +++ b/packages/eql/Cargo.lock @@ -4231,6 +4231,7 @@ dependencies = [ "ore-rs 0.12.0", "rand 0.10.1", "serde", + "serde_derive", "serde_json", "serdect", "sha2 0.11.0", diff --git a/packages/stack-encrypt/CHANGELOG.md b/packages/stack-encrypt/CHANGELOG.md index 6c3290cf3..b99eb690b 100644 --- a/packages/stack-encrypt/CHANGELOG.md +++ b/packages/stack-encrypt/CHANGELOG.md @@ -1209,7 +1209,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 key. Encrypt with `keyset.encrypt(OpaqueBlob::new(value))`, for any `Serialize + Zeroize` value. Decrypt with `keyset.decrypt::>(ct)`, for any - `DeserializeOwned + Zeroize` type, then call `into_inner()`. + `DeserializeOwned + Default + Zeroize` type, then call `into_inner()`. - The value is encoded with version 1 of Vitamin C's storage profile (`vitaminc_aead_frame::storage`). The encoded bytes start with a `VCS` header and a version byte, inside the plaintext. The profile has a @@ -1238,6 +1238,37 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 `Zeroizing`, so the value is still wiped on drop after it leaves the blob. `Zeroizing` derefs to `T`. A decrypted scalar is still an ordinary owned value, and nothing wipes it on drop. +- **A blob refused part-way through reading wipes the fields it read** + (#1676). A valid blob of another shape can be refused after some of its + fields are read, for example when a later field is missing or has another + type. Those fields used to be dropped unwiped, because serde holds them + until the whole `T` is built. Decrypting now reads the blob in place + into a `T::default()` held in a `Zeroizing`, through serde's + `Deserialize::deserialize_in_place`, and a refusal wipes that value. This + covers the fields of most derived structs, the fields of a struct nested + in one, and the elements of a `Vec` stored before the refusal. + - Decrypting an `OpaqueBlob` now needs `T: Default`. Add + `#[derive(Default)]` to the type. + - stack-encrypt turns on serde_derive's `deserialize_in_place` feature. + Cargo shares a crate's features across a build, so every + `#[derive(Deserialize)]` in a build with stack-encrypt also writes + `deserialize_in_place`. `deserialize` does not change. + - A field serde skips when reading (`#[serde(skip)]` or + `#[serde(skip_deserializing)]`) keeps the value `T::default()` gives + it. A `#[serde(default = "...")]` on that field or on its struct is not + used, so make `T::default()` give the value the field should have. + - serde still builds some values whole, and a refusal inside one of them + still drops what it built unwiped (#1754): an element of a sequence, a + map, an `Option`, a `Box`, an enum, a field read with + `deserialize_with`, and a struct the derive writes no in-place read + for. That is a struct marked `#[serde(transparent)]`, `from` or + `try_from`, one with a `#[serde(flatten)]` field, and one whose every + field uses `deserialize_with`; when `T` is such a struct, a refusal + wipes nothing `T` read. A part that wipes itself on drop, such as a + `Zeroizing`, closes that gap for that part. + - serde reserves room for at most 1 MiB of a sequence's elements before + reading them. A longer sequence regrows its buffer as it is read and + frees each old buffer unwiped, as it did before this change. - **Encrypting an `OpaqueBlob` wipes the value in every case.** The value is wiped before `encrypt` returns the pending request, both on success and when the value cannot be encoded. A failed encoding requests no key. A diff --git a/packages/stack-encrypt/Cargo.toml b/packages/stack-encrypt/Cargo.toml index 01531ff4f..45c3ac72c 100644 --- a/packages/stack-encrypt/Cargo.toml +++ b/packages/stack-encrypt/Cargo.toml @@ -12,6 +12,12 @@ license-file = "LICENSE" # Published to crates.io by release-plz.yml; release-plz.toml puts it in the # `stack-encrypt` version group. +# `serde_derive` is named only to turn on a feature of the derive every +# crate in the build shares (see the dependency), so no code names it and +# `cargo-udeps` reports it as unused. Ignore it. +[package.metadata.cargo-udeps.ignore] +normal = ["serde_derive"] + [dependencies] # `profile` (native only; stack-kms gates it off wasm32 itself) lets # `StackCipher::with_detected_credentials()` fall back to the client key @@ -68,6 +74,15 @@ futures = { version = "0.3.25", default-features = false, features = ["std"] } # control data (statistics, options, a plan) into typed messages. vitaminc-aead-frame = { workspace = true, features = ["serde"] } serde = { workspace = true } +# `deserialize_in_place`: `#[derive(Deserialize)]` also writes +# `Deserialize::deserialize_in_place` for most structs, which reads each field +# straight into a value the caller already holds. A decrypted +# `OpaqueBlob` is read that way into a `T::default()` it wipes, so a +# field read before a later one is refused is wiped with it, rather than +# dropped as serde's local. Cargo unifies a crate's features across the +# build, so every derive in a build with stack-encrypt writes the method; +# `Deserialize::deserialize` is unchanged. +serde_derive = { workspace = true, features = ["deserialize_in_place"] } # The order terms' serde: lowercase hex in JSON, raw bytes in a binary # format, through serdect's constant-time hex. serdect = { workspace = true } diff --git a/packages/stack-encrypt/docs/adr/0011-a-whole-value-is-one-storage-blob-sealed-as-one-leaf.md b/packages/stack-encrypt/docs/adr/0011-a-whole-value-is-one-storage-blob-sealed-as-one-leaf.md index 681fec73a..dbf69fc8b 100644 --- a/packages/stack-encrypt/docs/adr/0011-a-whole-value-is-one-storage-blob-sealed-as-one-leaf.md +++ b/packages/stack-encrypt/docs/adr/0011-a-whole-value-is-one-storage-blob-sealed-as-one-leaf.md @@ -103,7 +103,8 @@ own versions apart, it stores a version in the value. ### Cleanup follows the scalar API's rules -`T: Zeroize` is required to encrypt and to decrypt. +`T: Zeroize` is required to encrypt and to decrypt. Decrypting also +requires `T: Default`, for the value the blob is read into. On encrypt, these steps happen before the pending request is returned: @@ -118,6 +119,22 @@ If encoding fails, the source is wiped too. No key is requested. On decrypt, the opened bytes are held in a `Protected` buffer until the reader returns. +The blob is read into a `T::default()` in a `Zeroizing`, in place, +through serde's `Deserialize::deserialize_in_place`. For most derived +structs, serde stores each field in that value as it reads it. A valid +blob of another shape can be refused after some fields are read; the +refusal drops the `Zeroizing`, so those fields are wiped. Without +this, serde holds them as locals of its own and drops them unwiped, +because no `T` exists yet. The derive writes `deserialize_in_place` only +with serde_derive's `deserialize_in_place` feature, which this crate turns +on. Cargo unifies features, so every derive in the build writes it. +`Deserialize::deserialize` does not change. + +serde's in-place read never assigns a field it skips (`#[serde(skip)]` or +`#[serde(skip_deserializing)]`), so that field keeps the value +`T::default()` gives it, and a `#[serde(default = "...")]` on the field or +on its struct is not used. + The returned `OpaqueBlob` stores its value in a `Zeroizing`, so **the value is wiped on drop**. `into_inner` returns that `Zeroizing`, not a bare `T`, so the value is still guarded after it leaves the wrapper. A blob @@ -144,13 +161,23 @@ Vitamin C. number of elements, and whether each `Option` is present. A `String` scalar shows its length in the same way. Padding is the application's job. -- **Complete erasure.** A derived `Deserialize` might build some fields and - then refuse a later one. It drops those fields without wiping them, - because no `T` existed to wipe. `tests/heap_hygiene.rs` records this as a - negative control, so the gap stays visible. A `Copy` value that is moved - leaves its bytes behind. Compiler temporaries are not wiped. The - promise covers the owned source, the encoded buffer, the opened buffer, - and the library's own copies. +- **Complete erasure.** serde reads some values whole and stores them only + when they are complete: an element of a sequence, a map, an `Option`, a + `Box`, an enum, a field read with `deserialize_with`, a type whose own + `Deserialize` impl writes no `deserialize_in_place`, and a struct the + derive writes no in-place read for. That last is a struct marked + `#[serde(transparent)]`, `from` or `try_from`, one with a + `#[serde(flatten)]` field, and one whose every field uses + `deserialize_with`; when `T` is such a struct, a refusal wipes nothing + `T` read. A refusal inside any of these drops the parts of it already + read without wiping them. `tests/heap_hygiene.rs` records this with two + negative controls (a sequence element, and a `transparent` struct), so + the gap stays visible; #1754 tracks it. serde also reserves room for at + most 1 MiB of a sequence's elements before reading them, and a longer + sequence regrows its buffer, freeing each old one unwiped. A `Copy` + value that is moved leaves its bytes behind. Compiler temporaries are + not wiped. The promise covers the owned source, the encoded buffer, the + opened buffer, and the library's own copies. - **Search or partial reads.** A blob is opaque. Nothing inside it can be queried or read on its own. The structural API and the JSON index are for those needs. diff --git a/packages/stack-encrypt/examples/opaque_blob.rs b/packages/stack-encrypt/examples/opaque_blob.rs index ed31bb5b4..d5d36fce1 100644 --- a/packages/stack-encrypt/examples/opaque_blob.rs +++ b/packages/stack-encrypt/examples/opaque_blob.rs @@ -10,7 +10,7 @@ use zeroize::Zeroize; /// An ordinary application struct. `Serialize` and `Deserialize` give it a /// storage encoding; `Zeroize` lets the library wipe the owned source once /// it has been encoded, and lets a caller wipe a decrypted copy. -#[derive(Serialize, Deserialize, Zeroize, PartialEq, Debug)] +#[derive(Serialize, Deserialize, Zeroize, PartialEq, Debug, Default)] struct Profile { name: String, age: u32, @@ -20,7 +20,7 @@ struct Profile { /// The same data in a later shape: a field added with a default and one /// renamed under an alias. An old blob still reads into it. -#[derive(Serialize, Deserialize, Zeroize, PartialEq, Debug)] +#[derive(Serialize, Deserialize, Zeroize, PartialEq, Debug, Default)] struct ProfileV2 { name: String, age: u32, @@ -73,7 +73,7 @@ async fn main() -> Result<(), Box> { // The errors tell an authentic blob of another shape from tampering. // A type the blob does not fit is a mismatch after authentication... - #[derive(Deserialize, Zeroize)] + #[derive(Deserialize, Zeroize, Default)] struct Other { #[allow(dead_code)] id: u64, diff --git a/packages/stack-encrypt/fuzz/Cargo.lock b/packages/stack-encrypt/fuzz/Cargo.lock index 1950f5529..6cbc19aa4 100644 --- a/packages/stack-encrypt/fuzz/Cargo.lock +++ b/packages/stack-encrypt/fuzz/Cargo.lock @@ -2209,6 +2209,7 @@ dependencies = [ "ore-rs", "rand 0.10.1", "serde", + "serde_derive", "serde_json", "serdect", "sha2 0.11.0", diff --git a/packages/stack-encrypt/src/blob.rs b/packages/stack-encrypt/src/blob.rs index ff7503ad3..48c1b6fd7 100644 --- a/packages/stack-encrypt/src/blob.rs +++ b/packages/stack-encrypt/src/blob.rs @@ -15,7 +15,7 @@ //! use stack_encrypt::{OpaqueBlob, StackCipher}; //! use zeroize::Zeroize; //! -//! #[derive(Serialize, Deserialize, Zeroize, PartialEq, Debug)] +//! #[derive(Serialize, Deserialize, Zeroize, Default, PartialEq, Debug)] //! struct Profile { //! name: String, //! age: u32, @@ -113,9 +113,9 @@ //! ## Supported types //! //! To encrypt, `T` must implement `serde::Serialize` and [`Zeroize`]. To -//! decrypt, `T` must implement `serde::de::DeserializeOwned` and `Zeroize`. -//! [Cleanup](#cleanup) explains why `Zeroize` is needed. Each serde type is -//! written as follows: +//! decrypt, `T` must implement `serde::de::DeserializeOwned`, `Default` and +//! `Zeroize`. [Cleanup](#cleanup) explains why `Zeroize` and `Default` are +//! needed. Each serde type is written as follows: //! //! | serde type | Written as | //! |------------------------------------|-----------------------------------------------------| @@ -295,16 +295,52 @@ //! //! [`into_inner`]: OpaqueBlob::into_inner //! -//! One gap comes from serde and is not closed here. A derived -//! `Deserialize` might read some fields and then refuse a later one. It -//! then drops the fields it built as ordinary values, without -//! `T::zeroize`, because no `T` was ever built to wipe. The reader checks -//! the blob first, so this happens only for a valid blob of another shape -//! ([`BlobError::Mismatch`]), never for a malformed one. -//! -//! The bytes those fields were copied from are wiped with the buffer. A -//! field that wipes itself on drop closes the gap for that field. Examples +//! A blob can be refused after `T` has read some of it: a valid blob of +//! another shape ([`BlobError::Mismatch`]) whose first fields read and a +//! later one does not. The reader checks the whole blob first, so a +//! malformed blob is refused before `T` reads anything. To wipe what `T` +//! read before such a refusal, decrypting starts from `T::default()` in a +//! `Zeroizing` and reads the blob into it in place, with serde's +//! `Deserialize::deserialize_in_place`. For most derived structs, serde +//! reads each field straight into that value, so a refusal wipes every +//! field read before it, through `T::zeroize`. This holds at every level of +//! nested structs, tuples and arrays, and for the elements of a `Vec` or +//! another sequence stored before the refusal. This crate turns on serde's +//! `deserialize_in_place` derive feature for that, so every derive in the +//! build writes the method. +//! +//! serde reads some values whole and stores them only when they are +//! complete. If the refusal happens inside one of these, the parts of it +//! already read are dropped as ordinary values, without `T::zeroize`: +//! +//! - an element of a sequence, a map, an `Option`, a `Box`, and an enum; +//! - a field read with `#[serde(deserialize_with = "...")]` or +//! `#[serde(with = "...")]`; +//! - a struct the derive writes no in-place read for: one marked +//! `#[serde(transparent)]`, `#[serde(from = "...")]` or +//! `#[serde(try_from = "...")]`, one with a `#[serde(flatten)]` field, +//! and one whose every field uses `deserialize_with`. Such a struct is +//! read whole wherever it is, so if it is `T` itself, a refusal wipes +//! none of what was read; +//! - a type whose own `Deserialize` impl does not write +//! `deserialize_in_place`. +//! +//! A part that wipes itself on drop closes that gap for that part. Examples //! are a `Zeroizing` field, or a type that derives `ZeroizeOnDrop`. +//! The bytes those parts were copied from are wiped with the opened buffer. +//! +//! serde reserves room for at most 1 MiB of a sequence's elements before it +//! reads them. A longer sequence regrows its buffer as it is read, and each +//! old buffer is freed unwiped, whether or not the blob is refused. An +//! element that holds its value inline, such as an integer, leaves that +//! value in the old buffer; a `String` element leaves only its pointer and +//! length there. +//! +//! A field serde skips when reading (`#[serde(skip)]` or +//! `#[serde(skip_deserializing)]`) keeps the value `T::default()` gives it. +//! serde's in-place read never assigns it, so a +//! `#[serde(default = "...")]` on that field, or on the struct, is not +//! used. Make `T::default()` give the value the field should have. //! //! A Rust move does not erase memory. A `Copy` field leaves its bytes //! where it was moved from. Compiler temporaries are not wiped. This module @@ -350,8 +386,8 @@ use std::fmt; -use serde::de::DeserializeOwned; -use serde::Serialize; +use serde::de::{DeserializeOwned, Deserializer}; +use serde::{Deserialize, Serialize}; use vitaminc_aead_frame::serde::PathSegment; use vitaminc_aead_frame::storage::{self, ErrorKind}; use vitaminc_protected::{AsProtectedRef, Buffer, Controlled, Protected}; @@ -445,22 +481,47 @@ impl OpaqueBlob { } } -impl OpaqueBlob { +impl OpaqueBlob { /// Read a value from a storage blob: what decrypting does to the opened /// bytes. The caller's `bytes` are borrowed and not wiped; the opened /// buffer decrypting reads from is. /// + /// The value is read in place into a `T::default()` that is wiped if + /// the blob is refused, so for most derived structs the fields read + /// before a refusal are wiped with it. [Cleanup](self#cleanup) in the + /// module docs says which parts serde reads whole and does not wipe on + /// a refusal, and what a skipped field holds. + /// /// # Errors /// /// One [`BlobError`] per class: not a blob, a later version, malformed, /// or a well-formed blob that is not a `T`. pub fn decode(bytes: &[u8]) -> Result { - storage::from_slice::(bytes) - .map(Self::new) + storage::from_slice::>(bytes) + .map(|ReadInPlace(value)| Self(value)) .map_err(|error| BlobError::reading(error, bytes)) } } +/// A `T` read into a `T::default()` in place, inside a [`Zeroizing`]. For +/// most derived structs, serde stores each field in that value as it reads +/// it, so a field read before a later one is refused is wiped when the +/// refusal drops the value. The module docs' Cleanup section lists the +/// values serde reads whole instead. +struct ReadInPlace(Zeroizing); + +impl<'de, T: Deserialize<'de> + Default + Zeroize> Deserialize<'de> for ReadInPlace { + fn deserialize>(deserializer: D) -> Result { + let mut place = Zeroizing::new(T::default()); + // `deserialize_in_place` is hidden from serde's rustdoc, which says + // it is a stable, public API all the same. Its default reads a + // whole `T` and assigns it, so a type the derive writes no in-place + // read for behaves as `deserialize` does. + T::deserialize_in_place(deserializer, &mut place)?; + Ok(Self(place)) + } +} + impl sealed::Encode for OpaqueBlob { fn seal<'a, K: 'static>( &self, @@ -487,7 +548,7 @@ impl sealed::Encode for OpaqueBlob { } impl OpaqueEncode for OpaqueBlob {} -impl sealed::Decode for OpaqueBlob { +impl sealed::Decode for OpaqueBlob { fn open<'a, K: 'static>( leaf: SealedValue, cipher: &'a StackCipher, @@ -505,7 +566,7 @@ impl sealed::Decode for OpaqueBl .try_map(|bytes| Self::decode(bytes.risky_ref()).map_err(crate::Error::from)) } } -impl OpaqueDecode for OpaqueBlob {} +impl OpaqueDecode for OpaqueBlob {} /// Why an [`OpaqueBlob`] could not be written, or why an authentic /// ciphertext did not read as one. Each class of refusal has its own @@ -631,7 +692,7 @@ mod tests { use crate::ErrorPayload; use serde::Deserialize; - #[derive(Serialize, Deserialize, Zeroize, PartialEq, Debug)] + #[derive(Serialize, Deserialize, Zeroize, PartialEq, Debug, Default)] struct Pair { left: String, right: u32, diff --git a/packages/stack-encrypt/src/lib.rs b/packages/stack-encrypt/src/lib.rs index db538bcf8..ec27fe80e 100644 --- a/packages/stack-encrypt/src/lib.rs +++ b/packages/stack-encrypt/src/lib.rs @@ -479,7 +479,7 @@ endpoint — are `StackKmsBuilder`'s, and the two keyset-cache knobs are //! ``` //! # use serde::{Deserialize, Serialize}; //! # use zeroize::Zeroize; -//! # #[derive(Serialize, Deserialize, Zeroize)] +//! # #[derive(Serialize, Deserialize, Zeroize, Default)] //! # struct Card { number: String, expiry: (u8, u16) } //! # async fn example() -> Result<(), stack_encrypt::Error> { //! use stack_encrypt::{OpaqueBlob, StackCipher}; diff --git a/packages/stack-encrypt/tests/exchange_conformance.rs b/packages/stack-encrypt/tests/exchange_conformance.rs index c044b9dd4..37dfcc9fb 100644 --- a/packages/stack-encrypt/tests/exchange_conformance.rs +++ b/packages/stack-encrypt/tests/exchange_conformance.rs @@ -93,7 +93,7 @@ struct BlobCase { /// The blob's shape. The Go runner's struct carries the same field names /// as `vc` tags; a nil `tags` there reads back as an empty `Vec` here. -#[derive(Serialize, Deserialize, Zeroize, Clone, PartialEq, Debug)] +#[derive(Serialize, Deserialize, Zeroize, Clone, PartialEq, Debug, Default)] #[serde(deny_unknown_fields)] struct Profile { name: String, diff --git a/packages/stack-encrypt/tests/heap_hygiene.rs b/packages/stack-encrypt/tests/heap_hygiene.rs index ba277d425..fc3414ff2 100644 --- a/packages/stack-encrypt/tests/heap_hygiene.rs +++ b/packages/stack-encrypt/tests/heap_hygiene.rs @@ -1460,7 +1460,7 @@ mod cancellation { drop(future); } - #[derive(serde::Serialize, serde::Deserialize, zeroize::Zeroize)] + #[derive(serde::Serialize, serde::Deserialize, zeroize::Zeroize, Default)] struct Note { title: String, /// Written after the marked field, so the blob's buffer regrows @@ -1665,9 +1665,9 @@ fn the_spy_sees_a_leaked_block() { /// (which grows past its first allocation while it already holds the /// marker), the planned leaf, and on decrypt the opened buffer the blob /// is read from, all freed wiped, and none of them leaked rather than -/// freed. The opened value is the caller's and is wiped by hand before the -/// watch ends; a refusal of another shape, found before any field is -/// built, leaves nothing to wipe. +/// freed. The opened value is wiped when it is dropped, before the watch +/// ends. A refusal of another shape found before any field is built leaves +/// nothing to wipe; one found after some fields are built wipes them. mod opaque_blob { use super::*; @@ -1675,7 +1675,7 @@ mod opaque_blob { use stack_encrypt::{Error, OpaqueBlob}; use zeroize::Zeroize; - #[derive(Serialize, Deserialize, Zeroize)] + #[derive(Serialize, Deserialize, Zeroize, Default)] struct Doc { title: String, notes: Vec, @@ -1755,7 +1755,7 @@ mod opaque_blob { .await .unwrap() }); - #[derive(Deserialize, Zeroize)] + #[derive(Deserialize, Zeroize, Default)] #[allow(dead_code)] struct Other { title: u32, @@ -1766,49 +1766,215 @@ mod opaque_blob { .decrypt_with_context::>(sealed, "docs/body") .await }); - assert!(matches!( - result, - Err(Error::Blob(stack_encrypt::BlobError::Mismatch(_))) - )); + assertions::is_a_mismatch(&result); }); } - /// The limit the blob docs state, held as a negative control: a derived - /// `Deserialize` that built a `String` field and then refuses a later - /// field drops that `String` as an ordinary value, unwiped, because no - /// `T` was ever constructed to wipe. The opened buffer itself is wiped; - /// what leaks is serde's partial value. A type whose fields wipe on drop - /// closes it; this test documents that the library does not. - #[test] - #[should_panic(expected = "freed with plaintext in them")] - fn a_partial_decode_drops_the_fields_it_built_unwiped() { - let rt = runtime(); - let cipher = rt.block_on(common::stack_cipher()); - let keyset = cipher.default_keyset(); - let sealed = rt.block_on(async { - keyset - .encrypt_with_context(doc(), "docs/body") - .await - .unwrap() - }); - #[derive(Deserialize, Zeroize)] + /// A blob that reads part-way as the type it is opened as and is then + /// refused. The decode fills a `T::default()` in place, so every field + /// built before the refusal is in that value, and the refusal wipes it. + mod given_a_blob_refused_after_fields_are_built { + use super::*; + + use stack_encrypt::kms::FakeDataKeySource; + use stack_encrypt::{Ciphertext, StackCipher}; + + #[derive(Serialize, Zeroize)] + struct Shelf { + label: String, + sections: Vec
, + owner: Owner, + } + + #[derive(Serialize, Zeroize)] + struct Section { + name: String, + pages: u32, + } + + #[derive(Serialize, Zeroize)] + struct Owner { + name: String, + id: String, + } + + /// Every text but the owner's id is marked; the id is read as a + /// number, so a reader of that shape is refused last of all. + fn shelf() -> OpaqueBlob { + OpaqueBlob::new(Shelf { + label: marked("label"), + sections: vec![ + Section { + name: marked("section-1"), + pages: 3, + }, + Section { + name: marked("section-2"), + pages: 5, + }, + ], + owner: Owner { + name: marked("owner"), + id: "not-a-number".to_owned(), + }, + }) + } + + /// [`Doc`] read with a `u32` where its body is: the `String` and + /// the `Vec` read, then the `u32` refuses the text it finds. + #[derive(Deserialize, Zeroize, Default)] #[allow(dead_code)] - struct Later { + struct DocWithNumericBody { title: String, notes: Vec, body: u32, } - watched("OpaqueBlob decrypt (partial)", || { - let result = rt.block_on(async { - keyset - .decrypt_with_context::>(sealed, "docs/body") + + /// A source sealed under a cipher, with the runtime that cipher + /// runs on. + struct Sealed { + rt: tokio::runtime::Runtime, + cipher: StackCipher, + sealed: Ciphertext, + } + + /// `source` sealed under a fresh cipher. + fn sealed(source: OpaqueBlob) -> Sealed + where + T: Serialize + Zeroize + Send + 'static, + { + let rt = runtime(); + let cipher = rt.block_on(common::stack_cipher()); + let sealed = rt.block_on(async { + cipher + .default_keyset() + .encrypt_with_context(source, "docs/body") .await + .expect("the source seals") }); - assert!(matches!( - result, - Err(Error::Blob(stack_encrypt::BlobError::Mismatch(_))) - )); - }); + Sealed { rt, cipher, sealed } + } + + /// Open `source` as an `OpaqueBlob` while watched for marked + /// frees and leaks, and check it is refused as another shape. + fn opened_as(what: &str, source: Sealed) + where + T: serde::de::DeserializeOwned + Default + Zeroize + Send + 'static, + { + let Sealed { rt, cipher, sealed } = source; + let keyset = cipher.default_keyset(); + watched_for_leaks(what, || { + let result = rt.block_on(async { + keyset + .decrypt_with_context::>(sealed, "docs/body") + .await + }); + assertions::is_a_mismatch(&result); + }); + } + + /// The `String` and the `Vec` read before the `u32` that + /// refuses the text it finds. + #[test] + fn the_fields_built_before_it_are_wiped() { + opened_as::( + "OpaqueBlob decrypt (refused after fields)", + sealed(doc()), + ); + } + + /// A refusal inside a nested struct: the outer field, both whole + /// elements of the sequence, and the nested struct's own field read + /// before it are wiped. + #[test] + fn a_nested_field_and_whole_elements_built_before_it_are_wiped() { + #[derive(Deserialize, Zeroize, Default)] + #[allow(dead_code)] + struct ShelfRead { + label: String, + sections: Vec, + owner: OwnerRead, + } + #[derive(Deserialize, Zeroize, Default)] + #[allow(dead_code)] + struct SectionRead { + name: String, + pages: u32, + } + #[derive(Deserialize, Zeroize, Default)] + #[allow(dead_code)] + struct OwnerRead { + name: String, + id: u32, + } + opened_as::( + "OpaqueBlob decrypt (refused in a nested field)", + sealed(shelf()), + ); + } + + /// A limit that remains, held as a negative control. serde fills + /// a struct's fields in place, but builds each element of a + /// sequence whole before it stores it. A refusal inside an element + /// drops the fields that element built as ordinary values, + /// unwiped. The elements stored before it are wiped. + #[test] + #[should_panic(expected = "freed with plaintext in them")] + fn a_refusal_inside_a_sequence_element_drops_what_the_element_built() { + #[derive(Deserialize, Zeroize, Default)] + #[allow(dead_code)] + struct ShelfRead { + label: String, + sections: Vec, + } + #[derive(Deserialize, Zeroize, Default)] + #[allow(dead_code)] + struct SectionRead { + name: String, + pages: String, + } + opened_as::( + "OpaqueBlob decrypt (refused inside an element)", + sealed(shelf()), + ); + } + + /// A limit that remains, held as a negative control. serde's + /// derive writes no in-place read for a `#[serde(transparent)]` + /// struct, so the struct it wraps is built whole, and a refusal of + /// that struct's later field drops the fields read before it as + /// ordinary values, unwiped. `flatten`, `from`, `try_from`, and a + /// struct whose every field uses `deserialize_with` read whole in + /// the same way. + #[test] + #[should_panic(expected = "freed with plaintext in them")] + fn a_refusal_in_a_struct_the_derive_reads_whole_drops_its_fields() { + #[derive(Deserialize, Zeroize, Default)] + #[serde(transparent)] + struct Wrapped { + inner: DocWithNumericBody, + } + opened_as::( + "OpaqueBlob decrypt (refused in a transparent struct)", + sealed(doc()), + ); + } + } + + mod assertions { + use super::*; + + use stack_encrypt::BlobError; + + pub(super) fn is_a_mismatch(result: &Result, Error>) + where + T: Zeroize, + { + assert!( + matches!(result, Err(Error::Blob(BlobError::Mismatch(_)))), + "a blob of another shape is refused as a mismatch: {result:?}" + ); + } } } diff --git a/packages/stack-encrypt/tests/opaque_blob.rs b/packages/stack-encrypt/tests/opaque_blob.rs index 8e8431e5a..ee39f947f 100644 --- a/packages/stack-encrypt/tests/opaque_blob.rs +++ b/packages/stack-encrypt/tests/opaque_blob.rs @@ -6,7 +6,7 @@ //! The file has two parts: the types, constants and helpers the tests //! share, then the tests, in one module per scenario. use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; -use std::sync::Arc; +use std::sync::{Arc, Mutex}; use serde::{Deserialize, Serialize}; use stack_encrypt::blob::{HEADER, VERSION}; @@ -23,7 +23,7 @@ mod common; // --------------------------------------------------------------------------- /// The value most tests encrypt. -#[derive(Serialize, Deserialize, Zeroize, Clone, PartialEq, Debug)] +#[derive(Serialize, Deserialize, Zeroize, Clone, PartialEq, Debug, Default)] struct Profile { name: String, age: u32, @@ -50,7 +50,7 @@ fn grace() -> Profile { } /// A value of a different shape from [`Profile`]. -#[derive(Serialize, Deserialize, Zeroize, PartialEq, Debug)] +#[derive(Serialize, Deserialize, Zeroize, PartialEq, Debug, Default)] struct Pair { left: String, right: u32, @@ -58,7 +58,7 @@ struct Pair { /// A later version of [`Profile`] that still reads an old blob: a wider /// integer, a renamed field with an alias, and two new fields with defaults. -#[derive(Deserialize, Zeroize, PartialEq, Debug)] +#[derive(Deserialize, Zeroize, PartialEq, Debug, Default)] struct ProfileV2 { name: String, age: u64, @@ -73,7 +73,7 @@ struct ProfileV2 { /// A later version of [`Profile`] with a new field and no default, so it /// cannot read an old blob. -#[derive(Deserialize, Zeroize)] +#[derive(Deserialize, Zeroize, Default)] #[allow(dead_code)] struct ProfileWithRequiredField { name: String, @@ -84,15 +84,29 @@ struct ProfileWithRequiredField { } /// [`Profile`] with fewer fields and a narrower integer. -#[derive(Deserialize, Zeroize)] +#[derive(Deserialize, Zeroize, Default)] #[allow(dead_code)] struct NarrowProfile { name: String, age: u8, } +/// A type with a field serde skips, whose serde default differs from the +/// one `Default` gives it. +#[derive(Serialize, Deserialize, Zeroize, PartialEq, Debug, Default)] +struct WithSkippedField { + name: String, + #[serde(skip, default = "one")] + count: u32, +} + +/// The serde default of [`WithSkippedField::count`]. +fn one() -> u32 { + 1 +} + /// A byte string written as bytes, not as a sequence of `u8`. -#[derive(Serialize, Deserialize, Zeroize, PartialEq, Debug)] +#[derive(Serialize, Deserialize, Zeroize, PartialEq, Debug, Default)] struct RawBytes(#[serde(with = "serde_bytes_shim")] Vec); /// `serde_bytes` without the dependency: write and read a `Vec` as bytes. @@ -192,17 +206,19 @@ fn tracked() -> (OpaqueBlob, Arc) { } /// [`Tracked`] as it decrypts. -#[derive(Deserialize, Zeroize)] +#[derive(Deserialize, Zeroize, Default)] struct TrackedRead { value: String, } -/// How many times a [`Witness`] has been wiped. Only one test uses it, and -/// nextest runs each test in its own process. +/// How many times a [`Witness`] has been wiped. Only +/// `is_wiped_on_drop_and_into_inner_keeps_it_guarded` encrypts or decrypts a +/// `Witness`, so no other test moves the count while it runs, under nextest +/// or the threads of `cargo test`. static WITNESS_WIPES: AtomicUsize = AtomicUsize::new(0); /// A value that counts its wipes in [`WITNESS_WIPES`]. -#[derive(Serialize, Deserialize)] +#[derive(Serialize, Deserialize, Default)] struct Witness { value: String, } @@ -214,6 +230,30 @@ impl Zeroize for Witness { } } +/// What a [`WitnessThenMore`] held each time it was wiped. Only one test +/// uses it. +static WIPED_BEFORE_REFUSAL: Mutex> = Mutex::new(Vec::new()); + +/// [`Tracked`] read as a type with a later field the blob does not have. +/// `value` reads, then `more` is refused as missing. Its wipe records what +/// `value` held in [`WIPED_BEFORE_REFUSAL`] before it wipes it. +#[derive(Deserialize, Default)] +#[allow(dead_code)] +struct WitnessThenMore { + value: String, + more: u32, +} + +impl Zeroize for WitnessThenMore { + fn zeroize(&mut self) { + WIPED_BEFORE_REFUSAL + .lock() + .expect("the record of wipes") + .push(self.value.clone()); + self.value.zeroize(); + } +} + // --------------------------------------------------------------------------- // Pinned bytes // --------------------------------------------------------------------------- @@ -981,6 +1021,59 @@ mod given_a_later_version_of_the_type { } } +/// A decrypted blob is read in place into `T::default()`, and serde's +/// in-place read never assigns a field it skips. +mod given_a_field_serde_skips { + use super::*; + + fn source() -> WithSkippedField { + WithSkippedField { + name: "Ada".into(), + count: 5, + } + } + + #[tokio::test] + async fn decrypting_keeps_the_value_default_gives_it_not_its_serde_default() { + let cipher = common::stack_cipher().await; + let keyset = cipher.default_keyset(); + let ct = keyset.encrypt(OpaqueBlob::new(source())).await.unwrap(); + + let opened = keyset + .decrypt::>(ct) + .await + .unwrap() + .into_inner(); + + assert_eq!( + *opened, + WithSkippedField { + name: "Ada".into(), + count: 0, + }, + "a skipped field should keep the value T::default() gives it" + ); + } + + /// The contrast: serde's whole-value read gives the skipped field its + /// `#[serde(default = "...")]` value from the same bytes. + #[test] + fn a_whole_value_read_of_the_same_bytes_gives_its_serde_default() { + let encoded = OpaqueBlob::new(source()).encode().unwrap(); + + let whole: WithSkippedField = + vitaminc_aead_frame::storage::from_slice(encoded.risky_ref()).unwrap(); + let in_place = OpaqueBlob::::decode(encoded.risky_ref()).unwrap(); + + assert_eq!(whole.count, 1, "serde's own read should call `one`"); + assert_eq!( + in_place.get().count, + 0, + "the in-place read should leave T::default()'s value" + ); + } +} + /// What is wiped, and when, on encrypt. mod given_an_owned_source { use super::*; @@ -1166,6 +1259,29 @@ mod given_a_decrypted_blob { ); } + /// A blob refused after `T` has read a field: the field was read into + /// the value decrypting fills in place, and the refusal wipes that + /// value once, with the field in it. + #[tokio::test] + async fn a_field_read_before_a_refusal_is_wiped() { + let cipher = common::stack_cipher().await; + let keyset = cipher.default_keyset(); + let (source, _) = tracked(); + let ct = keyset.encrypt(source).await.unwrap(); + + let refused = keyset.decrypt::>(ct).await; + assert!( + matches!(refused, Err(Error::Blob(BlobError::Mismatch(_)))), + "a missing field is a mismatch: {refused:?}" + ); + let wiped = std::mem::take(&mut *WIPED_BEFORE_REFUSAL.lock().unwrap()); + assert_eq!( + wiped, + ["secret"], + "the refusal should wipe the field read before it, once" + ); + } + /// The inner `Zeroizing` wipes on drop anyway, so this is the only /// place an explicit wipe is visible. #[test] diff --git a/packages/stack-encrypt/tests/ui/opaque_blob_decrypt_requires_default.rs b/packages/stack-encrypt/tests/ui/opaque_blob_decrypt_requires_default.rs new file mode 100644 index 000000000..5be3b17e7 --- /dev/null +++ b/packages/stack-encrypt/tests/ui/opaque_blob_decrypt_requires_default.rs @@ -0,0 +1,23 @@ +//! Decrypting an `OpaqueBlob` needs `T: Default`: the blob is read in +//! place into a `T::default()` held in a `Zeroizing`, so a refusal part +//! way through the read wipes the fields read before it. `Zeroize` alone is +//! not enough, through `decrypt` or through `decode`. +use serde::Deserialize; +use stack_encrypt::{Ciphertext, KeysetCipher, OpaqueBlob}; +use stack_kms::FakeDataKeySource; +use zeroize::Zeroize; + +#[derive(Deserialize, Zeroize)] +struct NoDefault { + name: String, +} + +async fn decrypt(keyset: &KeysetCipher<'_, FakeDataKeySource>, ct: Ciphertext) { + let _refused: OpaqueBlob = keyset.decrypt(ct).await.unwrap(); +} + +fn decode(bytes: &[u8]) { + let _refused = OpaqueBlob::::decode(bytes); +} + +fn main() {} diff --git a/packages/stack-encrypt/tests/ui/opaque_blob_decrypt_requires_default.stderr b/packages/stack-encrypt/tests/ui/opaque_blob_decrypt_requires_default.stderr new file mode 100644 index 000000000..9121fd18c --- /dev/null +++ b/packages/stack-encrypt/tests/ui/opaque_blob_decrypt_requires_default.stderr @@ -0,0 +1,38 @@ +error[E0277]: the trait bound `OpaqueBlob: OpaqueDecode` is not satisfied + --> tests/ui/opaque_blob_decrypt_requires_default.rs:16:50 + | +16 | let _refused: OpaqueBlob = keyset.decrypt(ct).await.unwrap(); + | ^^^^^^^ the trait `OpaqueDecode` is not implemented for `OpaqueBlob` + | +help: the trait `OpaqueDecode` is implemented for `OpaqueBlob` + --> src/blob.rs + | + | impl OpaqueDecode for OpaqueBlob {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +note: required by a bound in `stack_encrypt::scalar::>::decrypt` + --> src/scalar.rs + | + | pub fn decrypt(&self, ciphertext: Ciphertext) -> Pending<'_, P, K> { + | ^^^^^^^^^^^^ required by this bound in `stack_encrypt::scalar::>::decrypt` + +error[E0599]: the function or associated item `decode` exists for struct `OpaqueBlob`, but its trait bounds were not satisfied + --> tests/ui/opaque_blob_decrypt_requires_default.rs:20:45 + | +11 | struct NoDefault { + | ---------------- doesn't satisfy `NoDefault: Default` +... +20 | let _refused = OpaqueBlob::::decode(bytes); + | ^^^^^^ function or associated item cannot be called on `OpaqueBlob` due to unsatisfied trait bounds + | +note: if you're trying to build a new `OpaqueBlob`, consider using `OpaqueBlob::::new` which returns `OpaqueBlob<_>` + --> src/blob.rs + | + | pub fn new(value: T) -> Self { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + = note: the following trait bounds were not satisfied: + `NoDefault: Default` +help: consider annotating `NoDefault` with `#[derive(Default)]` + | +11 + #[derive(Default)] +12 | struct NoDefault { + | 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 77e6917d1..ad432f03d 100644 --- a/packages/stack-encrypt/tests/ui/opaque_blob_requires_zeroize.stderr +++ b/packages/stack-encrypt/tests/ui/opaque_blob_requires_zeroize.stderr @@ -166,8 +166,8 @@ error[E0277]: the trait bound `OpaqueBlob: OpaqueDecode` is not satisfi help: the trait `OpaqueDecode` is implemented for `OpaqueBlob` --> src/blob.rs | - | impl OpaqueDecode for OpaqueBlob {} - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | impl OpaqueDecode for OpaqueBlob {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ note: required by a bound in `stack_encrypt::scalar::>::decrypt` --> src/scalar.rs |