Skip to content

Commit c9b6d77

Browse files
authored
Merge pull request #1245 from cipherstash/feat/stack-encrypt-frame-sinks
feat(stack-encrypt)!: hold a dynamic plaintext as its frame, not a value tree
2 parents d5e660d + 8dd8f32 commit c9b6d77

26 files changed

Lines changed: 3077 additions & 528 deletions

File tree

‎.cargo/mutants.toml‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,9 @@ exclude_re = [
8585
# the empty list (`dynamic::target::NoTargets`), which a test asserts on
8686
# and `resolve` turns into `TargetError::NoTargets`; `vec![]` is the body.
8787
'stack-encrypt/src/dynamic/target\.rs:\d+:\d+: replace <impl TargetResolver for NoTargets>::targets -> Vec<TargetDescriptor> with vec!\[\]$',
88+
# A passthrough has no kind: `KindOf::passthrough` returns `Ok(None)`,
89+
# which is `Ok(Default::default())`. `a_frame_names_its_kind` asserts it.
90+
'stack-encrypt/src/dynamic/value_frame\.rs:\d+:\d+: replace <impl Sink for KindOf>::passthrough -> Result<Self::Ok, DecodeError> with Ok\(Default::default\(\)\)$',
8891
]
8992

9093
# Headroom over the measured baseline before a slow-but-correct mutant is

‎.changeset/eql-v4-bindings.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,6 @@
22
'@cipherstash/eql': minor
33
---
44

5-
**The `eql-bindings` crate has an `eql_bindings::v4` module, with the `stack-encrypt` feature: payload types for the EQL v4 domains.** EQL v4 is the v3 SQL installed under a second name (ADR-0002), for values written by Stack Encrypt, so the module exists only with that feature and its types derive Stack Encrypt's traits without a further gate. The module is generated from the same catalog as `v3`, with `eql_v4_*` domain names and `"v": 4`. `SchemaVersion` is now generic over the version it admits: `v3::SchemaVersion` is `SchemaVersion<3>` and `v4::SchemaVersion` is `SchemaVersion<4>`, each refusing the other's payloads, and plain `SchemaVersion` still means v3. Only v4 types derive Stack Encrypt's `EncryptFrom` and `DecryptInto`, and the Stack Encrypt target table (now `eql_bindings::v4::targets`) names v4 domains. Besides `TextEq`, Stack Encrypt now produces the storage-only types `Text`, `Integer`, `Bigint`, `Boolean`, `Real` and `Double`, and `TextMatch` (3-grams, `k = 6`, a 2048-bit filter, pinned as `eql_bindings::encryption::EqlMatch`; text shorter than three characters is refused, stored or queried, and only `stored @@ query` matches until #1171 is fixed), from the Rust primitives `i32`, `i64`, `bool`, `f32` and `f64`; the Go SDK's `encrypt/eql` table marks them producible. Stack Encrypt also produces the number equality types `IntegerEq`, `BigintEq`, `RealEq` and `DoubleEq`, whose `=` compares as PostgreSQL compares the plain types: an integer has one term whatever its width, and for floats `-0.0 = 0.0` and `NaN = NaN` (ADR-0002's semantic baseline). Every type it cannot produce yet names the issue that tracks its blocker.
5+
**The `eql-bindings` crate has an `eql_bindings::v4` module, with the `stack-encrypt` feature: payload types for the EQL v4 domains.** EQL v4 is the v3 SQL installed under a second name (ADR-0002), for values written by Stack Encrypt, so the module exists only with that feature and its types derive Stack Encrypt's traits without a further gate. The module is generated from the same catalog as `v3`, with `eql_v4_*` domain names and `"v": 4`. `SchemaVersion` is now generic over the version it admits: `v3::SchemaVersion` is `SchemaVersion<3>` and `v4::SchemaVersion` is `SchemaVersion<4>`, each refusing the other's payloads, and plain `SchemaVersion` still means v3. Only v4 types derive Stack Encrypt's `EncryptFrom` and `DecryptInto`, and the Stack Encrypt target table (now `eql_bindings::v4::targets`) names v4 domains. Besides `TextEq`, Stack Encrypt now produces the storage-only types `Text`, `Integer`, `Bigint`, `Boolean`, `Real` and `Double`, and `TextMatch` (3-grams, `k = 6`, a 2048-bit filter, pinned as `eql_bindings::encryption::EqlMatch`; text shorter than three characters is refused, stored or queried, and only `stored @@ query` matches until #1171 is fixed), from the Rust primitives `i32`, `i64`, `bool`, `f32` and `f64`; the Go SDK's `encrypt/eql` table marks them producible. Stack Encrypt also produces the number equality types `IntegerEq`, `BigintEq`, `RealEq` and `DoubleEq`, whose `=` compares as PostgreSQL compares the plain types: an integer has one term whatever its width, and for floats `-0.0 = 0.0` and `NaN = NaN` (ADR-0002's semantic baseline). Every type it cannot produce yet names the issue that tracks its blocker. The by-name target entry points (`eql_bindings::encryption::targets::encrypt`, `decrypt` and `query`) exchange the plaintext as Stack Encrypt's `dynamic::ValueFrame`, one value as its transport frame, rather than a value tree.
66

77
Nothing a released version shipped has changed. The v3 types, the v3 SQL and the TypeScript package are as they were; the `stack-encrypt` derives on the v3 text types and the `v3::targets` module were added after the last release and are moved to v4 here, not removed from a release.

‎docs/adr/0002-one-value-model-three-encodings-and-eql-v4-by-producer.md‎

Lines changed: 55 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
---
22
status: accepted
33
date: 2026-10-08
4-
revised: 2026-10-12
4+
revised: 2026-10-12, amended 2026-10-18
55
relates-to: ADR-0001; stack-encrypt ADR-0003, ADR-0007
66
---
77

@@ -12,8 +12,24 @@ relates-to: ADR-0001; stack-encrypt ADR-0003, ADR-0007
1212
> vitaminc sits at the bottom of the stack, equality and order terms take
1313
> per-domain transforms over a shared semantic baseline, `vitaminc-prf` no
1414
> longer depends on order encodings, and `orderable-bytes` is frozen. The plan
15-
> keeps the steps; this document is the decision. One question is still open,
16-
> under "Open decision".
15+
> keeps the steps; this document is the decision.
16+
>
17+
> **Amended 2026-10-18.** vitaminc 0.6 removed the shared value type rather
18+
> than renaming `FfiValue` to `Value` (vitaminc ADR 0001: a value describes
19+
> itself once, and sinks consume it). Stack Encrypt follows:
20+
>
21+
> - A plaintext whose type is known only at run time is held as its
22+
> transport frame (`dynamic::ValueFrame`) and walked into vitaminc's sinks.
23+
> - `FfiValue` is removed. Each kind of control data a binding exchanges
24+
> with the engine (a plan, a context, options, statistics, a configuration,
25+
> the engine's answers) gets a type of its own, read from and written to a
26+
> frame. Credentials in a configuration, such as the client key, are held
27+
> in `Protected` fields. Until each message has its type, `FfiValue` carries
28+
> only control data, never plaintext.
29+
> - The open decision on exhaustive handling is settled by vitaminc 0.6's
30+
> design (see "Exhaustive handling of kinds").
31+
>
32+
> The bullets below that this changes say so where they stand.
1733
1834
Every value Stack Encrypt handles is encoded three times: as a **ciphertext**
1935
(reversible and self-describing), as an **equality term** (a keyed hash that
@@ -74,8 +90,8 @@ type, `eql_v3_boolean`, stores a ciphertext and nothing else.)
7490
2. **Keep it in vitaminc, and move term derivation there too.** All three
7591
encodings then live in one repository, next to the value type they
7692
encode. Chosen. How "a kind exists in every layer or in none" is enforced
77-
is the open decision below; until it is settled, the conformance test
78-
described under "Which kinds get which terms" is what enforces it.
93+
is under "Exhaustive handling of kinds" below, with the conformance test
94+
described under "Which kinds get which terms" as the backstop.
7995

8096
**Where order schemes sit.**
8197

@@ -119,9 +135,19 @@ bundle (see Consequences). Chosen.
119135
`UInt128`, `Date`, `Timestamp` and `Decimal`, each with a `ValueKind` name,
120136
a `Value` variant and a ciphertext tag, in one breaking release. Rust `i128`
121137
and `u128` get `Encrypt` and `Decrypt` impls.
122-
- `FfiValue` is renamed `Value`, with `#[deprecated] pub type FfiValue = Value`
123-
for one release. Whether `Value` and `ValueKind` are `#[non_exhaustive]` is
124-
the open decision.
138+
- ~~`FfiValue` is renamed `Value`, with `#[deprecated] pub type FfiValue = Value`
139+
for one release.~~ *Amended 2026-10-18:* vitaminc 0.6 has no shared value
140+
type to rename it to. Its ADR 0001 has a value describe itself once
141+
(`Encrypt`) and every consumer be a sink: the encrypting sink, a term
142+
deriver, a frame writer. A host binding walks its transport frame straight
143+
into those sinks. So Stack Encrypt holds a dynamic plaintext as its frame,
144+
`dynamic::ValueFrame`, in a wiped buffer, from the source a binding hands
145+
over to the sealed leaves and from the opened leaves back to the frame it
146+
returns, with no value tree in between. `FfiValue` is removed rather than
147+
kept for control data: each control message gets its own type, read from
148+
and written to a frame, and holds any credential in a `Protected` field.
149+
`ValueKind`, the vocabulary a plan field declares, stays, and is
150+
exhaustive.
125151
- Every variant exists in every build. `Date`, `Timestamp` and `Decimal` use
126152
vitaminc's own representation (the payloads in the table below), with
127153
conversions to and from chrono and rust_decimal behind those features. A
@@ -285,8 +311,11 @@ equal under `Value` semantics produce equal terms in both.
285311
### Stack Encrypt
286312

287313
- `dynamic::Value` and `dynamic::term::Scalar` are deleted. `dynamic::term`
288-
takes a `&vitaminc_aead_value::Value`. `admits` keeps only the rules that
289-
belong to Stack Encrypt, such as `Match` taking text only.
314+
takes any source that describes itself to vitaminc (amended 2026-10-17,
315+
#1232: there is no `vitaminc_aead_value::Value`; a binding's value arrives
316+
as a transport frame and stays one, `dynamic::ValueFrame`). `admits` keeps
317+
only the rules that belong to Stack Encrypt, such as `Match` taking text
318+
only.
290319
- Order terms go through `vitaminc-ore`. The index for an ORE or OPE column
291320
picks the concrete scheme (cllw-ore or ore-rs, through `OrderScheme`) and
292321
its transforms; Stack Encrypt no longer calls cllw-ore's typed API. A block
@@ -386,22 +415,22 @@ transformed bytes, and that choice is frozen once data is stored under it.
386415
Dan Draper signs off each such domain in writing before it ships. Domains
387416
whose equality and order transforms are independent need no such sign-off.
388417

389-
## Open decision: exhaustive handling of `Value`
418+
## Exhaustive handling of kinds
390419

391420
`vitaminc-prf`, `vitaminc-ore` and every binding must handle every kind of
392-
`Value`, and adding a kind should fail to build until each one does. Two
393-
approaches remain:
394-
395-
- **A: drop `#[non_exhaustive]`.** Every crate that matches `Value` gets
396-
exhaustiveness, and adding a kind is a breaking change for all of them.
397-
- **B: a `ValueVisitor` trait with one required method per kind, keeping
398-
`#[non_exhaustive]`.** Crates that must handle every kind implement it, and
399-
adding a kind is breaking only for them; other crates keep a `_ =>` arm.
400-
401-
The leaning is B. The layering plan sets out the comparison. Either way,
402-
the conformance test is the backstop: a `#[non_exhaustive]` enum lets a
403-
downstream match compile with a wildcard, so the compiler alone does not
404-
guarantee coverage under B.
421+
value, and adding a kind should fail to build until each one does. This was
422+
left open between dropping `#[non_exhaustive]` (A) and a visitor trait with
423+
one required method per kind (B).
424+
425+
*Settled 2026-10-18 by vitaminc 0.6's design.* There is no value enum to
426+
match. A sink receives each scalar as a physical value and an optional
427+
logical type. The physical enums (`Physical`, `Int`, `Float`) are exhaustive,
428+
so a new physical kind fails to build in every sink that matches them, which
429+
is A for the bytes a value is made of. `Logical` is `#[non_exhaustive]`, so a
430+
new logical type (a date, a timestamp) is additive, and a sink that does not
431+
know it refuses it at run time. Stack Encrypt's `ValueKind` is exhaustive.
432+
The conformance test stays the backstop for the logical types a sink reaches
433+
through a wildcard.
405434

406435
## Consequences
407436

@@ -413,8 +442,8 @@ guarantee coverage under B.
413442
changes follow.
414443
- **Adding a kind later** takes a tag, PRF and order encodings, a codec in
415444
every binding, test vectors and a row in the kind-to-family table, or an
416-
entry in the exceptions list. Whether it is a breaking change depends on
417-
the open decision.
445+
entry in the exceptions list. A new physical kind is a breaking change for
446+
every sink. A new logical type is not.
418447
- **Stack Encrypt's terms change** for `-0.0` and negative-sign NaN floats,
419448
for non-NFC text equality, for `Bool` order terms, which are removed, and
420449
for every text order term: `orderize_string` drops symbols and keeps case,

‎languages/golang/encrypt/guest/src/ops.rs‎

Lines changed: 63 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -36,14 +36,16 @@
3636
//! ABI's numeric term kinds, and the mapping from a library error to a
3737
//! status code.
3838
//!
39-
//! A term's value is not decoded at all: the frame is parsed and walked in
40-
//! place to the scalar it holds, the way vitaminc's own guest walks a frame
41-
//! into encryption, so no copy of the plaintext is built to derive it. A
42-
//! record's source, a plan and an options object are decoded into an
43-
//! [`FfiValue`]: the engine reads them, splits a source into fields and
44-
//! keeps each field's value past this call.
45-
46-
use stack_encrypt::dynamic::{self, FfiValue, Scope};
39+
//! Plaintext is never decoded into a value tree. A term's value is parsed and
40+
//! walked in place to the scalar it holds, the way vitaminc's own guest walks
41+
//! a frame into encryption. A record's source, a query's input and a page of
42+
//! values to verify are read as [`ValueFrame`]s: the frame is checked against
43+
//! the engine's value model, and the engine walks it, splitting a source into
44+
//! one frame per field as it goes. A record opens into one frame, which is
45+
//! the output. Control data (a plan, an options object, query statistics)
46+
//! carries no secret and is decoded into an [`FfiValue`].
47+
48+
use stack_encrypt::dynamic::{self, FfiValue, Scope, ValueFrame};
4749
use stack_encrypt::sem::MatchOptions;
4850
use stack_encrypt::target::IndexSpec;
4951
use stack_encrypt::ErrorPayload;
@@ -170,10 +172,11 @@ where
170172
K: DataKeySource + Sync + 'static,
171173
{
172174
let plan = parse_plan(plan)?;
173-
let tree = dynamic::record::encrypt_with(cipher, decode_value(source)?, &plan, &resolver())
174-
.map_err(|e| fail_dynamic(&e))?
175-
.await
176-
.map_err(|e| fail_error(&e))?;
175+
let tree =
176+
dynamic::record::encrypt_with(cipher, checked_plaintext(source)?, &plan, &resolver())
177+
.map_err(|e| fail_dynamic(&e))?
178+
.await
179+
.map_err(|e| fail_error(&e))?;
177180
encode_tree(tree)
178181
}
179182

@@ -209,7 +212,7 @@ where
209212
.map_err(|e| fail_dynamic(&e))?
210213
.await
211214
.map_err(|e| fail_error(&e))?;
212-
encode_value(value)
215+
encode_frame(value)
213216
}
214217

215218
// =============================================================================
@@ -250,7 +253,7 @@ where
250253
&plan,
251254
field,
252255
operator,
253-
decode_value(input)?,
256+
checked_plaintext(input)?,
254257
&resolver(),
255258
)
256259
.map_err(|e| fail_dynamic(&e))?
@@ -274,15 +277,19 @@ pub fn verify(
274277
operator: &[u8],
275278
) -> Result<Vec<u8>, u32> {
276279
let (plan, field, operator) = parse_query(plan, field, operator)?;
277-
let FfiValue::Array(values) = decode_value(values)? else {
278-
return Err(last_error::malformed("the values to verify are not a list"));
279-
};
280+
// Each value becomes a frame of its own (wiped on drop): vitaminc's
281+
// `Frame` walks a sequence but does not hand out its elements' frames,
282+
// and reading them out of the frame layout here would duplicate
283+
// vitaminc's parser.
284+
let values = decode_plaintext(values)?
285+
.elements()
286+
.ok_or_else(|| last_error::malformed("the values to verify are not a list"))?;
280287
let verified = dynamic::verify(
281288
&plan,
282289
field,
283290
operator,
284-
decode_value(input)?,
285-
&values,
291+
checked_plaintext(input)?,
292+
values,
286293
&resolver(),
287294
)
288295
.map_err(|e| fail_dynamic(&e))?;
@@ -466,7 +473,8 @@ pub mod validate {
466473
/// against its field's outputs).
467474
pub fn record(source: &[u8], plan: &[u8]) -> Result<(), u32> {
468475
let plan = parse_plan(plan)?;
469-
dynamic::record::check_source(decode_value(source)?, &plan).map_err(|e| fail_dynamic(&e))
476+
dynamic::record::check_source(checked_plaintext(source)?, &plan)
477+
.map_err(|e| fail_dynamic(&e))
470478
}
471479

472480
/// A query's inputs, as [`query_term`](super::query_term) takes them:
@@ -476,8 +484,14 @@ pub mod validate {
476484
/// term exists ([`dynamic::check_query`]).
477485
pub fn query_term(input: &[u8], plan: &[u8], field: &[u8], operator: &[u8]) -> Result<(), u32> {
478486
let (plan, field, operator) = parse_query(plan, field, operator)?;
479-
dynamic::check_query(&plan, field, operator, decode_value(input)?, &resolver())
480-
.map_err(|e| fail_dynamic(&e))
487+
dynamic::check_query(
488+
&plan,
489+
field,
490+
operator,
491+
checked_plaintext(input)?,
492+
&resolver(),
493+
)
494+
.map_err(|e| fail_dynamic(&e))
481495
}
482496

483497
/// A record tree against its plan, as [`decrypt_record`] takes them:
@@ -496,10 +510,37 @@ pub mod validate {
496510
// Codec glue
497511
// =============================================================================
498512

513+
/// Control data from a frame: a plan, an options object, statistics.
499514
fn decode_value(bytes: &[u8]) -> Result<FfiValue, u32> {
500515
FfiValue::from_frame(bytes).map_err(|_| not_a_frame())
501516
}
502517

518+
/// Plaintext from a frame: checked against the engine's value model and
519+
/// held as the frame, in a buffer wiped when it drops. The same frames are
520+
/// refused as control data's, so a malformed input fails the same way on
521+
/// every path.
522+
fn decode_plaintext(bytes: &[u8]) -> Result<ValueFrame, u32> {
523+
ValueFrame::from_bytes(bytes).map_err(|_| not_a_frame())
524+
}
525+
526+
/// Plaintext checked as [`decode_plaintext`] checks it, and walked in place
527+
/// from the host's buffer: for a source or an input that is walked once,
528+
/// where a frame of its own would be one more copy of the plaintext. The
529+
/// record split copies each field into its own wiped frame, and a query's
530+
/// input is read straight into its term.
531+
fn checked_plaintext(bytes: &[u8]) -> Result<Frame<'_>, u32> {
532+
ValueFrame::check(bytes).map_err(|_| not_a_frame())
533+
}
534+
535+
/// An opened value as the output buffer: its frame, copied into a buffer
536+
/// whose capacity is exactly its length (see [`encode_value`]); the frame
537+
/// is wiped when it drops.
538+
fn encode_frame(frame: ValueFrame) -> Result<Vec<u8>, u32> {
539+
let mut out = exact_buffer(Some(frame.risky_ref().len()))?;
540+
out.extend_from_slice(frame.risky_ref());
541+
Ok(out)
542+
}
543+
503544
/// One frame, parsed and checked but not decoded: what a term's value is
504545
/// walked from, in place.
505546
fn parse_frame(bytes: &[u8]) -> Result<Frame<'_>, u32> {

‎languages/golang/encrypt/guest/src/targets.rs‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ impl TargetResolver for EqlTargets {
6060
name: &str,
6161
keyset: &'a stack_encrypt::KeysetCipher<'_, K>,
6262
label: &stack_encrypt::Label,
63-
plaintext: stack_encrypt::dynamic::FfiValue,
63+
plaintext: stack_encrypt::dynamic::ValueFrame,
6464
) -> Result<stack_encrypt::Pending<'a, Vec<u8>, K>, TargetError> {
6565
eql_bindings::encryption::targets::encrypt(name, keyset, label, plaintext).map_err(convert)
6666
}
@@ -71,7 +71,8 @@ impl TargetResolver for EqlTargets {
7171
cipher: &'a stack_encrypt::StackCipher<K>,
7272
label: &stack_encrypt::Label,
7373
stored: &[u8],
74-
) -> Result<stack_encrypt::Pending<'a, stack_encrypt::dynamic::FfiValue, K>, TargetError> {
74+
) -> Result<stack_encrypt::Pending<'a, stack_encrypt::dynamic::ValueFrame, K>, TargetError>
75+
{
7576
eql_bindings::encryption::targets::decrypt(name, cipher, label, stored).map_err(convert)
7677
}
7778

@@ -80,7 +81,7 @@ impl TargetResolver for EqlTargets {
8081
name: &str,
8182
keyset: &'a stack_encrypt::KeysetCipher<'_, K>,
8283
label: &stack_encrypt::Label,
83-
plaintext: stack_encrypt::dynamic::FfiValue,
84+
plaintext: stack_encrypt::dynamic::ValueFrame,
8485
) -> Result<stack_encrypt::Pending<'a, Vec<u8>, K>, TargetError> {
8586
eql_bindings::encryption::targets::query(name, keyset, label, plaintext).map_err(convert)
8687
}

0 commit comments

Comments
 (0)