Skip to content

feat(stack-encrypt): typed encrypted records that cross to a language binding through serde - #2031

Draft
coderdan wants to merge 11 commits into
nextfrom
feat/stack-encrypt-tree-frame
Draft

coderdan wants to merge 11 commits into
nextfrom
feat/stack-encrypt-tree-frame

Conversation

@coderdan

@coderdan coderdan commented Nov 29, 2026 •

Copy link
Copy Markdown
Contributor

Summary

A language binding now gets an encrypted record as typed values: an
EncryptedRecord. The serde adapter moves it to the binding's language and
back as a frame. No binding walks a tree or renames a key.

This replaces the hand-written stored-frame module that this pull request
first added. stored_frame, read_stored, stored_field_frame,
read_stored_field, and the ["empty_seq", ...] and ["empty_map", ...]
markers are gone. The stored tree, StackCipherText, works as before.

Closes #2029.

Changes

Typed records in stack_encrypt::dynamic::record

pub struct EncryptedRecord { /* private */ }
impl EncryptedRecord {
    pub fn fields(&self) -> impl ExactSizeIterator<Item = (&str, &EncryptedField)>;
    pub fn field(&self, name: &str) -> Option<&EncryptedField>;
    pub fn to_frame(&self) -> Result<OwnedFrame, Error>;
    pub fn from_frame(frame: Frame<'_>) -> Result<Self, Error>;
    pub fn batch_to_frame(records: &[EncryptedRecord]) -> Result<OwnedFrame, Error>;
    pub fn batch_from_frame(frame: Frame<'_>) -> Result<Vec<Self>, Error>;
}

pub struct EncryptedField { /* private */ }
impl EncryptedField {
    pub fn ciphertext(&self) -> Option<&Ciphertext>;          // c
    pub fn term(&self, key: &str) -> Option<&TermBytes>;      // eq, match, ore, ope, ore_block
    pub fn passthrough(&self) -> Option<&PassthroughFrame>;
    pub fn target(&self) -> Option<&[u8]>;
    pub fn outputs(&self) -> impl Iterator<Item = &'static str> + '_;
    pub fn to_frame(&self) -> Result<OwnedFrame, Error>;
    pub fn from_frame(frame: Frame<'_>) -> Result<Self, Error>;
}

pub trait EncryptedForm: /* sealed */ {}  // StackCipherText, EncryptedRecord, Vec<EncryptedRecord>
pub trait StoredForm: /* sealed */ {}     // the same three

pub fn encrypt<'a, T: EncryptedForm, K: 'static>(cipher, source, plan) -> Result<Pending<'a, T, K>, Error>;
pub fn encrypt_with<'a, T: EncryptedForm, K: 'static>(cipher, source, plan, resolver) -> ...;
pub fn decrypt<'a, K: 'static>(cipher_ref, record: impl StoredForm, plan, expected) -> ...;
pub fn decrypt_with<'a, K: 'static>(cipher_ref, record: impl StoredForm, plan, expected, resolver) -> ...;
  • The owned API. Planned::new(&plan, row).encrypt_into(&keyset)
    returns any of the three forms, and Planned<Plan, S> decrypts from any
    of them.
  • The frame form. A record is an object of fields. A field is an
    object of its outputs under Stack Encrypt's keys. c is the sealed
    value's stable bytes (Ciphertext::to_bytes). A term and a target
    value are their bytes. passthrough is the value's frame node, as it is.
    A batch is an array of records. For example:
    { "email": { "c": <bytes>, "eq": <bytes> }, "id": { "passthrough": "u-7" } }.
  • One sealed value under c. A typed record has exactly one there. A sealed field
    whose value is a list or a map, an empty one included, is refused before
    any key is requested (not_one_value).
  • New reasons. not_one_value, not_an_output, and batch_shape.
    not_sealed now means "the node under c is not one sealed value's
    bytes". undeclared_output is gone.
  • Error::Record keeps output and the row of a batch. The typed
    record's refusals set them. decrypt of the stored tree leaves both as
    they were.

recipher-frame: serde::raw

recipher_frame::serde::raw writes one frame node as it is, and reads the
next node back as its bytes. A passthrough can be a date, a timestamp, a
decimal, or a UUID. serde has no model for those.

pub fn serialize<S: Serializer>(node: &Buffer, serializer: S) -> Result<S::Ok, S::Error>;
pub fn serialize_bytes<S: Serializer>(node: &[u8], serializer: S) -> Result<S::Ok, S::Error>;
pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Buffer, D::Error>;
  • Writing checks that the bytes are one well-formed node. The node's depth
    counts from where it is written.
  • The storage profile and every other serde format refuse a raw node.
  • An error never repeats the node's bytes.

Other files

  • Frame::entries in vitaminc-aead stays: the typed record's errors read
    a field's name from the frame with it.
  • Conformance: record-stored-frames-v1 is replaced by
    record-encrypted-v1, with its contract and a Rust runner. The Go runner
    is pending.
  • Tests that called record::encrypt and passed the result only to
    decrypt now name the form, StackCipherText: in stack-encrypt's
    tests and in packages/eql/tests/encryption/tests/json_tree_data_plan.rs.
    The Go guest needed no change.
  • CHANGELOG entries for stack-encrypt and recipher-frame, and the guide
    docs/language-integration.md.

Verification

All run locally on 495b6d13c, or on a069729fa with only the tests
and one rustdoc line changed since. Rust is 1.94.1.

  • cargo fmt --all -- --check: clean.
  • cargo clippy --workspace --all-targets --all-features -- -D warnings:
    clean. Also clean with --no-default-features for stack-encrypt and
    recipher-frame.
  • cargo doc --no-deps --all-features for stack-encrypt,
    recipher-frame, and vitaminc-aead, with and without
    --document-private-items, with -D warnings: clean. CI's first run
    failed on a redundant link in write.rs. That link is now fixed.
  • cargo nextest run for stack-encrypt, recipher-frame, and
    vitaminc-aead with all features: 2214 passed, 1 skipped. After the
    last tests were added, recipher-frame passed 133 of 133 and the typed
    record's tests passed 30 of 30.
  • Doctests: 95 and 5 passed.
  • The CRAP gate for stack-encrypt, as CI runs it: 1837 functions, none
    above 30.
  • cargo mutants --in-diff against origin/next for stack-encrypt,
    vitaminc-aead, and recipher-frame: 206 mutants. The first run left
    30 missed and 1 timed out. New tests catch them, and a rerun of those
    31 caught all 31.
  • The Go guests encrypt and auth pass four checks: the wasm32 check,
    wasm32 clippy, native clippy, and cargo test --locked --all-features. Their
    code did not change.
  • cargo check -p eql-encryption-tests -p eql-bindings --all-targets --all-features in packages/eql: passes.
  • scripts/__tests__/stack-conformance-ci.test.mjs: 30 passed. Biome
    code:check: clean.

Not run:

  • the Go runner for record-encrypted-v1, because it does not exist yet;
  • the live tests, because they need credentials.

Related

Follow-ups

  • A destination for one field, EncryptedField, for feat(stack-encrypt): encrypt and decrypt one field of a plan #2030's one-field
    plan.
  • Moving the Go guest from the stored tree and encode_tree to
    EncryptedRecord.
  • Naming the target output target in the stored tree and the rest of
    Stack Encrypt, where it is still eql.
  • The one-leaf rule in the static Rust API.
  • The row and output on decrypt's refusals of the stored tree.
    record-reads-v1 compares those payloads exactly in Rust and in Go.

Review notes

Why typed records through serde

A frame and a stored record are one serialise and deserialise apart. The
serde adapter already reads the plan, so a hand-written reader and writer
beside it was a second copy of the same work. The typed record has the
form. serde moves it.

Where the one-leaf rule applies

A plan field can put a list, a map, or an empty-container marker under
c. It does so for a field with c that is given a list or a map.
That is a field typed object or array. It is also a field with no type
that is given a list or a map. A
json field needs a target, so it has no c.

The typed forms refuse such a value before any key is requested. The
stored tree still takes it, because these depend on it:

  • packages/stack-encrypt/tests/fixtures/stored_rows_v1.json: a frozen
    fixture with lists, maps, and empty markers under c.
    tests/stored_rows.rs opens it.
  • a_typed_composite_field_round_trips_even_when_empty in
    src/dynamic/record.rs.
  • The Go guest, whose transport codec writes and reads the empty markers.

The form is a type parameter

record::encrypt::<T, _> names its result by type, as the owned API does.
A call that passes its result only to decrypt no longer infers it. So
those test calls now name StackCipherText. The Go guest infers it from
encode_tree and did not change.

Choices this pull request makes

  • c is the existing opaque Ciphertext, not SealedValue. It has no
    structural node. Its bytes are the stable leaf format.
  • A term is TermBytes. That type is already public.
  • json is not an output key. A plan with a JSON index is refused, so no
    stored record has one.
  • The encrypt-side refusal of a list or map under c is Error::Source,
    as every refusal of a source to encrypt is, not Error::Record.
  • A null for a field in the frame is refused (outputs_not_map). Reading a
    frame does not see the plan, so a field with no value is left out.
  • Reading a frame checks its structure only. decrypt ignores outputs that
    the plan does not open, as it does for the stored tree.
  • PassthroughFrame is not wiped, by its documented contract. The typed
    record copies a passthrough's frame into one, as encrypt does.

For Dan to decide

  • May a frame give a "null": "sql" field as null? Today it must leave
    the field out.
  • Should decrypt refuse an output or a field that the plan does not
    declare? Today it ignores them, for both forms.

A binding moves the stored record to its language and back. Until now,
each binding walked the tree itself, and the TypeScript binding renamed
its keys. Stack Encrypt now does this once, for every binding.

dynamic::record::stored_frame writes a stored record, or a batch, as a
frame under the record's own keys. read_stored reads the frame back. It
takes the plan, because only the plan says which output is sealed. Two
more functions do the same for one field's node.

vitaminc-aead gains Frame::entries. It reads a map's entries with no
copy, as Frame::elements reads a sequence's elements.

Closes #2029.
@changeset-bot

changeset-bot Bot commented Nov 29, 2026 •

Copy link
Copy Markdown

⚠️ No Changeset found

Latest commit: 495b6d1

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@coderabbitai

coderabbitai Bot commented Nov 29, 2026

Copy link
Copy Markdown
Contributor

Important

Draft PR not reviewed

Draft PRs are not automatically reviewed by default.

  • Trigger a manual review

To automatically review draft PRs, update your CodeRabbit configuration:

reviews:
  auto_review:
    drafts: true

@coderdan coderdan left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review at medium effort. The review found no bug in the conversion. There are four minor findings, posted inline.

Two more points, from reading the PR's report:

  1. Add the output key to Error::Record. The PR leaves it out because the Go guest's tests build that variant with every field. That is a workaround. A test that has to change is not a reason to keep an error less useful. Add the slot, and update the Go guest's tests in the same PR.
  2. Add a conformance profile now, with the Go runner marked pending. #2030 does this for record-fields-v1, as single-value-v1 did before it. Cases for the frame form fix that form for the next binding, including the new empty_seq and empty_map markers.

Each will be fixed or answered in a reply.

A refusal of a stored record in a batch did not say which row was at
fault. No refusal said which output was at fault.

`Error::Record` now has an `output` field. `stored_frame` and
`read_stored` set it, and they set the row in a batch. `decrypt` and
`check_record` leave the output unset. So their payloads do not change.

read_stored and stored_frame now refuse a term or an EQL value that is
not bytes. The docs say where a refusal names the field, list
Error::Internal, and say that a passthrough's frame is not wiped, as
PassthroughFrame's contract says.

The Go guest's test that builds an Error::Record sets the new field. A
new guest test checks that the output reaches the host.
…ending

record-stored-frames-v1 fixes the frame form of a stored record for every
binding. The cases cover these:

- every output kind, and a passthrough of each value kind
- a batch, and both null modes
- lists, maps, and empty markers under c
- the refusals, with their field, output, and row

The Rust runner is stored_frame_conformance. The Go runner waits until
the Go guest uses the frame form.
…e range

The property test drew dates up to 3,000,000 days, past the last date the
engine accepts (year 9999). A row with such a date was refused before it
was sealed, so the test failed at random. It now draws dates and
timestamps from the range that the engine accepts.
@coderdan

Copy link
Copy Markdown
Contributor Author

Answers to the two points in review 6103483734.

1. The output key in Error::Record. Done in 8eb4d74.

  • Error::Record has a new field, output: Option<String>. Error::output() returns it. The payload has it as output. The payload already has field and row. The message ends with (output "c").
  • stored_frame, read_stored, and the functions for one field set it for every refusal about one output. An undeclared key is named too, as a field name the plan does not know already is.
  • decrypt and check_record leave it None. Setting it there changes the payloads that record-reads-v1 compares exactly in Rust and Go. That belongs with the row change that I declined in the inline thread.
  • The Go guest test that builds an Error::Record now sets the field. A new guest test, a_stored_record_refusal_carries_its_output_to_the_host, checks that the output reaches the host's error. The guest passes the whole payload through, so the Go side gets it in Diagnostic.Fields.
  • Both guests pass cargo check and clippy for wasm32, clippy for native, and cargo test --locked --all-features. I did not run the Go module's tests. No path that Go calls today sets output, so the guest's error output does not change.

2. A conformance profile. Added in a2fd232, as record-stored-frames-v1, with the Go runner marked pending.

  • Contract: conformance/stack-encrypt/stored-frames-contract.md.
  • Cases: v1/record-stored-frames-v1.cases.json, formatted with Biome.
  • Rust runner: packages/stack-encrypt/tests/stored_frame_conformance.rs. scripts/stack-conformance.sh runs it.
  • README, coverage.md, and stack-conformance-ci.test.mjs list it the way single-value-v1 is listed.

Its 25 cases cover:

  • every output kind, and a passthrough of each value kind
  • a batch, an empty batch, and both null modes
  • a "null": "sql" field left out or sent as null, and index terms left out
  • lists, maps, and the empty_seq and empty_map markers under c
  • every read refusal, with its exact payload, including output and row

I checked that the runner fails when an expectation is changed.

The three open decisions are unchanged: the marker form, refusing undeclared fields and outputs, and accepting a null for a "null": "sql" field.

…rectory

The CRAP gate skips files under a tests directory. The unit tests of the
stored-frame module were in stored/tests.rs, so the gate scored their
helpers as source with no coverage, and one helper failed it. The tests
now live in stored/tests/mod.rs. No test changed.
serde has no model for a date, a decimal, a timestamp, a UUID, or a
passthrough. So such a value could not cross the serde adapter.
`recipher_frame::serde::raw` now writes one frame node as it is, and
reads the next node back as its bytes.

Writing checks that the bytes are one well-formed node, and counts its
depth from where it is written. The storage profile and every other
serde format refuse a raw node, so it never becomes another value.
A language binding now asks record::encrypt for an EncryptedRecord, or
a Vec of them, and gives either back to record::decrypt. The owned API
takes them too. Each field has its outputs under Stack Encrypt's keys.
The output c is one sealed value. A sealed field whose value is a list or a
map is refused before any key is requested.

The record moves to the binding's language as a frame through the serde
adapter: EncryptedRecord::to_frame and from_frame. It replaces the
hand-written stored-frame functions. Those are removed. The stored tree
works as before.

record::encrypt now takes the form as a type parameter, so a call that
passes its result only to decrypt names the form. The tests that did so
now name StackCipherText.
…pted-v1

The new profile fixes the frame form of a typed encrypted record for
every binding. It covers every output kind, each value kind as a
passthrough, a batch, both null modes, and the refusals at each stage.
A list, a map, or an empty container under c is refused. The Go runner
stays pending until the Go guest uses typed records.
A raw node now has a test for each kind of value that is not bytes. The
error must say that a raw node takes bytes and nothing else.

These tests are new:

- JSON is still refused after a raw node is written.
- Another format's errors say what each part should be.
- A typed record's refusal names its output in its message.
- A field gives back the term and target bytes that were set.

The writer's rustdoc names the raw module with an implicit link. An
explicit target there fails the private-items rustdoc build.
@coderdan coderdan changed the title feat(stack-encrypt): convert a stored record to a frame and back, for every binding feat(stack-encrypt): typed encrypted records that cross to a language binding through serde Nov 30, 2026
}
}
let Some(PathSegment::Entry(at)) = path.first() else {
return Error::Record {

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit (optional): batch_from_frame given the frame of one record returns not_an_object with found: object. The message reads "the record to decrypt is an object, not an object of stored fields", which contradicts itself. This branch runs for every error whose path has no entry, so a batch frame that is not an array is reported as "not an object". Fix: when the caller asked for a batch and the root is not an array, return Reason::BatchShape (the changelog already says reading does this), or a message that says an array of records was expected.

reasons say what was wrong:
- `not_an_output`: a key that is not an output
- `not_sealed`: anything under `c` but one sealed value's bytes
- `batch_shape`: one record where a batch is asked for, or a batch

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit (optional): the changelog lists batch_shape as one of the three reasons that reading a frame returns. No read path returns it. EncryptedRecord::from_frame and batch_from_frame return not_an_object for one record where a batch is expected, and for a batch where one record is. batch_shape comes only from record::encrypt, in check_form. Fix: move this bullet to the encrypt paragraph, or make the two read functions return batch_shape.

Some(PathSegment::Entry(at)) => name(*at).map(str::to_owned),
_ => None,
};
let output = match path.get(1) {

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit (optional): EncryptedField::to_frame never names the output at fault. For one field the error path is [Key("passthrough")], with no entry segment before it. This line reads the output from path.get(1), so it finds nothing and output is None. The record and batch paths are [Entry, Key], so they work. Fix: read the output from the segment after the optional row and entry segments, so a path that starts with a key gives that key. Add a test for a too-deep passthrough through EncryptedField::to_frame.

Verb::Target => targets.push(
outputs
.take_target()
.ok_or_else(|| misfit(Reason::NoEqlNode))?,

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit (optional): a typed record whose target field has no target output is refused with no_eql_node, and the message is no "eql" node. A typed record has no eql key: the output is target, and from_frame refuses eql with not_an_output. A binding author who follows the message adds eql and gets a second refusal. Fix: set output: Some("target") on this refusal, or add a reason and message that name the target output.

/// whose value is a list or a map, an empty one included, is refused. The
/// refusal names the field and the row of a batch, and never the value.
/// - The tree takes any row as it is.
pub(super) fn check_form(rows: &Rows<Row>, plan: &Plan, form: Shape) -> Result<(), Error> {

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit (optional): a row can pass record::encrypt, have its keys requested, and then fail at EncryptedRecord::to_frame with unframeable. A passthrough value whose root is at depth 1 in the source row sits at depth 2 in the record frame, so a value nested MAX_DEPTH - 1 levels fits the source and not the record. check_form runs before any key is requested and checks only sealed fields. Fix: for the typed forms, also refuse here a passthrough value that is too deep for the record frame (one level deeper again for a batch).

}

fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<EncryptedRecord, A::Error> {
let mut fields = Vec::with_capacity(map.size_hint().unwrap_or(0));

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit (optional): this reserves room for every entry the map claims before reading any. One (String, EncryptedField) is a few hundred bytes and a frame entry can be about 6 bytes, so a large frame of many small entries reserves tens of times its own size, even when the first field is then refused. serde uses a capped hint for its own Vec for this reason. Fix: cap the capacity, for example map.size_hint().unwrap_or(0).min(1024).

| `"$sealed"` | The bytes of a sealed value |
| `"$bytes"` | Any bytes, such as a term. `frame` only. |
| `{"$value": <value>}` | The frame of a value, such as a passthrough field's value |
| `{"$hex": "..."}` | These bytes |

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit (optional): the table says frame and a mutation value both take {"$hex": "..."}. The Rust runner reads $hex only in a mutation (shaped). In check, an object with $hex is compared as an object with the key $hex, so a case that uses it in frame fails with "is not an object". Fix: mark $hex as "Mutations only", as $passthrough is, or handle it in check.

`check_record` leave it `None` for the stored tree, so their payloads
do not change. Code that builds an `Error::Record` must set the new
field.
- A call that does not name its form, and passes the result only to

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit (optional): two source-breaking changes are listed under "Added". Error::Record has a new public field, so code that builds it or matches all its fields no longer compiles. record::encrypt and encrypt_with have a new type parameter, so a call that does not name its form no longer compiles. The Unreleased section has a "Breaking" heading that readers check before they upgrade. Fix: move these two bullets there, or add a short entry there that links to this one.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant