diff --git a/conformance/stack-encrypt/README.md b/conformance/stack-encrypt/README.md index 300bb29a6..0f0ed5ae2 100644 --- a/conformance/stack-encrypt/README.md +++ b/conformance/stack-encrypt/README.md @@ -61,7 +61,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. 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 @@ -253,13 +253,33 @@ 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. + +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 `RcUuid.from`. + +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. @@ -279,13 +299,38 @@ 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. - -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. +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. 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. A Rust build without the `uuid` feature +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 +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 +ciphertexts. Pull request #1996 lets the addon store a UUID, and the +TypeScript runner of the whole profile waits on it. ## Artifacts and evolution @@ -309,6 +354,19 @@ STACK_CONFORMANCE_UPDATE=1 mise x --env test -- cargo nextest run --locked \ mise run test:conformance ``` +`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/conformance/stack-encrypt/coverage.md b/conformance/stack-encrypt/coverage.md index 90b570655..c91bceee6 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). One value of a kind known only at run time, as one ciphertext: the [single-value profile](single-value-contract.md), run by native Rust (`v1/single-value-v1.cases.json`: every scalar kind, exact conversions, JSON documents, batches, and the refusals, with the plaintext of each leaf and a frozen ciphertext). `packages/stack-encrypt/tests/single_value.rs` compares the run-time interface with the typed interface. 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; the Go runner of the single-value profile (issue #2010), and Python and TypeScript runners | | 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 ecb01f633..4ac8c31a3 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 a3d3ebdf6..6170c19f1 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 ebccf34ab..02eef2aa8 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" || 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) { + 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 d83a90415..ebf676a30 100644 --- a/languages/typescript/packages/recipher-js/value-napi/tests/frames.cjs +++ b/languages/typescript/packages/recipher-js/value-napi/tests/frames.cjs @@ -33,14 +33,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')), @@ -56,9 +57,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 @@ -215,10 +231,6 @@ const inputs = [ 'record-values-v1/decimal-max-mantissa', ], ['RcDecimal -0.00', () => addon.makeWrapper('RcDecimal', '-0.00')], - [ - 'RcUuid', - () => addon.makeWrapper('RcUuid', '123e4567-e89b-12d3-a456-426614174000'), - ], ['array empty', () => []], ['array of bigint and string', () => [1n, 'x']], ['array of null', () => [null]], @@ -227,6 +239,18 @@ 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, +// made with `RcUuid.from` as an application makes one. The test addon's +// `from` returns `{ value }`, or `{ code, message }` when it refuses the +// text, and a refusal fails the check. +function uuidFrom(spelling) { + const made = addon.RcUuid.from(spelling) + assert.ok('value' in made, `RcUuid.from(${spelling}) refused: ${made.code}`) + return made.value +} +for (const [id, { text, spellings }] of Object.entries(uuids)) + for (const spelling of [text, ...spellings]) + inputs.push([`RcUuid ${spelling}`, () => uuidFrom(spelling), id]) const actual = {} for (const [name, make, corpusCase] of inputs) { @@ -257,8 +281,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 071060191..0ad8308da 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", @@ -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", @@ -52,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 ae7997876..0baad3e41 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,9 +320,6 @@ "RcDecimal -0.00": { "frame": "1400000200000000000000000000000000" }, - "RcUuid": { - "frame": "f305000b10000000123e4567e89b12d3a456426614174000" - }, "array empty": { "frame": "f000000000" }, @@ -343,6 +340,36 @@ }, "object nested": { "frame": "f103000000040000006c697374f0010000000c01030000006d6170f100000000020000006174f30301050000000000000000" + }, + "RcUuid 123e4567-e89b-12d3-a456-426614174000": { + "frame": "f305000b10000000123e4567e89b12d3a456426614174000", + "corpus_case": "record-scalars-v1/uuid", + "same_as_corpus": true + }, + "RcUuid 123E4567-E89B-12D3-A456-426614174000": { + "frame": "f305000b10000000123e4567e89b12d3a456426614174000", + "corpus_case": "record-scalars-v1/uuid", + "same_as_corpus": true + }, + "RcUuid 123e4567-E89B-12d3-A456-426614174000": { + "frame": "f305000b10000000123e4567e89b12d3a456426614174000", + "corpus_case": "record-scalars-v1/uuid", + "same_as_corpus": true + }, + "RcUuid 00000000-0000-0000-0000-000000000000": { + "frame": "f305000b1000000000000000000000000000000000000000", + "corpus_case": "record-scalars-v1/uuid-nil", + "same_as_corpus": true + }, + "RcUuid ffffffff-ffff-ffff-ffff-ffffffffffff": { + "frame": "f305000b10000000ffffffffffffffffffffffffffffffff", + "corpus_case": "record-scalars-v1/uuid-max", + "same_as_corpus": true + }, + "RcUuid FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF": { + "frame": "f305000b10000000ffffffffffffffffffffffffffffffff", + "corpus_case": "record-scalars-v1/uuid-max", + "same_as_corpus": true } } } diff --git a/packages/stack-encrypt/tests/common/mod.rs b/packages/stack-encrypt/tests/common/mod.rs index 27d931c49..72c46ee51 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 6d4b9621b..a456c8168 100644 --- a/packages/stack-encrypt/tests/conformance.rs +++ b/packages/stack-encrypt/tests/conformance.rs @@ -10,11 +10,13 @@ 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}; use stack_encrypt::target::IndexSpec; +#[cfg(feature = "uuid")] +use stack_encrypt::value::Uuid; use stack_encrypt::{ CipherText, Ciphertext, Error, KeysetCipher, Label, SealedValue, StackCipherText, }; @@ -39,6 +41,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, } @@ -49,7 +55,7 @@ struct ExpectedError { reason: String, } -#[derive(Deserialize, Serialize)] +#[derive(Deserialize, Serialize, Clone)] #[serde(deny_unknown_fields)] struct Artifacts { version: u32, @@ -58,7 +64,7 @@ struct Artifacts { cases: BTreeMap, } -#[derive(Deserialize, Serialize)] +#[derive(Deserialize, Serialize, Clone)] #[serde(deny_unknown_fields)] struct Artifact { frame: String, @@ -66,6 +72,59 @@ 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 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") +} + +/// 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 { PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../conformance/stack-encrypt/v1") } @@ -84,20 +143,23 @@ fn plan(corpus: &Corpus, case: &Case) -> record::Plan { .unwrap() } -fn stored(corpus: &Corpus, artifact: &Artifact) -> StackCipherText { - CipherText::Map(vec![( - corpus.field.clone(), +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![( + field.into(), 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(field: &str, artifact: &Artifact) -> StackCipherText { + try_stored(field, artifact).unwrap() } // Exercise the owned scalar API independently of dynamic record lowering. @@ -120,34 +182,88 @@ 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(read_uuid_text(&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}")) +} + +/// 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(()) } } @@ -175,12 +291,36 @@ async fn shared_record_scalar_profile() { .collect(); assert!(!positive_ids.is_empty()); - let update = std::env::var("STACK_CONFORMANCE_UPDATE").as_deref() == Ok("1"); + for case in &corpus.cases { + assert!( + 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 { + 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 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. 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" + ); let baseline: Option = if update { None } else { @@ -201,18 +341,36 @@ async fn shared_record_scalar_profile() { ); Some(artifacts) }; + // `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() + .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`; `written` 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 written = BTreeMap::new(); for case in &corpus.cases { eprintln!("conformance: {}", case.id); @@ -236,6 +394,7 @@ async fn shared_record_scalar_profile() { continue; } assert_eq!(case.kind, case.input.kind); + 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) @@ -243,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 @@ -274,13 +434,63 @@ 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), }; - let reference = baseline.as_ref().map_or(&artifact, |a| &a.cases[&case.id]); + #[cfg(feature = "uuid")] + for spelling in &case.spellings { + let spelt = frame(Uuid::new(read_uuid_text(spelling))); + assert_eq!( + hex(spelt.frame().as_bytes()), + artifact.frame, + "{}: the spelling {spelling}", + case.id + ); + } + 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) = 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", + case.id + ), + } + } + 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, @@ -288,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(), @@ -325,12 +542,17 @@ async fn shared_record_scalar_profile() { "{}: wrong context: {result:?}", case.id ); + written.insert(case.id.clone(), reference.clone()); output.cases.insert(case.id.clone(), artifact); } if update { + let expected = Artifacts { + cases: written, + ..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 6fdace302..447a585e0 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,35 @@ 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('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())) { + for (const spelling of [text, ...spellings]) { + const entry = pinned[`RcUuid ${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