From 32548e6679e74072fd9611b63b80cb430803616b Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sun, 29 Nov 2026 13:02:46 +1100 Subject: [PATCH 1/3] test(conformance): fix the bytes of a UUID in the scalar profile The value model takes a UUID, but no conformance case held one. So nothing checked that Rust, Go, and TypeScript write the same UUID frame and derive the same equality term. record-scalars-v1 now has three UUID cases: an ordinary UUID, the nil UUID, and the max UUID. The Rust engine froze the frame, equality term, and ciphertext of each. Two cases list the same UUID in other letter cases. Five new refusals show that the engine converts nothing to or from a UUID. A UUID field refuses a string, bytes, or a null. A bytes field and a string field each refuse a UUID. Native Rust and Go run every case. The TypeScript value bridge checks the frames, from each spelling. The TypeScript runner of the whole profile waits on the addon storing a UUID (#1996). An update of the frozen file now keeps the ciphertext of a case whose frame and equality term have not changed. So adding a case adds one entry. Refs #1821 --- conformance/stack-encrypt/README.md | 58 ++++++++++-- conformance/stack-encrypt/coverage.md | 2 +- .../v1/record-scalars-v1.cases.json | 89 +++++++++++++++++++ ...ecord-scalars-v1.expected.rust-native.json | 15 ++++ languages/golang/encrypt/conformance_test.go | 36 ++++++-- .../recipher-js/value-napi/tests/frames.cjs | 31 ++++++- .../tests/testdata/corpus-frames.json | 3 + .../value-napi/tests/testdata/js-frames.json | 29 +++++- .../stack-encrypt/tests/common/conformance.rs | 19 ++++ packages/stack-encrypt/tests/conformance.rs | 60 ++++++++++++- 10 files changed, 322 insertions(+), 20 deletions(-) diff --git a/conformance/stack-encrypt/README.md b/conformance/stack-encrypt/README.md index d3e5093d71..13fac77e72 100644 --- a/conformance/stack-encrypt/README.md +++ b/conformance/stack-encrypt/README.md @@ -59,7 +59,7 @@ These files read or copy cases, and are not runners: | File | Profile | What it reads | |---|---|---| -| `languages/typescript/packages/recipher-js/value-napi/tests/testdata/corpus-frames.json` | `record-values-v1` | The frames of the corpus cases that the TypeScript value bridge must write. `tests/frames.cjs` regenerates it with `RECIPHER_UPDATE_FIXTURES=1`, and `scripts/__tests__/recipher-js-frame-parity.test.mjs` holds it to the corpus. | +| `languages/typescript/packages/recipher-js/value-napi/tests/testdata/corpus-frames.json` | `record-values-v1`, `record-scalars-v1` | The frames of the corpus cases that the TypeScript value bridge must write. Among them is the frame of each UUID case of `record-scalars-v1`, which `tests/frames.cjs` also writes from each of the case's spellings. `tests/frames.cjs` regenerates it with `RECIPHER_UPDATE_FIXTURES=1`, and `scripts/__tests__/recipher-js-frame-parity.test.mjs` holds it to the corpus. | | `scripts/__tests__/stack-exchange-conformance.test.mjs` | `record-values-v1` | The IDs of the positive cases, to build test artifacts. | | `scripts/__tests__/stack-eql-conformance.test.mjs` | `eql-json-v1` | The documents and the reasons of `invalid_documents`. | `fixture-enrollment.json` is the one file not named after a profile: it maps @@ -223,13 +223,30 @@ versions, profiles, capabilities and input types fail. Every case must run. The profile fixes a one-field record with ciphertext (`c`) and equality (`eq`) outputs. Its field context is the record context followed by the field name. Each case declares the field's `kind` and a typed `input`. `input.text` is the -literal string value, canonical base-10 integer, `true`/`false`, or empty text -for null, as determined by `input.type`. Runners construct real typed host -values, preserving integer width. JSON numbers are deliberately not used for -values: future TypeScript runners must not pass 64-bit integers through Number. +literal string value, canonical base-10 integer, `true`/`false`, bytes in hex, +a UUID, or empty text for null, as determined by `input.type`. Runners +construct real typed host values, preserving integer width. JSON numbers are +deliberately not used for values: future TypeScript runners must not pass +64-bit integers through Number. -The initial positives cover int32 and int64 bounds, uint64 max, an integer -above JavaScript's safe-integer limit, Unicode text and empty text. For each: +A UUID is written in lowercase hex, in groups of 8, 4, 4, 4, and 12 digits, +with `-` between them. A case with a UUID input can also have `spellings`: +the same UUID in other letter cases. A runner whose language makes a UUID +from text reads each spelling. Each spelling must give the same UUID and the +same frozen frame. Go reads them with `vcvalue.ParseUUID`, Rust with the `uuid` +crate, and the TypeScript value bridge with `VcUuid`. + +The engine itself never reads UUID text: a string is not a UUID, so a UUID +field refuses one. + +The positive cases cover these values: + +- the int32 and int64 bounds, and the uint64 maximum +- an integer above JavaScript's safe-integer limit +- Unicode text, and empty text +- an ordinary UUID, the nil UUID (all zeros), and the max UUID (all ones) + +For each positive case: 1. The encoded typed frame must equal the frozen frame, including its type. 2. Record encryption and opening must preserve both value and type. @@ -249,14 +266,33 @@ above JavaScript's safe-integer limit, Unicode text and empty text. For each: Negative cases have `expected_error` and exercise the equality query only. They require the exact engine diagnostic `code`, `reason`, and field name; Go must also expose `ErrEncoding`. Native Rust verifies rejection occurs -before data-key generation or retrieval. String/bool inputs for an integer -field and a null query are currently covered. Error prose is not contractual. +before data-key generation or retrieval. Error prose is not contractual. The +negative cases query these values: + +- a string or a bool against an integer field +- a string that spells a UUID, or the same sixteen bytes as a bytes value, + against a UUID field +- a UUID against a bytes field or a string field +- a null, against an integer field and against a UUID field + +A null is refused as `null_query`, and every other value as `field_type`. +The engine converts nothing to or from a UUID. Boolean equality is not admitted by the current engine. Boolean scalar encryption, nullable records, other numeric kinds, bytes, JSON, EQL targets, other operators, declarations, cancellation and provider failures need later profiles or cases. The full SQL behavior is not part of this initial profile. +Native Rust and Go run every case. The TypeScript runner is pending. The +TypeScript value bridge checks only the frames. Its `tests/frames.cjs` writes +each UUID case and each of its spellings, and compares each frame with the +frozen one. + +The `@cipherstash/recipher` addon cannot store a UUID yet. So no +TypeScript test encrypts these cases, queries them, or opens their frozen +ciphertexts. Pull request #1996 lets the addon store a UUID, and the +TypeScript runner of the whole profile waits on it. + ## Artifacts and evolution `v1/record-scalars-v1.expected.rust-native.json` is a frozen artifact set produced by the Rust owned scalar API. @@ -279,6 +315,10 @@ STACK_CONFORMANCE_UPDATE=1 mise x --env test -- cargo nextest run --locked \ mise run test:conformance ``` +An update keeps the frozen ciphertext of a case whose frame and equality term +have not changed, and opens it as any run does. So adding a case adds one +entry, and the diff does not rewrite the ciphertexts of the other cases. + Review the case and artifact diff together. Never regenerate artifacts merely to make a regression pass. diff --git a/conformance/stack-encrypt/coverage.md b/conformance/stack-encrypt/coverage.md index 815fab2c52..2830fe690b 100644 --- a/conformance/stack-encrypt/coverage.md +++ b/conformance/stack-encrypt/coverage.md @@ -6,7 +6,7 @@ Paths are relative to the repository root. New profile cases run from `v1/`. | Requirement | Existing evidence | Remaining work | |---|---|---| -| Scalar value widths and lossless transport | Initial scalar cases, [value-kind requirements](fixture-contract.md#value-kind-requirements) and the [value boundary profile](values-contract.md) (`v1/record-values-v1.cases.json`: every kind's edges, float specials, bytes, decimal and timestamp precision, sealed/SQL nulls per kind, exact write conversions between widths, cross-kind write refusals, `undefined` on a typed field, Go host conversions); every positive case written fresh by each runner and opened by the other ([exchange profile](exchange-contract.md)) | Python/TS mappings; dates before year 1 and the timestamp range ends | +| Scalar value widths and lossless transport | Initial scalar cases, [value-kind requirements](fixture-contract.md#value-kind-requirements) and the [value boundary profile](values-contract.md) (`v1/record-values-v1.cases.json`: every kind's edges, float specials, bytes, decimal and timestamp precision, sealed/SQL nulls per kind, exact write conversions between widths, cross-kind write refusals, `undefined` on a typed field, Go host conversions); every positive case written fresh by each runner and opened by the other ([exchange profile](exchange-contract.md)); UUIDs in the scalar profile (`v1/record-scalars-v1.cases.json`: an ordinary UUID, the nil and max UUIDs, other letter cases, the refusal of a string, bytes or null for a UUID field and of a UUID for a bytes or string field, with frozen frames, equality terms and ciphertexts), run by native Rust and Go, and their frames checked by the TypeScript value bridge (`value-napi/tests/frames.cjs`) | Python/TS mappings; dates before year 1 and the timestamp range ends; UUIDs in the value boundary profile (sealed and SQL nulls) and the exchange profile; the TypeScript runner of the UUID cases, which waits on the addon storing a UUID (#1996) | | Owned opaque ciphertext and storage envelope | `packages/stack-encrypt/tests/scalar.rs`, `frozen_bytes.rs`; initial cross-opening cases; `owned_records.rs`, which tests the owned record derives: passthrough fields are moved, sealed fields are wiped, nested and renamed fields work, a record can store its context, and a column makes one batch. Whole-value blobs: `packages/stack-encrypt/tests/opaque_blob.rs` (round trips, the bytes leaf shared with the structural writer, a pinned storage blob and a pinned sealed ciphertext, refusals by class after authentication, source wipe) and `languages/golang/encrypt/gensupport/gensupport_internal_test.go::TestOpaqueReadsARustWrittenBlob`; the storage profile itself is pinned upstream by Vitamin C's golden corpus; fresh sealed blobs exchanged in both directions by the [exchange profile](exchange-contract.md). JSON documents as one ciphertext: `packages/stack-encrypt/tests/json_plaintext.rs` (round trips, the text leaf shared with a sealed string, refusals after authentication, a generated-document property) and, as the EQL type `Json`, `packages/eql/tests/encryption/tests/v4_types.rs` with the Go-sealed rows `v4_json_rows.json` and the frozen `stored_v4_json_rows_v1.json`, opened in Rust and Go | Encoded targets; supported version matrix | | Record declaration and lowering | [Declaration grammar](declaration-grammar.md); `v1/record-declarations-v1.cases.json` shared by native Rust and Go; native normalization observations; existing record lowering suites; `packages/stack-encrypt/tests/owned_equivalence.rs`, which seals one mixed, searchable record three ways: through a hand-written owned target, the owned derive, and the data plan. All three use one provider that records its requests. The test compares the descriptors and the term bytes, and checks that each way decrypts the records of the others | EQL-resolver profile; SDK-to-declaration mappings; runtime source/read shapes | | Context binding and composition | `packages/stack-encrypt/tests/target.rs`, `descriptor.rs`, `record_lowering.rs`; `languages/golang/encrypt/context_field_test.go`; initial wrong-context cases | Shared composition vectors; expected-context and required-input matrix | diff --git a/conformance/stack-encrypt/v1/record-scalars-v1.cases.json b/conformance/stack-encrypt/v1/record-scalars-v1.cases.json index ecb01f633e..4ac8c31a37 100644 --- a/conformance/stack-encrypt/v1/record-scalars-v1.cases.json +++ b/conformance/stack-encrypt/v1/record-scalars-v1.cases.json @@ -75,6 +75,35 @@ "text": "" } }, + { + "id": "uuid", + "kind": "uuid", + "input": { + "type": "uuid", + "text": "123e4567-e89b-12d3-a456-426614174000" + }, + "spellings": [ + "123E4567-E89B-12D3-A456-426614174000", + "123e4567-E89B-12d3-A456-426614174000" + ] + }, + { + "id": "uuid-nil", + "kind": "uuid", + "input": { + "type": "uuid", + "text": "00000000-0000-0000-0000-000000000000" + } + }, + { + "id": "uuid-max", + "kind": "uuid", + "input": { + "type": "uuid", + "text": "ffffffff-ffff-ffff-ffff-ffffffffffff" + }, + "spellings": ["FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF"] + }, { "id": "query-text-for-integer", "kind": "int64", @@ -99,6 +128,66 @@ "reason": "field_type" } }, + { + "id": "query-text-for-uuid", + "kind": "uuid", + "input": { + "type": "string", + "text": "123e4567-e89b-12d3-a456-426614174000" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_source", + "reason": "field_type" + } + }, + { + "id": "query-bytes-for-uuid", + "kind": "uuid", + "input": { + "type": "bytes", + "text": "123e4567e89b12d3a456426614174000" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_source", + "reason": "field_type" + } + }, + { + "id": "query-uuid-for-bytes", + "kind": "bytes", + "input": { + "type": "uuid", + "text": "123e4567-e89b-12d3-a456-426614174000" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_source", + "reason": "field_type" + } + }, + { + "id": "query-uuid-for-string", + "kind": "string", + "input": { + "type": "uuid", + "text": "123e4567-e89b-12d3-a456-426614174000" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_source", + "reason": "field_type" + } + }, + { + "id": "query-uuid-null", + "kind": "uuid", + "input": { + "type": "null", + "text": "" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_source", + "reason": "null_query" + } + }, { "id": "query-null", "kind": "int64", diff --git a/conformance/stack-encrypt/v1/record-scalars-v1.expected.rust-native.json b/conformance/stack-encrypt/v1/record-scalars-v1.expected.rust-native.json index a3d3ebdf69..6170c19f1e 100644 --- a/conformance/stack-encrypt/v1/record-scalars-v1.expected.rust-native.json +++ b/conformance/stack-encrypt/v1/record-scalars-v1.expected.rust-native.json @@ -42,6 +42,21 @@ "frame": "07ffffffffffffffff", "ciphertext": "01000000000000000000000000000000001aaf730b6c6bc77770144918b59a35932000ef235e515a8e50ff41f3a26ba62e5de76f5331373f245ced6bce3a5638acffd302e975cc6e364604b6b1c0563752772c462fc353b94531ddca1436504262400183186ff2f004", "equality": "04c8d7f02d9555152bdd770106eab974e517a0eba6b339e3ad1b0108796359d8" + }, + "uuid": { + "frame": "f305000b10000000123e4567e89b12d3a456426614174000", + "ciphertext": "0100000000000000000000000000000000f5b12c40ee6ffb7a9c85c69b03a779e4200056236fd096aafaed2275d4ad190e4d59db87adce04e5559e5bba3890896c5757024521688cff5eb89ecfab224ebc094626626e93d4f075e081d56792100f20d92e4e426972135dfd40bed6f730fdbd73c7", + "equality": "7634298ccb1ad44050b51acacd0771a8239d1b62733f2e304a22d0fbc171b4c8" + }, + "uuid-max": { + "frame": "f305000b10000000ffffffffffffffffffffffffffffffff", + "ciphertext": "0100000000000000000000000000000000a8ce1a0d8006f7f520bf442ccfb5e29b20004729b5919422affbfcc9adbd176531ab347d92efeffb29b2b490c0ea43b8ac7502d2148d315e954cbaeb917ef64b262406a0813f4450778f9e50ade56bec3f2b6e6bffd27fe00fbe99c51f99a1d10e9993", + "equality": "f6c58ca90a253859c9df165ca399f8f011cc35ae875cb5752a49c88f20bb5a61" + }, + "uuid-nil": { + "frame": "f305000b1000000000000000000000000000000000000000", + "ciphertext": "0100000000000000000000000000000000c7b57f8c77688afcb27fb34d7402cc102000a0662e0d9bdcae5e59de239b25fb140cfcae05d5ea7a77df8374e47031a8a9b902f41ea529a50937d4b7bddb8f255b6397f6e9931ade53a726cb6347f511dabd6b2202aa35c447ce707500ba23119a0748", + "equality": "fa20cfc9c2f9dcca704759a2751541fcac573fcaaaae5df9ec31bf843fb911cf" } } } diff --git a/languages/golang/encrypt/conformance_test.go b/languages/golang/encrypt/conformance_test.go index ebccf34ab8..888bf88c52 100644 --- a/languages/golang/encrypt/conformance_test.go +++ b/languages/golang/encrypt/conformance_test.go @@ -20,6 +20,7 @@ import ( "github.com/cipherstash/stack/languages/golang/encrypt" "github.com/cipherstash/stack/languages/golang/internal/record" "github.com/cipherstash/vitaminc/bindings/go/vcffi" + "github.com/cipherstash/vitaminc/bindings/go/vcvalue" ) // This runner tests the record interface used by generated SDK code. Generated @@ -37,9 +38,12 @@ type conformanceCorpus struct { } type conformanceCase struct { - ID string `json:"id"` - Kind string `json:"kind"` - Input conformanceInput `json:"input"` + ID string `json:"id"` + Kind string `json:"kind"` + Input conformanceInput `json:"input"` + // Spellings are other spellings of a UUID input's text, in another + // letter case, that vcvalue.ParseUUID must read as the same UUID. + Spellings []string `json:"spellings"` ExpectedError *struct { Code string `json:"code"` Reason string `json:"reason"` @@ -83,8 +87,8 @@ type conformanceInput struct { // conformanceValue is the typed Go value an input names: every integer at // its own width, the SDK's Int128, Uint128, Date and Decimal, a time.Time -// for a timestamp, and bytes from hex. A text the type cannot carry fails -// the test; nothing is rounded. +// for a timestamp, a vcvalue.UUID, and bytes from hex. A text the type +// cannot carry fails the test; nothing is rounded. func conformanceValue(t testing.TB, input conformanceInput) any { t.Helper() signed := func(bits int) int64 { @@ -172,6 +176,14 @@ func conformanceValue(t testing.TB, input conformanceInput) any { return input.Text == "true" case "string": return input.Text + case "uuid": + // The corpus spells a UUID in lowercase only, as Rust's reader + // requires; other spellings are a case's Spellings. + u, err := vcvalue.ParseUUID(input.Text) + if err != nil || u.String() != input.Text { + t.Fatalf("%q: not a canonical lowercase UUID", input.Text) + } + return u case "null": if input.Text != "" { t.Fatal("null has empty text") @@ -200,6 +212,14 @@ func TestStackConformance(t *testing.T) { t.Fatalf("empty or duplicate case ID %q", c.ID) } seen[c.ID] = true + if len(c.Spellings) > 0 && c.Input.Type != "uuid" { + t.Fatalf("%s: only a UUID input has other spellings", c.ID) + } + for _, spelling := range c.Spellings { + if spelling == c.Input.Text || !strings.EqualFold(spelling, c.Input.Text) { + t.Fatalf("%s: %q is not the input's text in another letter case", c.ID, spelling) + } + } if c.ExpectedError == nil { positive[c.ID] = true } @@ -255,6 +275,12 @@ func TestStackConformance(t *testing.T) { if hex.EncodeToString(encoded) != want.Frame || hex.EncodeToString(query.Terms[0]) != want.Equality { t.Fatal("typed frame or equality bytes disagree with the native vector") } + for _, spelling := range c.Spellings { + u, err := vcvalue.ParseUUID(spelling) + if err != nil || u != input { + t.Fatalf("%q: does not read as the input's UUID: %v", spelling, err) + } + } decode := func(text string) []byte { t.Helper() b, err := hex.DecodeString(text) diff --git a/languages/typescript/packages/recipher-js/value-napi/tests/frames.cjs b/languages/typescript/packages/recipher-js/value-napi/tests/frames.cjs index afe874bd39..3198796cc8 100644 --- a/languages/typescript/packages/recipher-js/value-napi/tests/frames.cjs +++ b/languages/typescript/packages/recipher-js/value-napi/tests/frames.cjs @@ -216,7 +216,36 @@ const inputs = [ 'record-values-v1/decimal-max-mantissa', ], ['VcDecimal -0.00', () => new VcDecimal('-0.00')], - ['VcUuid', () => new VcUuid('123e4567-e89b-12d3-a456-426614174000')], + [ + 'VcUuid', + () => new VcUuid('123e4567-e89b-12d3-a456-426614174000'), + 'record-scalars-v1/uuid', + ], + [ + 'VcUuid uppercase', + () => new VcUuid('123E4567-E89B-12D3-A456-426614174000'), + 'record-scalars-v1/uuid', + ], + [ + 'VcUuid mixed case', + () => new VcUuid('123e4567-E89B-12d3-A456-426614174000'), + 'record-scalars-v1/uuid', + ], + [ + 'VcUuid nil', + () => new VcUuid('00000000-0000-0000-0000-000000000000'), + 'record-scalars-v1/uuid-nil', + ], + [ + 'VcUuid max', + () => new VcUuid('ffffffff-ffff-ffff-ffff-ffffffffffff'), + 'record-scalars-v1/uuid-max', + ], + [ + 'VcUuid max uppercase', + () => new VcUuid('FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF'), + 'record-scalars-v1/uuid-max', + ], ['array empty', () => []], ['array of bigint and string', () => [1n, 'x']], ['array of null', () => [null]], diff --git a/languages/typescript/packages/recipher-js/value-napi/tests/testdata/corpus-frames.json b/languages/typescript/packages/recipher-js/value-napi/tests/testdata/corpus-frames.json index 0710601913..f98b8c4926 100644 --- a/languages/typescript/packages/recipher-js/value-napi/tests/testdata/corpus-frames.json +++ b/languages/typescript/packages/recipher-js/value-napi/tests/testdata/corpus-frames.json @@ -9,6 +9,9 @@ "record-scalars-v1/text-empty": "0a00000000", "record-scalars-v1/text-unicode": "0a11000000636166c3a920e69db1e4baac20f09f9490", "record-scalars-v1/u64-max": "07ffffffffffffffff", + "record-scalars-v1/uuid": "f305000b10000000123e4567e89b12d3a456426614174000", + "record-scalars-v1/uuid-max": "f305000b10000000ffffffffffffffffffffffffffffffff", + "record-scalars-v1/uuid-nil": "f305000b1000000000000000000000000000000000000000", "record-values-v1/bool-false": "02", "record-values-v1/bool-true": "03", "record-values-v1/bytes-binary": "0b0300000000ff10", diff --git a/languages/typescript/packages/recipher-js/value-napi/tests/testdata/js-frames.json b/languages/typescript/packages/recipher-js/value-napi/tests/testdata/js-frames.json index 1dd7138e05..971733a3ed 100644 --- a/languages/typescript/packages/recipher-js/value-napi/tests/testdata/js-frames.json +++ b/languages/typescript/packages/recipher-js/value-napi/tests/testdata/js-frames.json @@ -321,7 +321,34 @@ "frame": "1400000200000000000000000000000000" }, "VcUuid": { - "frame": "f305000b10000000123e4567e89b12d3a456426614174000" + "frame": "f305000b10000000123e4567e89b12d3a456426614174000", + "corpus_case": "record-scalars-v1/uuid", + "same_as_corpus": true + }, + "VcUuid uppercase": { + "frame": "f305000b10000000123e4567e89b12d3a456426614174000", + "corpus_case": "record-scalars-v1/uuid", + "same_as_corpus": true + }, + "VcUuid mixed case": { + "frame": "f305000b10000000123e4567e89b12d3a456426614174000", + "corpus_case": "record-scalars-v1/uuid", + "same_as_corpus": true + }, + "VcUuid nil": { + "frame": "f305000b1000000000000000000000000000000000000000", + "corpus_case": "record-scalars-v1/uuid-nil", + "same_as_corpus": true + }, + "VcUuid max": { + "frame": "f305000b10000000ffffffffffffffffffffffffffffffff", + "corpus_case": "record-scalars-v1/uuid-max", + "same_as_corpus": true + }, + "VcUuid max uppercase": { + "frame": "f305000b10000000ffffffffffffffffffffffffffffffff", + "corpus_case": "record-scalars-v1/uuid-max", + "same_as_corpus": true }, "array empty": { "frame": "f000000000" diff --git a/packages/stack-encrypt/tests/common/conformance.rs b/packages/stack-encrypt/tests/common/conformance.rs index ed4aecb075..d5218ecd41 100644 --- a/packages/stack-encrypt/tests/common/conformance.rs +++ b/packages/stack-encrypt/tests/common/conformance.rs @@ -50,6 +50,7 @@ pub fn value(input: &Input) -> OwnedFrame { Physical::Int(Int::I128(mantissa)), )) } + "uuid" => frame(Raw(Some(Logical::Uuid), Physical::Bytes(&parse_uuid(text)))), "null" => { assert!(input.text.is_empty()); frame(Raw(None, Physical::Null)) @@ -201,6 +202,24 @@ fn parse_timestamp(text: &str) -> i128 { ((days * 86_400 + hour * 3_600 + minute * 60 + second) * 1_000_000_000) + nanos } +/// The sixteen bytes of a UUID, from its canonical text. The canonical text +/// is lowercase hex in groups of 8, 4, 4, 4, and 12 digits, with `-` between +/// the groups. Any other spelling is a corpus error: uppercase, braces, or +/// no hyphens. +fn parse_uuid(text: &str) -> [u8; 16] { + let groups: Vec<&str> = text.split('-').collect(); + let lengths: Vec = groups.iter().map(|group| group.len()).collect(); + let digits = groups.concat(); + assert!( + lengths == [8, 4, 4, 4, 12] + && digits + .bytes() + .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)), + "{text}: not a canonical lowercase UUID" + ); + super::unhex(&digits).try_into().expect("sixteen bytes") +} + /// A decimal's mantissa and scale from fixed-point text, keeping every /// trailing zero: `-1234.5600` is `(-12345600, 4)`. fn parse_decimal(text: &str) -> (i128, u8) { diff --git a/packages/stack-encrypt/tests/conformance.rs b/packages/stack-encrypt/tests/conformance.rs index 6d4b9621b7..1302c8da70 100644 --- a/packages/stack-encrypt/tests/conformance.rs +++ b/packages/stack-encrypt/tests/conformance.rs @@ -15,6 +15,7 @@ use serde::{Deserialize, Serialize}; use serde_json::json; use stack_encrypt::dynamic::{self, frame::OwnedFrame, record, Fidelity, NoTargets, Op, Operand}; use stack_encrypt::target::IndexSpec; +use stack_encrypt::value::Uuid; use stack_encrypt::{ CipherText, Ciphertext, Error, KeysetCipher, Label, SealedValue, StackCipherText, }; @@ -39,6 +40,10 @@ struct Case { id: String, kind: String, input: Input, + /// Other spellings of a UUID input's text, in another letter case, + /// that a host's UUID parser must read as the same UUID. + #[serde(default)] + spellings: Vec, expected_error: Option, } @@ -58,7 +63,7 @@ struct Artifacts { cases: BTreeMap, } -#[derive(Deserialize, Serialize)] +#[derive(Deserialize, Serialize, Clone)] #[serde(deny_unknown_fields)] struct Artifact { frame: String, @@ -66,6 +71,13 @@ struct Artifact { equality: String, } +/// The UUID a corpus text spells. `value` has already held an input's text +/// to the canonical lowercase spelling; a case's `spellings` are checked +/// against it before they reach here. +fn parse_uuid(text: &str) -> uuid::Uuid { + uuid::Uuid::try_parse(text).expect("a hyphenated UUID") +} + fn root() -> PathBuf { PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../conformance/stack-encrypt/v1") } @@ -120,6 +132,7 @@ async fn scalar( "uint64" => seal!(input.text.parse::().unwrap()), "bool" => seal!(input.text.parse::().unwrap()), "string" => seal!(input.text.clone()), + "uuid" => seal!(Uuid::new(parse_uuid(&input.text))), other => panic!("unsupported scalar {other}"), } } @@ -147,6 +160,7 @@ async fn open_scalar( "uint64" => open!(u64), "bool" => open!(bool), "string" => open!(String), + "uuid" => open!(Uuid), other => panic!("unsupported scalar {other}"), } } @@ -175,6 +189,21 @@ async fn shared_record_scalar_profile() { .collect(); assert!(!positive_ids.is_empty()); + for case in &corpus.cases { + assert!( + case.spellings.is_empty() || case.input.kind == "uuid", + "{}: only a UUID input has other spellings", + case.id + ); + for spelling in &case.spellings { + assert!( + spelling != &case.input.text && spelling.eq_ignore_ascii_case(&case.input.text), + "{}: {spelling} is not the input's text in another letter case", + case.id + ); + } + } + let update = std::env::var("STACK_CONFORMANCE_UPDATE").as_deref() == Ok("1"); let imported = std::env::var_os("STACK_CONFORMANCE_INPUT"); assert!( @@ -201,6 +230,13 @@ async fn shared_record_scalar_profile() { ); Some(artifacts) }; + // An update keeps the frozen ciphertext of a case whose frame and + // equality term have not changed, so the diff shows only the cases that + // did. The kept ciphertext is opened below as any reference is. + let previous: Option = update + .then(|| std::fs::read(root().join("record-scalars-v1.expected.rust-native.json")).ok()) + .flatten() + .map(|bytes| serde_json::from_slice(&bytes).unwrap()); let cipher = common::deterministic_cipher(unhex(&corpus.seed).try_into().expect("32-byte seed")).await; @@ -280,7 +316,24 @@ async fn shared_record_scalar_profile() { ciphertext: hex(&ct.to_bytes()), equality: hex(term), }; - let reference = baseline.as_ref().map_or(&artifact, |a| &a.cases[&case.id]); + for spelling in &case.spellings { + let spelt = frame(Uuid::new(parse_uuid(spelling))); + assert_eq!( + hex(spelt.frame().as_bytes()), + artifact.frame, + "{}: the spelling {spelling}", + case.id + ); + } + let kept = previous + .as_ref() + .and_then(|p| p.cases.get(&case.id)) + .filter(|old| old.frame == artifact.frame && old.equality == artifact.equality); + let reference = baseline + .as_ref() + .map(|a| &a.cases[&case.id]) + .or(kept) + .unwrap_or(&artifact); assert_eq!(artifact.frame, reference.frame, "{}: typed frame", case.id); assert_eq!( artifact.equality, reference.equality, @@ -325,7 +378,8 @@ async fn shared_record_scalar_profile() { "{}: wrong context: {result:?}", case.id ); - output.cases.insert(case.id.clone(), artifact); + let written = if update { reference.clone() } else { artifact }; + output.cases.insert(case.id.clone(), written); } if update { std::fs::write( From 1d3d3c65a0480ab1331c22d6b36058d186ac0414 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sun, 29 Nov 2026 13:55:01 +1100 Subject: [PATCH 2/3] fix(conformance): let an update refresh a frozen ciphertext These changes address the review of the UUID cases. The scalar runner's update kept a frozen ciphertext and then failed when that ciphertext no longer opened. Now the update first checks that the kept ciphertext opens. If it does not, the update writes a fresh one. A previous file that does not parse keeps nothing. STACK_CONFORMANCE_UPDATE=all writes every artifact fresh. STACK_CONFORMANCE_OUTPUT always gets the artifacts this run made. The runner now builds without the uuid feature. Only the UUID arms need it, and a build without the feature skips the accepted UUID cases. The TypeScript frame suite reads each UUID case's text and spellings from the corpus, through its copy. The parity test fails when the copy differs from the corpus, or when a spelling has no pinned frame. The README says which bytes cases are still to come. Refs #1821 --- conformance/stack-encrypt/README.md | 38 ++-- .../recipher-js/value-napi/tests/frames.cjs | 67 +++---- .../tests/testdata/corpus-frames.json | 19 +- .../value-napi/tests/testdata/js-frames.json | 54 +++--- packages/stack-encrypt/tests/conformance.rs | 174 +++++++++++++++--- .../recipher-js-frame-parity.test.mjs | 36 ++++ 6 files changed, 286 insertions(+), 102 deletions(-) diff --git a/conformance/stack-encrypt/README.md b/conformance/stack-encrypt/README.md index 13fac77e72..823995bcf2 100644 --- a/conformance/stack-encrypt/README.md +++ b/conformance/stack-encrypt/README.md @@ -59,7 +59,7 @@ These files read or copy cases, and are not runners: | File | Profile | What it reads | |---|---|---| -| `languages/typescript/packages/recipher-js/value-napi/tests/testdata/corpus-frames.json` | `record-values-v1`, `record-scalars-v1` | The frames of the corpus cases that the TypeScript value bridge must write. Among them is the frame of each UUID case of `record-scalars-v1`, which `tests/frames.cjs` also writes from each of the case's spellings. `tests/frames.cjs` regenerates it with `RECIPHER_UPDATE_FIXTURES=1`, and `scripts/__tests__/recipher-js-frame-parity.test.mjs` holds it to the corpus. | +| `languages/typescript/packages/recipher-js/value-napi/tests/testdata/corpus-frames.json` | `record-values-v1`, `record-scalars-v1` | The frames of the corpus cases that the TypeScript value bridge must write. It also holds the text and spellings of each UUID case of `record-scalars-v1`, which `tests/frames.cjs` writes a frame from. `tests/frames.cjs` regenerates it with `RECIPHER_UPDATE_FIXTURES=1`, and `scripts/__tests__/recipher-js-frame-parity.test.mjs` holds it to the corpus. | | `scripts/__tests__/stack-exchange-conformance.test.mjs` | `record-values-v1` | The IDs of the positive cases, to build test artifacts. | | `scripts/__tests__/stack-eql-conformance.test.mjs` | `eql-json-v1` | The documents and the reasons of `invalid_documents`. | `fixture-enrollment.json` is the one file not named after a profile: it maps @@ -278,15 +278,20 @@ negative cases query these values: A null is refused as `null_query`, and every other value as `field_type`. The engine converts nothing to or from a UUID. -Boolean equality is not admitted by the current engine. Boolean scalar -encryption, nullable records, other numeric kinds, bytes, JSON, EQL targets, -other operators, declarations, cancellation and provider failures need later -profiles or cases. The full SQL behavior is not part of this initial profile. +Boolean equality is not admitted by the current engine. Later profiles or +cases need to cover these: Boolean scalar encryption, nullable records, and +other numeric kinds. Bytes need accepted cases and frozen equality terms: the +one bytes field here only refuses a UUID. JSON, EQL targets, other operators, +declarations, cancellation, and provider failures also need later cases. The +full SQL behavior is not part of this initial profile. -Native Rust and Go run every case. The TypeScript runner is pending. The -TypeScript value bridge checks only the frames. Its `tests/frames.cjs` writes -each UUID case and each of its spellings, and compares each frame with the -frozen one. +Native Rust and Go run every case. A Rust build without the `uuid` feature +has no typed UUID, so it skips the accepted UUID cases and runs the rest. + +The TypeScript runner is pending. The TypeScript value bridge checks only +the frames. Its `tests/frames.cjs` reads the text and the spellings of each +UUID case from the corpus. It writes a frame from each one, and compares the +frame with the frozen one. The `@cipherstash/recipher` addon cannot store a UUID yet. So no TypeScript test encrypts these cases, queries them, or opens their frozen @@ -315,9 +320,18 @@ STACK_CONFORMANCE_UPDATE=1 mise x --env test -- cargo nextest run --locked \ mise run test:conformance ``` -An update keeps the frozen ciphertext of a case whose frame and equality term -have not changed, and opens it as any run does. So adding a case adds one -entry, and the diff does not rewrite the ciphertexts of the other cases. +`STACK_CONFORMANCE_UPDATE=1` keeps the frozen ciphertext of a case whose +frame and equality term have not changed, if that ciphertext still opens. So +adding a case adds one entry, and the diff does not rewrite the ciphertexts +of the other cases. A frozen ciphertext that no longer opens is replaced +with a fresh one. A previous file that is missing or does not parse keeps +nothing. + +`STACK_CONFORMANCE_UPDATE=all` writes every artifact fresh, every ciphertext +included. Use it after a change to how a ciphertext is written. + +`STACK_CONFORMANCE_OUTPUT` always gets the artifacts this run made, never a +kept ciphertext. Review the case and artifact diff together. Never regenerate artifacts merely to make a regression pass. diff --git a/languages/typescript/packages/recipher-js/value-napi/tests/frames.cjs b/languages/typescript/packages/recipher-js/value-napi/tests/frames.cjs index 3198796cc8..902e0f38e6 100644 --- a/languages/typescript/packages/recipher-js/value-napi/tests/frames.cjs +++ b/languages/typescript/packages/recipher-js/value-napi/tests/frames.cjs @@ -34,14 +34,15 @@ if ( throw new Error('conformance checks must not update frozen fixtures') } +const corpusDir = path.join( + __dirname, + '../../../../../../conformance/stack-encrypt/v1', +) + // Every frame the corpus froze, by case id: the value-kinds profile's // `frame`, and the scalar profile's frames from its Rust artifacts. Read // from the corpus only to regenerate; a check reads the copy. function corpusFrames() { - const corpusDir = path.join( - __dirname, - '../../../../../../conformance/stack-encrypt/v1', - ) const frames = new Map() const values = JSON.parse( fs.readFileSync(path.join(corpusDir, 'record-values-v1.cases.json')), @@ -57,9 +58,24 @@ function corpusFrames() { frames.set(`record-scalars-v1/${id}`, artifact.frame) return frames } -const corpus = update - ? corpusFrames() - : new Map(Object.entries(JSON.parse(fs.readFileSync(vendored)).frames)) +// Every accepted UUID case of the scalar profile, by case id: its text and +// the other spellings the case lists. The bridge writes a frame from each. +function corpusUuids() { + const scalars = JSON.parse( + fs.readFileSync(path.join(corpusDir, 'record-scalars-v1.cases.json')), + ) + const uuids = {} + for (const c of scalars.cases) + if (c.input.type === 'uuid' && !c.expected_error) + uuids[`record-scalars-v1/${c.id}`] = { + text: c.input.text, + spellings: c.spellings ?? [], + } + return uuids +} +const copied = update ? undefined : JSON.parse(fs.readFileSync(vendored)) +const corpus = update ? corpusFrames() : new Map(Object.entries(copied.frames)) +const uuids = update ? corpusUuids() : copied.uuids // [name, the value, the corpus case that spells the same value, if any]. // The bridge picks a bigint's width itself and cannot be asked for one, so @@ -216,36 +232,6 @@ const inputs = [ 'record-values-v1/decimal-max-mantissa', ], ['VcDecimal -0.00', () => new VcDecimal('-0.00')], - [ - 'VcUuid', - () => new VcUuid('123e4567-e89b-12d3-a456-426614174000'), - 'record-scalars-v1/uuid', - ], - [ - 'VcUuid uppercase', - () => new VcUuid('123E4567-E89B-12D3-A456-426614174000'), - 'record-scalars-v1/uuid', - ], - [ - 'VcUuid mixed case', - () => new VcUuid('123e4567-E89B-12d3-A456-426614174000'), - 'record-scalars-v1/uuid', - ], - [ - 'VcUuid nil', - () => new VcUuid('00000000-0000-0000-0000-000000000000'), - 'record-scalars-v1/uuid-nil', - ], - [ - 'VcUuid max', - () => new VcUuid('ffffffff-ffff-ffff-ffff-ffffffffffff'), - 'record-scalars-v1/uuid-max', - ], - [ - 'VcUuid max uppercase', - () => new VcUuid('FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF'), - 'record-scalars-v1/uuid-max', - ], ['array empty', () => []], ['array of bigint and string', () => [1n, 'x']], ['array of null', () => [null]], @@ -254,6 +240,10 @@ const inputs = [ ['object of two keys', () => ({ b: 1n, a: 'x' })], ['object nested', () => ({ list: [1n], map: {}, at: new Date(0) })], ] +// A UUID from the text of each UUID case, and from each of its spellings. +for (const [id, { text, spellings }] of Object.entries(uuids)) + for (const spelling of [text, ...spellings]) + inputs.push([`VcUuid ${spelling}`, () => new VcUuid(spelling), id]) const actual = {} for (const [name, make, corpusCase] of inputs) { @@ -284,8 +274,9 @@ if (update) { ].sort() const copy = { _comment: - 'A copy of the conformance corpus frames tests/frames.cjs compares against, so the suite reads nothing outside this package. scripts/__tests__/recipher-js-frame-parity.test.mjs holds it to conformance/stack-encrypt/v1. Regenerate with RECIPHER_UPDATE_FIXTURES=1; never edit by hand.', + 'A copy of the conformance corpus frames tests/frames.cjs compares against, and of the text and spellings of each UUID case it writes a frame from, so the suite reads nothing outside this package. scripts/__tests__/recipher-js-frame-parity.test.mjs holds it to conformance/stack-encrypt/v1. Regenerate with RECIPHER_UPDATE_FIXTURES=1; never edit by hand.', frames: Object.fromEntries(used.map((id) => [id, corpus.get(id)])), + uuids, } fs.writeFileSync(vendored, `${JSON.stringify(copy, null, 2)}\n`) } else { diff --git a/languages/typescript/packages/recipher-js/value-napi/tests/testdata/corpus-frames.json b/languages/typescript/packages/recipher-js/value-napi/tests/testdata/corpus-frames.json index f98b8c4926..0ad8308dab 100644 --- a/languages/typescript/packages/recipher-js/value-napi/tests/testdata/corpus-frames.json +++ b/languages/typescript/packages/recipher-js/value-napi/tests/testdata/corpus-frames.json @@ -1,5 +1,5 @@ { - "_comment": "A copy of the conformance corpus frames tests/frames.cjs compares against, so the suite reads nothing outside this package. scripts/__tests__/recipher-js-frame-parity.test.mjs holds it to conformance/stack-encrypt/v1. Regenerate with RECIPHER_UPDATE_FIXTURES=1; never edit by hand.", + "_comment": "A copy of the conformance corpus frames tests/frames.cjs compares against, and of the text and spellings of each UUID case it writes a frame from, so the suite reads nothing outside this package. scripts/__tests__/recipher-js-frame-parity.test.mjs holds it to conformance/stack-encrypt/v1. Regenerate with RECIPHER_UPDATE_FIXTURES=1; never edit by hand.", "frames": { "record-scalars-v1/above-js-safe-integer": "050100000000002000", "record-scalars-v1/i32-max": "04ffffff7f", @@ -55,5 +55,22 @@ "record-values-v1/u32-zero": "0600000000", "record-values-v1/u8-max": "0dff", "record-values-v1/u8-zero": "0d00" + }, + "uuids": { + "record-scalars-v1/uuid": { + "text": "123e4567-e89b-12d3-a456-426614174000", + "spellings": [ + "123E4567-E89B-12D3-A456-426614174000", + "123e4567-E89B-12d3-A456-426614174000" + ] + }, + "record-scalars-v1/uuid-nil": { + "text": "00000000-0000-0000-0000-000000000000", + "spellings": [] + }, + "record-scalars-v1/uuid-max": { + "text": "ffffffff-ffff-ffff-ffff-ffffffffffff", + "spellings": ["FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF"] + } } } diff --git a/languages/typescript/packages/recipher-js/value-napi/tests/testdata/js-frames.json b/languages/typescript/packages/recipher-js/value-napi/tests/testdata/js-frames.json index 971733a3ed..606791b14a 100644 --- a/languages/typescript/packages/recipher-js/value-napi/tests/testdata/js-frames.json +++ b/languages/typescript/packages/recipher-js/value-napi/tests/testdata/js-frames.json @@ -320,56 +320,56 @@ "VcDecimal -0.00": { "frame": "1400000200000000000000000000000000" }, - "VcUuid": { + "array empty": { + "frame": "f000000000" + }, + "array of bigint and string": { + "frame": "f0020000000c010a0100000078" + }, + "array of null": { + "frame": "f00100000000" + }, + "array of undefined": { + "frame": "f00100000001" + }, + "object empty": { + "frame": "f100000000" + }, + "object of two keys": { + "frame": "f10200000001000000620c0101000000610a0100000078" + }, + "object nested": { + "frame": "f103000000040000006c697374f0010000000c01030000006d6170f100000000020000006174f30301050000000000000000" + }, + "VcUuid 123e4567-e89b-12d3-a456-426614174000": { "frame": "f305000b10000000123e4567e89b12d3a456426614174000", "corpus_case": "record-scalars-v1/uuid", "same_as_corpus": true }, - "VcUuid uppercase": { + "VcUuid 123E4567-E89B-12D3-A456-426614174000": { "frame": "f305000b10000000123e4567e89b12d3a456426614174000", "corpus_case": "record-scalars-v1/uuid", "same_as_corpus": true }, - "VcUuid mixed case": { + "VcUuid 123e4567-E89B-12d3-A456-426614174000": { "frame": "f305000b10000000123e4567e89b12d3a456426614174000", "corpus_case": "record-scalars-v1/uuid", "same_as_corpus": true }, - "VcUuid nil": { + "VcUuid 00000000-0000-0000-0000-000000000000": { "frame": "f305000b1000000000000000000000000000000000000000", "corpus_case": "record-scalars-v1/uuid-nil", "same_as_corpus": true }, - "VcUuid max": { + "VcUuid ffffffff-ffff-ffff-ffff-ffffffffffff": { "frame": "f305000b10000000ffffffffffffffffffffffffffffffff", "corpus_case": "record-scalars-v1/uuid-max", "same_as_corpus": true }, - "VcUuid max uppercase": { + "VcUuid FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF": { "frame": "f305000b10000000ffffffffffffffffffffffffffffffff", "corpus_case": "record-scalars-v1/uuid-max", "same_as_corpus": true - }, - "array empty": { - "frame": "f000000000" - }, - "array of bigint and string": { - "frame": "f0020000000c010a0100000078" - }, - "array of null": { - "frame": "f00100000000" - }, - "array of undefined": { - "frame": "f00100000001" - }, - "object empty": { - "frame": "f100000000" - }, - "object of two keys": { - "frame": "f10200000001000000620c0101000000610a0100000078" - }, - "object nested": { - "frame": "f103000000040000006c697374f0010000000c01030000006d6170f100000000020000006174f30301050000000000000000" } } } diff --git a/packages/stack-encrypt/tests/conformance.rs b/packages/stack-encrypt/tests/conformance.rs index 1302c8da70..ca6e4a5241 100644 --- a/packages/stack-encrypt/tests/conformance.rs +++ b/packages/stack-encrypt/tests/conformance.rs @@ -15,6 +15,7 @@ use serde::{Deserialize, Serialize}; use serde_json::json; use stack_encrypt::dynamic::{self, frame::OwnedFrame, record, Fidelity, NoTargets, Op, Operand}; use stack_encrypt::target::IndexSpec; +#[cfg(feature = "uuid")] use stack_encrypt::value::Uuid; use stack_encrypt::{ CipherText, Ciphertext, Error, KeysetCipher, Label, SealedValue, StackCipherText, @@ -54,7 +55,7 @@ struct ExpectedError { reason: String, } -#[derive(Deserialize, Serialize)] +#[derive(Deserialize, Serialize, Clone)] #[serde(deny_unknown_fields)] struct Artifacts { version: u32, @@ -71,9 +72,44 @@ struct Artifact { equality: String, } +/// How `STACK_CONFORMANCE_UPDATE` asks to rewrite the expected file. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Update { + /// Unset: compare with the expected file and write nothing. + No, + /// `1`: write the file, keeping each frozen ciphertext that still opens + /// for a case whose frame and equality term have not changed. + KeepUnchanged, + /// `all`: write every artifact fresh. + All, +} + +impl Update { + fn from_env() -> Self { + match std::env::var("STACK_CONFORMANCE_UPDATE").as_deref() { + Err(_) => Self::No, + Ok("1") => Self::KeepUnchanged, + Ok("all") => Self::All, + Ok(other) => panic!("STACK_CONFORMANCE_UPDATE={other}: use 1 or all"), + } + } +} + +/// The bytes of a hex text, or an error for text that is not hex. +fn try_unhex(text: &str) -> Result, String> { + if !text.is_ascii() || !text.len().is_multiple_of(2) { + return Err("not hex".into()); + } + (0..text.len()) + .step_by(2) + .map(|i| u8::from_str_radix(&text[i..i + 2], 16).map_err(|e| e.to_string())) + .collect() +} + /// The UUID a corpus text spells. `value` has already held an input's text /// to the canonical lowercase spelling; a case's `spellings` are checked /// against it before they reach here. +#[cfg(feature = "uuid")] fn parse_uuid(text: &str) -> uuid::Uuid { uuid::Uuid::try_parse(text).expect("a hyphenated UUID") } @@ -96,20 +132,23 @@ fn plan(corpus: &Corpus, case: &Case) -> record::Plan { .unwrap() } -fn stored(corpus: &Corpus, artifact: &Artifact) -> StackCipherText { - CipherText::Map(vec![( +fn try_stored(corpus: &Corpus, artifact: &Artifact) -> Result { + let leaf = + SealedValue::from_bytes(&try_unhex(&artifact.ciphertext)?).map_err(|e| format!("{e:?}"))?; + Ok(CipherText::Map(vec![( corpus.field.clone(), CipherText::Map(vec![ - ( - "c".into(), - CipherText::Single(SealedValue::from_bytes(&unhex(&artifact.ciphertext)).unwrap()), - ), + ("c".into(), CipherText::Single(leaf)), ( "eq".into(), - CipherText::Passthrough(common::passthrough(unhex(&artifact.equality))), + CipherText::Passthrough(common::passthrough(try_unhex(&artifact.equality)?)), ), ]), - )]) + )])) +} + +fn stored(corpus: &Corpus, artifact: &Artifact) -> StackCipherText { + try_stored(corpus, artifact).unwrap() } // Exercise the owned scalar API independently of dynamic record lowering. @@ -132,37 +171,77 @@ async fn scalar( "uint64" => seal!(input.text.parse::().unwrap()), "bool" => seal!(input.text.parse::().unwrap()), "string" => seal!(input.text.clone()), + #[cfg(feature = "uuid")] "uuid" => seal!(Uuid::new(parse_uuid(&input.text))), other => panic!("unsupported scalar {other}"), } } -async fn open_scalar( +async fn try_open_scalar( keyset: &KeysetCipher<'_, common::DeterministicSource>, bytes: &[u8], kind: &str, context: &Label, -) -> OwnedFrame { - let ct = Ciphertext::from_bytes(bytes).unwrap(); +) -> Result { + let ct = Ciphertext::from_bytes(bytes).map_err(|e| format!("{e:?}"))?; macro_rules! open { ($ty:ty) => { frame( keyset .decrypt_with_context::<$ty>(ct, context.clone()) .await - .unwrap(), + .map_err(|e| format!("{e:?}"))?, ) }; } - match kind { + Ok(match kind { "int32" => open!(i32), "int64" => open!(i64), "uint64" => open!(u64), "bool" => open!(bool), "string" => open!(String), + #[cfg(feature = "uuid")] "uuid" => open!(Uuid), other => panic!("unsupported scalar {other}"), + }) +} + +async fn open_scalar( + keyset: &KeysetCipher<'_, common::DeterministicSource>, + bytes: &[u8], + kind: &str, + context: &Label, +) -> OwnedFrame { + try_open_scalar(keyset, bytes, kind, context) + .await + .unwrap_or_else(|e| panic!("the scalar opens: {e}")) +} + +/// Whether `candidate`'s ciphertext opens to `input`, through the owned +/// scalar API and through the record path. An update asks this of a frozen +/// ciphertext before keeping it. +async fn reopens( + keyset: &KeysetCipher<'_, common::DeterministicSource>, + corpus: &Corpus, + case: &Case, + plan: &record::Plan, + candidate: &Artifact, + (input, row): (&OwnedFrame, &OwnedFrame), + context: &Label, +) -> Result<(), String> { + let bytes = try_unhex(&candidate.ciphertext)?; + let opened = try_open_scalar(keyset, &bytes, &case.kind, context).await?; + if opened.frame().as_bytes() != input.frame().as_bytes() { + return Err("the scalar opens to another value".into()); } + let opened = record::decrypt(keyset.clone(), try_stored(corpus, candidate)?, plan, None) + .map_err(|e| format!("{e:?}"))? + .await + .map_err(|e| format!("{e:?}"))?; + if opened.frame().as_bytes() != row.frame().as_bytes() { + return Err("the record opens to another value".into()); + } + Ok(()) } #[tokio::test] @@ -204,12 +283,19 @@ async fn shared_record_scalar_profile() { } } - let update = std::env::var("STACK_CONFORMANCE_UPDATE").as_deref() == Ok("1"); + let mode = Update::from_env(); + let update = mode != Update::No; let imported = std::env::var_os("STACK_CONFORMANCE_INPUT"); assert!( !(update && imported.is_some()), "cannot update from external artifacts" ); + // Without the `uuid` feature there is no typed UUID, so the positive + // UUID cases are skipped, and an update would drop their artifacts. + assert!( + !update || cfg!(feature = "uuid"), + "an update needs the uuid feature" + ); let baseline: Option = if update { None } else { @@ -230,25 +316,36 @@ async fn shared_record_scalar_profile() { ); Some(artifacts) }; - // An update keeps the frozen ciphertext of a case whose frame and - // equality term have not changed, so the diff shows only the cases that - // did. The kept ciphertext is opened below as any reference is. - let previous: Option = update + // `STACK_CONFORMANCE_UPDATE=1` keeps the frozen ciphertext of a case + // whose frame and equality term have not changed, if it still opens, so + // the diff shows only the cases that changed. A previous file that is + // missing or no longer parses keeps nothing. + let previous: Option = (mode == Update::KeepUnchanged) .then(|| std::fs::read(root().join("record-scalars-v1.expected.rust-native.json")).ok()) .flatten() - .map(|bytes| serde_json::from_slice(&bytes).unwrap()); + .and_then(|bytes| match serde_json::from_slice(&bytes) { + Ok(artifacts) => Some(artifacts), + Err(error) => { + eprintln!("conformance: the previous expected file does not parse ({error}); writing every artifact fresh"); + None + } + }); let cipher = common::deterministic_cipher(unhex(&corpus.seed).try_into().expect("32-byte seed")).await; let keyset = cipher.default_keyset(); let context = Label::new(corpus.context.iter().chain(std::iter::once(&corpus.field))).unwrap(); let (counting, generates, retrieves) = common::counting_cipher().await; + // `output` holds the artifacts this run made, for + // `STACK_CONFORMANCE_OUTPUT`; `frozen` holds what an update writes to + // the expected file, kept ciphertexts included. let mut output = Artifacts { version: 1, profile: PROFILE.into(), producer: format!("rust-native/stack-encrypt-{}", env!("CARGO_PKG_VERSION")), cases: BTreeMap::new(), }; + let mut frozen = BTreeMap::new(); for case in &corpus.cases { eprintln!("conformance: {}", case.id); @@ -272,6 +369,10 @@ async fn shared_record_scalar_profile() { continue; } assert_eq!(case.kind, case.input.kind); + if cfg!(not(feature = "uuid")) && case.input.kind == "uuid" { + eprintln!("conformance: {}: skipped, needs the uuid feature", case.id); + continue; + } let input = value(&case.input); let expected_row = object(vec![(corpus.field.clone(), value(&case.input))]); let fresh = record::encrypt(&keyset, &expected_row, &plan) @@ -316,6 +417,7 @@ async fn shared_record_scalar_profile() { ciphertext: hex(&ct.to_bytes()), equality: hex(term), }; + #[cfg(feature = "uuid")] for spelling in &case.spellings { let spelt = frame(Uuid::new(parse_uuid(spelling))); assert_eq!( @@ -325,10 +427,30 @@ async fn shared_record_scalar_profile() { case.id ); } - let kept = previous + let unchanged = previous .as_ref() .and_then(|p| p.cases.get(&case.id)) .filter(|old| old.frame == artifact.frame && old.equality == artifact.equality); + let mut kept = None; + if let Some(old) = unchanged { + match reopens( + &keyset, + &corpus, + case, + &plan, + old, + (&input, &expected_row), + &context, + ) + .await + { + Ok(()) => kept = Some(old), + Err(error) => eprintln!( + "conformance: {}: the frozen ciphertext no longer opens ({error}); writing a fresh one", + case.id + ), + } + } let reference = baseline .as_ref() .map(|a| &a.cases[&case.id]) @@ -378,13 +500,17 @@ async fn shared_record_scalar_profile() { "{}: wrong context: {result:?}", case.id ); - let written = if update { reference.clone() } else { artifact }; - output.cases.insert(case.id.clone(), written); + frozen.insert(case.id.clone(), reference.clone()); + output.cases.insert(case.id.clone(), artifact); } if update { + let expected = Artifacts { + cases: frozen, + ..output.clone() + }; std::fs::write( root().join("record-scalars-v1.expected.rust-native.json"), - serde_json::to_string_pretty(&output).unwrap() + "\n", + serde_json::to_string_pretty(&expected).unwrap() + "\n", ) .unwrap(); } diff --git a/scripts/__tests__/recipher-js-frame-parity.test.mjs b/scripts/__tests__/recipher-js-frame-parity.test.mjs index 6fdace3021..d1d2ad2fe8 100644 --- a/scripts/__tests__/recipher-js-frame-parity.test.mjs +++ b/scripts/__tests__/recipher-js-frame-parity.test.mjs @@ -42,6 +42,23 @@ function corpusFrames() { return frames } +/** + * Every accepted UUID case of the scalar profile, by `/`: + * its text and the other spellings the case lists. + */ +function corpusUuids() { + const uuids = {} + for (const c of read(`${CORPUS}/record-scalars-v1.cases.json`).cases) { + if (c.input.type === 'uuid' && !c.expected_error) { + uuids[`record-scalars-v1/${c.id}`] = { + text: c.input.text, + spellings: c.spellings ?? [], + } + } + } + return uuids +} + describe('the JavaScript bridge frame suite', () => { it('compares against a copy of the corpus that is the corpus', () => { const corpus = corpusFrames() @@ -64,6 +81,25 @@ describe('the JavaScript bridge frame suite', () => { expect([...named].sort()).toEqual(Object.keys(copy).sort()) }) + it('copies the text and spellings of every UUID case', () => { + const uuids = corpusUuids() + expect(Object.keys(uuids).length).toBeGreaterThan(0) + const copy = read(`${BRIDGE_TESTDATA}/corpus-frames.json`).uuids + expect(copy).toEqual(uuids) + }) + + it('pins the corpus frame for each spelling of each UUID case', () => { + const pinned = read(`${BRIDGE_TESTDATA}/js-frames.json`).frames + for (const [id, { text, spellings }] of Object.entries(corpusUuids())) { + for (const spelling of [text, ...spellings]) { + const entry = pinned[`VcUuid ${spelling}`] + expect(entry, `${id}: no input for ${spelling}`).toBeDefined() + expect(entry.corpus_case, spelling).toBe(id) + expect(entry.same_as_corpus, spelling).toBe(true) + } + } + }) + it("pins the same Date frames the engine's host cases read", () => { const bridge = read(`${BRIDGE_TESTDATA}/js-frames.json`).frames const host = read(VALUE_BYTES).host From 87b03c3e0db6fdcf166907bb4232f02654267e26 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sun, 29 Nov 2026 14:12:36 +1100 Subject: [PATCH 3/3] fix(conformance): check the UUID record path in every build These changes address the second review of the UUID cases. The Rust and Go runners, and the frame parity test, now refuse `spellings` on a refused case. No runner read them there. A Rust build without the uuid feature now runs the record path and the equality term of each UUID case. It skips only the owned scalar API and the spellings, and takes its fresh ciphertext from the record's leaf. The hex reader that can fail moves into the shared test helpers, and `unhex` calls it. The runner's UUID reader is renamed, so that it no longer shares a name with the strict corpus reader. One struct now holds what a ciphertext must open to. Two variables have clearer names. Refs #1821 --- conformance/stack-encrypt/README.md | 10 +- languages/golang/encrypt/conformance_test.go | 4 +- packages/stack-encrypt/tests/common/mod.rs | 14 +- packages/stack-encrypt/tests/conformance.rs | 212 +++++++++++------- .../recipher-js-frame-parity.test.mjs | 10 + 5 files changed, 155 insertions(+), 95 deletions(-) diff --git a/conformance/stack-encrypt/README.md b/conformance/stack-encrypt/README.md index 823995bcf2..ef8c5f9cd8 100644 --- a/conformance/stack-encrypt/README.md +++ b/conformance/stack-encrypt/README.md @@ -230,8 +230,11 @@ deliberately not used for values: future TypeScript runners must not pass 64-bit integers through Number. A UUID is written in lowercase hex, in groups of 8, 4, 4, 4, and 12 digits, -with `-` between them. A case with a UUID input can also have `spellings`: -the same UUID in other letter cases. A runner whose language makes a UUID +with `-` between them. + +An accepted case with a UUID input can also have +`spellings`: the same UUID in other letter cases. The Rust and Go runners +and the frame parity test refuse `spellings` on any other case. A runner whose language makes a UUID from text reads each spelling. Each spelling must give the same UUID and the same frozen frame. Go reads them with `vcvalue.ParseUUID`, Rust with the `uuid` crate, and the TypeScript value bridge with `VcUuid`. @@ -286,7 +289,8 @@ declarations, cancellation, and provider failures also need later cases. The full SQL behavior is not part of this initial profile. Native Rust and Go run every case. A Rust build without the `uuid` feature -has no typed UUID, so it skips the accepted UUID cases and runs the rest. +has no typed UUID. For a UUID case it checks the record path and the +equality term, and skips the owned scalar API and the spellings. The TypeScript runner is pending. The TypeScript value bridge checks only the frames. Its `tests/frames.cjs` reads the text and the spellings of each diff --git a/languages/golang/encrypt/conformance_test.go b/languages/golang/encrypt/conformance_test.go index 888bf88c52..02eef2aa8e 100644 --- a/languages/golang/encrypt/conformance_test.go +++ b/languages/golang/encrypt/conformance_test.go @@ -212,8 +212,8 @@ func TestStackConformance(t *testing.T) { t.Fatalf("empty or duplicate case ID %q", c.ID) } seen[c.ID] = true - if len(c.Spellings) > 0 && c.Input.Type != "uuid" { - t.Fatalf("%s: only a UUID input has other spellings", c.ID) + if len(c.Spellings) > 0 && (c.Input.Type != "uuid" || c.ExpectedError != nil) { + t.Fatalf("%s: only an accepted case with a UUID input has other spellings", c.ID) } for _, spelling := range c.Spellings { if spelling == c.Input.Text || !strings.EqualFold(spelling, c.Input.Text) { diff --git a/packages/stack-encrypt/tests/common/mod.rs b/packages/stack-encrypt/tests/common/mod.rs index da2fca6bd9..84b272beb1 100644 --- a/packages/stack-encrypt/tests/common/mod.rs +++ b/packages/stack-encrypt/tests/common/mod.rs @@ -376,13 +376,17 @@ pub fn hex(bytes: &[u8]) -> String { bytes.iter().map(|b| format!("{b:02x}")).collect() } pub fn unhex(text: &str) -> Vec { - assert!( - text.is_ascii() && text.len().is_multiple_of(2), - "invalid hex" - ); + try_unhex(text).expect("hex") +} + +/// The bytes of a hex text, or an error for text that is not hex. +pub fn try_unhex(text: &str) -> Result, String> { + if !text.is_ascii() || !text.len().is_multiple_of(2) { + return Err("invalid hex".into()); + } (0..text.len()) .step_by(2) - .map(|i| u8::from_str_radix(&text[i..i + 2], 16).expect("hex byte")) + .map(|i| u8::from_str_radix(&text[i..i + 2], 16).map_err(|e| e.to_string())) .collect() } #[cfg(feature = "dynamic")] diff --git a/packages/stack-encrypt/tests/conformance.rs b/packages/stack-encrypt/tests/conformance.rs index ca6e4a5241..a456c8168b 100644 --- a/packages/stack-encrypt/tests/conformance.rs +++ b/packages/stack-encrypt/tests/conformance.rs @@ -10,7 +10,7 @@ use std::sync::atomic::Ordering; use common::conformance::{refusal, stored_outputs, value, Input}; use common::frames::{frame, object}; -use common::{hex, unhex}; +use common::{hex, try_unhex, unhex}; use serde::{Deserialize, Serialize}; use serde_json::json; use stack_encrypt::dynamic::{self, frame::OwnedFrame, record, Fidelity, NoTargets, Op, Operand}; @@ -95,23 +95,34 @@ impl Update { } } -/// The bytes of a hex text, or an error for text that is not hex. -fn try_unhex(text: &str) -> Result, String> { - if !text.is_ascii() || !text.len().is_multiple_of(2) { - return Err("not hex".into()); - } - (0..text.len()) - .step_by(2) - .map(|i| u8::from_str_radix(&text[i..i + 2], 16).map_err(|e| e.to_string())) - .collect() +/// The UUID in a text the `uuid` crate reads, in any letter case: a case's +/// input text, which `value` has already held to the canonical spelling, or +/// one of its `spellings`, which differ from it only in letter case. +#[cfg(feature = "uuid")] +fn read_uuid_text(text: &str) -> uuid::Uuid { + uuid::Uuid::try_parse(text).expect("a UUID") } -/// The UUID a corpus text spells. `value` has already held an input's text -/// to the canonical lowercase spelling; a case's `spellings` are checked -/// against it before they reach here. -#[cfg(feature = "uuid")] -fn parse_uuid(text: &str) -> uuid::Uuid { - uuid::Uuid::try_parse(text).expect("a hyphenated UUID") +/// Whether this build has the typed Rust value of a case's input. A UUID +/// needs the `uuid` feature; the record path takes one without it. +fn typed(input: &Input) -> bool { + cfg!(feature = "uuid") || input.kind != "uuid" +} + +/// The bytes of the ciphertext leaf `c` of a sealed one-field record. +fn record_leaf(tree: &StackCipherText, field: &str) -> Vec { + let CipherText::Map(fields) = tree else { + panic!("expected record") + }; + let (_, CipherText::Map(outputs)) = fields.iter().find(|(name, _)| name == field).unwrap() + else { + panic!("expected outputs") + }; + let (_, CipherText::Single(leaf)) = outputs.iter().find(|(name, _)| name == "c").unwrap() + else { + panic!("expected ciphertext") + }; + leaf.to_bytes().to_vec() } fn root() -> PathBuf { @@ -132,11 +143,11 @@ fn plan(corpus: &Corpus, case: &Case) -> record::Plan { .unwrap() } -fn try_stored(corpus: &Corpus, artifact: &Artifact) -> Result { +fn try_stored(field: &str, artifact: &Artifact) -> Result { let leaf = SealedValue::from_bytes(&try_unhex(&artifact.ciphertext)?).map_err(|e| format!("{e:?}"))?; Ok(CipherText::Map(vec![( - corpus.field.clone(), + field.into(), CipherText::Map(vec![ ("c".into(), CipherText::Single(leaf)), ( @@ -147,8 +158,8 @@ fn try_stored(corpus: &Corpus, artifact: &Artifact) -> Result StackCipherText { - try_stored(corpus, artifact).unwrap() +fn stored(field: &str, artifact: &Artifact) -> StackCipherText { + try_stored(field, artifact).unwrap() } // Exercise the owned scalar API independently of dynamic record lowering. @@ -172,7 +183,7 @@ async fn scalar( "bool" => seal!(input.text.parse::().unwrap()), "string" => seal!(input.text.clone()), #[cfg(feature = "uuid")] - "uuid" => seal!(Uuid::new(parse_uuid(&input.text))), + "uuid" => seal!(Uuid::new(read_uuid_text(&input.text))), other => panic!("unsupported scalar {other}"), } } @@ -217,31 +228,43 @@ async fn open_scalar( .unwrap_or_else(|e| panic!("the scalar opens: {e}")) } -/// Whether `candidate`'s ciphertext opens to `input`, through the owned -/// scalar API and through the record path. An update asks this of a frozen -/// ciphertext before keeping it. -async fn reopens( - keyset: &KeysetCipher<'_, common::DeterministicSource>, - corpus: &Corpus, - case: &Case, - plan: &record::Plan, - candidate: &Artifact, - (input, row): (&OwnedFrame, &OwnedFrame), - context: &Label, -) -> Result<(), String> { - let bytes = try_unhex(&candidate.ciphertext)?; - let opened = try_open_scalar(keyset, &bytes, &case.kind, context).await?; - if opened.frame().as_bytes() != input.frame().as_bytes() { - return Err("the scalar opens to another value".into()); - } - let opened = record::decrypt(keyset.clone(), try_stored(corpus, candidate)?, plan, None) - .map_err(|e| format!("{e:?}"))? - .await - .map_err(|e| format!("{e:?}"))?; - if opened.frame().as_bytes() != row.frame().as_bytes() { - return Err("the record opens to another value".into()); +/// What one accepted case's ciphertext must open to, and where. +struct Opening<'a> { + keyset: &'a KeysetCipher<'a, common::DeterministicSource>, + plan: &'a record::Plan, + context: &'a Label, + field: &'a str, + kind: &'a str, + /// Whether to open through the owned scalar API too (see [`typed`]). + typed: bool, + /// The input's frame, which the scalar opens to. + input: &'a OwnedFrame, + /// The one-field record of the input, which the record opens to. + row: &'a OwnedFrame, +} + +impl Opening<'_> { + /// Whether `candidate`'s ciphertext opens to the input, through the + /// owned scalar API and through the record path. An update asks this of + /// a frozen ciphertext before keeping it. + async fn check(&self, candidate: &Artifact) -> Result<(), String> { + if self.typed { + let bytes = try_unhex(&candidate.ciphertext)?; + let opened = try_open_scalar(self.keyset, &bytes, self.kind, self.context).await?; + if opened.frame().as_bytes() != self.input.frame().as_bytes() { + return Err("the scalar opens to another value".into()); + } + } + let stored = try_stored(self.field, candidate)?; + let opened = record::decrypt(self.keyset.clone(), stored, self.plan, None) + .map_err(|e| format!("{e:?}"))? + .await + .map_err(|e| format!("{e:?}"))?; + if opened.frame().as_bytes() != self.row.frame().as_bytes() { + return Err("the record opens to another value".into()); + } + Ok(()) } - Ok(()) } #[tokio::test] @@ -270,8 +293,9 @@ async fn shared_record_scalar_profile() { for case in &corpus.cases { assert!( - case.spellings.is_empty() || case.input.kind == "uuid", - "{}: only a UUID input has other spellings", + case.spellings.is_empty() + || (case.input.kind == "uuid" && case.expected_error.is_none()), + "{}: only an accepted case with a UUID input has other spellings", case.id ); for spelling in &case.spellings { @@ -290,8 +314,9 @@ async fn shared_record_scalar_profile() { !(update && imported.is_some()), "cannot update from external artifacts" ); - // Without the `uuid` feature there is no typed UUID, so the positive - // UUID cases are skipped, and an update would drop their artifacts. + // Without the `uuid` feature there is no typed UUID. A UUID case's fresh + // ciphertext then comes from the record path, not from the owned scalar + // API that made the expected file's ciphertexts. assert!( !update || cfg!(feature = "uuid"), "an update needs the uuid feature" @@ -337,7 +362,7 @@ async fn shared_record_scalar_profile() { let context = Label::new(corpus.context.iter().chain(std::iter::once(&corpus.field))).unwrap(); let (counting, generates, retrieves) = common::counting_cipher().await; // `output` holds the artifacts this run made, for - // `STACK_CONFORMANCE_OUTPUT`; `frozen` holds what an update writes to + // `STACK_CONFORMANCE_OUTPUT`; `written` holds what an update writes to // the expected file, kept ciphertexts included. let mut output = Artifacts { version: 1, @@ -345,7 +370,7 @@ async fn shared_record_scalar_profile() { producer: format!("rust-native/stack-encrypt-{}", env!("CARGO_PKG_VERSION")), cases: BTreeMap::new(), }; - let mut frozen = BTreeMap::new(); + let mut written = BTreeMap::new(); for case in &corpus.cases { eprintln!("conformance: {}", case.id); @@ -369,10 +394,7 @@ async fn shared_record_scalar_profile() { continue; } assert_eq!(case.kind, case.input.kind); - if cfg!(not(feature = "uuid")) && case.input.kind == "uuid" { - eprintln!("conformance: {}: skipped, needs the uuid feature", case.id); - continue; - } + let typed = typed(&case.input); let input = value(&case.input); let expected_row = object(vec![(corpus.field.clone(), value(&case.input))]); let fresh = record::encrypt(&keyset, &expected_row, &plan) @@ -380,6 +402,7 @@ async fn shared_record_scalar_profile() { .await .unwrap(); let stored_term = stored_outputs(&fresh, &corpus.field).unwrap().0; + let record_ciphertext = record_leaf(&fresh, &corpus.field); let opened = record::decrypt(keyset.clone(), fresh, &plan, None) .unwrap() .await @@ -411,15 +434,25 @@ async fn shared_record_scalar_profile() { panic!("expected one equality term") }; assert_eq!(&stored_term, term, "{}: stored equality", case.id); - let ct = scalar(&keyset, &case.input, &context).await; + // A build without the typed value checks the record path only, and + // its fresh ciphertext is the record's own leaf. + let ciphertext = if typed { + scalar(&keyset, &case.input, &context).await.to_bytes() + } else { + eprintln!( + "conformance: {}: no owned scalar API without the uuid feature; checking the record path", + case.id + ); + record_ciphertext + }; let artifact = Artifact { frame: hex(input.frame().as_bytes()), - ciphertext: hex(&ct.to_bytes()), + ciphertext: hex(&ciphertext), equality: hex(term), }; #[cfg(feature = "uuid")] for spelling in &case.spellings { - let spelt = frame(Uuid::new(parse_uuid(spelling))); + let spelt = frame(Uuid::new(read_uuid_text(spelling))); assert_eq!( hex(spelt.frame().as_bytes()), artifact.frame, @@ -427,23 +460,25 @@ async fn shared_record_scalar_profile() { case.id ); } - let unchanged = previous + let opening = Opening { + keyset: &keyset, + plan: &plan, + context: &context, + field: &corpus.field, + kind: &case.kind, + typed, + input: &input, + row: &expected_row, + }; + // The previous artifact of this case, if its frame and equality term + // are the ones this run derived. + let previous_match = previous .as_ref() .and_then(|p| p.cases.get(&case.id)) .filter(|old| old.frame == artifact.frame && old.equality == artifact.equality); let mut kept = None; - if let Some(old) = unchanged { - match reopens( - &keyset, - &corpus, - case, - &plan, - old, - (&input, &expected_row), - &context, - ) - .await - { + if let Some(old) = previous_match { + match opening.check(old).await { Ok(()) => kept = Some(old), Err(error) => eprintln!( "conformance: {}: the frozen ciphertext no longer opens ({error}); writing a fresh one", @@ -463,18 +498,25 @@ async fn shared_record_scalar_profile() { case.id ); for (origin, candidate) in [("fresh", &artifact), ("reference", reference)] { - let opened = - open_scalar(&keyset, &unhex(&candidate.ciphertext), &case.kind, &context).await; - assert_eq!( - opened.frame().as_bytes(), - input.frame().as_bytes(), - "{}: {origin} scalar cross-open", - case.id - ); - let opened = record::decrypt(keyset.clone(), stored(&corpus, candidate), &plan, None) - .unwrap() - .await - .unwrap(); + if typed { + let opened = + open_scalar(&keyset, &unhex(&candidate.ciphertext), &case.kind, &context).await; + assert_eq!( + opened.frame().as_bytes(), + input.frame().as_bytes(), + "{}: {origin} scalar cross-open", + case.id + ); + } + let opened = record::decrypt( + keyset.clone(), + stored(&corpus.field, candidate), + &plan, + None, + ) + .unwrap() + .await + .unwrap(); assert_eq!( opened.frame().as_bytes(), expected_row.frame().as_bytes(), @@ -500,12 +542,12 @@ async fn shared_record_scalar_profile() { "{}: wrong context: {result:?}", case.id ); - frozen.insert(case.id.clone(), reference.clone()); + written.insert(case.id.clone(), reference.clone()); output.cases.insert(case.id.clone(), artifact); } if update { let expected = Artifacts { - cases: frozen, + cases: written, ..output.clone() }; std::fs::write( diff --git a/scripts/__tests__/recipher-js-frame-parity.test.mjs b/scripts/__tests__/recipher-js-frame-parity.test.mjs index d1d2ad2fe8..3bb5f11849 100644 --- a/scripts/__tests__/recipher-js-frame-parity.test.mjs +++ b/scripts/__tests__/recipher-js-frame-parity.test.mjs @@ -88,6 +88,16 @@ describe('the JavaScript bridge frame suite', () => { expect(copy).toEqual(uuids) }) + it('finds spellings only on accepted UUID cases', () => { + for (const c of read(`${CORPUS}/record-scalars-v1.cases.json`).cases) { + if (c.spellings === undefined) continue + expect(c.input.type, `${c.id}: spellings of a UUID`).toBe('uuid') + expect(c.expected_error, `${c.id}: spellings of an accepted case`).toBe( + undefined, + ) + } + }) + it('pins the corpus frame for each spelling of each UUID case', () => { const pinned = read(`${BRIDGE_TESTDATA}/js-frames.json`).frames for (const [id, { text, spellings }] of Object.entries(corpusUuids())) {