Skip to content

Commit 4f275d1

Browse files
committed
fix(stack-encrypt): address the review of CipherRef
- The rustdoc on CipherRef named every entry point that runs through a cipher. It now names the ones that take it: the decrypt entry points and the Pending constructors. It says that an encrypt entry point takes a KeysetCipher, and that a CipherRef lives as long as the connection. - The CHANGELOG entry lists every changed function. It says that an owned KeysetCipher is now accepted, that a pending through a temporary keyset handle now compiles, and what to write in place of a CipherScope bound. - CipherRef has one accessor for the keyset, keyset_id(). Its Debug output names the field keyset_id, as KeysetCipher's does. - Functions that only forward the argument no longer convert it first. The private collect_releasing and decrypt_through take a CipherRef. - New tests: an owned KeysetCipher refuses a foreign leaf before any key is retrieved, and opens its own; a pending outlives a temporary keyset handle; the guest's scope_for gives the right keyset for each selector; and a compile-fail case pins the "consider borrowing" hint for a StackCipher passed by value. - CONTEXT.md is rewrapped and names the owned KeysetCipher. The plan's tracking line says that #1120 is closed and #1504 is merged.
1 parent 15e5f8c commit 4f275d1

12 files changed

Lines changed: 134 additions & 37 deletions

File tree

‎docs/plans/2026-10-24-stack-encrypt-api-plan.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1758,7 +1758,7 @@ records only the work.
17581758
the Go guest builds one from its keyset selector. A `Keyset` reference
17591759
refuses a foreign leaf with `ForeignKeyset`. A `Cipher` reference opens leaves from any keyset the client has.
17601760
Done, in the second pull request for #1488.
1761-
- **Tracked in.** Issue #1488 is open. It is the chain removal. Issue #1120 is open. Pull request #1504 is open and adds the record pairs.
1761+
- **Tracked in.** Issue #1488 is open. It is the chain removal. Issue #1120 is closed. Pull request #1504 is merged and added the record pairs.
17621762
- **Finished when** these are all true:
17631763
- the examples in [Target state](#target-state) compile;
17641764
- the compile-fail cases in `tests/ui` cover a binding in a query, and

‎languages/golang/encrypt/guest/tests/native_ops.rs‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ use stack_encrypt::{
2727
};
2828
use stack_encrypt::{Controlled, Protected};
2929
use stack_encrypt_guest::ops::{self, TERM_EQUALITY, TERM_MATCH, TERM_OPE, TERM_ORE};
30+
use stack_encrypt_guest::options::{scope_for, KeysetSelector};
3031
use stack_encrypt_guest::status::{
3132
STATUS_AUTH, STATUS_CONTEXT_MISMATCH, STATUS_ENCODING, STATUS_FOREIGN_KEYSET, STATUS_TERM,
3233
};
@@ -1010,6 +1011,28 @@ fn a_mixed_keyset_record_batch_opens_through_any_one_call_per_keyset() {
10101011
assert_eq!(cipher.kms().retrieve_calls.load(Ordering::SeqCst), before);
10111012
}
10121013

1014+
/// Each opening selector names the reference a decrypt runs through:
1015+
/// `{"any"}` the client, confined to no keyset, and every other selector
1016+
/// the keyset it resolves to.
1017+
#[test]
1018+
fn each_opening_selector_names_its_keyset() {
1019+
let cipher = cipher();
1020+
let acme = keyset_named(&cipher, "acme").keyset_id();
1021+
let keyset_of =
1022+
|selector: KeysetSelector| block_on(scope_for(&cipher, &selector)).map(|r| r.keyset_id());
1023+
1024+
assert_eq!(keyset_of(KeysetSelector::Any), Ok(None));
1025+
assert_eq!(
1026+
keyset_of(KeysetSelector::Default),
1027+
Ok(Some(cipher.default_keyset().keyset_id()))
1028+
);
1029+
let name = zerokms_protocol::Name::try_from("acme")
1030+
.ok()
1031+
.expect("a valid name");
1032+
assert_eq!(keyset_of(KeysetSelector::Name(name)), Ok(Some(acme)));
1033+
assert_eq!(keyset_of(KeysetSelector::Id(acme)), Ok(Some(acme)));
1034+
}
1035+
10131036
/// Terms derive under the selected keyset's index key: the same probe
10141037
/// under two keysets differs, and matches the native derivation for each.
10151038
#[test]

‎packages/stack-encrypt/CHANGELOG.md‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -95,8 +95,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
9595
`&KeysetCipher`, or an owned `KeysetCipher`, and in no other way.
9696
- Every entry point that took `impl CipherScope` takes
9797
`impl Into<CipherRef>`. A call that passes `&cipher` or `&keyset`
98-
compiles unchanged: `decrypt_from`, `Pending::ready`, `Pending::failed`,
99-
`Pending::request`, and `Pending::all`.
98+
compiles unchanged. These are `DecryptFrom::decrypt_from` and
99+
`decrypt_from_with_context`, the legacy `decrypt_into`, `decrypt_from`
100+
and `decrypt_from_with_context`, and `Pending::ready`, `failed`,
101+
`request` and `all`.
102+
- A function of your own that took `impl CipherScope<'a, K>` takes
103+
`impl Into<CipherRef<'a, K>>` instead.
104+
- These entry points now also take an owned `KeysetCipher`.
105+
- A pending built through `&keyset` now lives as long as the
106+
connection, not as long as the borrow of the keyset handle. So
107+
`i32::decrypt_from(ciphertext, &cipher.default_keyset())` compiles
108+
when the pending is stored and awaited later.
100109
- `dynamic::record::decrypt` and `decrypt_with` take
101110
`impl Into<CipherRef>` too. Write `&cipher` in place of
102111
`Scope::Client(&cipher)`, and `&keyset` or `keyset` in place of

‎packages/stack-encrypt/CONTEXT.md‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -373,8 +373,9 @@ What a `Pending` was built through, and therefore what it is allowed to do:
373373
a `KeysetCipher` scope mints under its keyset and opens leaves from no
374374
other; a `StackCipher` scope mints nothing and opens leaves from any keyset.
375375
`CipherRef` is the one borrowed value that carries the choice: a connection
376-
and an optional keyset ID, built from a reference to either cipher. The typed
377-
API and the dynamic interface both take it. Two pendings merge when their scopes agree on a keyset — which
376+
and an optional keyset ID. It is built from a reference to either cipher, or
377+
from an owned `KeysetCipher`. The typed API and the dynamic interface both
378+
take it. Two pendings merge when their scopes agree on a keyset — which
378379
cipher *value* each came from is not part of the rule.
379380
_Avoid_: binding (that is a name's), context (that is the AAD's), opener
380381

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

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1057,7 +1057,7 @@ impl<K: DataKeySource + IndexKeySource> KeysetCipher<'_, K> {
10571057
T: Decrypt,
10581058
A: IntoContext<'a>,
10591059
{
1060-
decrypt_through(self, ciphertext, context).await
1060+
decrypt_through(self.into(), ciphertext, context).await
10611061
}
10621062
}
10631063

@@ -1073,14 +1073,13 @@ impl<K: DataKeySource + IndexKeySource> KeysetCipher<'_, K> {
10731073
/// `for_sequence_element`, `for_map_entry`, `for_leaf` — and that
10741074
/// derivation is the library's to compute, never the caller's to supply.
10751075
async fn decrypt_through<'s, 'a, T, K: DataKeySource + IndexKeySource + 's>(
1076-
scope: impl Into<crate::target::CipherRef<'s, K>>,
1076+
scope: crate::target::CipherRef<'s, K>,
10771077
ciphertext: StackCipherText,
10781078
aad: impl IntoContext<'a>,
10791079
) -> Result<T, Error>
10801080
where
10811081
T: Decrypt,
10821082
{
1083-
let scope: crate::target::CipherRef<'s, K> = scope.into();
10841083
let context = aad.into_context();
10851084
let keyed = crate::target::bind_pending(scope, ciphertext, Descriptor::of(context.clone()))
10861085
.settle()
@@ -1128,7 +1127,7 @@ impl<K: DataKeySource + IndexKeySource> StackCipher<K> {
11281127
T: Decrypt,
11291128
A: IntoContext<'a>,
11301129
{
1131-
decrypt_through(self, ciphertext, context).await
1130+
decrypt_through(self.into(), ciphertext, context).await
11321131
}
11331132
}
11341133

‎packages/stack-encrypt/src/dynamic/record.rs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2117,7 +2117,7 @@ pub fn decrypt_with<'a, K: 'static>(
21172117
let rows = record_rows(record, plan)?;
21182118
let extend = plan.declared_context();
21192119
let shape = plan.shape();
2120-
let (cipher, keyset) = (scope.cipher(), scope.keyset());
2120+
let (cipher, keyset) = (scope.cipher(), scope.keyset_id());
21212121
let mut pendings = Vec::new();
21222122
let mut targets = |row: StoredRow| -> Result<(Absent, FieldValues, usize), Error> {
21232123
let fields = plan
@@ -5609,7 +5609,7 @@ mod tests {
56095609
async fn debug_names_the_keyset_a_reference_is_confined_to() {
56105610
let cipher = cipher().await;
56115611
let any = format!("{:?}", CipherRef::from(&cipher));
5612-
assert!(any.contains("keyset: None"), "{any}");
5612+
assert!(any.contains("keyset_id: None"), "{any}");
56135613
let keyset = cipher.default_keyset();
56145614
let one = format!("{:?}", CipherRef::from(&keyset));
56155615
assert!(one.contains(&format!("{:?}", keyset.keyset_id())), "{one}");

‎packages/stack-encrypt/src/target/conversion.rs‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -130,7 +130,6 @@ pub trait DecryptFrom: Zeroize + Sized + 'static {
130130
S: DecryptSource<Self>,
131131
S::ContextInput: AllowsNoContext,
132132
{
133-
let cipher: CipherRef<'a, K> = cipher.into();
134133
source
135134
.decryption(S::ContextInput::omitted())
136135
.open_in(cipher)
@@ -146,7 +145,6 @@ pub trait DecryptFrom: Zeroize + Sized + 'static {
146145
S: DecryptSource<Self>,
147146
S::ContextInput: AcceptsContext,
148147
{
149-
let cipher: CipherRef<'a, K> = cipher.into();
150148
source
151149
.decryption(S::ContextInput::supplied(context.into()))
152150
.open_in(cipher)

‎packages/stack-encrypt/src/target/operations.rs‎

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1369,7 +1369,7 @@ impl<T: 'static, K: 'static> Decryption<T, K> {
13691369
Opening::Failed(error) => return Pending::failed(scope, error),
13701370
Opening::Open(open) => open(scope.cipher()),
13711371
};
1372-
match scope.keyset() {
1372+
match scope.keyset_id() {
13731373
Some(id) => pending.scoped_to(id),
13741374
None => pending,
13751375
}
@@ -1573,7 +1573,6 @@ pub trait LegacyDecryptFrom: Sized + 'static {
15731573
where
15741574
Self: DecryptInto<P>,
15751575
{
1576-
let cipher: CipherRef<'a, K> = cipher.into();
15771576
self.decryption(context.into()).open_in(cipher)
15781577
}
15791578
/// Recover `Self` from `source` with its default context — the plain
@@ -1587,7 +1586,6 @@ pub trait LegacyDecryptFrom: Sized + 'static {
15871586
S: DecryptInto<Self> + 'static,
15881587
S::Context: Default,
15891588
{
1590-
let cipher: CipherRef<'a, K> = cipher.into();
15911589
source.decrypt_into(cipher, S::Context::default())
15921590
}
15931591
/// Recover `Self` from `source` under `context`.
@@ -1599,7 +1597,6 @@ pub trait LegacyDecryptFrom: Sized + 'static {
15991597
where
16001598
S: DecryptInto<Self> + 'static,
16011599
{
1602-
let cipher: CipherRef<'a, K> = cipher.into();
16031600
source.decrypt_into(cipher, context.into())
16041601
}
16051602
}

‎packages/stack-encrypt/src/target/pending.rs‎

Lines changed: 20 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -90,10 +90,18 @@ pub struct Pending<'a, T, K> {
9090
/// What a [`Pending`] is built through: a borrowed connection, and the
9191
/// keyset it is confined to, if any.
9292
///
93-
/// Build one from a reference to a [`StackCipher`] or to a
94-
/// [`KeysetCipher`]. Every entry point that runs through a cipher takes
95-
/// `impl Into<CipherRef>`, so a caller passes `&cipher` or `&keyset` and
96-
/// never names this type.
93+
/// Build one from a reference to a [`StackCipher`], or from a
94+
/// [`KeysetCipher`], borrowed or owned. The entry points that can run
95+
/// through either cipher take `impl Into<CipherRef>`. These are the decrypt
96+
/// entry points, such as [`DecryptFrom::decrypt_from`](super::DecryptFrom::decrypt_from)
97+
/// and `dynamic::record::decrypt`, and the [`Pending`] constructors. So a
98+
/// caller passes `&cipher` or `&keyset` and does not name this type. An
99+
/// entry point that encrypts needs a keyset to generate keys under, so it
100+
/// takes a [`KeysetCipher`] and not a `CipherRef`.
101+
///
102+
/// A `CipherRef` built from a [`KeysetCipher`] keeps the keyset's ID and
103+
/// the connection, not the handle. So it lives as long as the connection,
104+
/// even when the handle is a temporary value.
97105
///
98106
/// - A reference to a [`StackCipher`] is confined to no keyset. It opens a
99107
/// leaf sealed under any keyset the client can use. It cannot generate a
@@ -132,11 +140,6 @@ impl<'c, K> CipherRef<'c, K> {
132140
self.cipher
133141
}
134142

135-
/// The keyset the pending is confined to, if any.
136-
pub(crate) fn keyset(&self) -> Option<Uuid> {
137-
self.keyset
138-
}
139-
140143
/// The ID of the keyset this reference is confined to. `None` for a
141144
/// reference to a [`StackCipher`], which is confined to no keyset.
142145
pub fn keyset_id(&self) -> Option<Uuid> {
@@ -156,7 +159,7 @@ impl<K> Copy for CipherRef<'_, K> {}
156159
impl<K> std::fmt::Debug for CipherRef<'_, K> {
157160
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
158161
f.debug_struct("CipherRef")
159-
.field("keyset", &self.keyset)
162+
.field("keyset_id", &self.keyset)
160163
.finish_non_exhaustive()
161164
}
162165
}
@@ -196,7 +199,7 @@ impl<'a, T: 'a, K> Pending<'a, T, K> {
196199
match result {
197200
Ok(value) => Self {
198201
cipher: scope.cipher(),
199-
keyset: scope.keyset(),
202+
keyset: scope.keyset_id(),
200203
requests: Vec::new(),
201204
failed: None,
202205
contexts: Vec::new(),
@@ -224,7 +227,7 @@ impl<'a, T: 'a, K> Pending<'a, T, K> {
224227
let scope: CipherRef<'a, K> = scope.into();
225228
Self {
226229
cipher: scope.cipher(),
227-
keyset: scope.keyset(),
230+
keyset: scope.keyset_id(),
228231
requests: Vec::new(),
229232
failed: Some(error),
230233
contexts: Vec::new(),
@@ -259,12 +262,12 @@ impl<'a, T: 'a, K> Pending<'a, T, K> {
259262
{
260263
let scope: CipherRef<'a, K> = scope.into();
261264
let (generated, retrieved, keysets) = tally(&requests);
262-
if let Err(error) = check_scope(scope.keyset(), &requests) {
265+
if let Err(error) = check_scope(scope.keyset_id(), &requests) {
263266
return Self::failed(scope, error);
264267
}
265268
Self {
266269
cipher: scope.cipher(),
267-
keyset: scope.keyset(),
270+
keyset: scope.keyset_id(),
268271
requests,
269272
failed: None,
270273
contexts: Vec::new(),
@@ -466,7 +469,6 @@ impl<'a, T: 'a, K> Pending<'a, T, K> {
466469
scope: impl Into<CipherRef<'a, K>>,
467470
items: Vec<Pending<'a, T, K>>,
468471
) -> Pending<'a, Vec<T>, K> {
469-
let scope: CipherRef<'a, K> = scope.into();
470472
Self::collect(scope, items)
471473
}
472474

@@ -507,14 +509,13 @@ impl<'a, T: 'a, K> Pending<'a, T, K> {
507509
/// When an item fails or panics, `release` receives the items fulfilled
508510
/// before it. When every item succeeds, `release` is not called.
509511
fn collect_releasing(
510-
scope: impl Into<CipherRef<'a, K>>,
512+
scope: CipherRef<'a, K>,
511513
items: impl IntoIterator<Item = Pending<'a, T, K>>,
512514
release: impl FnOnce(Vec<T>) + MaybeSend + 'a,
513515
) -> Pending<'a, Vec<T>, K> {
514-
let scope: CipherRef<'a, K> = scope.into();
515516
let items = items.into_iter();
516517
let cipher = scope.cipher();
517-
let mut keyset = scope.keyset();
518+
let mut keyset = scope.keyset_id();
518519
let mut requests = Vec::new();
519520
let mut contexts = Vec::new();
520521
let mut fulfils = Vec::with_capacity(items.size_hint().0);
@@ -916,7 +917,6 @@ mod tests {
916917
let owned = CipherRef::from(keyset.clone());
917918
for one in [borrowed, owned] {
918919
assert_eq!(one.keyset_id(), Some(keyset.keyset_id()));
919-
assert_eq!(one.keyset(), one.keyset_id());
920920
assert!(std::ptr::eq(one.cipher(), &cipher));
921921
}
922922
// A pending keeps the keyset of the reference it was built through.
@@ -925,7 +925,7 @@ mod tests {
925925
let pending = Pending::ready(&cipher, Ok(()));
926926
assert_eq!(pending.keyset, None);
927927
let shown = format!("{any:?} {borrowed:?}");
928-
assert!(shown.contains("keyset: None"), "{shown}");
928+
assert!(shown.contains("keyset_id: None"), "{shown}");
929929
assert!(
930930
shown.contains(&format!("{:?}", keyset.keyset_id())),
931931
"{shown}"

‎packages/stack-encrypt/tests/scalar.rs‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -243,6 +243,43 @@ async fn wrong_keyset_is_rejected_before_retrieval() {
243243
assert_eq!(retrieves.load(Ordering::SeqCst), 0);
244244
}
245245

246+
/// An owned keyset handle confines a decrypt as a borrowed one does: a
247+
/// leaf from another keyset is refused before any key is retrieved, and
248+
/// its own leaf opens.
249+
#[tokio::test]
250+
async fn an_owned_keyset_confines_a_typed_decrypt() {
251+
use std::sync::atomic::Ordering;
252+
let (cipher, _, retrieves) = common::counting_cipher().await;
253+
let keyset = cipher.default_keyset();
254+
let other = cipher
255+
.keyset(stack_encrypt::kms::IdentifiedBy::Uuid(uuid::Uuid::new_v4()))
256+
.await
257+
.unwrap();
258+
let ct = keyset.encrypt(42i32).await.unwrap();
259+
assert!(matches!(
260+
i32::decrypt_from(ct, other).await,
261+
Err(Error::ForeignKeyset { .. })
262+
));
263+
assert_eq!(retrieves.load(Ordering::SeqCst), 0);
264+
265+
let ct = keyset.encrypt(42i32).await.unwrap();
266+
assert_eq!(i32::decrypt_from(ct, keyset.clone()).await.unwrap(), 42);
267+
}
268+
269+
/// A pending built through a keyset keeps the keyset's ID, not a borrow of
270+
/// the handle. So the handle can be a temporary value, and the pending can
271+
/// be stored and awaited after the handle is dropped.
272+
#[tokio::test]
273+
async fn a_pending_outlives_a_temporary_keyset_handle() {
274+
let (cipher, _, _) = common::counting_cipher().await;
275+
let ct = cipher.default_keyset().encrypt(42i32).await.unwrap();
276+
// The borrow is the point of this test, so clippy's advice to pass the
277+
// handle by value does not apply.
278+
#[allow(clippy::needless_borrows_for_generic_args)]
279+
let pending = i32::decrypt_from(ct, &cipher.default_keyset());
280+
assert_eq!(pending.await.unwrap(), 42);
281+
}
282+
246283
// Deliberately not Clone: selecting a scalar field must not copy its owner.
247284
struct Tracked {
248285
value: String,

0 commit comments

Comments
 (0)