Skip to content

feat(stack-encrypt): convert a stored record to a frame and back, for every binding - #2031

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

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

Conversation

@coderdan

@coderdan coderdan commented Nov 29, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Stack Encrypt now converts a stored record to a frame and back. So every
binding moves the encrypted record to its language with one function call,
and no binding walks the tree or renames a key.

dynamic::record::stored_frame(&stored, &plan) writes the stored record as
a frame. dynamic::record::read_stored(frame, &plan) reads it back as the
StackCipherText that decrypt takes. Two more functions do the same for
one field's node.

A binding builds its language's value from the frame, as it does for any
value. So in TypeScript a row comes out as
{ email: { c: Uint8Array, eq: Uint8Array }, id: { passthrough: 7n } },
under Stack Encrypt's own keys.

Closes #2029.

Changes

New functions in stack_encrypt::dynamic::record, in the new file
src/dynamic/record/stored.rs:

pub fn stored_frame(record: &StackCipherText, plan: &Plan) -> Result<OwnedFrame, Error>;
pub fn read_stored(frame: Frame<'_>, plan: &Plan) -> Result<StackCipherText, Error>;
pub fn stored_field_frame(node: &StackCipherText, plan: &Plan, field: &str) -> Result<OwnedFrame, Error>;
pub fn read_stored_field(frame: Frame<'_>, plan: &Plan, field: &str) -> Result<StackCipherText, Error>;

The frame form:

In the stored record In the frame
a row an object of fields
a batch an array of rows
a field an object of its outputs, under the stored record's keys
a sealed value its bytes (SealedValue::to_bytes)
a term or an EQL value its bytes
a passthrough field's value the value itself
a list or map under c an array or object
the marker of an empty list ["empty_seq", <bytes>]
the marker of an empty map ["empty_map", <bytes>]

Other changes:

  • Two new reasons: undeclared_output and not_sealed. They are at
    the end of Reason, so no existing value moves.
  • Error::Record has a new field, output: the key of the output at
    fault, such as c or eq. Error::output() returns it, and the payload
    has it as output. The new functions set it, and they also set the row
    of every refusal in a batch. decrypt and check_record leave it
    None, so their payloads do not change.
  • A term or an EQL value must be bytes. Both directions refuse one that
    is not, with not_passthrough.
  • The Go guest's tests set the new field, and a new guest test checks
    that the output reaches the host.
  • A conformance profile, record-stored-frames-v1, with its contract,
    25 cases, and a Rust runner, tests/stored_frame_conformance.rs. The Go
    runner is pending.
  • The message of Reason::Unframeable no longer says "passthrough". It
    was already given for values that are not passthroughs.
  • Frame::entries in vitaminc-aead. It lends a map's keys and
    values' frames with no copy, as Frame::elements does for a sequence.
    recipher-frame re-exports its iterator, Entries.
  • Tests in src/dynamic/record/stored/tests/mod.rs, and two in the frame
    module of vitaminc-aead. The test resolver FakeEql in record.rs is
    now visible to the new tests. Nothing else in it changed.
  • Docs. The rustdoc has a runnable example. The guide
    docs/language-integration.md has a paragraph in "Encrypt a record" and
    one in "Decrypt a record". The CHANGELOG.md files of stack-encrypt,
    vitaminc-aead, and recipher-frame have entries.

No stored byte changes. The Go guest and the TypeScript binding are not
changed. Moving them to these functions is follow-up work.

Verification

I ran these in a scratch worktree with MISE_DISABLE=1 RUSTUP_TOOLCHAIN=1.94.1.

Check Result
cargo fmt --all -- --check clean
cargo clippy --workspace --all-features --all-targets -- -D warnings clean
cargo clippy -p stack-encrypt --no-default-features --all-targets -- -D warnings, and with default features clean
cargo nextest run -p stack-encrypt -p vitaminc-aead -p recipher-frame --all-features, which includes the trybuild tests/ui, after the review fixes 2,211 passed, 1 skipped
cargo nextest run -p vitaminc-aead, with default features and with --no-default-features 351 passed each time
Doctests of stack-encrypt, vitaminc-aead, and recipher-frame, all features 96, 52, and 4 passed
RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --all-features for the three crates clean
Both Go guests: cargo check --locked --target wasm32-wasip1 --all-features, clippy for wasm32 and native with -D warnings, and cargo test --locked --all-features clean, and all tests passed
The stored-frame conformance runner passed. It fails when an expectation is changed.
pnpm run test:scripts 1,651 passed. Two eql-release-assets tests timed out under load, and passed when run again.
pnpm run code:check no errors
The CRAP gate, cargo llvm-cov 0.9.1 and cargo crap 0.6.1 with the flags of crap:stack-encrypt none of 1,803 functions above 30
cargo mutants --in-diff over the review fixes 33 mutants: 20 caught, 13 unviable, 0 missed
cargo mutants --in-diff over the three crates, before the review fixes 50 mutants: 30 caught, 19 unviable, 1 missed. The missed one was an equivalent match arm in the marker reader, which I then removed. A second run over the changed functions: 5 caught, 2 unviable, 0 missed
The plain-language checker on the new prose and this description 0 "must fix"

The new tests include two property tests:

  • Any value, sealed under c or passed through, decrypts the same after
    the trip through the frame. The values cover every scalar kind, a date, a
    timestamp, a decimal, a UUID, and nested lists and maps.
  • Any shape of sealed node under c, empty markers included, reads back to
    a record that writes the same frame.

I did not run these:

  • The Go module's tests. No Go code changed, and the guests were not
    rebuilt for them.
  • The EQL and protect-ffi Cargo workspaces. Neither calls the new
    functions.

Related

Review notes

The frame form

The keys are Stack Encrypt's: c, the index keys, passthrough, and
eql. A sealed value is its stable leaf bytes, so a binding stores the
same bytes as it does today. A passthrough node is the value in it, put
into the frame as it is. The rustdoc says that the frame is a transport
form and not a storage format, as the leaf's serde docs say.

Lists, maps, and empty markers under c

A field typed object or array seals a list or map under c. So does a
field with no type. An empty list or map seals as a marker. The marker is
a sealed value of its own.

In a frame, a marker cannot be plain bytes. It would read back as an
ordinary sealed value, and then fail to open. An object such as
{ "empty_seq": <bytes> } would clash with a sealed map that has that key.

A sealed node is never text, so an array that starts with text has no other
meaning. So the marker is ["empty_seq", <bytes>]. I chose this over a
tagged object around every list and map. Tags would double the depth of
the frame. A frame is limited to 128 levels.

Why the plan is an argument

A sealed value and a term are both bytes in the frame. Only the plan says
which output is sealed. So read_stored takes the plan, and never decides
from the bytes. stored_frame takes the plan too, and refuses a record
that the plan could not read back. Functions in record take &Plan in
the same way as encrypt, decrypt, and check_record.

The issue suggests serde on CipherText. Serde does not work here, for two
reasons:

  • recipher_frame::serde refuses a date, a decimal, and a timestamp. A
    passthrough field can contain any of them.
  • Serde would need a type tag on every node. That is the guessing that the
    plan avoids.

Fields with no value

A "null": "sql" field with no value has no entry in the stored record.
So it has no entry in the frame. read_stored reads a field that is left
out, or given as null, as no entry. decrypt opens a missing entry as a
null.

So for a column that contains SQL NULL, a binding sends either one. A
null for any other field is refused, with outputs_not_map. This follows
NullMode::Sql. On the encrypt side, it already treats a null and a
missing field the same way.

What is refused, and what is left to decrypt

read_stored refuses a frame that is not in the frame form. It also
refuses a field or output that the plan does not declare, because it
cannot tell what that node is. That is stricter than decrypt. decrypt
ignores such entries.

decrypt makes every other check, such as the check for a missing c. So
each check is made in one place. A passthrough anywhere under c is
refused in both directions, as decrypt refuses it.

Naming the output and the row at fault

Error::Record has a new field, output. The new functions set it for
every refusal about one output, an undeclared key included, and set the
row of every refusal in a batch.

decrypt and check_record still set neither for a field refusal.
record-reads-v1 compares their payloads exactly, in Rust and in Go, so
that change also needs the corpus, the Go runner, and rebuilt guests. It is
left for a separate issue.

Code outside this crate that builds an Error::Record must now set
output. In this repository, that was one Go guest test.

One field's node

stored_field_frame and read_stored_field convert the map of one
field's outputs. A row has the same node under the field's name. The two
functions refuse a null, because a field with no value has no node.

Plaintext

  • The frame out is an OwnedFrame. Its buffer is wiped when it is dropped.
  • read_stored copies a passthrough node's frame into a
    PassthroughFrame, as encrypt does. That memory is not wiped:
    PassthroughFrame's doc says it is "non-sensitive by contract" and
    "never wiped". read_stored's docs now say so, and that a passthrough
    field must not contain a secret. Wiping passthroughs would be a change to
    PassthroughFrame itself. That is a decision for Dan.
  • No error and no Debug output contains a value. The tests check this
    for a forged value and for a key inside c.

Depth

The frame has one more level than the value, for the field's outputs. An
empty marker adds one more. So a value nested close to the frame's limit
can be sealed but not written as a frame. That is refused with
unframeable.

Conformance

record-stored-frames-v1 fixes the frame form for the next binding. The
cases use a notation that any language can read:

  • $sealed is a sealed value's bytes.
  • $bytes is a term.
  • {"$value": ...} is a passthrough value.
  • A mutation changes the frame before it is read back.
    Objects compare by key, because the corpus file's key order is not
    kept by every JSON reader. The Go runner is marked pending, as for
    single-value-v1, until the Go guest uses the frame form.

The profile does not cover the write-side refusals, because a binding never
builds a stored record itself. It does not cover a field that names an EQL
type, or one field's node. The native tests cover those.

For Dan to decide

  • The marker form, ["empty_seq", <bytes>]. It is the one new piece of
    wire text in this pull request.
  • Whether read_stored should refuse a field or output that the plan does
    not declare, as it does now, or drop it, as decrypt ignores it.
  • Whether a frame null for a "null": "sql" field should be accepted, as
    it is now, or only a missing entry.

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: 0302e15

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.

records
.enumerate()
.map(|(at, record)| match record.entries() {
Some(fields) => read_record(fields, plan).map(CipherText::Map),

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: in a batch, a refusal names no row.

read_stored and stored_frame set row only for NotAnObject. The other refusals from read_record and write_record drop it: UnknownField, UndeclaredOutput, NotSealed, OutputsNotMap, and the rest.

Example: a binding sends a batch of 500 rows, and row 312 has an extra output foo. The error is Error::Record { field: Some("email"), row: None, reason: UndeclaredOutput }, so the caller cannot tell which row to fix.

Fix: in the batch loop, attach the row index to the error (row: Some(at)). decrypt's record_rows has the same gap, so this repeats an existing one.

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.

Fixed in 8eb4d74.

The batch loops of read_stored and stored_frame now put the row on every refusal of a row, not only on not_an_object. In your example, the error is now { field: "email", output: "foo", row: 312, reason: "undeclared_output" }.

Two new tests check this, one for each direction: it_names_the_row_of_a_refusal_in_a_batch in reading_a_frame_back and in writing_a_frame. I ran both against the code with the row step disabled first, and both failed.

I did not change decrypt's record_rows. It is not the same small change:

  • record-reads-v1 stores every record as a batch, and both runners compare each refusal's payload exactly.
  • With the row added, the payload of every field refusal in that profile changes: it has "row": 0.
  • So the change also needs the corpus updated, the Go runner rerun against rebuilt guests, and the error docs changed for decrypt and check_record.

I suggest a separate issue for it.

//!
//! ## Refusals
//!
//! Each refusal is [`Error::Record`], and names the field. The one

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: the docs say that every refusal names the field, but several do not.

These refusals have field: None:

  • the errors of writer.map(..) and record.end() in write_record;
  • the batch's seq, element, and end errors (Error::bad_record(Reason::Unframeable));
  • NotAnObject;
  • Error::Internal.

The CHANGELOG entry makes the same claim.

Example: a binding author trusts the docs, and unwraps error.field() for each Error::Record from stored_frame. A batch nested too deep returns field: None, and that code panics.

Fix: say "names the field when there is one", as the functions' # Errors sections do, and list Error::Internal.

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.

Fixed in 8eb4d74.

The record module docs now say that a refusal names the field, the output, and the row of a batch, "where there is one". They give a record that is not a map as an example of a refusal with no field. They list the two errors that are not Error::Record: Error::Plan, from the functions for one field, and Error::Internal, for a defect in the crate.

The # Errors section of stored_frame now lists Error::Internal. The CHANGELOG entry says "where there is one" too.

//!
//! No refusal contains a value, or the text of a key inside a sealed node.
//!
//! [`read_stored`] refuses a frame that is not in the frame form. It also

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: read_stored does not check the form of an output in the clear.

read_outputs copies any frame under a term key or under eql, as it is. The term keys are eq, match, ore, and ope. So a term given as text, an object, or a null is accepted.

Example: a binding sends { email: { c: <bytes>, eq: "oops" } }. read_stored accepts it. stored_frame then writes "oops" back as the term. The binding finds out only when it compares that term later.

Fix: refuse a node under a term key or eql that is not bytes, with NotPassthrough. Or change the docs to say that only c is checked for form.

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.

Fixed in 8eb4d74.

read_stored now refuses a node under a term key or eql that is not bytes. The reason is not_passthrough, and the error names the output. stored_frame refuses the same thing on the way out, so the two directions agree. A passthrough output still takes any value, because a passthrough field's value can be of any kind.

New tests:

  • it_refuses_a_term_or_an_eql_value_that_is_not_bytes checks text, null, an object, and a number under eq and ore, and text under eql. It also checks that a passthrough of text is still accepted.
  • The write-side test it_refuses_an_output_in_the_clear_that_is_not_one_frame has a new case: a passthrough of text under eq.

Both failed first, with the bytes check disabled.

Content::Sealed => read_sealed(node).map_err(at_fault)?,
// A passthrough is in the clear by contract. Its frame is kept
// as it is, as `encrypt` keeps it.
Content::Clear => CipherText::Passthrough(PassthroughFrame(node.as_bytes().to_vec())),

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: on the read side, a passthrough field's plaintext is copied into memory that is not wiped.

read_outputs builds PassthroughFrame(node.as_bytes().to_vec()). stored_frame writes into a wiped Buffer, because a passthrough field's value is caller plaintext. So one direction wipes that plaintext and the other does not.

Example: a binding reads back many rows whose passthrough fields contain caller plaintext, such as a tenant name. Each value stays in freed heap memory after the StackCipherText drops.

Fix: check whether PassthroughFrame is meant to be unwiped. If it is not, keep the copy in a wiped buffer. If it is, say so in read_stored's docs.

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.

I checked: PassthroughFrame is meant not to be wiped. Its doc says so (packages/vitaminc-aead/src/frame.rs:525): "Non-sensitive by contract; neither sealed nor authenticated, and never wiped."

encrypt follows the same contract. passthrough_frame in record.rs copies a passthrough field's value into an unwiped PassthroughFrame when it builds the stored record. So the value is already unwiped in the StackCipherText before a binding writes the frame. Wiping only the copy that read_stored makes would not change what stays in memory.

So I did not change the code. In 8eb4d74 I:

  • said in read_stored's docs that an output in the clear is copied into memory that is not wiped, as encrypt stores it;
  • said there that a passthrough field must not contain a secret;
  • fixed stored_frame's docs. They said the buffer is wiped "because a passthrough field's value is caller plaintext". Now they say it is wiped because every frame the engine returns is.

Wiping passthroughs would be a change to PassthroughFrame itself. Its field is a public Vec<u8>. A Drop impl would stop every binding from moving that field out. That is a decision for Dan, not a fix for this pull request.

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.

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