Skip to content

Commit 55ff30f

Browse files
committed
feat(stack-encrypt)!: derive owned record declarations with EncryptTarget and DecryptSource
Records, derives and plans still spoke the structural `EncryptFrom` / `DecryptInto` pair over a borrowed plaintext while the scalar API had moved to `EncryptTarget` / `DecryptSource` with explicit caller-context capabilities. A user could not write the mixed record the public examples show (`id` in the clear, `name` and `email` sealed) as an owned conversion that consumes and wipes the plaintext, and nothing said how the two pairs relate. `EncryptTarget` gains `owned_encryption()`, the description over the plaintext by value, defaulting to guard-and-wipe over the borrowed `encryption()`, and `indexes()`. `EncryptInto` and the owned column run it. A new `#[derive(EncryptTarget, DecryptSource)]` composes the field targets directly: a `struct = User` record projects each field out of a borrow in its borrowed form and divides the struct between its fields with the new `Encryption::split` in its owned form, so a `#[stash(passthrough)]` field is moved into the record (never cloned, never encrypted or authenticated) and each sealed field is guarded by its own target's owned description. Caller context is a capability composed through the tree: `ContextExtension<C>` for a record whose fields carry their own pairs, `ExpectedContext<T>` (now a `ContextInput`) for a stored context, and `RequiredContext` of the core contexts for `plaintext` records and the core leaves, which all implement the owned pair now (terms as `EncryptTarget` alone). A field whose target cannot take the record's pair is refused at that field. Both owned derives also emit the structural declarations as a bridge, so an owned record is a field of a structural record or a typed plan field; `FieldsBuilder::target` admits an owned-only target such as a `Ciphertext`. The dynamic lowering is untouched: the equivalence test seals one record through a hand-written target, the derive and the data plan against one recording provider and compares descriptors, term bytes and cross-opening. Breaking: the structural `Vec<T>: DecryptInto<Vec<P>>` and `DecryptField<Vec<P>, _>` impls open through the wiping collection path and so require `P: Zeroize`; before, the elements recovered before a late element failure were dropped unwiped (the CodeRabbit finding on the owned collections PR). A drop-witness test fails without the wipe. ADR-0011 records the signature and ownership map. The structural derives stay for the plans and the dynamic engine; their removal is #1488. Closes #1483 Refs #1488
1 parent 4b42186 commit 55ff30f

46 files changed

Lines changed: 3458 additions & 73 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎Cargo.lock‎

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎conformance/stack-encrypt/coverage.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,8 @@ Paths are relative to the repository root. New profile cases run from `v1/`.
77
| Requirement | Existing evidence | Remaining work |
88
|---|---|---|
99
| Scalar value widths and lossless transport | Initial scalar cases and [value-kind requirements](fixture-contract.md#value-kind-requirements), executed by the existing Rust and generated Go runners | Complete per-kind boundary matrices, bytes and broader floats; Python/TS mappings |
10-
| Owned opaque ciphertext and storage envelope | `packages/stack-encrypt/tests/scalar.rs`, `frozen_bytes.rs`; initial cross-opening cases | Blob profile; encoded targets; supported version matrix |
11-
| Record declaration and lowering | [Declaration grammar](declaration-grammar.md); `v1/declarations.json` shared by native Rust and Go; native normalization observations; existing record lowering suites | EQL-resolver profile; SDK-to-declaration mappings; runtime source/read shapes |
10+
| Owned opaque ciphertext and storage envelope | `packages/stack-encrypt/tests/scalar.rs`, `frozen_bytes.rs`; initial cross-opening cases; `owned_records.rs` (owned record derives: passthrough ownership transfer, sealed-field wiping, nested and renamed fields, stored context, one batch per column) | Blob profile; encoded targets; supported version matrix |
11+
| Record declaration and lowering | [Declaration grammar](declaration-grammar.md); `v1/declarations.json` shared by native Rust and Go; native normalization observations; existing record lowering suites; `packages/stack-encrypt/tests/owned_equivalence.rs` seals one mixed, searchable record through a hand-written owned target, the owned derive and the data plan against one recording provider and compares descriptors, term bytes and cross-opening | EQL-resolver profile; SDK-to-declaration mappings; runtime source/read shapes |
1212
| Context binding and composition | `packages/stack-encrypt/tests/target.rs`, `descriptor.rs`, `record_lowering.rs`; `languages/golang/encrypt/context_field_test.go`; initial wrong-context cases | Shared composition vectors; expected-context and required-input matrix |
1313
| Query terms and diagnostics | [Query-operator requirements](fixture-contract.md#query-operator-requirements), existing Rust/Go runners and initial equality/query-error cases | Common rejection corpus for every operator, capability and input shape; wider kind/index combinations |
1414
| Missing, SQL NULL and sealed null | `packages/stack-encrypt/src/dynamic/record.rs` null tests; `languages/golang/encrypt/null_test.go` | Explicit language mappings and common missing/null fixtures |

‎packages/stack-encrypt-derive/Cargo.toml‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ syn = { version = "3", features = ["full", "extra-traits"] }
2424
# The dev-dependencies below are used only by the crate-level doctests.
2525
# `cargo-udeps` cannot see into rustdoc, so it reports them as unused.
2626
[package.metadata.cargo-udeps.ignore]
27-
development = ["stack-encrypt", "tokio"]
27+
development = ["stack-encrypt", "tokio", "zeroize"]
2828

2929
[dev-dependencies]
3030
# The plain-segment rule is copied from stack-encrypt (a proc-macro crate cannot
@@ -37,3 +37,5 @@ serde_json = { workspace = true }
3737
# these doctests are what exercises that forwarding.
3838
stack-encrypt = { path = "../stack-encrypt", features = ["test-support"] }
3939
tokio = { workspace = true, features = ["rt", "macros"] }
40+
# The owned-record doctest derives `Zeroize` on its plaintext, as a user does.
41+
zeroize = { workspace = true }

‎packages/stack-encrypt-derive/docs/attributes.md‎

Lines changed: 94 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,11 @@
11
# Attributes
22

3-
All attributes live under `#[stash(...)]`.
3+
All attributes live under `#[stash(...)]`. The four derives read the same
4+
attributes: `EncryptFrom` / `DecryptInto` emit the structural declarations,
5+
run over a borrowed plaintext; `EncryptTarget` / `DecryptSource` emit the
6+
owned declarations (and the structural ones beside them as a bridge), run
7+
over a plaintext handed over by value, and alone accept `passthrough`. Derive
8+
one pair or the other on a record, not both.
49

510
## On the struct
611

@@ -32,7 +37,8 @@ literal.
3237
| `identity = "..."` | With `struct` only: key this field under the segment `identity` instead of the plaintext field's name, so it is derived under `("<context>", "<identity>")`. One plain segment. The plan builder's `.identity(segment)`. |
3338
| `from = field` / `from = 0` | With `struct` only: derive this field from `plaintext.field` (or `plaintext.0` for a tuple struct) when its name differs from its plaintext field's. A plaintext field has one output: two fields `from` one plaintext field are refused (a ciphertext with its terms is one `Encrypted<Terms>` field). |
3439
| `default` / `default = expr` | Not derived: filled with `Default::default()` or `expr`. Never encrypted, never authenticated. |
35-
| `decrypt` | Decryption opens this field (`DecryptInto` only). Needed only when the field types cannot decide it — see below. |
40+
| `decrypt` | Decryption opens this field (`DecryptInto` / `DecryptSource` only). Needed only when the field types cannot decide it — see below. |
41+
| `passthrough` | With `struct` on the owned derives only: carry the plaintext field of this name (or `from = field`) into the record as it is, **not encrypted and not authenticated**, moved rather than cloned, and move it back on decryption. Keyed under nothing; excludes `identity`, `default` and `decrypt`. |
3642

3743
A field takes no `context = ".."` of its own, on any derive: it is a compile
3844
error. A plan has exactly one context source, and every output sits under it.
@@ -64,6 +70,92 @@ from a `NonEmpty<T>` or a supported integer. Both encodings and the descriptor's
6470
structured identity are preserved when borrowing context data is converted into
6571
an owned declaration. No context is inferred from a Rust type's name.
6672

73+
## Owned records
74+
75+
`#[derive(EncryptTarget, DecryptSource)]` takes the attributes above and
76+
declares the record the owned way: `value.encrypt_into(&keyset)` consumes
77+
the plaintext, and `Plaintext::decrypt_from(record, &cipher)` returns it.
78+
The plaintext type is `Zeroize` (the trait bound says where the wiping
79+
obligation lies), and the conversion wipes every plaintext field it seals.
80+
What the caller may or must pass is the record's `ContextInput`:
81+
82+
| Record | Encrypt input | Decrypt input | A call |
83+
|---|---|---|---|
84+
| `struct = User, context = "users"` | `ContextExtension<DeclaredContext>` | the same | `user.encrypt_into(&keyset)`, or `.encrypt_into_with_context(&keyset, 7u64)` to extend every field's pair by the row id |
85+
| `plaintext = T` | `RequiredContext<CallerContext>` (`RequiredContext<AeadContext>` with `context_type = AeadContext`) | the same | `value.encrypt_into_with_context(&keyset, nonempty!("users/email"))` |
86+
| with a `context_field` of type `C` | `RequiredContext<NonEmpty<C>>` | `ExpectedContext<C>` | `T::decrypt_from(record, &cipher)` opens under the stored context; `decrypt_from_with_context(record, &cipher, nonempty!(..))` also checks it |
87+
88+
A `struct` record's field is handed its pair, extended by the caller's part
89+
if one was given, so the field's target must accept a caller context: a
90+
`Ciphertext` (`OptionalContext`), a term or an `Encrypted<Terms>`
91+
(`RequiredContext<CallerContext>`), a `StackCipherText`
92+
(`RequiredContext<AeadContext>`), a `plaintext` record, or another `struct`
93+
record (whose own pairs the outer pair then extends). A target that declares
94+
its whole context itself (`NoCallerContext`) or requires a context of another
95+
type (`RequiredContext<u64>`) is refused at that field. A `#[stash(passthrough)]`
96+
field is moved into the record by the owned conversion; its type is `Clone`
97+
too, since the record's borrowed form, which a plan or a structural record
98+
runs, copies it.
99+
100+
A `plaintext` record's fields are all handed the one context the record
101+
requires, so a term beside an `AeadContext`-only record is refused at the
102+
term. Omitting a required context is refused at the call
103+
(`AllowsNoContext`), whatever `Default` the context type has.
104+
105+
Both owned derives also emit the structural declarations: `EncryptTarget`
106+
emits `EncryptFrom` (the record's legacy context — `DeclaredContext`,
107+
`CallerContext` or `NonEmpty<C>` — converted into its owned input) and
108+
`Decryptable`; `DecryptSource` emits `DecryptInto` and `DecryptField`. An
109+
owned record is therefore a field of a `#[derive(EncryptFrom)]` struct
110+
record and a typed field of a plan (`encrypt_into::<Record, _>`) without
111+
a second derive. A hand-written owned target that is to be a record field
112+
implements `Decryptable` and `DecryptField` beside `DecryptSource`.
113+
114+
```rust
115+
use stack_encrypt::sem::EqualityTerm;
116+
use stack_encrypt::target::{DecryptSource, EncryptTarget};
117+
use stack_encrypt::{Ciphertext, DecryptFrom, EncryptInto, StackCipher};
118+
119+
#[derive(Debug, PartialEq, zeroize::Zeroize)]
120+
struct User { id: u64, name: String, email: String }
121+
122+
/// A searchable scalar: the ciphertext and an equality term, under the one
123+
/// context the field (or a caller) supplies.
124+
#[derive(EncryptTarget, DecryptSource)]
125+
#[stash(plaintext = String)]
126+
struct SearchableEmail { ciphertext: Ciphertext, equality: EqualityTerm }
127+
128+
#[derive(EncryptTarget, DecryptSource)]
129+
#[stash(struct = User, context = "users")]
130+
struct SearchableUser {
131+
#[stash(passthrough)]
132+
id: u64,
133+
name: Ciphertext, // ("users", "name")
134+
email: SearchableEmail, // ("users", "email")
135+
}
136+
137+
# tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async {
138+
let cipher = StackCipher::builder()
139+
.kms(stack_encrypt::kms::FakeDataKeySource::new()).init().await?;
140+
let keyset = cipher.default_keyset();
141+
let users = vec![
142+
User { id: 42, name: "Alice".into(), email: "alice@example.com".into() },
143+
User { id: 43, name: "Bob".into(), email: "bob@example.com".into() },
144+
];
145+
// One batched key request for both rows' four sealed fields.
146+
let rows: Vec<SearchableUser> = users.encrypt_into(&keyset).await?;
147+
// A query term is the same derivation under the same context.
148+
let wanted: EqualityTerm = String::from("alice@example.com")
149+
.encrypt_into_with_context(&keyset, stack_encrypt::nonempty!("users").with("email"))
150+
.await?;
151+
let matched: Vec<SearchableUser> = rows.into_iter().filter(|r| r.email.equality == wanted).collect();
152+
let opened = Vec::<User>::decrypt_from(matched, &cipher).await?;
153+
assert_eq!(opened.len(), 1);
154+
assert_eq!(opened[0].id, 42);
155+
# Ok::<(), stack_encrypt::Error>(())
156+
# }).unwrap();
157+
```
158+
67159
## Which context a record takes
68160

69161
`CallerContext` holds both of Vitamin C's encodings of the context — the AEAD

‎packages/stack-encrypt-derive/src/attrs.rs‎

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -223,6 +223,10 @@ pub(crate) struct FieldAttrs {
223223
pub(crate) default: Option<Option<Expr>>,
224224
/// `#[stash(decrypt)]`: decryption opens this field.
225225
pub(crate) decrypt: bool,
226+
/// `#[stash(passthrough)]`: with `struct = ..` on the owned derives,
227+
/// the plaintext field is carried into the record in the clear, moved
228+
/// rather than encrypted, and moved back when the record is decrypted.
229+
pub(crate) passthrough: bool,
226230
}
227231

228232
impl FieldAttrs {
@@ -296,6 +300,13 @@ impl FieldAttrs {
296300
parsed.decrypt = true;
297301
return Ok(());
298302
}
303+
if meta.path.is_ident("passthrough") {
304+
if parsed.passthrough {
305+
return Err(meta.error("`passthrough` is given twice"));
306+
}
307+
parsed.passthrough = true;
308+
return Ok(());
309+
}
299310
// Removed rather than unknown, so the message can say what
300311
// to write instead.
301312
if meta.path.is_ident("nested") {
@@ -310,8 +321,8 @@ impl FieldAttrs {
310321
}
311322
Err(meta.error(
312323
"unsupported field attribute; expected `context_field`, \
313-
`identity = \"...\"`, `from = field`, `default`, `default = expr` or \
314-
`decrypt`",
324+
`identity = \"...\"`, `from = field`, `default`, `default = expr`, \
325+
`decrypt` or `passthrough`",
315326
))
316327
})?;
317328
}

‎packages/stack-encrypt-derive/src/decrypt.rs‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -148,7 +148,7 @@ pub(crate) fn derive(input: DeriveInput) -> Result<TokenStream> {
148148
);
149149
Ok(quote!(#(#impls)* #field #definition_check))
150150
}
151-
fn struct_literal_path(plaintext: &Type) -> Result<Path> {
151+
pub(crate) fn struct_literal_path(plaintext: &Type) -> Result<Path> {
152152
let Type::Path(type_path) = plaintext else {
153153
return Err(syn::Error::new_spanned(
154154
plaintext,
@@ -204,7 +204,12 @@ impl<'a> Auto<'a> {
204204
}
205205
}
206206

207-
fn check(krate: &Path, name: &Ident, from: Option<&Member>, fields: &[&Field]) -> TokenStream {
207+
pub(crate) fn check(
208+
krate: &Path,
209+
name: &Ident,
210+
from: Option<&Member>,
211+
fields: &[&Field],
212+
) -> TokenStream {
208213
let terms = fields.iter().map(|field| {
209214
let ty = &field.ty;
210215
// Spanned at the field type: a type that is not `Decryptable` is

‎packages/stack-encrypt-derive/src/encrypt.rs‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,9 @@ fn assignments<'a>(
3535
Kind::Default(Some(expr)) => quote!(#expr),
3636
Kind::Default(None) => quote!(::core::default::Default::default()),
3737
Kind::Context => stored.clone(),
38+
Kind::Passthrough { .. } => {
39+
unreachable!("the structural derive refuses a passthrough field")
40+
}
3841
};
3942
quote!(#member: #value)
4043
})
@@ -272,7 +275,11 @@ fn value_derive(input: &DeriveInput, record: &Record, fields: &[&Field]) -> Toke
272275
quote!(#plan #(#impls)*)
273276
}
274277

275-
fn decryptable_impl(input: &DeriveInput, record: &Record, derived: &[&Field]) -> TokenStream {
278+
pub(crate) fn decryptable_impl(
279+
input: &DeriveInput,
280+
record: &Record,
281+
derived: &[&Field],
282+
) -> TokenStream {
276283
let krate = &record.krate;
277284
let name = &input.ident;
278285
let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();

‎packages/stack-encrypt-derive/src/lib.rs‎

Lines changed: 38 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,13 @@
1-
//! Derive operation declarations for encrypted records. `EncryptFrom<P>`
2-
//! declares how to produce a target; `DecryptInto<P>` selects ciphertext for
3-
//! recovery. Stack Encrypt owns execution through Vitamin C's plaintext traits.
4-
//! Generated code receives context and encrypted outputs, never a cipher.
1+
//! Derive operation declarations for encrypted records. The owned pair,
2+
//! `EncryptTarget<P>` / `DecryptSource<P>`, declares a record the owned
3+
//! conversions (`value.encrypt_into(&keyset)`, `P::decrypt_from(record, &cipher)`)
4+
//! run, consuming and wiping the plaintext; the structural pair,
5+
//! `EncryptFrom<P>` / `DecryptInto<P>`, declares one run over a borrowed
6+
//! plaintext by `keyset.encrypt_as` and `cipher.decrypt_as`. Both take the
7+
//! same attributes (see [Owned records](#owned-records) for what only the
8+
//! owned pair adds). Stack Encrypt owns execution through Vitamin C's
9+
//! plaintext traits. Generated code receives context and encrypted outputs,
10+
//! never a cipher.
511
//!
612
//! ```
713
//! use stack_encrypt::{EncryptFrom, DecryptInto, StackCipher, StackCipherText, nonempty};
@@ -204,6 +210,8 @@ use syn::{parse_macro_input, DeriveInput};
204210
mod attrs;
205211
mod decrypt;
206212
mod encrypt;
213+
mod owned_decrypt;
214+
mod owned_encrypt;
207215
mod shape;
208216

209217
/// Derive `EncryptFrom` for a record struct. See the [crate
@@ -229,3 +237,29 @@ pub fn derive_decrypt_into(input: TokenStream) -> TokenStream {
229237
.unwrap_or_else(syn::Error::into_compile_error)
230238
.into()
231239
}
240+
241+
/// Derive the owned `EncryptTarget` declaration for a record struct, with
242+
/// the structural `EncryptFrom` beside it as a bridge. Takes the same
243+
/// attributes as `EncryptFrom`, plus `#[stash(passthrough)]` on a field of
244+
/// a `struct = ..` record. See [Owned records](crate#owned-records).
245+
#[doc = include_str!("../docs/attributes.md")]
246+
#[proc_macro_derive(EncryptTarget, attributes(stash))]
247+
pub fn derive_encrypt_target(input: TokenStream) -> TokenStream {
248+
let input = parse_macro_input!(input as DeriveInput);
249+
owned_encrypt::derive(input)
250+
.unwrap_or_else(syn::Error::into_compile_error)
251+
.into()
252+
}
253+
254+
/// Derive the owned `DecryptSource<Plaintext>` declaration for a record
255+
/// struct, one impl per `plaintext` type, with the structural `DecryptInto`
256+
/// and `DecryptField` beside it as a bridge. See
257+
/// [Owned records](crate#owned-records).
258+
#[doc = include_str!("../docs/attributes.md")]
259+
#[proc_macro_derive(DecryptSource, attributes(stash))]
260+
pub fn derive_decrypt_source(input: TokenStream) -> TokenStream {
261+
let input = parse_macro_input!(input as DeriveInput);
262+
owned_decrypt::derive(input)
263+
.unwrap_or_else(syn::Error::into_compile_error)
264+
.into()
265+
}

0 commit comments

Comments
 (0)