Skip to content

Commit b4be625

Browse files
committed
fix(stack-encrypt): context_from picks a stored context field, not any value of the plaintext
Review findings on #1588. `select` saw the whole plaintext and returned any context, so a context could be computed from the value being sealed and leave it as a ZeroKMS descriptor, a clear `i`, and an AAD that needed the plaintext to open. It also allowed a context read from the plaintext and never stored, which the API plan rules out: a program must never need the plaintext to learn the context that opens it. `context_from` now takes `pick: fn(&S) -> &C`, a reference to a field the plaintext holds, and applies only to a target whose context input is `NonEmpty<C>`: a record with a `context_field`, or an EQL type, which stores its column in `i`. It checks the context is non-empty itself, so callers no longer map the error. A `# Security` section says the field is sent to ZeroKMS and stored in the clear. ADR-0004 gains an amendment recording the third way to set a context and the limits that keep decision 2's reasons, and the module and type docs that listed only `under` and `extend` now name it. Tests move onto a target that stores its context: the value opens from the row alone; another column is a `ContextMismatch`; an empty column is refused with no key request and the plaintext wiped; each row of a column is sent under its own descriptor in one batch; and one bad row refuses the whole column. The migration shim's rename test now opens the value under the new column and shows a relabelled value fails authentication, and its ORE check orders the value between 40 and 42.
1 parent dda7335 commit b4be625

5 files changed

Lines changed: 279 additions & 158 deletions

File tree

‎packages/eql/tests/encryption/tests/migration_shim.rs‎

Lines changed: 69 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,8 @@
1313
1414
mod common;
1515

16+
use std::cmp::Ordering;
17+
1618
use eql_bindings::v4::integer::{IntegerOrdOre, IntegerOrdOreQuery};
1719
use eql_bindings::v4::text::{TextEq, TextEqQuery};
1820
use eql_bindings::Identifier;
@@ -25,7 +27,7 @@ struct V3Plaintext<P> {
2527
p: P,
2628
}
2729
impl<P: Zeroize> Zeroize for V3Plaintext<P> {
28-
// The column is not secret.
30+
// The column is not secret: it is stored in the clear in `i`.
2931
fn zeroize(&mut self) {
3032
self.p.zeroize();
3133
}
@@ -46,9 +48,7 @@ where
4648
{
4749
T::encryption()
4850
.project(|source: &V3Plaintext<P>| &source.p)
49-
.context_from(|source| {
50-
NonEmpty::new(source.i.clone()).map_err(|e| Error::Other(Box::new(e)))
51-
})
51+
.context_from(|source: &V3Plaintext<P>| &source.i)
5252
.map(Shim)
5353
}
5454
}
@@ -64,6 +64,26 @@ fn column(table: &str, column: &str) -> NonEmpty<Identifier> {
6464
Identifier::for_column(table, column).unwrap()
6565
}
6666

67+
async fn email_query(
68+
keyset: &stack_encrypt::KeysetCipher<'_, common::Observed>,
69+
name: &str,
70+
) -> TextEqQuery {
71+
"alan@example.com"
72+
.to_owned()
73+
.encrypt_into_with_context(keyset, column("customers", name))
74+
.await
75+
.unwrap()
76+
}
77+
78+
async fn age_query(
79+
keyset: &stack_encrypt::KeysetCipher<'_, common::Observed>,
80+
age: i32,
81+
) -> IntegerOrdOreQuery {
82+
age.encrypt_into_with_context(keyset, column("customers", "age"))
83+
.await
84+
.unwrap()
85+
}
86+
6787
#[tokio::test]
6888
async fn a_v3_value_encrypts_as_the_v4_type_with_no_context_argument() {
6989
let (cipher, _) = common::cipher().await;
@@ -106,22 +126,28 @@ async fn the_same_shim_covers_an_ordered_type() {
106126
};
107127
let Shim(migrated): Shim<IntegerOrdOre> = source.encrypt_into(&keyset).await.unwrap();
108128

109-
// A block ORE term carries a nonce, so it is compared by order.
110-
let query: IntegerOrdOreQuery = 41_i32
111-
.encrypt_into_with_context(&keyset, column("customers", "age"))
112-
.await
113-
.unwrap();
114-
assert!(
115-
migrated.ob == query.ob,
116-
"the query orders equal to the migrated value"
129+
// A block ORE term carries a nonce, so it is compared by order: the
130+
// migrated value sits between the queries for 40 and 42, and orders
131+
// equal to the query for 41.
132+
let compare = |query: &IntegerOrdOreQuery| migrated.ob.partial_cmp(&query.ob);
133+
assert_eq!(
134+
compare(&age_query(&keyset, 40).await),
135+
Some(Ordering::Greater)
136+
);
137+
assert_eq!(
138+
compare(&age_query(&keyset, 41).await),
139+
Some(Ordering::Equal)
117140
);
141+
assert_eq!(compare(&age_query(&keyset, 42).await), Some(Ordering::Less));
118142

119-
let opened = i32::decrypt_from(migrated, &keyset).await.unwrap();
143+
let opened = i32::decrypt_from_with_context(migrated, &keyset, column("customers", "age"))
144+
.await
145+
.unwrap();
120146
assert_eq!(opened, 41);
121147
}
122148

123149
#[tokio::test]
124-
async fn a_renamed_column_is_the_column_the_value_is_stored_under() {
150+
async fn a_renamed_column_is_the_column_the_value_is_sealed_under() {
125151
let (cipher, _) = common::cipher().await;
126152
let keyset = cipher.default_keyset();
127153

@@ -131,27 +157,39 @@ async fn a_renamed_column_is_the_column_the_value_is_stored_under() {
131157
};
132158
source.i.c = "contact_email".to_owned();
133159
let Shim(migrated): Shim<TextEq> = source.encrypt_into(&keyset).await.unwrap();
134-
135160
assert_eq!(migrated.i.c, "contact_email");
136-
let renamed: TextEqQuery = "alan@example.com"
137-
.to_owned()
138-
.encrypt_into_with_context(&keyset, column("customers", "contact_email"))
139-
.await
140-
.unwrap();
141-
let original: TextEqQuery = "alan@example.com"
142-
.to_owned()
143-
.encrypt_into_with_context(&keyset, column("customers", "email"))
144-
.await
145-
.unwrap();
146-
assert_eq!(migrated.hm, renamed.hm, "the new column's query finds it");
147-
assert_ne!(migrated.hm, original.hm, "the old column's query does not");
148161

162+
// The new column's query finds it, and the old column's does not.
163+
assert_eq!(migrated.hm, email_query(&keyset, "contact_email").await.hm);
164+
assert_ne!(migrated.hm, email_query(&keyset, "email").await.hm);
165+
166+
// The ciphertext is sealed under the new column: it opens there.
167+
let opened = String::decrypt_from_with_context(
168+
migrated.clone(),
169+
&keyset,
170+
column("customers", "contact_email"),
171+
)
172+
.await
173+
.unwrap();
174+
assert_eq!(opened, "alan@example.com");
175+
176+
// Asked for the old column, the stored column does not match, so it is
177+
// refused before any key is requested.
178+
let result =
179+
String::decrypt_from_with_context(migrated.clone(), &keyset, column("customers", "email"))
180+
.await;
149181
assert!(
150-
String::decrypt_from_with_context(migrated, &keyset, column("customers", "email"))
151-
.await
152-
.is_err(),
153-
"it does not open as the old column"
182+
matches!(result, Err(Error::ContextMismatch { .. })),
183+
"{:?}",
184+
result.err()
154185
);
186+
187+
// With the stored column changed back to the old one, the ciphertext
188+
// itself refuses to open: it is bound to the new column, not the label.
189+
let mut relabelled = migrated;
190+
relabelled.i.c = "email".to_owned();
191+
let result = String::decrypt_from(relabelled, &keyset).await;
192+
assert!(matches!(result, Err(Error::Aead)), "{:?}", result.err());
155193
}
156194

157195
#[tokio::test]

‎packages/stack-encrypt/CHANGELOG.md‎

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -71,15 +71,19 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7171

7272
### Added
7373

74-
- **A target can take its context from the plaintext:
74+
- **A target can take its context from a field of the plaintext:
7575
`Encryption::context_from`** (#1586). A value that arrives with the
7676
context it is stored under, such as a value decrypted from an older
7777
format together with its column, encrypts with no context argument. A
78-
type that wraps the target reads the context out of the plaintext once,
79-
in its `EncryptTarget` declaration, and declares `NoCallerContext`. If
80-
the context cannot be read, the encryption fails and no key is
81-
requested. The context is read through a plain function pointer, which
82-
cannot reach a cipher.
78+
type that wraps the target names the field once, in its `EncryptTarget`
79+
declaration, and declares `NoCallerContext`. It applies to a target whose
80+
context input is a typed `NonEmpty<C>`, such as a record with a
81+
`context_field` or an EQL type, so the context is also stored in the row
82+
and opening a value never needs its plaintext. The field is picked by
83+
reference, so a context cannot be computed from the sealed value. An
84+
empty context fails the encryption before any key is requested. The
85+
picked field is sent to ZeroKMS and stored in the clear, so it must not
86+
be secret.
8387
- **Optional values through the owned API: `Option<T>`** (#1585). An
8488
`Option<S>` encrypts into an `Option<T>` for any owned target `T`, and
8589
decrypts back.

‎packages/stack-encrypt/docs/adr/0004-one-context-per-target-threaded-through-the-declaration-tree.md‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,9 @@ literal `"users/age"`. A column is the pair now, which renders the ZeroKMS
113113
descriptor `users/age`; the joined literal is one part and renders escaped.
114114
See ADR-0006.)
115115

116+
A third way, `context_from`, reads the context from a field of the plaintext.
117+
See the amendment of 2026-11-09 below.
118+
116119
Two further combinators change nothing about *which* context reaches a
117120
subtree, only its type at the root. `accepting` converts the context a record
118121
declares its caller supplies into the one its operations need, once, at the
@@ -354,3 +357,36 @@ language allows; Go-1). The dynamic-to-static dispatch itself is unchanged.
354357
Decisions 1 to 4, 7 and 8 do not change. Decision 2's `extend` is what
355358
`Cipher.Extend` does from Go: a caller's context appends to the declared one,
356359
and never replaces it.
360+
361+
## Amended 2026-11-09 (#1586)
362+
363+
Decision 2 gains a third way to set a subtree's context:
364+
`Encryption::context_from`. It records the case `under` and `extend` do not
365+
cover: a value that arrives carrying the context it is stored under, such as a
366+
value decrypted from EQL v3 together with its column. Re-encrypting it as EQL
367+
v4 should read that column, not ask the caller to repeat it.
368+
369+
`context_from(pick)` reads the context from a field of the plaintext and
370+
discharges the requirement into `NoCallerContext`, so the caller supplies
371+
none. Three limits keep decision 2's reasons intact:
372+
373+
- **It applies only to a target whose context input is a typed context,
374+
`NonEmpty<C>`.** A record that stores its context in a `context_field`
375+
declares that, and so does an EQL type, which stores its column in `i`. So
376+
the context comes from the plaintext on the way in and from the row on the
377+
way out. Opening a value never needs its plaintext.
378+
- **`pick` returns a reference to a field the plaintext holds.** It cannot
379+
compute a context from the plaintext. Where the context type differs from
380+
the sealed value's type, the sealed field cannot be picked at all.
381+
- **The field is named in the declaration.** It is a plain function pointer,
382+
visible at review, like `project`'s selector. It is not a value supplied at
383+
the call that could reach one side and not another.
384+
385+
It replaces the surrounding context rather than extending it. A target that
386+
takes its context this way is not a field of a record that declares contexts,
387+
since its context input is `NoCallerContext`.
388+
389+
As with two `under` literals, two halves of one target zipped after separate
390+
`context_from` calls could each take a different field. That is the
391+
divergence decision 1 already accepts for declared per-side contexts: each
392+
field is named in the declaration.

0 commit comments

Comments
 (0)