diff --git a/conformance/stack-encrypt/README.md b/conformance/stack-encrypt/README.md index d3e5093d7..300bb29a6 100644 --- a/conformance/stack-encrypt/README.md +++ b/conformance/stack-encrypt/README.md @@ -44,6 +44,8 @@ these rules. | `record-values-v1.cases.json` | cases | `tests/value_conformance.rs` | `value_conformance_test.go` | | `record-query-refusals-v1.cases.json` | cases | `tests/query_refusal_conformance.rs` | `query_refusal_conformance_test.go` | | `record-raw-frames-v1.cases.json` | cases | `tests/raw_frame_conformance.rs` | `raw_frame_conformance_test.go` | +| `single-value-v1.cases.json` | cases | `tests/single_value_conformance.rs` | — (pending, issue #2010) | +| `single-value-v1.expected.rust-native.json` | expected | `tests/single_value_conformance.rs` (writes it) | — (pending, issue #2010) | | `artifact-exchange-v1.cases.json` | cases | `tests/exchange_conformance.rs`, run by `scripts/stack-exchange-conformance.mjs` | `exchange_conformance_test.go`, run by `scripts/stack-exchange-conformance.mjs` | | `eql-json-v1.cases.json` | cases | `tests/json_operators.rs`; EQL's `tests/encryption/tests/json_tree_data_plan.rs` | `json_conformance_test.go` | | `eql-json-v1.enrollment.json` | enrollment | `scripts/stack-eql-conformance.mjs` runs the tests it names | `scripts/stack-eql-conformance.mjs` runs the tests it names | @@ -90,6 +92,9 @@ fixtures described below. It ends with the fresh artifact exchange in both directions (`test:conformance:exchange`, which also needs the deterministic EQL guest). Set no fixture-update variables when checking conformance. +The task runs the single-value cases in native Rust only, because the Go +runner of that profile is pending. + The Rust runner is `packages/stack-encrypt/tests/conformance.rs`; the Go runner is `languages/golang/encrypt/conformance_test.go`. Go calls the record interface used by generated code. Testing public SDK declarations is a separate layer. @@ -177,6 +182,31 @@ in the Rust crate and `TestValueConformance`, `TestQueryRefusalConformance` and `TestRawFrameConformance` in the Go module; `test:conformance` runs all six. +## Single values + +The [single-value contract](single-value-contract.md) defines +`single-value-v1` in `v1/single-value-v1.cases.json`, and the terms used here. +The profile encrypts one value as one ciphertext through the run-time +interface of the engine, and decrypts it again. Each case gives a value, the +kind declared for it, and a context. The cases cover: + +- every scalar kind +- the exact conversions that a declared kind makes +- JSON documents +- the one stored form of a string and a document +- batches of single-value calls merged into one key request +- the refusals of an array, an object, a passthrough, a null, `undefined`, + and a value of another kind + +`v1/single-value-v1.expected.rust-native.json` freezes three things for each +case: the frame of the input, the plaintext that the leaf is sealed with, and +a ciphertext that every runner must open. + +The native runner is `single_value_conformance` in the Rust crate. +`test:conformance` runs it. The runner also compares the run-time interface +with the typed interface. The Go runner is pending. The Go runner will be +written with the single-value calls of the Go SDK (issue #2010). + ## `record-reads-v1` contract The [read contract](read-contract.md) defines cases in `v1/record-reads-v1.cases.json` for diff --git a/conformance/stack-encrypt/coverage.md b/conformance/stack-encrypt/coverage.md index 815fab2c5..90b570655 100644 --- a/conformance/stack-encrypt/coverage.md +++ b/conformance/stack-encrypt/coverage.md @@ -7,7 +7,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 | -| 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 | +| 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 | | Query terms and diagnostics | [Query-operator requirements](fixture-contract.md#query-operator-requirements), existing Rust/Go runners, initial equality/query-error cases and the [query-refusal profile](query-refusals-contract.md) (`v1/record-query-refusals-v1.cases.json`: every scalar operator against every field capability that does not answer it, the listed range shapes, other-kind values and nulls, by class, with the typed query's refusal stage) | JSON operator and EQL target refusals | diff --git a/conformance/stack-encrypt/single-value-contract.md b/conformance/stack-encrypt/single-value-contract.md new file mode 100644 index 000000000..0ebb0a0d0 --- /dev/null +++ b/conformance/stack-encrypt/single-value-contract.md @@ -0,0 +1,241 @@ +# Single-value profile + +`single-value-v1` is the conformance profile for one value encrypted as one +ciphertext. The profile describes the cases in +`v1/single-value-v1.cases.json`. The cases run through the run-time interface +of the engine, `stack_encrypt::dynamic::value`. The profile is an experimental +test contract. + +The run-time interface takes a value as a frame, with a declared kind. The +typed Rust interface must decrypt the result. The run-time interface must +decrypt a ciphertext that the typed Rust interface made. So every language +can decrypt a value that one language encrypted. + +## Terms + +- A frame is one value written as bytes, in the format that the engine reads. +- A kind is the name of what a value is, such as `string` or `uint64`. The + declared kind is the kind that the caller says the value has. +- A leaf is the encrypted form of one scalar. A ciphertext of one value + contains one leaf. +- To seal a value is to encrypt and authenticate it. To open a ciphertext is + to decrypt it and check it. +- A passthrough is a value that a record stores without encrypting it. +- A refusal is an error that the engine returns for a value it does not + accept. +- The typed interface is the Rust API for a value of a Rust type: + `keyset.encrypt` and `keyset.decrypt`. + +## Runners + +The Rust runner is `packages/stack-encrypt/tests/single_value_conformance.rs`. +The Go runner is pending. The Go runner will be written with the single-value +calls of the Go SDK (issue #2010). The Python and TypeScript runners are +pending too. A missing runner is not a passing result. + +## Cases + +The file has three parts: a public `seed` for the deterministic key provider, +a list of `cases`, and a list of `batches`. Each case has these keys: + +| Key | Meaning | +|---|---| +| `id` | The name of the case | +| `kind` | The name of the declared kind, or empty for no declared kind | +| `context` | The parts of the context, or an empty list for the empty context | +| `input` | The value, in the `{type, text}` form that the [value profile](values-contract.md#cases) defines | +| `stored` | The value in the ciphertext, where it differs from the input | +| `opens_as` | Kinds that the ciphertext must open as, other than the declared kind. Each entry has the `value` that the ciphertext opens to. | +| `refused_as` | Kinds that the ciphertext must not open as | +| `expected_error` | For a refused case, the `code`, the `reason`, and the `found` kind of the refusal | + +A context of two parts is a pair. For example, `["conformance", "value"]` is +the Rust context `("conformance", "value")`. For an empty list, a runner calls +the form with no context. For any other list, a runner calls the form with a +context. + +This profile adds two input types to those of the value profile: + +| `type` | `text` | +|---|---| +| `uuid` | The UUID in lowercase hex, in groups of 8, 4, 4, 4, and 12 digits | +| `shape` | The name of a value that `{type, text}` cannot spell. The next table lists the names. | + +| Shape | The value | +|---|---| +| `array` | The array of the two strings `a` and `b` | +| `empty_array` | The array with no elements | +| `object` | The object with one member, `a`, the `uint32` 1 | +| `passthrough` | A passthrough of the string `clear` | +| `typed_null` | A typed null of `int64` | + +Some host languages cannot build every shape. A runner in such a language +sends the frame that the artifact file records for the case. + +## Artifacts + +The Rust runner writes `v1/single-value-v1.expected.rust-native.json`. The +file has one entry for each case: + +- `frame`: the frame of the input, in hex. Every case has one. +- `leaf`: the plaintext that the leaf of the ciphertext is sealed with, in + hex. That plaintext is the type tag of the leaf and its payload. Only an + accepted case has one. +- `ciphertext`: a ciphertext of the value, in hex. Only an accepted case has + one. + +The typed Rust interface made each `ciphertext` where a Rust type spells the +stored value. No Rust type spells a lone `uint8`, so the run-time interface +made the ciphertext of that case. + +A runner never compares whole ciphertexts. Each sealed leaf has a random +AES-GCM nonce, so two ciphertexts of one value differ. A runner compares the +parts of a ciphertext that the nonce does not change: + +- the keyset +- the IV and tag of the data key +- the length of the ciphertext +- the plaintext of the leaf + +The deterministic provider derives a data key from the seed, the context, and +a counter. So a runner makes a new provider for each ciphertext it compares. + +Regenerate the artifacts deliberately, with `STACK_ENCRYPT_UPDATE_FIXTURES=1` +and the native runner. Review the diff of the cases and the diff of the +artifacts together. + +An update keeps the frozen ciphertext of a case whose frame and leaf have not +changed. The update checks that ciphertext as any run does. So a ciphertext +stays frozen from one update to the next, and the diff shows only the cases +that changed. + +## Required behavior + +### An accepted case + +A case with no `expected_error` is an accepted case. For each one: + +1. The frame of the input equals the frozen `frame`. +2. The run-time encrypt accepts the value with the declared kind and the + context. The plaintext of the leaf that it seals equals the frozen `leaf`. +3. The new ciphertext and the frozen `ciphertext` agree in every part that + the nonce does not change. +4. Each of the two ciphertexts opens under the same context, with no declared + kind. The result is `stored`, or the input where the case has no `stored`. +5. Each of the two ciphertexts opens under the same context, with the + declared kind, to the same value. With the kind `json`, the result is the + stored JSON text as a bytes value. +6. Each ciphertext opens as each kind in `opens_as`, to the `value` of that + entry. +7. Each ciphertext is refused when it is opened as a kind in `refused_as`. + The code of the refusal is `stack_encrypt::opened_type`. The `expected` + field of the refusal is the name of the kind. The refusal never says what + the value opened as. +8. Each ciphertext is refused under the context `["conformance", "wrong"]`. + The deterministic provider refuses the key request as forbidden, as + ZeroKMS does. Other providers can report a wrong context differently. + +Native Rust also checks two things. The typed interface seals the same parts +for the stored value. The typed decrypt opens both ciphertexts. + +### Conversions + +A case with `stored` is a conversion. The engine seals a number of another +width or kind as the value of the declared kind, when the conversion is exact. +The conversion rules are the ones that a typed field of a record uses. The +engine seals a document with the kind `json` as its compact JSON text. + +### Strings and JSON documents + +`json` is a declared kind and not a stored kind. A `string` and a document +have one stored form: text. So a check of the stored kind cannot distinguish +them. Three groups of cases pin the consequences: + +- `json-given-string`: a sealed document opens as `string`, to the JSON text + that was sealed. +- `string-json-number-text` and `string-json-spaced-text`: a sealed string + whose text is a JSON document opens as `json`. Decrypt as `json` checks that + the text parses. Decrypt then returns the document as the engine writes it, + as a bytes value. So `{ "b" : [ 1 , null ], "a" : true }` comes back as + `{"a":true,"b":[1,null]}`. +- `string-not-json-text`: a sealed string whose text is not a JSON document is + refused as `json`. + +### A refused case + +A case with `expected_error` is a refused case. The run-time encrypt refuses +the value before any key request, with the diagnostic `code`, `reason`, and +`found` of the case. The code of every such refusal is +`stack_encrypt::dynamic_value`. A single value has its own refusal, with no +record, plan, or field in it. + +`found` is the kind of the value to encrypt, as the payload field `found` +names it. Every refusal of a single value names that kind. The name is a +kind name such as `array`, `string`, or `int64`, or one of `null`, +`undefined`, `passthrough`, and `unknown`. The kind is the kind of the +input. A refusal never names the kind of a decrypted value. + +The cases cover these values: + +- An array, an object, a passthrough, a plain null, and a typed null. Each is + tested with no declared kind and with one. The reason is `not_a_scalar`. + `found` is `array`, `object`, `passthrough`, or `null`. A typed null is a + `null`. +- JavaScript's `undefined`, with a declared kind and with none. The reason is + `not_a_scalar`. `found` is `undefined`. +- A value of another kind that does not convert exactly. The reason is + `field_type`. `found` is the kind of the input. +- Text that is not a JSON document, with the kind `json`. The reason is + `json_syntax`, `json_duplicate_key`, or `json_integer_range`. `found` is + `string` or `bytes`. + +A runner checks all three of `code`, `reason`, and `found`. `reason` says +which rule the value breaks, and `found` says what the value is. + +The engine refuses `undefined` with any declared kind. An `undefined` value is +most often a misspelt property name. No typed call could read it back. + +A host language with no `undefined` has two options for those cases. The +runner can send the frame that the artifact file records. Or the runner can +check that the cases are well formed, and skip them. + +## Batches + +The run-time interface has no batch call. To encrypt many values, a binding +makes one single-value call for each value. The binding then merges the +pending calls into one key request. In Rust, `Pending::all` merges the calls. +A binding decrypts many ciphertexts the same way. + +Each call has its own declared kind, so one batch can contain values of +different kinds. Each entry of `batches` has three keys: + +- `inputs`: a list of values +- `kinds`: the declared kind for each input, or empty for none +- `context`: one context for all the inputs + +A runner seals and opens each entry as a binding does: + +- An accepted batch seals in one key request and opens in one key request. + The values come back in the order of the inputs. The expected values are + `stored` where the batch has one, and the inputs otherwise. +- An empty batch makes no key request. +- In a batch with `expected_error`, the single-value call refuses one of the + values with that `code`, `reason`, and `found`. The batch then makes no + key request. + +The counts of key requests are native observations: the Rust runner counts +them on its key source. + +## Scope and remaining work + +The profile covers every scalar kind, the exact conversions, JSON documents, +and the refusals of the run-time encrypt. The profile does not cover these: + +- A ciphertext of a null. Only the tree interface seals one. +- A scalar of a logical type that the engine does not define. The + `{type, text}` form cannot spell one. With no declared kind, the engine + seals such a scalar as it arrived. + `packages/stack-encrypt/tests/single_value.rs` tests that natively. +- Decrypt limited to one keyset. + `packages/stack-encrypt/tests/single_value.rs` tests that natively. +- New ciphertexts exchanged between languages. That needs a second runner. diff --git a/conformance/stack-encrypt/v1/single-value-v1.cases.json b/conformance/stack-encrypt/v1/single-value-v1.cases.json new file mode 100644 index 000000000..26e3372d3 --- /dev/null +++ b/conformance/stack-encrypt/v1/single-value-v1.cases.json @@ -0,0 +1,1040 @@ +{ + "version": 1, + "profile": "single-value-v1", + "seed": "0000000000000000000000000000000000000000000000000000000000000000", + "required_capabilities": [ + "single-value", + "value-kinds", + "context-binding", + "refusals" + ], + "cases": [ + { + "id": "as-is-string", + "kind": "", + "context": [], + "input": { + "type": "string", + "text": "ada@example.com" + }, + "refused_as": ["int64", "bytes"] + }, + { + "id": "as-is-empty-string", + "kind": "", + "context": [], + "input": { + "type": "string", + "text": "" + } + }, + { + "id": "as-is-int64-above-js-safe", + "kind": "", + "context": [], + "input": { + "type": "int64", + "text": "9007199254740993" + }, + "refused_as": ["int32", "uint64", "float64", "string"] + }, + { + "id": "as-is-bool", + "kind": "", + "context": [], + "input": { + "type": "bool", + "text": "true" + } + }, + { + "id": "as-is-bytes", + "kind": "", + "context": [], + "input": { + "type": "bytes", + "text": "00ff10" + }, + "refused_as": ["string", "uuid"] + }, + { + "id": "as-is-float64-negative-zero", + "kind": "", + "context": [], + "input": { + "type": "float64", + "text": "-0" + } + }, + { + "id": "as-is-uint8", + "kind": "", + "context": [], + "input": { + "type": "uint8", + "text": "200" + } + }, + { + "id": "as-is-uuid", + "kind": "", + "context": [], + "input": { + "type": "uuid", + "text": "123e4567-e89b-12d3-a456-426614174000" + }, + "refused_as": ["bytes"] + }, + { + "id": "as-is-string-with-context", + "kind": "", + "context": ["conformance", "value"], + "input": { + "type": "string", + "text": "ada@example.com" + } + }, + { + "id": "string-json-number-text", + "kind": "", + "context": [], + "input": { + "type": "string", + "text": "42" + }, + "opens_as": [ + { + "kind": "json", + "value": { + "type": "bytes", + "text": "3432" + } + }, + { + "kind": "string", + "value": { + "type": "string", + "text": "42" + } + } + ] + }, + { + "id": "string-json-spaced-text", + "kind": "string", + "context": ["conformance", "value"], + "input": { + "type": "string", + "text": "{ \"b\" : [ 1 , null ], \"a\" : true }" + }, + "opens_as": [ + { + "kind": "json", + "value": { + "type": "bytes", + "text": "7b2261223a747275652c2262223a5b312c6e756c6c5d7d" + } + } + ] + }, + { + "id": "string-not-json-text", + "kind": "", + "context": [], + "input": { + "type": "string", + "text": "ada@example.com" + }, + "refused_as": ["json"] + }, + { + "id": "bool-false", + "kind": "bool", + "context": ["conformance", "value"], + "input": { + "type": "bool", + "text": "false" + } + }, + { + "id": "int8-min", + "kind": "int8", + "context": ["conformance", "value"], + "input": { + "type": "int8", + "text": "-128" + } + }, + { + "id": "int16-min", + "kind": "int16", + "context": ["conformance", "value"], + "input": { + "type": "int16", + "text": "-32768" + } + }, + { + "id": "int32-min", + "kind": "int32", + "context": ["conformance", "value"], + "input": { + "type": "int32", + "text": "-2147483648" + } + }, + { + "id": "int64-min", + "kind": "int64", + "context": ["conformance", "value"], + "input": { + "type": "int64", + "text": "-9223372036854775808" + } + }, + { + "id": "int128-min", + "kind": "int128", + "context": ["conformance", "value"], + "input": { + "type": "int128", + "text": "-170141183460469231731687303715884105728" + } + }, + { + "id": "uint8-max", + "kind": "uint8", + "context": ["conformance", "value"], + "input": { + "type": "uint8", + "text": "255" + } + }, + { + "id": "uint16-max", + "kind": "uint16", + "context": ["conformance", "value"], + "input": { + "type": "uint16", + "text": "65535" + } + }, + { + "id": "uint32-max", + "kind": "uint32", + "context": ["conformance", "value"], + "input": { + "type": "uint32", + "text": "4294967295" + } + }, + { + "id": "uint64-max", + "kind": "uint64", + "context": ["conformance", "value"], + "input": { + "type": "uint64", + "text": "18446744073709551615" + } + }, + { + "id": "uint128-max", + "kind": "uint128", + "context": ["conformance", "value"], + "input": { + "type": "uint128", + "text": "340282366920938463463374607431768211455" + } + }, + { + "id": "float32-fraction", + "kind": "float32", + "context": ["conformance", "value"], + "input": { + "type": "float32", + "text": "1.5" + } + }, + { + "id": "float64-infinity", + "kind": "float64", + "context": ["conformance", "value"], + "input": { + "type": "float64", + "text": "inf" + } + }, + { + "id": "decimal-trailing-zeros", + "kind": "decimal", + "context": ["conformance", "value"], + "input": { + "type": "decimal", + "text": "-1234.5600" + } + }, + { + "id": "date-leap-day", + "kind": "date", + "context": ["conformance", "value"], + "input": { + "type": "date", + "text": "2024-02-29" + } + }, + { + "id": "timestamp-nanoseconds", + "kind": "timestamp", + "context": ["conformance", "value"], + "input": { + "type": "timestamp", + "text": "2026-10-17T01:02:03.123456789Z" + } + }, + { + "id": "string-unicode", + "kind": "string", + "context": ["conformance", "value"], + "input": { + "type": "string", + "text": "café ☕" + } + }, + { + "id": "bytes-empty", + "kind": "bytes", + "context": ["conformance", "value"], + "input": { + "type": "bytes", + "text": "" + } + }, + { + "id": "uuid", + "kind": "uuid", + "context": ["conformance", "value"], + "input": { + "type": "uuid", + "text": "123e4567-e89b-12d3-a456-426614174000" + } + }, + { + "id": "uint64-given-float64", + "kind": "uint64", + "context": ["conformance", "value"], + "input": { + "type": "float64", + "text": "34" + }, + "stored": { + "type": "uint64", + "text": "34" + }, + "refused_as": ["float64", "uint32"] + }, + { + "id": "int8-given-int16", + "kind": "int8", + "context": ["conformance", "value"], + "input": { + "type": "int16", + "text": "1" + }, + "stored": { + "type": "int8", + "text": "1" + } + }, + { + "id": "int128-given-int64", + "kind": "int128", + "context": ["conformance", "value"], + "input": { + "type": "int64", + "text": "1" + }, + "stored": { + "type": "int128", + "text": "1" + } + }, + { + "id": "float32-given-float64", + "kind": "float32", + "context": ["conformance", "value"], + "input": { + "type": "float64", + "text": "1.5" + }, + "stored": { + "type": "float32", + "text": "1.5" + } + }, + { + "id": "float64-given-int32", + "kind": "float64", + "context": [], + "input": { + "type": "int32", + "text": "12" + }, + "stored": { + "type": "float64", + "text": "12" + } + }, + { + "id": "decimal-given-int64", + "kind": "decimal", + "context": ["conformance", "value"], + "input": { + "type": "int64", + "text": "5" + }, + "stored": { + "type": "decimal", + "text": "5" + } + }, + { + "id": "json-given-string", + "kind": "json", + "context": ["conformance", "value"], + "input": { + "type": "string", + "text": "{ \"b\": [1, 2.5, null], \"a\": \"é\" }" + }, + "stored": { + "type": "string", + "text": "{\"a\":\"é\",\"b\":[1,2.5,null]}" + }, + "opens_as": [ + { + "kind": "string", + "value": { + "type": "string", + "text": "{\"a\":\"é\",\"b\":[1,2.5,null]}" + } + } + ], + "refused_as": ["int64", "bytes"] + }, + { + "id": "json-given-bytes", + "kind": "json", + "context": [], + "input": { + "type": "bytes", + "text": "6e756c6c" + }, + "stored": { + "type": "string", + "text": "null" + } + }, + { + "id": "json-scalar-string", + "kind": "json", + "context": ["conformance", "value"], + "input": { + "type": "string", + "text": "\"plain\"" + }, + "stored": { + "type": "string", + "text": "\"plain\"" + } + }, + { + "id": "array-no-kind", + "kind": "", + "context": [], + "input": { + "type": "shape", + "text": "array" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_value", + "reason": "not_a_scalar", + "found": "array" + } + }, + { + "id": "array-array", + "kind": "array", + "context": [], + "input": { + "type": "shape", + "text": "array" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_value", + "reason": "not_a_scalar", + "found": "array" + } + }, + { + "id": "array-int64", + "kind": "int64", + "context": [], + "input": { + "type": "shape", + "text": "array" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_value", + "reason": "not_a_scalar", + "found": "array" + } + }, + { + "id": "empty-array-no-kind", + "kind": "", + "context": ["conformance", "value"], + "input": { + "type": "shape", + "text": "empty_array" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_value", + "reason": "not_a_scalar", + "found": "array" + } + }, + { + "id": "object-no-kind", + "kind": "", + "context": [], + "input": { + "type": "shape", + "text": "object" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_value", + "reason": "not_a_scalar", + "found": "object" + } + }, + { + "id": "object-object", + "kind": "object", + "context": [], + "input": { + "type": "shape", + "text": "object" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_value", + "reason": "not_a_scalar", + "found": "object" + } + }, + { + "id": "object-json", + "kind": "json", + "context": [], + "input": { + "type": "shape", + "text": "object" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_value", + "reason": "not_a_scalar", + "found": "object" + } + }, + { + "id": "passthrough-no-kind", + "kind": "", + "context": [], + "input": { + "type": "shape", + "text": "passthrough" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_value", + "reason": "not_a_scalar", + "found": "passthrough" + } + }, + { + "id": "passthrough-string", + "kind": "string", + "context": [], + "input": { + "type": "shape", + "text": "passthrough" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_value", + "reason": "not_a_scalar", + "found": "passthrough" + } + }, + { + "id": "null-no-kind", + "kind": "", + "context": ["conformance", "value"], + "input": { + "type": "null", + "text": "" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_value", + "reason": "not_a_scalar", + "found": "null" + } + }, + { + "id": "null-int64", + "kind": "int64", + "context": ["conformance", "value"], + "input": { + "type": "null", + "text": "" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_value", + "reason": "not_a_scalar", + "found": "null" + } + }, + { + "id": "null-string", + "kind": "string", + "context": ["conformance", "value"], + "input": { + "type": "null", + "text": "" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_value", + "reason": "not_a_scalar", + "found": "null" + } + }, + { + "id": "null-bool", + "kind": "bool", + "context": ["conformance", "value"], + "input": { + "type": "null", + "text": "" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_value", + "reason": "not_a_scalar", + "found": "null" + } + }, + { + "id": "typed-null-no-kind", + "kind": "", + "context": [], + "input": { + "type": "shape", + "text": "typed_null" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_value", + "reason": "not_a_scalar", + "found": "null" + } + }, + { + "id": "typed-null-int64", + "kind": "int64", + "context": [], + "input": { + "type": "shape", + "text": "typed_null" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_value", + "reason": "not_a_scalar", + "found": "null" + } + }, + { + "id": "undefined-no-kind", + "kind": "", + "context": [], + "input": { + "type": "undefined", + "text": "" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_value", + "reason": "not_a_scalar", + "found": "undefined" + } + }, + { + "id": "undefined-int32", + "kind": "int32", + "context": [], + "input": { + "type": "undefined", + "text": "" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_value", + "reason": "not_a_scalar", + "found": "undefined" + } + }, + { + "id": "undefined-json", + "kind": "json", + "context": ["conformance", "value"], + "input": { + "type": "undefined", + "text": "" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_value", + "reason": "not_a_scalar", + "found": "undefined" + } + }, + { + "id": "int64-given-string", + "kind": "int64", + "context": [], + "input": { + "type": "string", + "text": "34" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_value", + "reason": "field_type", + "found": "string" + } + }, + { + "id": "uint64-given-fraction", + "kind": "uint64", + "context": [], + "input": { + "type": "float64", + "text": "34.5" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_value", + "reason": "field_type", + "found": "float64" + } + }, + { + "id": "int8-given-300", + "kind": "int8", + "context": [], + "input": { + "type": "int64", + "text": "300" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_value", + "reason": "field_type", + "found": "int64" + } + }, + { + "id": "date-given-int32", + "kind": "date", + "context": [], + "input": { + "type": "int32", + "text": "0" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_value", + "reason": "field_type", + "found": "int32" + } + }, + { + "id": "decimal-given-float64", + "kind": "decimal", + "context": [], + "input": { + "type": "float64", + "text": "1.5" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_value", + "reason": "field_type", + "found": "float64" + } + }, + { + "id": "string-given-int64", + "kind": "string", + "context": [], + "input": { + "type": "int64", + "text": "34" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_value", + "reason": "field_type", + "found": "int64" + } + }, + { + "id": "bytes-given-string", + "kind": "bytes", + "context": [], + "input": { + "type": "string", + "text": "" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_value", + "reason": "field_type", + "found": "string" + } + }, + { + "id": "array-given-string", + "kind": "array", + "context": [], + "input": { + "type": "string", + "text": "a" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_value", + "reason": "field_type", + "found": "string" + } + }, + { + "id": "object-given-int64", + "kind": "object", + "context": [], + "input": { + "type": "int64", + "text": "1" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_value", + "reason": "field_type", + "found": "int64" + } + }, + { + "id": "json-given-int64", + "kind": "json", + "context": [], + "input": { + "type": "int64", + "text": "1" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_value", + "reason": "field_type", + "found": "int64" + } + }, + { + "id": "json-syntax", + "kind": "json", + "context": [], + "input": { + "type": "string", + "text": "{\"a\": " + }, + "expected_error": { + "code": "stack_encrypt::dynamic_value", + "reason": "json_syntax", + "found": "string" + } + }, + { + "id": "json-duplicate-key", + "kind": "json", + "context": [], + "input": { + "type": "string", + "text": "{\"a\":1,\"a\":2}" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_value", + "reason": "json_duplicate_key", + "found": "string" + } + }, + { + "id": "json-integer-range", + "kind": "json", + "context": [], + "input": { + "type": "bytes", + "text": "3138343436373434303733373039353531363136" + }, + "expected_error": { + "code": "stack_encrypt::dynamic_value", + "reason": "json_integer_range", + "found": "bytes" + } + } + ], + "batches": [ + { + "id": "batch-strings", + "kinds": ["string", "string", "string"], + "context": ["conformance", "value"], + "inputs": [ + { + "type": "string", + "text": "ada" + }, + { + "type": "string", + "text": "" + }, + { + "type": "string", + "text": "grace" + } + ] + }, + { + "id": "batch-converted", + "kinds": ["uint32", "uint32", "uint32"], + "context": [], + "inputs": [ + { + "type": "float64", + "text": "1" + }, + { + "type": "int64", + "text": "2" + }, + { + "type": "uint16", + "text": "3" + } + ], + "stored": [ + { + "type": "uint32", + "text": "1" + }, + { + "type": "uint32", + "text": "2" + }, + { + "type": "uint32", + "text": "3" + } + ] + }, + { + "id": "batch-mixed-no-kind", + "kinds": ["", "", ""], + "context": [], + "inputs": [ + { + "type": "int64", + "text": "1" + }, + { + "type": "string", + "text": "two" + }, + { + "type": "bool", + "text": "true" + } + ] + }, + { + "id": "batch-mixed-kinds", + "kinds": ["uint64", "string", ""], + "context": ["conformance", "value"], + "inputs": [ + { + "type": "float64", + "text": "34" + }, + { + "type": "string", + "text": "ada" + }, + { + "type": "bool", + "text": "true" + } + ], + "stored": [ + { + "type": "uint64", + "text": "34" + }, + { + "type": "string", + "text": "ada" + }, + { + "type": "bool", + "text": "true" + } + ] + }, + { + "id": "batch-empty", + "kinds": [], + "context": [], + "inputs": [] + }, + { + "id": "batch-with-null", + "kinds": ["", "", ""], + "context": ["conformance", "value"], + "inputs": [ + { + "type": "string", + "text": "ada" + }, + { + "type": "null", + "text": "" + }, + { + "type": "string", + "text": "grace" + } + ], + "expected_error": { + "code": "stack_encrypt::dynamic_value", + "reason": "not_a_scalar", + "found": "null" + } + }, + { + "id": "batch-with-mismatch", + "kinds": ["int64", "int64"], + "context": [], + "inputs": [ + { + "type": "int64", + "text": "1" + }, + { + "type": "string", + "text": "two" + } + ], + "expected_error": { + "code": "stack_encrypt::dynamic_value", + "reason": "field_type", + "found": "string" + } + } + ] +} diff --git a/conformance/stack-encrypt/v1/single-value-v1.expected.rust-native.json b/conformance/stack-encrypt/v1/single-value-v1.expected.rust-native.json new file mode 100644 index 000000000..69a7558b1 --- /dev/null +++ b/conformance/stack-encrypt/v1/single-value-v1.expected.rust-native.json @@ -0,0 +1,300 @@ +{ + "version": 1, + "profile": "single-value-v1", + "producer": "rust-native/stack-encrypt-0.3.0", + "cases": { + "array-array": { + "frame": "f0020000000a01000000610a0100000062" + }, + "array-given-string": { + "frame": "0a0100000061" + }, + "array-int64": { + "frame": "f0020000000a01000000610a0100000062" + }, + "array-no-kind": { + "frame": "f0020000000a01000000610a0100000062" + }, + "as-is-bool": { + "frame": "03", + "leaf": "03", + "ciphertext": "0100000000000000000000000000000000953d2c5d27e5e549f2d84c34dffa03f4200046e77e88ca69bc28c79328ea2e7022660434e03342f93f07f852ccdcf45765de029fe04f1b508676453ac04e339b2f80f53847a5ff818dcf1c532fa846fb" + }, + "as-is-bytes": { + "frame": "0b0300000000ff10", + "leaf": "0b00ff10", + "ciphertext": "0100000000000000000000000000000000953d2c5d27e5e549f2d84c34dffa03f4200046e77e88ca69bc28c79328ea2e7022660434e03342f93f07f852ccdcf45765de02fa48756303bc32df4b8307a6f58ac8386d7f82425cccbe656ddd5e73615c571a" + }, + "as-is-empty-string": { + "frame": "0a00000000", + "leaf": "0a", + "ciphertext": "0100000000000000000000000000000000953d2c5d27e5e549f2d84c34dffa03f4200046e77e88ca69bc28c79328ea2e7022660434e03342f93f07f852ccdcf45765de0225bef2bfdae4755442824942ed0d94a1f3ec6cb626299e50653b372e98" + }, + "as-is-float64-negative-zero": { + "frame": "090000000000000080", + "leaf": "090000000000000080", + "ciphertext": "0100000000000000000000000000000000953d2c5d27e5e549f2d84c34dffa03f4200046e77e88ca69bc28c79328ea2e7022660434e03342f93f07f852ccdcf45765de02350d1ec5e03af0f13153705c6fb65b905d078d75d23a437399a38f864d524ed0f751b60d6b" + }, + "as-is-int64-above-js-safe": { + "frame": "050100000000002000", + "leaf": "050100000000002000", + "ciphertext": "0100000000000000000000000000000000953d2c5d27e5e549f2d84c34dffa03f4200046e77e88ca69bc28c79328ea2e7022660434e03342f93f07f852ccdcf45765de02a352279f2d7314d0814b67ade0b98d96c474f8fb7008e6071ba144db50a10e1e6634a5c5f7" + }, + "as-is-string": { + "frame": "0a0f000000616461406578616d706c652e636f6d", + "leaf": "0a616461406578616d706c652e636f6d", + "ciphertext": "0100000000000000000000000000000000953d2c5d27e5e549f2d84c34dffa03f4200046e77e88ca69bc28c79328ea2e7022660434e03342f93f07f852ccdcf45765de02b725799857a54d0788360432755b45db393f1b7e6f2f4c153f0c54bc7e5c1938148196d75552bf87b9aeb13b" + }, + "as-is-string-with-context": { + "frame": "0a0f000000616461406578616d706c652e636f6d", + "leaf": "0a616461406578616d706c652e636f6d", + "ciphertext": "01000000000000000000000000000000005902b1723e57208119a7343912d41d182000de8bb2e291bdcd46deccaa88a9e007ef2aec7757541decec19b7dfc96075ae4d025cadd464b84b4d38682d1e50b58f59a4992f4929674814ab6ace0325ee6b5b7c65981e3d20f187a1cd3cdd8c" + }, + "as-is-uint8": { + "frame": "0dc8", + "leaf": "0dc8", + "ciphertext": "0100000000000000000000000000000000953d2c5d27e5e549f2d84c34dffa03f4200046e77e88ca69bc28c79328ea2e7022660434e03342f93f07f852ccdcf45765de0282a2279d098f66f8776c5750e57acd502a6c3ecbbf4f77fa32e92a8aca60" + }, + "as-is-uuid": { + "frame": "f305000b10000000123e4567e89b12d3a456426614174000", + "leaf": "f305000b123e4567e89b12d3a456426614174000", + "ciphertext": "0100000000000000000000000000000000953d2c5d27e5e549f2d84c34dffa03f4200046e77e88ca69bc28c79328ea2e7022660434e03342f93f07f852ccdcf45765de02de2cfad59578fbdde2113e2408c83a2e622469ff2a8561c1df6f024c6c43603ffab884daca5df9dc618361b6e4163958" + }, + "bool-false": { + "frame": "02", + "leaf": "02", + "ciphertext": "01000000000000000000000000000000005902b1723e57208119a7343912d41d182000de8bb2e291bdcd46deccaa88a9e007ef2aec7757541decec19b7dfc96075ae4d0204b52dce3c7883f4357cb091a330b4d3b6b560a28f9c9e2eeb334df765" + }, + "bytes-empty": { + "frame": "0b00000000", + "leaf": "0b", + "ciphertext": "01000000000000000000000000000000005902b1723e57208119a7343912d41d182000de8bb2e291bdcd46deccaa88a9e007ef2aec7757541decec19b7dfc96075ae4d025e243904c6b98ce10005f8b7809b03b772109d33b767c90077102e2f2a" + }, + "bytes-given-string": { + "frame": "0a00000000" + }, + "date-given-int32": { + "frame": "0400000000" + }, + "date-leap-day": { + "frame": "1281460b00", + "leaf": "1281460b00", + "ciphertext": "01000000000000000000000000000000005902b1723e57208119a7343912d41d182000de8bb2e291bdcd46deccaa88a9e007ef2aec7757541decec19b7dfc96075ae4d02bf360e838a4e7e80dbb78b24519ac81dc083892471b3272c8ed466ca416d28124a" + }, + "decimal-given-float64": { + "frame": "09000000000000f83f" + }, + "decimal-given-int64": { + "frame": "050500000000000000", + "leaf": "1400000000050000000000000000000000", + "ciphertext": "01000000000000000000000000000000005902b1723e57208119a7343912d41d182000de8bb2e291bdcd46deccaa88a9e007ef2aec7757541decec19b7dfc96075ae4d028a8e782f7f1aa3a3067b3d8057ab95ede3b78d267ba118e90422a1bd0be22e700f37fbd32deaed33fc0ec5c41c" + }, + "decimal-trailing-zeros": { + "frame": "14000004800061bc000000000000000000", + "leaf": "14000004800061bc000000000000000000", + "ciphertext": "01000000000000000000000000000000005902b1723e57208119a7343912d41d182000de8bb2e291bdcd46deccaa88a9e007ef2aec7757541decec19b7dfc96075ae4d02eeaf9c1474e50601ee703ef75901fdcf953c9267d98b425ae42508aaeb3fa2d45adabb6470ea78059d509dae72" + }, + "empty-array-no-kind": { + "frame": "f000000000" + }, + "float32-fraction": { + "frame": "080000c03f", + "leaf": "080000c03f", + "ciphertext": "01000000000000000000000000000000005902b1723e57208119a7343912d41d182000de8bb2e291bdcd46deccaa88a9e007ef2aec7757541decec19b7dfc96075ae4d02693227bfd9a4e28995f12272ba296a599a9df3649e04e4ac24b7f73714618363c5" + }, + "float32-given-float64": { + "frame": "09000000000000f83f", + "leaf": "080000c03f", + "ciphertext": "01000000000000000000000000000000005902b1723e57208119a7343912d41d182000de8bb2e291bdcd46deccaa88a9e007ef2aec7757541decec19b7dfc96075ae4d02730a34dc8aea8436e24ede609ea29417503948651cc9232fbc9ae7dba32f867867" + }, + "float64-given-int32": { + "frame": "040c000000", + "leaf": "090000000000002840", + "ciphertext": "0100000000000000000000000000000000953d2c5d27e5e549f2d84c34dffa03f4200046e77e88ca69bc28c79328ea2e7022660434e03342f93f07f852ccdcf45765de021bfb53623f66f1b72532971cef2477fc61b379f9e973d3daa6f6afc05b813d85602137026c" + }, + "float64-infinity": { + "frame": "09000000000000f07f", + "leaf": "09000000000000f07f", + "ciphertext": "01000000000000000000000000000000005902b1723e57208119a7343912d41d182000de8bb2e291bdcd46deccaa88a9e007ef2aec7757541decec19b7dfc96075ae4d02636c99a930f39fd9ac116bf57de36cec9477a076fcf815f7b1acca891d8d028330396f0149" + }, + "int128-given-int64": { + "frame": "050100000000000000", + "leaf": "1001000000000000000000000000000000", + "ciphertext": "01000000000000000000000000000000005902b1723e57208119a7343912d41d182000de8bb2e291bdcd46deccaa88a9e007ef2aec7757541decec19b7dfc96075ae4d020f001346503a8a31858c52a494fa6552ad609605e0dce79835fac9ec3e33c208596ce7df6caf4b04ff7faeb954" + }, + "int128-min": { + "frame": "1000000000000000000000000000000080", + "leaf": "1000000000000000000000000000000080", + "ciphertext": "01000000000000000000000000000000005902b1723e57208119a7343912d41d182000de8bb2e291bdcd46deccaa88a9e007ef2aec7757541decec19b7dfc96075ae4d0203d9fc37a766f04e6eb14ebf0c05b7d0784c17df29a5802c6d05d3c433bb0890389a848b65b37f1c1b559c5aa8" + }, + "int16-min": { + "frame": "0e0080", + "leaf": "0e0080", + "ciphertext": "01000000000000000000000000000000005902b1723e57208119a7343912d41d182000de8bb2e291bdcd46deccaa88a9e007ef2aec7757541decec19b7dfc96075ae4d02bf38b95faaf29d4e843e72134abd32961e68d42d509a27e7d628d92983b493" + }, + "int32-min": { + "frame": "0400000080", + "leaf": "0400000080", + "ciphertext": "01000000000000000000000000000000005902b1723e57208119a7343912d41d182000de8bb2e291bdcd46deccaa88a9e007ef2aec7757541decec19b7dfc96075ae4d020a4033afe1a5b353a0f9661ae2981e6239d719ff4cf758c9fda3627e52f6ca8da3" + }, + "int64-given-string": { + "frame": "0a020000003334" + }, + "int64-min": { + "frame": "050000000000000080", + "leaf": "050000000000000080", + "ciphertext": "01000000000000000000000000000000005902b1723e57208119a7343912d41d182000de8bb2e291bdcd46deccaa88a9e007ef2aec7757541decec19b7dfc96075ae4d0226a292092dc07c14807aaee032309eb627272f40c4fd98a795f8e24c03814b23d4b54ca92e" + }, + "int8-given-300": { + "frame": "052c01000000000000" + }, + "int8-given-int16": { + "frame": "0e0100", + "leaf": "0c01", + "ciphertext": "01000000000000000000000000000000005902b1723e57208119a7343912d41d182000de8bb2e291bdcd46deccaa88a9e007ef2aec7757541decec19b7dfc96075ae4d024c557ec1d7f0e338af7d9c88878c47c5fe066178ec92f4953df25ae9b63e" + }, + "int8-min": { + "frame": "0c80", + "leaf": "0c80", + "ciphertext": "01000000000000000000000000000000005902b1723e57208119a7343912d41d182000de8bb2e291bdcd46deccaa88a9e007ef2aec7757541decec19b7dfc96075ae4d02306ce03ce2b20cb0a7337942f156669e16eb3b639055674875b8f8b79392" + }, + "json-duplicate-key": { + "frame": "0a0d0000007b2261223a312c2261223a327d" + }, + "json-given-bytes": { + "frame": "0b040000006e756c6c", + "leaf": "0a6e756c6c", + "ciphertext": "0100000000000000000000000000000000953d2c5d27e5e549f2d84c34dffa03f4200046e77e88ca69bc28c79328ea2e7022660434e03342f93f07f852ccdcf45765de02830450b50101f6a3b3f49caf66e78f55fe0365d5a7a308a715285840baddf67354" + }, + "json-given-int64": { + "frame": "050100000000000000" + }, + "json-given-string": { + "frame": "0a220000007b202262223a205b312c20322e352c206e756c6c5d2c202261223a2022c3a922207d", + "leaf": "0a7b2261223a22c3a9222c2262223a5b312c322e352c6e756c6c5d7d", + "ciphertext": "01000000000000000000000000000000005902b1723e57208119a7343912d41d182000de8bb2e291bdcd46deccaa88a9e007ef2aec7757541decec19b7dfc96075ae4d02e591294b87dde6fa2cd3f5509ab93920b87e3d0f6999bea7e0212abd9f4dced82bd64622c68752a866af0195253a784228a6ad4547d6f986" + }, + "json-integer-range": { + "frame": "0b140000003138343436373434303733373039353531363136" + }, + "json-scalar-string": { + "frame": "0a0700000022706c61696e22", + "leaf": "0a22706c61696e22", + "ciphertext": "01000000000000000000000000000000005902b1723e57208119a7343912d41d182000de8bb2e291bdcd46deccaa88a9e007ef2aec7757541decec19b7dfc96075ae4d028e622a3d896eba4f36057db0f1dc63b1a9f93f6191c3262bea067f4a68ddb3defd74d12c" + }, + "json-syntax": { + "frame": "0a060000007b2261223a20" + }, + "null-bool": { + "frame": "00" + }, + "null-int64": { + "frame": "00" + }, + "null-no-kind": { + "frame": "00" + }, + "null-string": { + "frame": "00" + }, + "object-given-int64": { + "frame": "050100000000000000" + }, + "object-json": { + "frame": "f10100000001000000610601000000" + }, + "object-no-kind": { + "frame": "f10100000001000000610601000000" + }, + "object-object": { + "frame": "f10100000001000000610601000000" + }, + "passthrough-no-kind": { + "frame": "f20a05000000636c656172" + }, + "passthrough-string": { + "frame": "f20a05000000636c656172" + }, + "string-given-int64": { + "frame": "052200000000000000" + }, + "string-json-number-text": { + "frame": "0a020000003432", + "leaf": "0a3432", + "ciphertext": "0100000000000000000000000000000000953d2c5d27e5e549f2d84c34dffa03f4200046e77e88ca69bc28c79328ea2e7022660434e03342f93f07f852ccdcf45765de02c5470c71a49e4a40e9cc0ecf0d2c83331b14df48b422bab48a5b6527a49c38" + }, + "string-json-spaced-text": { + "frame": "0a220000007b20226222203a205b2031202c206e756c6c205d2c20226122203a2074727565207d", + "leaf": "0a7b20226222203a205b2031202c206e756c6c205d2c20226122203a2074727565207d", + "ciphertext": "01000000000000000000000000000000005902b1723e57208119a7343912d41d182000de8bb2e291bdcd46deccaa88a9e007ef2aec7757541decec19b7dfc96075ae4d0230b18ebf21ce9d80030906b36df0a068478d59ed3758f82f62f37c43aa058d84932cfb94cfc506bc765c338ebe5b6033ff00f8cba133f7103ebe9b0d8d9a0b" + }, + "string-not-json-text": { + "frame": "0a0f000000616461406578616d706c652e636f6d", + "leaf": "0a616461406578616d706c652e636f6d", + "ciphertext": "0100000000000000000000000000000000953d2c5d27e5e549f2d84c34dffa03f4200046e77e88ca69bc28c79328ea2e7022660434e03342f93f07f852ccdcf45765de02110a04698a1a246da6c8e432473b2e29e735e2c681205381dfea450121429847858582af90a83c75bbd405d8" + }, + "string-unicode": { + "frame": "0a09000000636166c3a920e29895", + "leaf": "0a636166c3a920e29895", + "ciphertext": "01000000000000000000000000000000005902b1723e57208119a7343912d41d182000de8bb2e291bdcd46deccaa88a9e007ef2aec7757541decec19b7dfc96075ae4d02b06def1c5a6e1cbc44d41af64f5b733d3c2c6f22ab4d68f588725725fdeee215928cd6baa1dd" + }, + "timestamp-nanoseconds": { + "frame": "130bc9d26a0000000015cd5b07", + "leaf": "130bc9d26a0000000015cd5b07", + "ciphertext": "01000000000000000000000000000000005902b1723e57208119a7343912d41d182000de8bb2e291bdcd46deccaa88a9e007ef2aec7757541decec19b7dfc96075ae4d02a66b3872cd846657a41af5155ad5c0eeb680b54de242d99ed02d32287c9aad40d738aaa09230856e76" + }, + "typed-null-int64": { + "frame": "150500000000000000" + }, + "typed-null-no-kind": { + "frame": "150500000000000000" + }, + "uint128-max": { + "frame": "11ffffffffffffffffffffffffffffffff", + "leaf": "11ffffffffffffffffffffffffffffffff", + "ciphertext": "01000000000000000000000000000000005902b1723e57208119a7343912d41d182000de8bb2e291bdcd46deccaa88a9e007ef2aec7757541decec19b7dfc96075ae4d02433597c92b736ea642fdac7b846f29b6a30616f48ef97eeda089ff30745be880cddd611075b80ecf2a94a2712c" + }, + "uint16-max": { + "frame": "0fffff", + "leaf": "0fffff", + "ciphertext": "01000000000000000000000000000000005902b1723e57208119a7343912d41d182000de8bb2e291bdcd46deccaa88a9e007ef2aec7757541decec19b7dfc96075ae4d02ec21438b0724ce61a47824b18fd6800703b6c14d875b41b91d11c993986d8b" + }, + "uint32-max": { + "frame": "06ffffffff", + "leaf": "06ffffffff", + "ciphertext": "01000000000000000000000000000000005902b1723e57208119a7343912d41d182000de8bb2e291bdcd46deccaa88a9e007ef2aec7757541decec19b7dfc96075ae4d02b0e8441266090f216b6364619fa66c95f511fe1832467eca30f95ee24b9f93c079" + }, + "uint64-given-float64": { + "frame": "090000000000004140", + "leaf": "072200000000000000", + "ciphertext": "01000000000000000000000000000000005902b1723e57208119a7343912d41d182000de8bb2e291bdcd46deccaa88a9e007ef2aec7757541decec19b7dfc96075ae4d024d8ceabb74d6249c2115af1dcde9c55db0736dcdffc10de38b896c5594d946650b216d8423" + }, + "uint64-given-fraction": { + "frame": "090000000000404140" + }, + "uint64-max": { + "frame": "07ffffffffffffffff", + "leaf": "07ffffffffffffffff", + "ciphertext": "01000000000000000000000000000000005902b1723e57208119a7343912d41d182000de8bb2e291bdcd46deccaa88a9e007ef2aec7757541decec19b7dfc96075ae4d02a9104cf6c7fc888b3be880b0ef77c8c90c39cae789b8734075fa23f57eedc832a273f3da8b" + }, + "uint8-max": { + "frame": "0dff", + "leaf": "0dff", + "ciphertext": "01000000000000000000000000000000005902b1723e57208119a7343912d41d182000de8bb2e291bdcd46deccaa88a9e007ef2aec7757541decec19b7dfc96075ae4d0210713e7cf318d8bcdafc7ed5bda20a513d00948785335c60e21c2d3c0e7f" + }, + "undefined-int32": { + "frame": "01" + }, + "undefined-json": { + "frame": "01" + }, + "undefined-no-kind": { + "frame": "01" + }, + "uuid": { + "frame": "f305000b10000000123e4567e89b12d3a456426614174000", + "leaf": "f305000b123e4567e89b12d3a456426614174000", + "ciphertext": "01000000000000000000000000000000005902b1723e57208119a7343912d41d182000de8bb2e291bdcd46deccaa88a9e007ef2aec7757541decec19b7dfc96075ae4d02f8a12b99d4ec25ceb2e20f075c6de2577470599a6e3fb6c88fde3663da1fd5be113edfe7087a06411b67a3d1bf773fa5" + } + } +} diff --git a/languages/golang/encrypt/guest/src/status.rs b/languages/golang/encrypt/guest/src/status.rs index 46d664c07..258d39793 100644 --- a/languages/golang/encrypt/guest/src/status.rs +++ b/languages/golang/encrypt/guest/src/status.rs @@ -193,6 +193,10 @@ pub fn status_for_dynamic(error: &stack_encrypt::dynamic::Error) -> u32 { | Error::UntypedIndex { .. } | Error::Source { .. } | Error::SourceFailed { .. } + // One value that a single ciphertext cannot contain: an array, an + // object, a null, a passthrough, `undefined`, or a value of another + // kind than the one declared. + | Error::Value { .. } | Error::Record { .. } // A `match` predicate refused at an offset in its text: a construct // the grammar does not read or the index cannot answer, a variable @@ -544,7 +548,7 @@ mod tests { #[test] fn dynamic_input_errors_are_encoding_and_a_library_bug_is_internal() { - use stack_encrypt::dynamic::{Error, Reason}; + use stack_encrypt::dynamic::{Error, Found, Reason}; use stack_encrypt::sem::MatchOptions; use stack_encrypt::target::IndexSpec; let age = || Some("age".to_string()); @@ -594,6 +598,13 @@ mod tests { cause: stack_encrypt::dynamic::plaintext::SourceError::msg("getter threw"), }, ), + ( + "a refused single value", + Error::Value { + reason: Reason::NotAScalar, + found: Found::Null, + }, + ), ( "a bad record", Error::Record { diff --git a/languages/typescript/packages/recipher-js/Cargo.lock b/languages/typescript/packages/recipher-js/Cargo.lock index 2f2ed3116..0f2572e31 100644 --- a/languages/typescript/packages/recipher-js/Cargo.lock +++ b/languages/typescript/packages/recipher-js/Cargo.lock @@ -2510,7 +2510,6 @@ dependencies = [ "tokio", "vitaminc-aead 0.10.0", "vitaminc-protected 0.10.0", - "zeroize", ] [[package]] diff --git a/languages/typescript/packages/recipher-js/crate/Cargo.toml b/languages/typescript/packages/recipher-js/crate/Cargo.toml index 3d6fa1191..b79575a18 100644 --- a/languages/typescript/packages/recipher-js/crate/Cargo.toml +++ b/languages/typescript/packages/recipher-js/crate/Cargo.toml @@ -46,9 +46,6 @@ miette = "7.5.0" thiserror = "1.0.56" # For the structured fields of an engine error (`ErrorPayload::payload`). serde_json = "1" -# The engine's opaque path wipes a value it did not seal. The version the -# engine resolves. -zeroize = "1" [dev-dependencies] stack-encrypt = { path = "../../../../../packages/stack-encrypt", default-features = false, features = ["dynamic", "http", "test-support"] } diff --git a/languages/typescript/packages/recipher-js/crate/src/cipher.rs b/languages/typescript/packages/recipher-js/crate/src/cipher.rs index 200477e36..30cd68af6 100644 --- a/languages/typescript/packages/recipher-js/crate/src/cipher.rs +++ b/languages/typescript/packages/recipher-js/crate/src/cipher.rs @@ -16,16 +16,15 @@ use std::sync::Arc; use napi::bindgen_prelude::{JavaScriptClassExt, JsValue, Object, PromiseRaw, Unknown}; use napi::Env; use napi_derive::napi; -use stack_encrypt::dynamic::frame::OwnedFrame; +use stack_encrypt::dynamic::{frame::OwnedFrame, value, ValueKind}; use stack_encrypt::kms::{DataKeySource, IndexKeySource, StackKms}; -use stack_encrypt::{CipherRef, DecryptFrom, EncryptInto, KeysetCipher, StackCipher}; +use stack_encrypt::{CipherRef, DecryptFrom, KeysetCipher, Pending, StackCipher}; use vitaminc_protected::OpaqueDebug; use crate::ciphertext::Ciphertext; use crate::error::{Error, RecipherErrorFields}; use crate::js; use crate::outcome::{not_made, refused, spawn, Outcome}; -use crate::value::OneValue; /// The engine's cipher, with the key source it was built with. A napi class /// cannot be generic, so each key source is one variant. @@ -155,7 +154,7 @@ impl Keyset { env: &'e Env, value: Unknown<'_>, ) -> napi::Result>> { - let value = match js::read(env, value).and_then(OneValue::new) { + let value = match js::read(env, value).and_then(a_string) { Ok(value) => value, Err(error) => return refused(env, error), }; @@ -301,18 +300,42 @@ pub(crate) async fn open_in( }) } -/// Encrypts values under `keyset`. Each value becomes one ciphertext with -/// its own data key. All the values use one key request, however many -/// there are. +/// Returns `value` when it is one string. This build only encrypts strings. +/// +/// # Errors +/// +/// Returns `recipher_js::not_a_string` for any other value. +pub(crate) fn a_string(value: OwnedFrame) -> Outcome { + if value.frame().kind() == Some(ValueKind::String) { + Ok(value) + } else { + Err(Error::NotAString.into()) + } +} + +/// Encrypts strings under `keyset`, with the engine's +/// `dynamic::value::encrypt`. Each value becomes one ciphertext with its own +/// data key. Rust's `keyset.decrypt::` decrypts each ciphertext. The +/// function merges the calls, so all the values use one key request. +/// +/// The engine checks each value again. The engine refuses a value that is +/// not one string with its own error, before any key request. pub(crate) async fn seal( keyset: &KeysetCipher<'_, K>, - values: Vec, + values: Vec, ) -> Outcome> where K: DataKeySource + IndexKeySource + Sync + 'static, { - values - .encrypt_into::, K>(keyset) + let calls = values + .iter() + .map(|value| value::encrypt(keyset, value.frame(), Some(ValueKind::String))) + .collect::, _>>() + .map_err(|error| RecipherErrorFields::engine(&error))?; + // The engine has read every value. `drop` wipes the frames, so no value + // stays in a frame during the key request. + drop(values); + Pending::all(keyset, calls) .await .map_err(|error| RecipherErrorFields::engine(&error)) } @@ -320,6 +343,11 @@ where /// Decrypts ciphertexts through `cipher`: a cipher, or one keyset of it. /// The function makes one key request for each keyset the ciphertexts /// were made under. +/// +/// Each value comes back in a frame, as it was encrypted. A call has no +/// kind to check at run time, because the type of a `Ciphertext` exists +/// only in TypeScript. So this function uses the engine's typed decrypt +/// into frames. That decrypt checks no kind. pub(crate) async fn unseal<'c, K>( cipher: impl Into>, sealed: Vec, @@ -336,6 +364,25 @@ where mod tests { use super::*; + #[test] + fn a_string_is_taken_and_another_value_is_not() { + assert!( + a_string(OwnedFrame::of("text").unwrap()).is_ok(), + "a string is taken" + ); + for other in [ + OwnedFrame::of(5i64).unwrap(), + OwnedFrame::of(vec!["a", "b"]).unwrap(), + OwnedFrame::null(), + ] { + let refused = a_string(other).unwrap_err(); + assert_eq!( + refused.code, "recipher_js::not_a_string", + "a value that is not a string is refused" + ); + } + } + #[test] fn a_build_without_the_test_cipher_says_how_to_get_one() { let error = RecipherErrorFields::from(Error::NoTesting); diff --git a/languages/typescript/packages/recipher-js/crate/src/engine_tests.rs b/languages/typescript/packages/recipher-js/crate/src/engine_tests.rs index 3eaae4240..5f3a39f0a 100644 --- a/languages/typescript/packages/recipher-js/crate/src/engine_tests.rs +++ b/languages/typescript/packages/recipher-js/crate/src/engine_tests.rs @@ -7,7 +7,6 @@ use stack_encrypt::kms::DeterministicSource; use stack_encrypt::StackCipher; use crate::cipher::{open_in, seal, unseal, Confined, Engine}; -use crate::value::OneValue; const SEED: [u8; 32] = [7; 32]; @@ -19,12 +18,12 @@ async fn engine() -> StackCipher { .unwrap() } -fn one(text: &str) -> OneValue { - OneValue::new(OwnedFrame::of(text).unwrap()).unwrap() +fn one(text: &str) -> OwnedFrame { + OwnedFrame::of(text).unwrap() } /// Encrypts `values` through the crate, with the test keys. -async fn sdk_seal(values: Vec) -> Vec { +async fn sdk_seal(values: Vec) -> Vec { seal(&engine().await.default_keyset(), values) .await .unwrap() diff --git a/languages/typescript/packages/recipher-js/crate/src/lib.rs b/languages/typescript/packages/recipher-js/crate/src/lib.rs index 858ed99b1..53356392c 100644 --- a/languages/typescript/packages/recipher-js/crate/src/lib.rs +++ b/languages/typescript/packages/recipher-js/crate/src/lib.rs @@ -55,7 +55,6 @@ mod ciphertext; mod error; mod js; mod outcome; -mod value; #[cfg(all(test, feature = "testing"))] mod engine_tests; diff --git a/languages/typescript/packages/recipher-js/crate/src/value.rs b/languages/typescript/packages/recipher-js/crate/src/value.rs deleted file mode 100644 index 1cb17ee93..000000000 --- a/languages/typescript/packages/recipher-js/crate/src/value.rs +++ /dev/null @@ -1,84 +0,0 @@ -//! A value that the engine encrypts as one leaf. -//! -//! The engine is the Stack Encrypt engine, the `stack-encrypt` crate. A -//! leaf is one value that the engine encrypts as a single ciphertext. - -use stack_encrypt::dynamic::plaintext::{depth, Error as _, Scalar, Sink, SourceError}; -use stack_encrypt::dynamic::{frame::OwnedFrame, ValueKind}; -use stack_encrypt::Encrypt; -use vitaminc_protected::OpaqueDebug; - -use crate::error::{Error, RecipherErrorFields}; - -/// A value checked to be one string. -/// -/// The engine encrypts the value through its opaque scalar path. That path -/// encrypts a whole value as one leaf. Rust's `keyset.encrypt(value)` uses -/// the same path. So each ciphertext has the form that Rust and Go write -/// for the same value. -/// -/// The engine encrypts a value as one opaque leaf only when its type -/// implements `Scalar`, a trait of vitaminc, CipherStash's cryptography -/// library. An [`OwnedFrame`] can contain any value of the engine's value -/// model, the set of value types the engine reads. So an [`OwnedFrame`] is -/// not a `Scalar`. This type checks that the frame contains one string. The -/// check runs once, before the engine reads the value. -/// -/// The opaque path also needs a value it can wipe (`Zeroize`). Wiping drops -/// the frame, and the frame wipes its own buffer when it drops. `Debug` -/// hides the value. -#[derive(OpaqueDebug)] -pub(crate) struct OneValue(Option); - -impl OneValue { - /// Returns `value` as a [`OneValue`], if it is one string. - /// - /// # Errors - /// - /// Returns `recipher_js::not_a_string` for any other value. - pub(crate) fn new(value: OwnedFrame) -> Result { - if value.frame().kind() == Some(ValueKind::String) { - Ok(Self(Some(value))) - } else { - Err(Error::NotAString.into()) - } - } -} - -impl zeroize::Zeroize for OneValue { - fn zeroize(&mut self) { - // Dropping the frame wipes its buffer. - self.0 = None; - } -} - -impl Encrypt for &OneValue { - const DEPTH: Option = depth::SCALAR; - fn visit(self, sink: S) -> Result { - match &self.0 { - Some(frame) => frame.visit(sink), - None => Err(S::Error::source(SourceError::msg("a wiped value"))), - } - } -} - -impl Scalar for &OneValue {} - -#[cfg(test)] -mod tests { - use super::OneValue; - use stack_encrypt::dynamic::frame::OwnedFrame; - - #[test] - fn a_string_is_one_value_and_another_value_is_not() { - assert!(OneValue::new(OwnedFrame::of("text").unwrap()).is_ok()); - let refused = OneValue::new(OwnedFrame::of(5i64).unwrap()).unwrap_err(); - assert_eq!(refused.code, "recipher_js::not_a_string"); - } - - #[test] - fn debug_hides_the_value() { - let value = OneValue::new(OwnedFrame::of("secret").unwrap()).unwrap(); - assert!(!format!("{value:?}").contains("secret")); - } -} diff --git a/packages/stack-encrypt/CHANGELOG.md b/packages/stack-encrypt/CHANGELOG.md index ca0482d82..3d07b4e66 100644 --- a/packages/stack-encrypt/CHANGELOG.md +++ b/packages/stack-encrypt/CHANGELOG.md @@ -9,6 +9,73 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +- **Encrypt and decrypt one value whose type is known only at run time** + (#2009). `dynamic::value` has two functions for a value in a frame. The + two functions are the run-time counterparts of the typed `keyset.encrypt` + and `keyset.decrypt`. A frame is one value written as bytes. A language + SDK has each value as a frame. The kind of the value is only known when + the code runs. + - `dynamic::value::encrypt(&keyset, frame, kind)` takes a borrowed + `Frame` and an optional declared `ValueKind`. The call returns a + `Ciphertext` that `keyset.decrypt::` decrypts. So each language can + decrypt what another language encrypted. + - `dynamic::value::decrypt(cipher, ciphertext, kind)` decrypts a + ciphertext into an `OwnedFrame` of one scalar. Pass `&keyset` to + decrypt only the ciphertexts of that keyset. Pass `&cipher` to decrypt + a ciphertext of any keyset. + - Each function has a form with a context: `encrypt_with_context` and + `decrypt_with_context`. + - There is no batch call. Each call returns a `Pending`. A `Pending` does + not send its key request until it is awaited. To encrypt or decrypt + many values, make one call for each value. Then merge the calls with + `Pending::all`. Awaiting the merged call makes one key request, and + returns the results in order. + - Each value keeps its own declared kind, so one merged call can contain + values of different kinds. + - On encrypt, a declared kind converts a number of another width or kind + when the conversion is exact. The rules are those of a typed field of a + record. With no declared kind, the scalar is stored as it arrived. + - On decrypt, a declared kind is the kind that the value must have been + stored as. Nothing is converted. A value of another kind is + `Error::OpenedType`. That error names the kind that was expected, and + never says what kind the value had. + - The kind `json` takes a document as its JSON text, as a text value or a + bytes value. The engine checks the text, and stores the document as it + stores a `JsonPlaintext`. On decrypt, `json` returns the text of the + document as a bytes value. A `json` field of a record decrypts to the + same form. + - `json` is a declared kind and not a stored kind. The engine stores a + document as text, as it stores a string. So a check of the stored kind + cannot distinguish them. An encrypted document decrypts as `string`. An + encrypted string whose text is a JSON document decrypts as `json`. + - Decrypt as `json` checks that the text parses, and returns the document + as the engine writes it. + - A ciphertext contains one scalar. `encrypt` refuses an array, an + object, a passthrough, and a null before it requests any key. The null + can be plain or typed. `encrypt` also refuses JavaScript's `undefined`, + with a declared kind and with none. An `undefined` value is most often + a misspelt property name. No typed call could read it back. + - The refusal is a new variant, `dynamic::Error::Value`, with the code + `stack_encrypt::dynamic_value`. The error names no field, and its + message is about one value. + - The reason of each of those refusals is the new `Reason::NotAScalar` + (`not_a_scalar`). A value of another kind is `Reason::FieldType`. + - Every `Error::Value` names the kind of the value to encrypt as a + `dynamic::Found`. The kind is in `Error::found()`, in the payload field + `found`, and in the message, such as + `the value to encrypt is an array, not a scalar`. The error never + contains the value, and a refused decrypt never names the kind of the + decrypted value. + - Two ciphertexts of one value never have the same bytes, because each + encrypted scalar has a random nonce. The two interfaces agree on every + other part: the keyset, the data key, the length, and the plaintext of + the encrypted scalar. `tests/single_value.rs` tests that for every + kind. + - The conformance profile `single-value-v1` has the shared cases. The + contract of the profile is + `conformance/stack-encrypt/single-value-contract.md`. + - `ScalarTarget` is re-exported from Vitamin C at the crate root. + - **Encrypt a UUID as a UUID** (#1833). `value::Uuid` is vitaminc's wipeable UUID, built from the uuid crate's `Uuid` with `Uuid::new`. It seals as one leaf, and an `Option`'s `None` seals as a null as long @@ -504,6 +571,48 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Breaking +- **A `Ciphertext` decrypts only into a type that is built from one scalar** + (#2009). `OpaqueDecode` was implemented for every `Decrypt` type that is + `Zeroize`. So `keyset.decrypt::>(ciphertext)` compiled, + requested a key, decrypted, and only then failed with + `Error::OpenedType`. That call could never succeed, because a ciphertext + contains one scalar. `OpaqueDecode` is now bounded on Vitamin C's + `ScalarTarget`, so such a call does not compile. + - The bound applies to `keyset.decrypt`, `keyset.decrypt_with_context`, + `T::decrypt_from(ciphertext, ..)`, and a `Ciphertext` field of a derived + record. + - Still accepted: + - every scalar: `bool`, the fixed-width integers other than `u8`, the + floats, `String`, `Vec`, `[u8; N]`, `value::Date`, + `value::Timestamp`, `value::Decimal`, and `value::Uuid` + - `JsonPlaintext` + - a `Protected` or an `Option` of a scalar + - `OwnedFrame` + - a newtype that derives `Decrypt` over a scalar, such as + `struct Email(String)` + - any type of your own that implements `FromScalar` + - `OpaqueBlob`, through its own impl + - No longer accepted: + - a `Vec` of anything but bytes + - a `HashMap` or a `BTreeMap` + - a struct that derives `Decrypt` with named fields + - a newtype, a `Protected`, or an `Option` of one of those + - A type of your own is accepted when it is built from one scalar. The + type must also implement `Zeroize` and `Send`, and be `'static`. A + `'static` type borrows no data. + - You cannot implement `ScalarTarget` directly. A type is a + `ScalarTarget` when it is built from one scalar. The compiler derives + that from how the type decrypts. + - The compile error names the type that you wrote, such as + `Vec`. The error says what one `Ciphertext` decrypts into, and + what to use for the other types. + - A sequence, a map, or a struct is stored as a tree of encrypted + scalars: a `StackCipherText`. Decrypt one with `keyset.decrypt_tree`. + - A column of ciphertexts is a `Vec`. A `Vec` + still decrypts into a `Vec` with `Vec::::decrypt_from`. + - No stored byte changes. Every ciphertext that decrypted before still + decrypts into the same type. + - **An error about input that is not an object names the kind of value and the row** (#1985). The input is a plan, a field spec, a record to encrypt, or a stored record. A field spec is the entry in a plan that diff --git a/packages/stack-encrypt/docs/adr/0012-owned-record-declarations.md b/packages/stack-encrypt/docs/adr/0012-owned-record-declarations.md index d04fcabcf..93a22bc6e 100644 --- a/packages/stack-encrypt/docs/adr/0012-owned-record-declarations.md +++ b/packages/stack-encrypt/docs/adr/0012-owned-record-declarations.md @@ -2,6 +2,7 @@ status: accepted date: 2026-11-03 revised: 2026-11-11 +amended: 2026-11-28 extends: ADR-0003, ADR-0004 --- @@ -181,6 +182,24 @@ case needs a trait for "a scalar, or a `Protected` of one". Rust allows that trait to be implemented for both only in Vitamin C, the crate that defines `FromScalar`. +> **Amended 2026-11-28 (pull request #2011).** Vitamin C now has that +> trait, `ScalarTarget`: a decrypt target that is built from one scalar. +> No one implements `ScalarTarget` directly. +> +> A sink is the type that builds a decrypt target. Vitamin C marks each of +> its sinks that builds its value from one scalar. A target is a +> `ScalarTarget` when its sink has that mark. +> +> So every `FromScalar` type is a `ScalarTarget`. An `Option`, a +> `Protected`, and a derived newtype of a scalar target are `ScalarTarget`s +> too. `OwnedFrame` is also one. +> +> The bound of a single `Ciphertext`'s target is now +> `ScalarTarget + Zeroize`, and no longer `Decrypt + Zeroize`. So a target +> that is not a scalar, such as `Vec`, does not compile. +> `keyset.decrypt::>(ct)` compiles as before. The other +> stored types keep the bound `Decrypt + Zeroize`. + ### 5. The structural traits are a bridge Each owned derive also implements the structural traits: diff --git a/packages/stack-encrypt/docs/language-integration.md b/packages/stack-encrypt/docs/language-integration.md index 1631f78f8..064f5c2b0 100644 --- a/packages/stack-encrypt/docs/language-integration.md +++ b/packages/stack-encrypt/docs/language-integration.md @@ -170,6 +170,49 @@ says which cipher opens ([`crate::CipherRef`]): A record encrypted with a scope or a binding is decrypted with the same ones, through `decrypt_from_with_context`. +### One value as one ciphertext + +A record is not the only stored form. Rust's `keyset.encrypt(value)` +encrypts one value into one [`crate::Ciphertext`], with no plan. A binding +does the same through [`crate::dynamic::value`]: + +- [`crate::dynamic::value::encrypt`] takes the value as a + [`crate::dynamic::frame::Frame`], and an optional declared kind + ([`crate::dynamic::ValueKind`]). The call settles to a ciphertext that the + typed Rust call can decrypt. So every language can read what any language + wrote. +- [`crate::dynamic::value::decrypt`] takes a ciphertext, and an optional + kind that the value must have been stored as. The call settles to the + frame of the value. + +Each function has a form that takes a context. A declared kind reads the +value by the rules that a typed field of a record uses. So a binding can +pass a number in the form that its language uses. The kind `json` takes a +document as its JSON text. + +There is no batch call. Each call returns a [`crate::Pending`]. So a binding +makes one call for each value, and merges the calls with +[`crate::Pending::all`]. Awaiting the merged call makes one key request. +Each value keeps its own declared kind. + +A ciphertext contains one scalar. The engine refuses an array, an object, a +passthrough, and a null before it requests any key. The engine also refuses +JavaScript's `undefined`, with any declared kind. The refusal is +[`crate::dynamic::Error::Value`], with the code +`stack_encrypt::dynamic_value` and the reason `not_a_scalar`. An SDK stores +an absent value as a database `NULL`. + +Every refusal of a single value names the kind of the value to encrypt, in +the payload field `found`. Examples are `array`, `null`, `undefined`, and +`string`. An SDK reports `found` as it reports the kind in a record's +`not_an_object` error. The kind is the kind of the input. A refused decrypt +never names the kind of the decrypted value. + +`json` is a declared kind, and the engine stores a document as text. So a +`string` and a document have one stored form. A check of the stored kind +cannot distinguish them. A stored document decrypts as `string`. A stored +string whose text is a JSON document decrypts as `json`. + ### Scopes and bindings A field is sealed under its label, `["profiles", "age"]`. A caller adds to @@ -830,12 +873,29 @@ lists every profile and its Rust and Go runners. Before a binding is called done: 1. **The conformance profiles pass in your language.** Write a runner for - each profile in `conformance/stack-encrypt/v1`, as - `languages/golang/encrypt/*conformance_test.go` does for Go: scalar - records, declarations, reads, runtime and nulls, contexts and bindings, - value boundaries, query refusals, raw frames and, if your binding links - the EQL types, EQL and JSON. Read the frozen expectations; never - regenerate them to pass. A profile you have not run is not a pass. + each profile in `conformance/stack-encrypt/v1`. The files + `languages/golang/encrypt/*conformance_test.go` are the Go runners. The + profiles are: + + - scalar records + - declarations + - reads + - runtime and nulls + - contexts and bindings + - value boundaries + - query refusals + - raw frames + + If your binding links the EQL types, the EQL and JSON profiles apply + too. + + If your SDK encrypts one value into one ciphertext, write a runner for + the single-value profile too. Only Rust runs that profile today, because + the Go runner is not written yet. So follow + `packages/stack-encrypt/tests/single_value_conformance.rs`. + + Read the frozen expectations. Never regenerate them to make a run pass. + A profile that you have not run is not a pass. 2. **Fresh artifacts cross both ways.** The exchange profile (`conformance/stack-encrypt/exchange-contract.md`) has your binding open what Rust wrote in the same run, and Rust open what your binding wrote, diff --git a/packages/stack-encrypt/src/codes.rs b/packages/stack-encrypt/src/codes.rs index d7b47ae44..3a5648e0b 100644 --- a/packages/stack-encrypt/src/codes.rs +++ b/packages/stack-encrypt/src/codes.rs @@ -205,7 +205,7 @@ mod tests { #[cfg(feature = "dynamic")] fn dynamic_variants() -> Vec { - use crate::dynamic::{Error, Reason, TargetError, ValueKind}; + use crate::dynamic::{Error, Found, Reason, TargetError, ValueKind}; use crate::target::IndexSpec; let name = || "email".to_string(); let target = || "TextEq".to_string(); @@ -219,6 +219,7 @@ mod tests { Error::Plan { .. } => Error::bad_plan(Reason::NoFields), Error::UntypedIndex { .. } => Error::UntypedIndex { field: name() }, Error::Source { .. } => Error::bad_source(Reason::FieldMissing), + Error::Value { .. } => Error::bad_value(Reason::NotAScalar, Found::Null), Error::SourceFailed { .. } => Error::SourceFailed { field: Some(name()), row: None, @@ -609,6 +610,17 @@ mod tests { }), json!({ "field": "email", "reason": "source_failed", "row": 0 }), ), + ( + // One value names no field, even after `in_field`. + Box::new( + Error::bad_value( + Reason::NotAScalar, + crate::dynamic::Found::Kind(ValueKind::Array), + ) + .in_field("email"), + ), + json!({ "reason": "not_a_scalar", "found": "array" }), + ), ( Box::new(Error::UntypedIndex { field: name() }), json!({ "field": "email" }), diff --git a/packages/stack-encrypt/src/dynamic/mod.rs b/packages/stack-encrypt/src/dynamic/mod.rs index 786e8c0b3..23771176e 100644 --- a/packages/stack-encrypt/src/dynamic/mod.rs +++ b/packages/stack-encrypt/src/dynamic/mod.rs @@ -32,6 +32,11 @@ //! * [`frame::OwnedFrame`] — the engine's plaintext for a value whose type //! is known only at run time: vitaminc's, re-exported with the rest of the //! frame. +//! * [`value`] — encrypts one value in a frame as one +//! [`Ciphertext`](crate::Ciphertext), and decrypts it again. +//! [`KeysetCipher::encrypt`](crate::KeysetCipher::encrypt) and +//! [`KeysetCipher::decrypt`](crate::KeysetCipher::decrypt) do the same for +//! a value of a Rust type. //! * [`term`](term()) — one index term for a value, derived at the one //! scalar it is walked to. //! * [`record`] — a record's declaration as data, *lowered* into the @@ -59,12 +64,15 @@ //! //! # What is not here //! -//! Encrypting a whole value is not: an [`OwnedFrame`](frame::OwnedFrame), -//! like any source, -//! implements `Encrypt` already, so `keyset.encrypt_tree(value, aad)` is the whole -//! of it and needs nothing from this module. Nor is a second executor: nothing here calls -//! the term functions or the seal path to produce a record. A capability a -//! data plan needs and the combinators lack is added to the combinators, +//! Encrypting a whole value as a tree of leaves is not here. An +//! [`OwnedFrame`](frame::OwnedFrame) implements `Encrypt` already, like any +//! source. So `keyset.encrypt_tree(value, aad)` encrypts it, and needs +//! nothing from this module. [`value`] encrypts one scalar as one opaque +//! ciphertext. That is a different stored form. +//! +//! A second executor is not here either: nothing in this module calls the +//! term functions or the seal path to produce a record. When a data plan +//! needs a capability that the combinators lack, add it to the combinators, //! once. //! //! # Stability @@ -113,6 +121,7 @@ mod target; mod term; #[cfg(test)] mod test_frame; +pub mod value; /// The document a `json` field's value holds, as [`read_json`] returns it: /// [`crate::json::JsonPlaintext`], named here for a binding that reaches diff --git a/packages/stack-encrypt/src/dynamic/value.rs b/packages/stack-encrypt/src/dynamic/value.rs new file mode 100644 index 000000000..2938b6342 --- /dev/null +++ b/packages/stack-encrypt/src/dynamic/value.rs @@ -0,0 +1,622 @@ +//! Encrypt and decrypt one value whose type is only known when the code +//! runs. +//! +//! [`KeysetCipher::encrypt`] encrypts one value of a Rust type into one +//! [`Ciphertext`]. [`KeysetCipher::decrypt`] decrypts that ciphertext into a +//! Rust type. This documentation names those two methods the typed calls. A +//! language binding has no Rust type to name. So this module has the same +//! two operations for a value that arrives as a frame. +//! +//! # Terms +//! +//! - A *frame* is one value written as bytes, in the format that the engine +//! reads. A [`Frame`] borrows those bytes. An [`OwnedFrame`] owns them, +//! and wipes them when it is dropped. +//! - A *scalar* is one value that has no parts: text, a number, a boolean, +//! bytes, a date, a timestamp, a decimal, or a UUID. +//! - A *kind* is the name of what a value is, such as `string`, `int64`, or +//! `timestamp`. [`ValueKind`] lists the kinds. +//! - A *leaf* is the encrypted form of one scalar or of one null. A +//! [`Ciphertext`] contains exactly one leaf. +//! - A *context* is data that is authenticated with a value. The +//! ciphertext does not store the context, so decrypting needs the same +//! context. +//! - A *key request* is one request to the key service for data keys. +//! - A *refusal* is an error that a function returns for a value it does not +//! accept. +//! +//! # The functions +//! +//! - [`encrypt`] encrypts the one scalar in a frame. The typed +//! `keyset.decrypt` decrypts the result. So every language can decrypt a +//! value that one language encrypted. +//! - [`decrypt`] decrypts a ciphertext into an [`OwnedFrame`] of one scalar. +//! - [`encrypt_with_context`] and [`decrypt_with_context`] do the same with +//! a context. +//! +//! # Many values in one key request +//! +//! Each call returns a [`Pending`]. A `Pending` is a prepared call. The key +//! request of a `Pending` is not sent until the `Pending` is awaited. +//! +//! To encrypt or decrypt many values, make one call for each value. Then +//! merge the results with [`Pending::all`]. Awaiting the merged call makes +//! one key request for each keyset, and returns the results in the order of +//! the calls. +//! +//! Each value has its own declared kind and its own context. So one merged +//! call can contain values of different kinds. The examples on [`encrypt`] +//! and [`decrypt`] show how. +//! +//! # The declared kind +//! +//! Each function takes an optional [`ValueKind`]. That is the declared kind: +//! the kind that the caller says the value has. +//! +//! When [`encrypt`] has a declared kind, it stores the value as that kind. +//! `encrypt` converts a number of another width or kind when the conversion +//! is exact. The conversion rules are those of [`read`](super::read), the +//! function that reads a typed field of a record. +//! +//! For example, a JavaScript `34` arrives as a float. `encrypt` stores it as +//! the integer `34` when the caller declares `uint64`. With no declared +//! kind, `encrypt` stores the scalar as it arrived. +//! +//! When [`decrypt`] has a declared kind, the value must have been stored as +//! that kind. `decrypt` converts nothing, and refuses a value that was +//! stored as another kind. With no declared kind, `decrypt` returns the +//! value as it was stored. +//! +//! # A JSON document +//! +//! The kind [`ValueKind::Json`] is a JSON document. +//! +//! [`encrypt`] takes the JSON text of the document, as a text value or a +//! bytes value in the frame. `encrypt` checks the text by the engine's JSON +//! rules. `encrypt` then stores the document as +//! `keyset.encrypt(JsonPlaintext)` stores a [`JsonPlaintext`]. +//! +//! [`decrypt`] returns the JSON text of the document as a bytes value in the +//! frame. A `json` field of a record decrypts to the same form +//! ([`json_frame`](super::json_frame)). +//! +//! `json` is a declared kind and not a stored kind. The engine stores a +//! document as its JSON text, in the same stored form as a `string`. So a +//! check of the stored kind cannot distinguish `string` from `json`: +//! +//! - An encrypted document decrypts as `string`. The frame contains the JSON +//! text that was stored. +//! - An encrypted string decrypts as `json` when its text is a JSON +//! document. The string `42` is a document. So is `"ada"` with its quotes. +//! The string `ada` is not a document, so `decrypt` refuses it. +//! +//! [`decrypt`] with the kind `json` checks that the text parses by the +//! engine's JSON rules. `decrypt` then returns the document as the engine +//! writes it: with no whitespace between tokens, and with each number in its +//! shortest form. So when a value was encrypted as a string, the text that +//! `decrypt` returns as `json` can differ from the text that was encrypted. +//! +//! # What is refused +//! +//! A [`Ciphertext`] contains one scalar. So [`encrypt`] refuses an array, an +//! object, a passthrough, and a null. A passthrough is a value that a record +//! stores without encrypting it. `encrypt` returns each refusal before it +//! requests any key. +//! +//! The typed call cannot encrypt a null either: `Option` is not an +//! [`OpaqueEncode`](crate::OpaqueEncode) type. Store an absent value as a +//! database `NULL`. Or encrypt it in a record, where the field declares how +//! a null is stored ([`NullMode`](super::NullMode)). +//! +//! [`encrypt`] also refuses JavaScript's `undefined`, with any declared kind +//! or with none. An `undefined` value is most often a misspelt property +//! name. No typed call could decrypt it. +//! +//! A logical type is a meaning that the frame format gives to a plain +//! scalar, such as a date stored as an integer. A scalar can have a logical +//! type that this build does not define. Such a scalar has no kind. The frame +//! format and the leaf format record an unknown logical type by its numeric +//! id. So an older build can store and return a value of a type that a newer +//! build added. +//! +//! - With no declared kind, [`encrypt`] stores such a scalar as it arrived. +//! [`decrypt`] returns it only when no kind is declared. +//! - With a declared kind, [`encrypt`] refuses such a scalar. +//! +//! A refusal names the kind of the value to encrypt as a [`Found`]. A +//! refusal never contains the value. A refused decrypt never names the kind +//! of the decrypted value, because that kind is part of the plaintext. +//! +//! [`KeysetCipher::encrypt`]: crate::KeysetCipher::encrypt +//! [`KeysetCipher::decrypt`]: crate::KeysetCipher::decrypt + +use vitaminc_aead::frame::{Frame, OwnedFrame}; +use vitaminc_aead::plaintext::{Logical, Physical}; +use vitaminc_aead::{Encrypt, IntoContext}; + +use super::kind::convert; +use super::term::OneScalar; +use super::{read_json, Error, Found, JsonValueError, Reason, ValueKind}; +use crate::json::inputs::json_reason; +use crate::json::JsonPlaintext; +use crate::target::core::encrypt_opaque; +use crate::target::{CipherRef, Pending, ScalarContext}; +use crate::{Ciphertext, ContextPiece, DecryptFrom, KeysetCipher}; + +/// Encrypt the one scalar in `value` as one [`Ciphertext`], with the empty +/// context. +/// +/// [`KeysetCipher::decrypt`] and [`decrypt`] both decrypt the result. `kind` +/// is the kind that the caller declares for the value. Pass `None` to store +/// the scalar as it arrived. The [module docs](self) describe how a declared +/// kind converts a value, and how a JSON document is stored. +/// +/// `encrypt` reads the frame before it returns. The pending call keeps only +/// the value in the form that will be encrypted, in a buffer that is wiped. +/// The caller still owns the frame, and wipes it when the caller no longer +/// needs it. An [`OwnedFrame`] wipes its bytes when it is dropped. +/// +/// ``` +/// use stack_encrypt::dynamic::{frame::OwnedFrame, value, ValueKind}; +/// use stack_encrypt::StackCipher; +/// +/// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { +/// // With no `.kms(..)`, the cipher uses ZeroKMS. It reads credentials from +/// // the environment, or from the profile that `npx stash auth login` writes. +/// let cipher = StackCipher::builder() +/// # .kms(stack_encrypt::kms::FakeDataKeySource::new()) +/// .init() +/// .await?; +/// let keyset = cipher.default_keyset(); +/// +/// // A binding has the value as a frame. A JavaScript number is a float. +/// let age = OwnedFrame::of(34.0f64)?; +/// +/// // The caller declares the kind, so the value is stored as an integer. +/// let stored = value::encrypt(&keyset, age.frame(), Some(ValueKind::UInt64))?.await?; +/// +/// // The typed call decrypts it. +/// let typed: u64 = keyset.decrypt(stored.clone()).await?; +/// assert_eq!(typed, 34); +/// +/// // `value::decrypt` decrypts it too, into a frame of the declared kind. +/// let opened = value::decrypt(&keyset, stored, Some(ValueKind::UInt64)).await?; +/// assert_eq!(opened.frame(), OwnedFrame::of(34u64)?.frame()); +/// # Ok::<(), Box>(()) +/// # }).unwrap(); +/// ``` +/// +/// # Many values in one key request +/// +/// Call `encrypt` for each value, then merge the pending calls with +/// [`Pending::all`]. Awaiting the merged call makes one key request for +/// every value. No key is requested before that. The ciphertexts come back +/// in the order of the calls. +/// +/// Each value gets its own data key. Each value is authenticated separately. +/// Each call takes its own declared kind, so one merged call can contain +/// values of different kinds. +/// +/// `encrypt` returns `Err` for a refused value before any call is merged. So +/// a set of values with one refused value requests no key. +/// +/// ``` +/// use stack_encrypt::dynamic::{frame::OwnedFrame, value, ValueKind}; +/// use stack_encrypt::{Pending, StackCipher}; +/// +/// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { +/// // With no `.kms(..)`, the cipher uses ZeroKMS. It reads credentials from +/// // the environment, or from the profile that `npx stash auth login` writes. +/// let cipher = StackCipher::builder() +/// # .kms(stack_encrypt::kms::FakeDataKeySource::new()) +/// .init() +/// .await?; +/// let keyset = cipher.default_keyset(); +/// +/// // Three values, each with the kind the caller declares for it. +/// let values = [ +/// (OwnedFrame::of(34.0f64)?, Some(ValueKind::UInt64)), +/// (OwnedFrame::of("ada@example.com")?, Some(ValueKind::String)), +/// (OwnedFrame::of(true)?, None), +/// ]; +/// +/// // One call for each value. A refused value returns here, before any +/// // key request. +/// let mut calls = Vec::new(); +/// for (frame, kind) in &values { +/// calls.push(value::encrypt(&keyset, frame.frame(), *kind)?); +/// } +/// +/// // One key request for all three. +/// let stored = Pending::all(&keyset, calls).await?; +/// assert_eq!(stored.len(), 3); +/// +/// let age: u64 = keyset.decrypt(stored[0].clone()).await?; +/// assert_eq!(age, 34); +/// # Ok::<(), Box>(()) +/// # }).unwrap(); +/// ``` +/// +/// # Errors +/// +/// `encrypt` returns [`Error::Value`] before it requests any key. The reason +/// in the error is one of these: +/// +/// - [`Reason::NotAScalar`] for an array, an object, a null, a passthrough, +/// or JavaScript's `undefined`, with a declared kind or with none. A typed +/// null is a null. +/// - [`Reason::FieldType`] for a value of another kind that does not convert +/// exactly to the declared kind. +/// - [`Reason::JsonSyntax`], [`Reason::JsonDuplicateKey`], or +/// [`Reason::JsonIntegerRange`] for text that is not a JSON document, when +/// the declared kind is [`ValueKind::Json`]. +/// +/// [`Error::found`] returns the kind of the value, such as +/// [`Found::Null`] or `Found::Kind(ValueKind::Array)`. The error names no +/// field and contains no part of the value. When the +/// pending call fails, the error is the engine's [`Error`](crate::Error), as +/// it is for [`KeysetCipher::encrypt`]. +/// +/// [`KeysetCipher::encrypt`]: crate::KeysetCipher::encrypt +/// [`KeysetCipher::decrypt`]: crate::KeysetCipher::decrypt +pub fn encrypt<'a, K: 'static>( + keyset: &'a KeysetCipher<'_, K>, + value: Frame<'_>, + kind: Option, +) -> Result, Error> { + seal(keyset, value, kind, ().into_context()) +} + +/// Encrypt as [`encrypt`] does, and authenticate `context` with the value. +/// +/// [`KeysetCipher::encrypt_with_context`] does the same for a typed value. +/// Decrypting needs the same context. +/// +/// ``` +/// use stack_encrypt::dynamic::{frame::OwnedFrame, value}; +/// use stack_encrypt::StackCipher; +/// +/// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { +/// // With no `.kms(..)`, the cipher uses ZeroKMS. It reads credentials from +/// // the environment, or from the profile that `npx stash auth login` writes. +/// let cipher = StackCipher::builder() +/// # .kms(stack_encrypt::kms::FakeDataKeySource::new()) +/// .init() +/// .await?; +/// let keyset = cipher.default_keyset(); +/// +/// let email = OwnedFrame::of("ada@example.com")?; +/// let stored = +/// value::encrypt_with_context(&keyset, email.frame(), None, ("users", "email"))?.await?; +/// +/// let typed: String = keyset +/// .decrypt_with_context(stored, ("users", "email")) +/// .await?; +/// assert_eq!(typed, "ada@example.com"); +/// # Ok::<(), Box>(()) +/// # }).unwrap(); +/// ``` +/// +/// # Errors +/// +/// The errors of [`encrypt`]. A context that cannot be used fails the +/// pending call, as it does for the typed call. +/// +/// [`KeysetCipher::encrypt_with_context`]: crate::KeysetCipher::encrypt_with_context +pub fn encrypt_with_context<'a, 'c, K: 'static>( + keyset: &'a KeysetCipher<'_, K>, + value: Frame<'_>, + kind: Option, + context: impl IntoContext<'c>, +) -> Result, Error> { + seal(keyset, value, kind, context.into_context().into_owned()) +} + +/// Decrypt a [`Ciphertext`] that was encrypted with the empty context. The +/// result is a frame that contains the one scalar. +/// +/// `decrypt` decrypts a ciphertext from [`encrypt`] or from +/// [`KeysetCipher::encrypt`]. `kind` is the kind that the value must have +/// been stored as. Pass `None` to take the value as it was stored. With +/// [`ValueKind::Json`], the frame contains the JSON text of the document as +/// a bytes value. +/// +/// `string` and `json` have one stored form. So an encrypted document +/// decrypts as `string`. An encrypted string whose text is a JSON document +/// decrypts as `json`. The [section on a JSON document](self#a-json-document) +/// describes what `json` checks and returns. +/// +/// Pass `&keyset` to decrypt only a ciphertext of that keyset. `decrypt` +/// then refuses a ciphertext of another keyset before it retrieves any key. +/// Pass `&cipher` to decrypt a ciphertext of any keyset that the client can +/// use. +/// +/// The frame is plaintext. An [`OwnedFrame`] wipes its bytes when it is +/// dropped. +/// +/// With no declared kind, a ciphertext of a null decrypts as the null frame. +/// [`encrypt`] never encrypts a null. +/// [`KeysetCipher::encrypt_tree`](crate::KeysetCipher::encrypt_tree) can +/// encrypt one. +/// +/// ``` +/// use stack_encrypt::dynamic::{frame::OwnedFrame, value, ValueKind}; +/// use stack_encrypt::{Error, StackCipher}; +/// +/// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { +/// // With no `.kms(..)`, the cipher uses ZeroKMS. It reads credentials from +/// // the environment, or from the profile that `npx stash auth login` writes. +/// let cipher = StackCipher::builder() +/// # .kms(stack_encrypt::kms::FakeDataKeySource::new()) +/// .init() +/// .await?; +/// let keyset = cipher.default_keyset(); +/// +/// // A ciphertext that the typed call made. +/// let stored = keyset.encrypt(String::from("ada@example.com")).await?; +/// +/// // The ciphertext decrypts as the kind it was stored as. +/// let email = value::decrypt(&keyset, stored.clone(), Some(ValueKind::String)).await?; +/// assert_eq!(email.frame(), OwnedFrame::of("ada@example.com")?.frame()); +/// +/// // The ciphertext does not decrypt as another kind. The error names the +/// // expected kind, and nothing about the value. +/// let refused = value::decrypt(&keyset, stored, Some(ValueKind::Int64)).await; +/// assert!(matches!(refused, Err(Error::OpenedType { expected: "int64" }))); +/// # Ok::<(), Box>(()) +/// # }).unwrap(); +/// ``` +/// +/// # Many values in one key request +/// +/// Call `decrypt` for each ciphertext, then merge the pending calls with +/// [`Pending::all`]. Awaiting the merged call makes one key request for each +/// keyset that the ciphertexts were encrypted under. The frames come back in +/// the order of the calls. Each call takes its own declared kind. +/// +/// Pass the same cipher or keyset to `Pending::all` as to each `decrypt`. If +/// one value fails, the merged call fails with the error of that value. The +/// frames that were decrypted before that value are dropped. A dropped frame +/// wipes its bytes. +/// +/// ``` +/// use stack_encrypt::dynamic::{frame::OwnedFrame, value, ValueKind}; +/// use stack_encrypt::{Pending, StackCipher}; +/// +/// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { +/// // With no `.kms(..)`, the cipher uses ZeroKMS. It reads credentials from +/// // the environment, or from the profile that `npx stash auth login` writes. +/// let cipher = StackCipher::builder() +/// # .kms(stack_encrypt::kms::FakeDataKeySource::new()) +/// .init() +/// .await?; +/// let keyset = cipher.default_keyset(); +/// +/// // Two ciphertexts of different kinds, as a database returns them. +/// let stored = [ +/// (keyset.encrypt(34u64).await?, Some(ValueKind::UInt64)), +/// (keyset.encrypt(String::from("ada@example.com")).await?, Some(ValueKind::String)), +/// ]; +/// +/// // One call for each ciphertext, with the kind it must decrypt as. +/// let calls: Vec<_> = stored +/// .into_iter() +/// .map(|(ciphertext, kind)| value::decrypt(&keyset, ciphertext, kind)) +/// .collect(); +/// +/// // One key request for both. +/// let opened = Pending::all(&keyset, calls).await?; +/// assert_eq!(opened[0].frame(), OwnedFrame::of(34u64)?.frame()); +/// assert_eq!(opened[1].frame(), OwnedFrame::of("ada@example.com")?.frame()); +/// # Ok::<(), Box>(()) +/// # }).unwrap(); +/// ``` +/// +/// # Errors +/// +/// The pending call fails with the engine's [`Error`](crate::Error), as +/// [`KeysetCipher::decrypt`] does: +/// +/// - [`ForeignKeyset`](crate::Error::ForeignKeyset) for a ciphertext of +/// another keyset, before any key is retrieved. +/// - The error of a key provider. +/// - [`Aead`](crate::Error::Aead) for a wrong context or an altered +/// ciphertext. +/// - [`OpenedType`](crate::Error::OpenedType) for a value that was stored as +/// another kind than `kind`. +/// - [`OpenedType`](crate::Error::OpenedType) for text that is not a JSON +/// document, when `kind` is `json`. +/// +/// `OpenedType` names the kind that was expected. `OpenedType` never says +/// what kind the value had. A ciphertext never contains an array or an +/// object. So `decrypt` fails the same way for those two kinds, before any +/// key is retrieved. +/// +/// [`KeysetCipher::encrypt`]: crate::KeysetCipher::encrypt +/// [`KeysetCipher::decrypt`]: crate::KeysetCipher::decrypt +pub fn decrypt<'a, K: 'static>( + cipher_ref: impl Into>, + ciphertext: Ciphertext, + kind: Option, +) -> Pending<'a, OwnedFrame, K> { + open(cipher_ref.into(), ciphertext, kind, ().into_context()) +} + +/// Decrypt as [`decrypt`] does, with the context that the value was +/// encrypted with. +/// +/// [`KeysetCipher::decrypt_with_context`] does the same for a typed value. +/// +/// # Errors +/// +/// The errors of [`decrypt`]. A context other than the one that the value +/// was encrypted with fails the pending call. +/// +/// [`KeysetCipher::decrypt_with_context`]: crate::KeysetCipher::decrypt_with_context +pub fn decrypt_with_context<'a, 'c, K: 'static>( + cipher_ref: impl Into>, + ciphertext: Ciphertext, + kind: Option, + context: impl IntoContext<'c>, +) -> Pending<'a, OwnedFrame, K> { + open( + cipher_ref.into(), + ciphertext, + kind, + context.into_context().into_owned(), + ) +} + +/// Check that `value` is one scalar that a ciphertext can contain. +/// +/// # Errors +/// +/// [`Error::Value`] with [`Reason::NotAScalar`], for an array, an object, a +/// null, a passthrough, or `undefined`. The error names the kind of the +/// value. +fn one_scalar(value: Frame<'_>) -> Result<(), Error> { + let scalar = match value.kind() { + Some(ValueKind::Array | ValueKind::Object) => false, + Some(_) => true, + // A value of no kind is a null, a passthrough, `undefined`, or a + // scalar of a logical type that this build does not define. The + // leaf format records a logical type that this build does not + // define, so an older build can store a value of a newer type. Such + // a value is one scalar. `seal` stores it as it arrived. + None => !(value.is_null() || value.has_passthrough() || is_undefined(value)), + }; + if scalar { + Ok(()) + } else { + Err(Error::bad_value(Reason::NotAScalar, Found::of_frame(value))) + } +} + +/// Whether `value` is JavaScript's `undefined`. +fn is_undefined(value: Frame<'_>) -> bool { + value + .visit(OneScalar::new(|ty: Option, _: Physical<'_>| { + Ok(ty == Some(Logical::Undefined)) + })) + .unwrap_or(false) +} + +/// Plan the encryption of one value under `context`, as the typed call plans +/// it. Both calls write the value into the same operation, so the leaf has +/// the same form. +fn seal<'a, K: 'static>( + keyset: &'a KeysetCipher<'_, K>, + value: Frame<'_>, + kind: Option, + context: ContextPiece<'static>, +) -> Result, Error> { + one_scalar(value)?; + let sealed = match kind { + None => encrypt_opaque(value, keyset, context), + Some(ValueKind::Json) => { + // A document arrives as text or bytes, so nothing is converted. + let document = read_json(value).map_err(|error| not_a_document(error, value))?; + // The document is encrypted through a borrow. The document is + // wiped when it is dropped here, as the typed call's owned + // document is. + encrypt_opaque(&document, keyset, context) + } + // The conversion also refuses a value that is not of the declared + // kind. A converted value is wiped when it is dropped. + Some(kind) => match convert(kind, value).map_err(|error| of_one_value(error, value))? { + Some(converted) => encrypt_opaque(converted.frame(), keyset, context), + None => encrypt_opaque(value, keyset, context), + }, + }; + Ok(sealed.try_map(Ciphertext::from_tree)) +} + +/// Turn a refusal that the shared conversion made for a record field into +/// the refusal of `value`. The reason stays the same. No field is named. +fn of_one_value(error: Error, value: Frame<'_>) -> Error { + match error.reason() { + Some(reason) => Error::bad_value(reason, Found::of_frame(value)), + None => error, + } +} + +/// The refusal of `value` for the declared kind `json`, when `value` is not +/// a document. +fn not_a_document(error: JsonValueError, value: Frame<'_>) -> Error { + let reason = match error { + JsonValueError::NotText => Reason::FieldType, + JsonValueError::Text(error) => json_reason(error), + }; + Error::bad_value(reason, Found::of_frame(value)) +} + +/// The error for a value that was stored as another kind than the declared +/// kind. The error names only the declared kind. +fn not_opened_as(kind: ValueKind) -> crate::Error { + crate::Error::OpenedType { + expected: kind.name(), + } +} + +/// Whether a ciphertext can contain a value of `kind`. A ciphertext contains +/// one scalar, so it never contains an array or an object. +fn is_scalar_kind(kind: ValueKind) -> bool { + !matches!(kind, ValueKind::Array | ValueKind::Object) +} + +/// Decrypt one ciphertext under `context` into an [`OwnedFrame`], as the +/// typed call does. Then check the value against `kind`. +fn open<'a, K: 'static>( + cipher_ref: CipherRef<'a, K>, + ciphertext: Ciphertext, + kind: Option, + context: ContextPiece<'static>, +) -> Pending<'a, OwnedFrame, K> { + if let Some(kind) = kind.filter(|kind| !is_scalar_kind(*kind)) { + return Pending::failed(cipher_ref, not_opened_as(kind)); + } + let opened = + OwnedFrame::decrypt_from_with_context(ciphertext, cipher_ref, ScalarContext::from(context)); + match kind { + None => opened, + Some(kind) => opened.try_map(move |value| opened_as(kind, value)), + } +} + +/// Return the decrypted `value` as a value of `kind`. For a document, that +/// is the JSON text as a bytes value. For every other kind, that is the +/// value itself. +/// +/// # Errors +/// +/// [`crate::Error::OpenedType`] that names `kind`, for a value of another +/// kind. A refused frame is dropped, and a dropped frame wipes its bytes. +fn opened_as(kind: ValueKind, value: OwnedFrame) -> Result { + if kind == ValueKind::Json { + return document_frame(&value); + } + if kind.holds(value.frame().kind()) { + Ok(value) + } else { + Err(not_opened_as(kind)) + } +} + +/// The document in a decrypted JSON value, in the form that a `json` field +/// decrypts to: the JSON text as a bytes value. +/// +/// # Errors +/// +/// [`crate::Error::OpenedType`] for a value that is not text that contains a +/// document. The typed call's `JsonPlaintext` refuses the same values. +fn document_frame(value: &OwnedFrame) -> Result { + let document = value + .visit(OneScalar::new( + |ty: Option, value: Physical<'_>| match (ty, value) { + (None, Physical::Text(text)) => JsonPlaintext::parse(text).map_err(|_| None), + _ => Err(None), + }, + )) + .map_err(|_| not_opened_as(ValueKind::Json))?; + super::json_frame(document.value()) +} diff --git a/packages/stack-encrypt/src/lib.rs b/packages/stack-encrypt/src/lib.rs index eac8764e7..077268c39 100644 --- a/packages/stack-encrypt/src/lib.rs +++ b/packages/stack-encrypt/src/lib.rs @@ -370,12 +370,19 @@ endpoint — are `StackKmsBuilder`'s, and the two keyset-cache knobs are //! human-readable format such as JSON, raw bytes in a binary one. Parsing //! does not authenticate a value; decryption does. //! -//! The scalar API accepts owned [`OpaqueEncode`] values. It wipes the owned source -//! before returning the pending request, including on planning failure. A -//! successful decrypt returns an ordinary owned value: the caller is then +//! The scalar API accepts owned [`OpaqueEncode`] values. The API wipes the +//! owned source before it returns the pending request, including when +//! planning fails. +//! +//! A ciphertext decrypts into an [`OpaqueDecode`] type: a type that is built +//! from one scalar. A target that needs a container, such as a +//! `Vec`, does not compile. +//! +//! A successful decrypt returns an ordinary owned value. The caller is then //! responsible for its cleanup. A whole value decrypted as an -//! [`OpaqueBlob`](crate::OpaqueBlob) is wiped on drop. Copy types may still have copies held by the -//! caller, and this is not a guarantee about every compiler-generated copy. +//! [`OpaqueBlob`](crate::OpaqueBlob) is wiped on drop. The caller can +//! still have copies of a `Copy` type. This crate makes no guarantee about +//! the copies that the compiler generates. //! //! For target-directed conversion, import [`EncryptInto`] and [`DecryptFrom`]: //! @@ -672,6 +679,11 @@ endpoint — are `StackKmsBuilder`'s, and the two keyset-cache knobs are //! module (feature `dynamic`). The guide to building such a binding, with //! the Go SDK as the reference, is `dynamic::guide`. //! +//! A binding has each value as a frame: one value written as bytes. The kind +//! of the value is only known when the code runs. `dynamic::value` encrypts +//! such a value as one [`Ciphertext`], and decrypts a ciphertext into a +//! frame. The typed [`KeysetCipher::decrypt`] decrypts the same ciphertext. +//! //! # Relationship to vitaminc //! //! A `KeysetCipher` seals through a vitaminc `Cipher`; everything vitaminc @@ -778,7 +790,7 @@ pub use target::{ // derivations see the same bytes. pub use vitaminc_aead::{ CipherText, Context, ContextPiece, ContextTag, DecodeError, Decrypt, Encrypt, EncryptRef, - IntoAad, IntoContext, Node, PassthroughFrame, Unspecified, + IntoAad, IntoContext, Node, PassthroughFrame, ScalarTarget, Unspecified, }; /// A type with an order target of its own: what an order index /// ([`Ore`], [`Ope`], [`OreBlock`]), an order term ([`sem::OreTerm`], diff --git a/packages/stack-encrypt/src/refusal.rs b/packages/stack-encrypt/src/refusal.rs index 611c434f7..ed4bc34c5 100644 --- a/packages/stack-encrypt/src/refusal.rs +++ b/packages/stack-encrypt/src/refusal.rs @@ -61,9 +61,11 @@ use crate::target::IndexSpec; /// Some operations take an object: a plan, a record to encrypt, or a /// stored record to decrypt. When the caller passes another kind of value, /// the error names that kind as a [`Found`]. For example, the error says -/// that the record is a null or an array. The error never includes the -/// value. The kind is in the message, in [`found`](Self::found), and in the -/// payload field `found`. +/// that the record is a null or an array. An error about one value to +/// encrypt as a single ciphertext ([`Value`](Error::Value)) always names +/// the kind of that value. The error never includes the value. The kind is +/// in the message, in [`found`](Self::found), and in the payload field +/// `found`. /// /// An error names a kind only when the engine can read that kind without /// decrypting anything. There are two such kinds: @@ -95,13 +97,19 @@ use crate::target::IndexSpec; /// Not every variant has a [`Reason`]. These variants have one: /// [`Context`](Error::Context), [`Plan`](Error::Plan), /// [`Source`](Error::Source), [`SourceFailed`](Error::SourceFailed), -/// [`Record`](Error::Record), and [`Predicate`](Error::Predicate). The -/// reason is in the message, in [`reason`](Self::reason), and in the payload -/// (`reason`). The others carry their own payload fields instead: -/// [`Term`](Error::Term) names the index it was asked for (`index`), -/// [`UntypedIndex`](Error::UntypedIndex) the field (`field`), `Target` and -/// `Cipher` carry the payload of the error they hold, and `Internal` carries -/// none. A binding reads `reason` when it is there, and does not require it. +/// [`Record`](Error::Record), [`Predicate`](Error::Predicate), and +/// [`Value`](Error::Value). The reason is in the message, in +/// [`reason`](Self::reason), and in the payload (`reason`). +/// +/// The other variants have payload fields of their own: +/// +/// - [`Term`](Error::Term) names the index that was asked for (`index`). +/// - [`UntypedIndex`](Error::UntypedIndex) names the field (`field`). +/// - `Target` and `Cipher` have the payload of the error they wrap. +/// - `Internal` has no payload. +/// +/// A binding reads `reason` when it is present. A binding must not require +/// it. /// /// `Debug` prints no text from the caller's own code. The cause of a /// [`SourceFailed`](Error::SourceFailed) is a @@ -343,6 +351,38 @@ pub enum Error { at: usize, }, + /// One value cannot be encrypted as a single ciphertext. Only + /// [`value::encrypt`](crate::dynamic::value::encrypt) and + /// [`value::encrypt_with_context`](crate::dynamic::value::encrypt_with_context) + /// return this error. The cause is one of these: + /// + /// - The value is an array, an object, a passthrough, a null, or + /// `undefined`. + /// - The value is of another kind than the declared kind, with no exact + /// conversion to the declared kind. + /// - The text of the value is not a JSON document, when the declared + /// kind is `json`. + /// + /// The error names no field, because there is no record. The error + /// names the kind of the value to encrypt as a [`Found`]. The kind is in + /// the message, in [`found`](Self::found), and in the payload field + /// `found`. The error never contains the value. + /// + /// The kind is always the kind of the value that the caller sent. A + /// refused decrypt is not this error, and never names the kind of the + /// decrypted value. + #[error("{}", value_text(*reason, *found))] + #[diagnostic( + code(stack_encrypt::dynamic_value), + help("One ciphertext contains one scalar that is present. A scalar is text, a number, a boolean, bytes, a date, a timestamp, a decimal, a UUID, or a JSON document. To encrypt a list, encrypt each value separately. Store an absent value as a database NULL.") + )] + Value { + /// What was wrong with the value. + reason: Reason, + /// The kind of the value to encrypt. + found: Found, + }, + /// An invariant this module maintains did not hold — a slot count that /// did not line up, a re-proof that should not have been able to fail. /// Always a bug here, never a statement about the caller's data. @@ -375,6 +415,34 @@ fn in_field_text(field: &Option) -> String { .unwrap_or_default() } +/// The message of an [`Error::Value`]. +/// +/// The message is one sentence that starts with the kind of the value to +/// encrypt. There are three forms: +/// +/// - For [`Reason::NotAScalar`], the message says that the value is not a +/// scalar. An example is `the value to encrypt is an array, not a scalar`. +/// - For [`Reason::FieldType`], the message says that the value does not +/// convert to the declared kind. A record's message for that reason names +/// a field, and one value has no field. +/// - For every other reason, the message ends with the reason. For +/// example, the message can end with `a JSON object names a member +/// twice`. +fn value_text(reason: Reason, found: Found) -> String { + match reason { + Reason::NotAScalar => format!("the value to encrypt is {found}, not a scalar"), + Reason::FieldType => format!( + "the value to encrypt is {found}, and does not convert exactly to the declared kind" + ), + Reason::JsonSyntax | Reason::JsonDuplicateKey | Reason::JsonIntegerRange => format!( + "the value to encrypt is {found}, and its text is not a JSON document: {reason}" + ), + reason => { + format!("the value to encrypt is {found}, and cannot be encrypted: {reason}") + } + } +} + /// The end of the message of an error that can name a row and a field. /// /// The text is ` (row 2, field "age")`, ` (row 2)`, ` (field "age")`, or an @@ -541,6 +609,12 @@ fn misfit_text( } impl Error { + /// An error for one value that cannot be encrypted as a single + /// ciphertext. `found` is the kind of that value. + pub(crate) fn bad_value(reason: Reason, found: Found) -> Self { + Self::Value { reason, found } + } + /// A context error with no field named yet. pub(crate) fn bad_context(reason: Reason) -> Self { Self::Context { @@ -615,7 +689,7 @@ impl Error { Self::UntypedIndex { field } => Some(field), #[cfg(feature = "dynamic")] Self::Target(_) => None, - Self::Internal | Self::Cipher(_) => None, + Self::Value { .. } | Self::Internal | Self::Cipher(_) => None, } } @@ -637,15 +711,16 @@ impl Error { } } - /// What was wrong, for a context, plan, source, record or predicate - /// error. + /// What was wrong, for a context, plan, source, record, predicate, or + /// single-value error. pub fn reason(&self) -> Option { match self { Self::Context { reason, .. } | Self::Plan { reason, .. } | Self::Source { reason, .. } | Self::Record { reason, .. } - | Self::Predicate { reason, .. } => Some(*reason), + | Self::Predicate { reason, .. } + | Self::Value { reason, .. } => Some(*reason), Self::SourceFailed { .. } => Some(Reason::SourceFailed), #[cfg(feature = "dynamic")] Self::Target(_) => None, @@ -676,18 +751,23 @@ impl Error { } } - /// The kind of value that the caller passed where the operation takes - /// an object. + /// The kind of value that the caller passed, where the operation does + /// not take that kind. + /// + /// - For [`Reason::NotAnObject`], the value is a plan, a field spec, a + /// record source, a stored record, or a row of a batch. + /// - For [`Reason::JsonVarsNotObject`], the value is the vars of a + /// `match` query. + /// - For [`Error::Value`], the value is the one value to encrypt. Every + /// `Value` error names its kind. /// - /// For [`Reason::NotAnObject`], the value is a plan, a field spec, a - /// record source, a stored record, or a row of a batch. For - /// [`Reason::JsonVarsNotObject`], the value is the vars of a `match` - /// query. `None` for every other error. + /// `None` for every other error. pub fn found(&self) -> Option { match self { Self::Plan { found, .. } | Self::Source { found, .. } | Self::Record { found, .. } => { *found } + Self::Value { found, .. } => Some(*found), _ => None, } } @@ -885,6 +965,12 @@ reasons! { /// A passthrough value cannot be stored as a frame: it nests deeper, /// or holds text, bytes or a key longer, than a frame carries. Unframeable => "unframeable", "a passthrough value nests deeper, or holds a longer value, than a frame carries"; + /// A value to encrypt as one ciphertext is not a scalar that is + /// present. The value is an array, an object, a null, a + /// passthrough, or `undefined`. The null can be plain or typed. + /// [`Error::found`] returns the kind of the value + /// ([`value::encrypt`](crate::dynamic::value::encrypt)). + NotAScalar => "not_a_scalar", "the value is not a scalar, and one ciphertext contains one scalar"; /// A stored field is not a map of outputs. OutputsNotMap => "outputs_not_map", "a stored field is not a map of outputs"; /// A stored sealed field has no `"c"` node. diff --git a/packages/stack-encrypt/src/scalar.rs b/packages/stack-encrypt/src/scalar.rs index 553be5448..54dab925a 100644 --- a/packages/stack-encrypt/src/scalar.rs +++ b/packages/stack-encrypt/src/scalar.rs @@ -4,8 +4,9 @@ use crate::target::{ DecryptFrom, DecryptSource, Decryption, EncryptInto, EncryptTarget, Encryption, OptionalContext, Pending, ScalarContext, }; -use crate::{CipherText, ContextPiece, Decrypt, Error, KeysetCipher, LeafBytesError, SealedValue}; +use crate::{CipherText, ContextPiece, Error, KeysetCipher, LeafBytesError, SealedValue}; use vitaminc_aead::plaintext::Scalar; +use vitaminc_aead::ScalarTarget; use vitaminc_protected::OpaqueDebug; use zeroize::Zeroize; @@ -111,20 +112,117 @@ pub trait OpaqueEncode: sealed::Encode + Zeroize + Send + 'static {} /// A plaintext type that one opaque [`Ciphertext`] decrypts to. /// -/// `OpaqueDecode` is implemented for every [`Decrypt`] type that also -/// implements [`Zeroize`], and for [`OpaqueBlob`](crate::OpaqueBlob). -/// The `Decrypt` types include each scalar, such as `String`, and a -/// [`Protected`](vitaminc_protected::Protected) of one, such as -/// `Protected`. The trait is sealed, as `OpaqueEncode` is. +/// A `Ciphertext` contains one scalar. So `OpaqueDecode` is implemented for +/// every type that meets two conditions: +/// +/// - The type is built from one scalar. Vitamin C names such a type a +/// [`ScalarTarget`]. +/// - The type implements [`Zeroize`] and `Send`, and is `'static`. A +/// `'static` type borrows no data. +/// +/// The `OpaqueDecode` types are: +/// +/// - each scalar: `bool`, the fixed-width integers other than `u8`, the +/// floats, `String`, `Vec`, and `[u8; N]` +/// - the date, timestamp, decimal, and UUID [values](crate::value) +/// - [`JsonPlaintext`](crate::json::JsonPlaintext), a JSON document +/// - a [`Protected`](vitaminc_protected::Protected) of one, such as +/// `Protected` +/// - an `Option` of one, such as `Option`. An encrypted null decrypts +/// as `None`. +/// - a newtype that derives [`Decrypt`](crate::Decrypt) over one, such as +/// `struct Email(String)` +/// - an `OwnedFrame`: the value written as bytes, for a caller that only +/// learns the kind of the value when the code runs +/// +/// [`OpaqueBlob`](crate::OpaqueBlob) is an `OpaqueDecode` type too. The +/// trait is sealed, as `OpaqueEncode` is. +/// +/// A target that needs a container does not compile: +/// +/// - a `Vec` of anything but bytes +/// - a map +/// - a struct that derives `Decrypt` with named fields +/// +/// Each of those targets reads a tree of leaves. A leaf is one encrypted +/// scalar. A tree of leaves is a +/// [`StackCipherText`](crate::StackCipherText), and +/// [`KeysetCipher::decrypt_tree`] decrypts it. +/// +/// A column of ciphertexts is a `Vec`. A `Vec` +/// decrypts into a `Vec` through [`DecryptFrom`]. The +/// [crate docs on collections](crate#collections) explain how. +/// +/// ```compile_fail,E0277 +/// # fn example(keyset: &stack_encrypt::KeysetCipher<'_, K>, ciphertext: stack_encrypt::Ciphertext) { +/// // A ciphertext contains one scalar, never a sequence. +/// let _ = keyset.decrypt::>(ciphertext); +/// # } +/// ``` +/// +/// A type of your own is an `OpaqueDecode` type when it meets the same two +/// conditions. You cannot implement `ScalarTarget` for it: a type is a +/// `ScalarTarget` because of how it decrypts. A newtype that derives +/// `Decrypt` over a scalar meets the first condition with no extra code. So +/// does a type that implements Vitamin C's `FromScalar`. +/// +/// For the second condition, derive or implement `Zeroize`. A type that +/// borrows data is not `'static`, so it is refused. +/// +/// The derive is Vitamin C's, so your crate needs `vitaminc-aead` as a +/// dependency to use it. +/// +/// ``` +/// # async fn example() -> Result<(), stack_encrypt::Error> { +/// use stack_encrypt::{Decrypt, StackCipher}; +/// use zeroize::Zeroize; +/// +/// #[derive(Decrypt, Zeroize)] +/// struct Email(String); +/// +/// // With no `.kms(..)`, the cipher uses ZeroKMS. It reads credentials from +/// // the environment, or from the profile that `npx stash auth login` writes. +/// let cipher = StackCipher::builder() +/// # .kms(stack_encrypt::kms::FakeDataKeySource::new()) +/// .init() +/// .await?; +/// let keyset = cipher.default_keyset(); +/// let stored = keyset.encrypt(String::from("ada@example.com")).await?; +/// +/// let email: Email = keyset.decrypt(stored).await?; +/// assert_eq!(email.0, "ada@example.com"); +/// # Ok(()) +/// # } +/// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(example()).unwrap(); +/// ``` /// /// A scalar decrypted into a bare type, such as `String`, is an ordinary /// owned value, and nothing wipes it when it is dropped: `Zeroize` is the /// bound, not a drop guard. Decrypt into a `Protected` to have it wiped on /// drop. A decrypted `OpaqueBlob` also wipes its value on drop. -/// -/// A `Ciphertext` holds one scalar. A target that is not a scalar, such as -/// `Vec`, compiles, but decryption refuses it with -/// [`Error::OpenedType`]. +#[diagnostic::on_unimplemented( + message = "`{Self}` cannot be decrypted from one `Ciphertext`", + label = "one `Ciphertext` decrypts into one owned value", + note = "one value is a scalar, such as a `String`, a `bool`, a float, a `Vec`, or a \ + fixed-width integer other than `u8`. The docs of `OpaqueDecode` list every type \ + that is accepted.", + note = "an `Option` or a `Protected` of a scalar is one value too. So is a newtype that \ + derives `Decrypt` over a scalar.", + note = "for a date, a timestamp, a decimal, or a UUID, use `value::Date`, \ + `value::Timestamp`, `value::Decimal`, or `value::Uuid`. A `uuid::Uuid`, a \ + `rust_decimal::Decimal`, and the jiff types do not implement `Zeroize`.", + note = "the type must also implement `Zeroize`, so that a decrypted value can be wiped when \ + a later decrypt in the same call fails.", + note = "the type must also be `Send` and `'static`. A `'static` type borrows no \ + data.", + note = "to decrypt a `Vec` into a `Vec`, with one element from each \ + `Ciphertext`, use `DecryptFrom`.", + note = "to decrypt a sequence, a map, or a struct that derives `Decrypt`, use \ + `keyset.decrypt_tree`. `keyset.encrypt_tree` makes the tree of ciphertexts that it \ + reads.", + note = "to decrypt a whole `Deserialize` value from one `Ciphertext`, decrypt into \ + `OpaqueBlob`. `T` must also implement `Default` and `Zeroize`." +)] pub trait OpaqueDecode: sealed::Decode + Zeroize + Send + 'static {} // An owned `S` is sealed through a borrow of it. `&S` is one of Vitamin C's @@ -150,7 +248,7 @@ where for<'a> &'a S: Scalar, { } -impl sealed::Decode for P { +impl sealed::Decode for P { fn open<'a, K: 'static>( leaf: SealedValue, cipher: &'a crate::StackCipher, @@ -159,7 +257,12 @@ impl sealed::Decode for P { crate::target::core::open_opaque(CipherText::Single(leaf), cipher, context) } } -impl OpaqueDecode for P {} +// `do_not_recommend` makes the compiler report a refused type against +// `OpaqueDecode`. The message of `OpaqueDecode` says what one `Ciphertext` +// decrypts into, and what to use instead. Without the attribute, the +// compiler reports the bound below that failed, in Vitamin C's terms. +#[diagnostic::do_not_recommend] +impl OpaqueDecode for P {} /// One opaque ciphertext, with no exposed structural node variants. /// diff --git a/packages/stack-encrypt/tests/common/conformance.rs b/packages/stack-encrypt/tests/common/conformance.rs index ed4aecb07..d5218ecd4 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/common/leaves.rs b/packages/stack-encrypt/tests/common/leaves.rs new file mode 100644 index 000000000..41a4a276d --- /dev/null +++ b/packages/stack-encrypt/tests/common/leaves.rs @@ -0,0 +1,205 @@ +//! Read the plaintext of a sealed leaf. +//! +//! A sealed leaf is one encrypted scalar inside a ciphertext. Each sealed +//! leaf has a random AES-GCM nonce, so two ciphertexts of one value never +//! have the same bytes. A test can compare the plaintext that each leaf was +//! sealed with. +//! +//! [`kept_cipher`] is a cipher over [`DeterministicSource`] that keeps each +//! data key it generates. [`reveal`] opens leaves with those keys, and with +//! the additional authenticated data (AAD) that the engine uses for a leaf. + +use std::borrow::Cow; +use std::cell::RefCell; +use std::collections::HashMap; +use std::sync::{Arc, Mutex}; + +use stack_encrypt::{CipherText, Ciphertext, SealedValue, StackCipher, StackCipherText}; +use stack_kms::{ + DataKey, DataKeySource, DataKeyWithTag, GenerateKeyPayload, IdentifiedBy, IndexKey, + IndexKeySource, RetrieveKeyPayload, UnverifiedContext, +}; +use uuid::Uuid; +use vitaminc_aead::seal::Cipher; +use vitaminc_aead::{Context, FrameWriter, IntoContext, LocalCipherText, Unspecified}; +use vitaminc_encrypt::{Aes256Cipher, Key as AesKey}; +use vitaminc_protected::{Buffer, Controlled as _, Protected}; + +use super::{hex, DeterministicSource}; + +/// The data keys that a [`KeptKeys`] source generated, by IV. +pub type Kept = Mutex, [u8; 32]>>; + +/// [`DeterministicSource`], with each data key it generates kept by its IV. +/// A test can then open the leaves sealed under those keys without the +/// engine. +pub struct KeptKeys { + inner: DeterministicSource, + keys: Arc, +} + +impl stack_kms::KeySourceKind for KeptKeys { + type Kind = stack_kms::OwnIdentity; +} + +impl DataKeySource for KeptKeys { + async fn generate_keys( + &self, + payloads: Vec>, + keyset_id: Option, + unverified_context: Option>, + ) -> Result, stack_kms::Error> { + let keys = self + .inner + .generate_keys(payloads, keyset_id, unverified_context) + .await?; + let mut kept = self.keys.lock().unwrap(); + for key in &keys { + let _ = kept.insert(key.key.iv.to_vec(), *key.key.key()); + } + Ok(keys) + } + + async fn retrieve_keys( + &self, + payloads: Vec>, + keyset_id: Option, + unverified_context: Option<&UnverifiedContext>, + ) -> Result, stack_kms::Error> { + self.inner + .retrieve_keys(payloads, keyset_id, unverified_context) + .await + } +} + +impl IndexKeySource for KeptKeys { + async fn load_index_key( + &self, + keyset_id: Option, + ) -> Result<(Uuid, IndexKey), stack_kms::Error> { + self.inner.load_index_key(keyset_id).await + } +} + +/// A cipher over the kept keys of `seed`, and the keys. +pub async fn kept_cipher(seed: [u8; 32]) -> (StackCipher, Arc) { + let keys = Arc::default(); + let cipher = StackCipher::builder() + .kms(KeptKeys { + inner: DeterministicSource::new(seed), + keys: Arc::clone(&keys), + }) + .init() + .await + .expect("build cipher"); + (cipher, keys) +} + +/// A vitaminc cipher that opens a stored leaf with its kept key, and keeps +/// each plaintext it opened, in walk order. +/// +/// The cipher opens the leaf under the AAD that the engine binds a leaf to. +/// That AAD is a pre-authentication encoding (PAE) of five parts: +/// +/// - the text `stack-encrypt/leaf` +/// - the format version +/// - the keyset +/// - the AAD of the leaf's place +/// - the key tag +struct Reveal<'k> { + keys: &'k HashMap, [u8; 32]>, + opened: RefCell>, +} + +impl Cipher for Reveal<'_> { + type Leaf = SealedValue; + type Error = Unspecified; + + fn seal(&self, _: Protected>, _: &Context<'_>) -> Result { + Err(Unspecified) + } + + fn open( + &self, + leaf: SealedValue, + aad: &Context<'_>, + ) -> Result>, Unspecified> { + let (keyset_id, iv, tag, ciphertext) = leaf.into_parts(); + let key = self.keys.get(iv.as_slice()).ok_or(Unspecified)?; + let aad = Context::pae(&[ + b"stack-encrypt/leaf", + &[SealedValue::FORMAT_VERSION], + keyset_id.as_bytes(), + aad.as_bytes(), + &tag, + ]); + let cipher = Aes256Cipher::new(&AesKey::from(*key))?; + let plaintext = cipher.open(LocalCipherText::from(ciphertext), &aad)?; + self.opened.borrow_mut().push(hex(plaintext.risky_ref())); + Ok(plaintext) + } +} + +/// The plaintext of every leaf of `tree`, sealed under `context`, in walk +/// order. The plaintext of a scalar is its tagged bytes. The plaintext of a +/// typed null is its padded bytes. The plaintext of an empty container is +/// its marker, shown as the empty string. +pub fn reveal<'c>( + keys: &Kept, + tree: StackCipherText, + context: impl IntoContext<'c>, +) -> Vec { + let keys = keys.lock().unwrap(); + let reveal = Reveal { + keys: &keys, + opened: RefCell::default(), + }; + let mut out = Buffer::default(); + vitaminc_aead::decrypt_into( + &reveal, + tree, + context.into_context(), + FrameWriter::new(&mut out), + ) + .unwrap_or_else(|_| { + panic!( + "the leaves open under their kept keys: if every case fails here, \ + the AAD `Reveal` builds no longer mirrors `leaf_aad` in src/cipher.rs" + ) + }); + reveal.opened.into_inner() +} + +/// Every part of a single ciphertext that does not depend on the nonce of +/// its leaf. Two ciphertexts of one value, sealed under the same data key +/// and context, have the same parts and different bytes. +#[derive(Debug, PartialEq, Eq)] +pub struct Parts { + /// The bytes of the ciphertext before the output of the leaf's + /// authenticated encryption (AEAD), in hex. Those bytes are the format + /// version, the keyset, the IV of the data key, and the key tag with its + /// length. + pub header: String, + /// The length of the whole ciphertext in bytes. + pub len: usize, + /// The plaintext that the leaf was sealed with, in hex: its tag and payload. + pub leaf: String, +} + +/// The parts of `ciphertext`, a ciphertext sealed under `context`. The kept +/// keys in `keys` open its leaf. +pub fn parts<'c>(keys: &Kept, ciphertext: Ciphertext, context: impl IntoContext<'c>) -> Parts { + let bytes = ciphertext.to_bytes(); + // The AEAD output of the leaf is the last part of the bytes: the nonce, + // the encrypted plaintext, and the authentication tag. + let (_, _, _, sealed) = SealedValue::from(ciphertext.clone()).into_parts(); + let header = hex(&bytes[..bytes.len() - sealed.len()]); + let leaf = SealedValue::from(ciphertext); + let mut leaves = reveal(keys, CipherText::Single(leaf), context); + assert_eq!(leaves.len(), 1, "a ciphertext is one leaf"); + Parts { + header, + len: bytes.len(), + leaf: leaves.remove(0), + } +} diff --git a/packages/stack-encrypt/tests/common/mod.rs b/packages/stack-encrypt/tests/common/mod.rs index da2fca6bd..27d931c49 100644 --- a/packages/stack-encrypt/tests/common/mod.rs +++ b/packages/stack-encrypt/tests/common/mod.rs @@ -387,3 +387,4 @@ pub fn unhex(text: &str) -> Vec { } #[cfg(feature = "dynamic")] pub mod conformance; +pub mod leaves; diff --git a/packages/stack-encrypt/tests/scalar.rs b/packages/stack-encrypt/tests/scalar.rs index 3a568025a..6a9f66df9 100644 --- a/packages/stack-encrypt/tests/scalar.rs +++ b/packages/stack-encrypt/tests/scalar.rs @@ -112,22 +112,33 @@ async fn a_scalar_decrypts_straight_into_a_protected() { } #[tokio::test] -async fn a_ciphertext_opens_only_as_a_scalar_whatever_the_target() { - // A `Ciphertext` holds one scalar. The bound is `Decrypt`, so a target - // that is not a scalar compiles. Opening refuses a sequence, and reads a - // nullable target as present. +async fn a_ciphertext_opens_as_a_nullable_target() { + // A `Ciphertext` contains one scalar, so its target must be built from one + // scalar. A sequence does not compile + // (`tests/ui/scalar_decrypt_into_a_container.rs`). A nullable target + // compiles. That target reads a value as present, and an encrypted null + // as absent. let cipher = common::stack_cipher().await; let keyset = cipher.default_keyset(); - let ct = keyset - .encrypt("alice@example.com".to_owned()) - .await - .unwrap(); - assert!(matches!( - keyset.decrypt::>(ct).await, - Err(Error::OpenedType { .. }) - )); let ct = keyset.encrypt(42i32).await.unwrap(); - assert_eq!(keyset.decrypt::>(ct).await.unwrap(), Some(42)); + assert_eq!( + keyset.decrypt::>(ct).await.unwrap(), + Some(42), + "a value opens as present" + ); + + let node = keyset.encrypt_tree(None::, "users/age").await.unwrap(); + let stack_encrypt::CipherText::Single(leaf) = node else { + panic!("a null seals as one leaf") + }; + assert_eq!( + keyset + .decrypt_with_context::>(Ciphertext::from(leaf), "users/age") + .await + .unwrap(), + None, + "a sealed null opens as absent" + ); } #[tokio::test] diff --git a/packages/stack-encrypt/tests/single_value.rs b/packages/stack-encrypt/tests/single_value.rs new file mode 100644 index 000000000..1a38f94ff --- /dev/null +++ b/packages/stack-encrypt/tests/single_value.rs @@ -0,0 +1,1251 @@ +//! Tests that the run-time interface (`dynamic::value`) and the typed +//! interface (`keyset.encrypt`, `keyset.decrypt`) agree on one value as one +//! ciphertext. +//! +//! In these tests, "seal" means encrypt and authenticate a value. "Open" +//! means decrypt a ciphertext and check it. A leaf is the one sealed scalar +//! inside a ciphertext. +//! +//! Each sealed leaf has a random AES-GCM nonce, so two ciphertexts of one +//! value never have the same bytes. The two interfaces must agree on every +//! other part: +//! +//! - the bytes before the output of the leaf's authenticated encryption: +//! the format version, the keyset, and the IV and tag of the data key +//! - the length of the ciphertext +//! - the plaintext that the leaf was sealed with +//! +//! The tests seal each value through both interfaces, and compare those +//! parts. Each interface gets a new deterministic key source with the same +//! seed. The tests also open the ciphertext of each interface through the +//! other interface. +// The typed `Uuid` case needs the `uuid` feature. The `dynamic` feature +// does not turn `uuid` on. +#![cfg(all(feature = "dynamic", feature = "uuid"))] + +mod common; + +use std::sync::atomic::Ordering; + +use common::frames::{frame, owned}; +use common::leaves::{kept_cipher, parts, Parts}; +use miette::Diagnostic as _; +use proptest::prelude::*; +use serde_json::json; +use stack_encrypt::dynamic::{self, frame::OwnedFrame, value, Found, Reason, ValueKind}; +use stack_encrypt::json::JsonPlaintext; +use stack_encrypt::kms::IdentifiedBy; +use stack_encrypt::value::{Date, Decimal, Timestamp, Uuid as UuidValue}; +use stack_encrypt::{CipherText, Ciphertext, ContextPiece, Error, IntoContext, OpaqueEncode}; +use vitaminc_aead::frame::PASSTHROUGH; +use vitaminc_aead::plaintext::{FixedType, Int, Logical, Physical, Raw, Width}; + +const SEED: [u8; 32] = *b"stack-encrypt single value v1 "; + +/// A context that a test seals under, other than the empty context. +fn column() -> ContextPiece<'static> { + ("users", "value").into_context().into_owned() +} + +/// The empty context. `keyset.encrypt` and `value::encrypt` use it. +fn no_context() -> ContextPiece<'static> { + ().into_context() +} + +/// `value` sealed by the typed call, over a new key source of the seed. +async fn typed(value: S, context: &ContextPiece<'static>) -> (Ciphertext, Parts) { + let (cipher, keys) = kept_cipher(SEED).await; + let sealed = cipher + .default_keyset() + .encrypt_with_context(value, context.clone()) + .await + .expect("the typed call seals"); + (sealed.clone(), parts(&keys, sealed, context.clone())) +} + +/// `value` sealed by the run-time call, over a new key source of the seed. +async fn run_time( + value: &OwnedFrame, + kind: Option, + context: &ContextPiece<'static>, +) -> (Ciphertext, Parts) { + let (cipher, keys) = kept_cipher(SEED).await; + let sealed = value::encrypt_with_context( + &cipher.default_keyset(), + value.frame(), + kind, + context.clone(), + ) + .expect("the run-time call takes the value") + .await + .expect("the run-time call seals"); + (sealed.clone(), parts(&keys, sealed, context.clone())) +} + +/// The run-time call and the typed call seal the same parts for one value, +/// and each call opens the ciphertext of the other. `typed_value` builds the +/// typed value. `frame_of` builds the frame that a binding passes. `stored` +/// builds the frame that the value opens as. +async fn assert_same_ciphertext( + name: &str, + typed_value: impl Fn() -> S, + frame_of: &OwnedFrame, + kind: Option, + stored: &OwnedFrame, + read_back: impl Fn(&T) -> OwnedFrame, +) where + S: OpaqueEncode, + T: stack_encrypt::OpaqueDecode, +{ + for context in [no_context(), column()] { + let (typed_ciphertext, typed_parts) = typed(typed_value(), &context).await; + let (run_time_ciphertext, run_time_parts) = run_time(frame_of, kind, &context).await; + assert_eq!( + run_time_parts, typed_parts, + "{name}: the run-time ciphertext differs from the typed one in a part that is not the nonce" + ); + + let (cipher, _) = kept_cipher(SEED).await; + let keyset = cipher.default_keyset(); + let opened: T = keyset + .decrypt_with_context(run_time_ciphertext, context.clone()) + .await + .unwrap_or_else(|error| { + panic!("{name}: the typed call opens the run-time ciphertext: {error}") + }); + assert_eq!( + read_back(&opened).frame(), + stored.frame(), + "{name}: the typed call reads another value from the run-time ciphertext" + ); + let opened = value::decrypt_with_context(&keyset, typed_ciphertext, None, context.clone()) + .await + .unwrap_or_else(|error| { + panic!("{name}: the run-time call opens the typed ciphertext: {error}") + }); + assert_eq!( + opened.frame(), + stored.frame(), + "{name}: the run-time call reads another value from the typed ciphertext" + ); + } +} + +fn int(int: Int) -> OwnedFrame { + frame(Raw(None, Physical::Int(int))) +} + +fn date() -> Date { + Date::new("2024-02-29".parse::().expect("a date")) +} + +fn timestamp() -> Timestamp { + Timestamp::new( + "2026-10-17T01:02:03.123456789Z" + .parse::() + .expect("an instant"), + ) + .expect("in range") +} + +fn decimal() -> Decimal { + Decimal::new( + "-1234.5600" + .parse::() + .expect("a decimal"), + ) +} + +fn uuid_value() -> UuidValue { + UuidValue::new(uuid::Uuid::from_u128( + 0x123e_4567_e89b_12d3_a456_4266_1417_4000, + )) +} + +mod the_run_time_ciphertext_is_the_typed_one { + use super::*; + + /// A value of a Rust type whose frame is of the same kind. The test + /// runs with the kind declared and with no declared kind. + macro_rules! same { + ($name:literal, $kind:expr, $ty:ty, $value:expr) => {{ + let stored = frame($value); + for declared in [None, Some($kind)] { + assert_same_ciphertext( + $name, + || $value, + &stored, + declared, + &stored, + |opened: &$ty| frame(opened), + ) + .await; + } + }}; + } + + #[tokio::test] + async fn for_every_scalar_kind_a_rust_type_spells() { + same!("bool", ValueKind::Bool, bool, true); + same!("int8", ValueKind::Int8, i8, -8i8); + same!("int16", ValueKind::Int16, i16, -300i16); + same!("int32", ValueKind::Int32, i32, -2i32); + same!("int64", ValueKind::Int64, i64, -9_007_199_254_740_993i64); + same!("int128", ValueKind::Int128, i128, i128::MIN); + same!("uint16", ValueKind::UInt16, u16, 60_000u16); + same!("uint32", ValueKind::UInt32, u32, 4_000_000_000u32); + same!("uint64", ValueKind::UInt64, u64, u64::MAX); + same!("uint128", ValueKind::UInt128, u128, u128::MAX); + same!("float32", ValueKind::Float32, f32, 1.5f32); + same!("float64", ValueKind::Float64, f64, -0.0f64); + same!("string", ValueKind::String, String, String::from("café")); + same!("empty string", ValueKind::String, String, String::new()); + same!("bytes", ValueKind::Bytes, Vec, vec![0u8, 255, 16]); + same!("date", ValueKind::Date, Date, date()); + same!("timestamp", ValueKind::Timestamp, Timestamp, timestamp()); + same!("decimal", ValueKind::Decimal, Decimal, decimal()); + same!("uuid", ValueKind::Uuid, UuidValue, uuid_value()); + } + + /// No Rust type spells a lone `u8`: a `Vec` is a byte string. So + /// the test compares the run-time leaf with another leaf: the one that + /// the cipher seals for the same scalar walked as a tree. + #[tokio::test] + async fn for_an_unsigned_8_bit_integer() { + let context = column(); + let scalar = || Raw(None, Physical::Int(Int::U8(200))); + let (cipher, keys) = kept_cipher(SEED).await; + let tree = cipher + .default_keyset() + .encrypt_tree(scalar(), context.clone()) + .await + .expect("a scalar seals as a tree of one leaf"); + let CipherText::Single(leaf) = tree else { + panic!("a scalar seals as one leaf"); + }; + let walked = parts(&keys, Ciphertext::from(leaf), context.clone()); + for declared in [None, Some(ValueKind::UInt8)] { + let (_, run_time_parts) = run_time(&frame(scalar()), declared, &context).await; + assert_eq!( + run_time_parts, walked, + "uint8 declared as {declared:?}: the run-time leaf differs from the cipher's own" + ); + } + } + + /// A number of another width or kind seals as the value of the + /// declared kind. The typed call makes the same ciphertext parts for + /// that value. + #[tokio::test] + async fn for_a_number_converted_to_its_declared_kind() { + assert_same_ciphertext( + "float64 34 as uint64", + || 34u64, + &frame(34.0f64), + Some(ValueKind::UInt64), + &frame(34u64), + |opened: &u64| frame(*opened), + ) + .await; + assert_same_ciphertext( + "int64 -7 as int8", + || -7i8, + &frame(-7i64), + Some(ValueKind::Int8), + &frame(-7i8), + |opened: &i8| frame(*opened), + ) + .await; + assert_same_ciphertext( + "int32 12 as float64", + || 12.0f64, + &frame(12i32), + Some(ValueKind::Float64), + &frame(12.0f64), + |opened: &f64| frame(*opened), + ) + .await; + assert_same_ciphertext( + "int64 5 as decimal", + || Decimal::new(rust_decimal::Decimal::new(5, 0)), + &frame(5i64), + Some(ValueKind::Decimal), + &frame(Decimal::new(rust_decimal::Decimal::new(5, 0))), + |opened: &Decimal| frame(opened), + ) + .await; + } + + /// A document arrives as JSON text, as a text value or a bytes value. + /// `encrypt` seals it as the typed call seals the document: as its + /// compact JSON text. + #[tokio::test] + async fn for_a_json_document() { + let text = r#"{ "b": [1, 2.5, null], "a": "é" }"#; + let document = || JsonPlaintext::parse(text).expect("a document"); + // What a `String` reads back: the text that the document was sealed as. + let sealed_text = frame(r#"{"a":"é","b":[1,2.5,null]}"#); + for (name, crossing) in [ + ("json as text", frame(text)), + ("json as bytes", frame(text.as_bytes().to_vec())), + ] { + assert_same_ciphertext( + name, + document, + &crossing, + Some(ValueKind::Json), + &sealed_text, + |opened: &String| frame(opened.as_str()), + ) + .await; + } + } + + proptest! { + #![proptest_config(ProptestConfig::with_cases(48))] + + /// For any scalar, any context, and the scalar's own kind as the + /// declared kind, the run-time ciphertext has the parts of the typed + /// ciphertext. + #[test] + fn for_any_generated_scalar( + scalar in any_scalar(), + declare in any::(), + context in proptest::option::of("[a-z]{1,8}"), + ) { + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .expect("a runtime"); + let context = match &context { + Some(context) => context.as_str().into_context().into_owned(), + None => no_context(), + }; + let (run_time_parts, typed_parts) = runtime.block_on(async { + let declared = declare.then_some(scalar.kind()); + let (_, run_time_parts) = run_time(&scalar.frame(), declared, &context).await; + (run_time_parts, scalar.typed_parts(&context).await) + }); + prop_assert_eq!( + run_time_parts, + typed_parts, + "a {:?} sealed at run time differs from the typed ciphertext", + scalar.kind() + ); + } + } + + /// One generated scalar, of a kind that a Rust type spells. + #[derive(Debug, Clone)] + enum Scalar { + Bool(bool), + Int64(i64), + UInt64(u64), + Float64(f64), + Text(String), + Bytes(Vec), + } + + fn any_scalar() -> impl Strategy { + prop_oneof![ + any::().prop_map(Scalar::Bool), + any::().prop_map(Scalar::Int64), + any::().prop_map(Scalar::UInt64), + any::().prop_map(Scalar::Float64), + ".{0,24}".prop_map(Scalar::Text), + proptest::collection::vec(any::(), 0..24).prop_map(Scalar::Bytes), + ] + } + + impl Scalar { + fn kind(&self) -> ValueKind { + match self { + Scalar::Bool(_) => ValueKind::Bool, + Scalar::Int64(_) => ValueKind::Int64, + Scalar::UInt64(_) => ValueKind::UInt64, + Scalar::Float64(_) => ValueKind::Float64, + Scalar::Text(_) => ValueKind::String, + Scalar::Bytes(_) => ValueKind::Bytes, + } + } + + fn frame(&self) -> OwnedFrame { + match self { + Scalar::Bool(value) => frame(*value), + Scalar::Int64(value) => frame(*value), + Scalar::UInt64(value) => frame(*value), + Scalar::Float64(value) => frame(*value), + Scalar::Text(value) => frame(value.as_str()), + Scalar::Bytes(value) => frame(value.clone()), + } + } + + async fn typed_parts(&self, context: &ContextPiece<'static>) -> Parts { + match self { + Scalar::Bool(value) => typed(*value, context).await.1, + Scalar::Int64(value) => typed(*value, context).await.1, + Scalar::UInt64(value) => typed(*value, context).await.1, + Scalar::Float64(value) => typed(*value, context).await.1, + Scalar::Text(value) => typed(value.clone(), context).await.1, + Scalar::Bytes(value) => typed(value.clone(), context).await.1, + } + } + } +} + +/// A frame written by hand: a passthrough of the text `clear`. +fn passthrough() -> OwnedFrame { + let mut bytes = vec![PASSTHROUGH]; + bytes.extend_from_slice(frame("clear").frame().as_bytes()); + owned(&bytes) +} + +fn typed_null() -> OwnedFrame { + OwnedFrame::typed_null(FixedType::plain(Width::I64).expect("a fixed type")) +} + +fn undefined() -> OwnedFrame { + frame(Raw(Some(Logical::Undefined), Physical::Null)) +} + +/// The refusal that `value::encrypt` makes for `value` under `kind`. Also +/// checks that the call made no key request. +async fn refused(value: &OwnedFrame, kind: Option) -> dynamic::Error { + let (cipher, generates, retrieves) = common::counting_cipher().await; + let keyset = cipher.default_keyset(); + let single = match value::encrypt(&keyset, value.frame(), kind) { + Err(error) => error, + Ok(_) => panic!("a value under {kind:?} was taken where a refusal was expected"), + }; + let with_context = + match value::encrypt_with_context(&keyset, value.frame(), kind, "users/value") { + Err(error) => error, + Ok(_) => panic!("the form with a context took what the form without refused"), + }; + assert_eq!( + (with_context.reason(), with_context.found()), + (single.reason(), single.found()), + "the form with a context refuses for the same reason, and names the same kind" + ); + assert_eq!( + generates.load(Ordering::SeqCst), + 0, + "a refused value requests no data key" + ); + assert_eq!( + retrieves.load(Ordering::SeqCst), + 0, + "a refused value retrieves no data key" + ); + single +} + +/// A single-value refusal has its own variant and code, the reason, the kind +/// of the value to encrypt, and a message about one value. The message +/// mentions no record, plan, or field. +fn assert_value_refusal(error: &dynamic::Error, reason: Reason, found: Found, what: &str) { + use stack_encrypt::ErrorPayload as _; + assert!( + matches!(error, dynamic::Error::Value { .. }), + "{what}: expected a single-value refusal, got: {error:?}" + ); + assert_eq!(error.reason(), Some(reason), "{what}: the reason"); + assert_eq!(error.field(), None, "{what}: one value names no field"); + assert_eq!( + error.code().map(|code| code.to_string()).as_deref(), + Some("stack_encrypt::dynamic_value"), + "{what}: the diagnostic code" + ); + assert_eq!( + error + .payload() + .get("reason") + .and_then(|value| value.as_str()), + Some(reason.as_str()), + "{what}: the payload carries the reason" + ); + assert_eq!(error.found(), Some(found), "{what}: the kind found"); + assert_eq!( + error + .payload() + .get("found") + .and_then(|value| value.as_str()), + Some(found.as_str()), + "{what}: the payload carries the kind found" + ); + // The message starts with the kind of the value. A record's message + // for a value of another type names a field, and one value has none. + let rest = match reason { + Reason::NotAScalar => ", not a scalar".to_owned(), + Reason::FieldType => ", and does not convert exactly to the declared kind".to_owned(), + reason => format!(", and its text is not a JSON document: {reason}"), + }; + let message = error.to_string(); + assert_eq!( + message, + format!("the value to encrypt is {found}{rest}"), + "{what}: the message is about one value" + ); + for word in ["field", "record", "plan"] { + assert!( + !message.contains(word), + "{what}: the message speaks of a {word}, and one value has none: {message}" + ); + } +} + +mod encrypt_refuses_before_any_key_request { + use super::*; + + #[tokio::test] + async fn a_value_that_is_not_one_scalar() { + let array = Found::Kind(ValueKind::Array); + let cases = [ + ("an array", frame(vec!["a", "b"]), array), + ("an empty array", frame(Vec::::new()), array), + ( + "an object", + frame(std::collections::BTreeMap::from([("a", 1u32)])), + Found::Kind(ValueKind::Object), + ), + ("a passthrough", passthrough(), Found::Passthrough), + ("a plain null", OwnedFrame::null(), Found::Null), + ("a typed null", typed_null(), Found::Null), + ]; + for (what, value, found) in &cases { + // With no declared kind, and with a kind of each shape. The refusal + // names the kind of the value, whatever kind was declared. + for kind in [ + None, + Some(ValueKind::Int64), + Some(ValueKind::Array), + Some(ValueKind::Object), + Some(ValueKind::Json), + ] { + let error = refused(value, kind).await; + assert_value_refusal( + &error, + Reason::NotAScalar, + *found, + &format!("{what} under {kind:?}"), + ); + } + } + } + + /// `undefined` is most often a misspelt property name. No typed call + /// could read it back. So `encrypt` refuses it with a declared kind and + /// with none. + #[tokio::test] + async fn undefined_whatever_kind_is_declared() { + for kind in [ + None, + Some(ValueKind::Int64), + Some(ValueKind::String), + Some(ValueKind::Json), + Some(ValueKind::Array), + ] { + let error = refused(&undefined(), kind).await; + assert_value_refusal( + &error, + Reason::NotAScalar, + Found::Undefined, + &format!("undefined under {kind:?}"), + ); + } + } + + #[tokio::test] + async fn a_value_that_is_not_of_the_declared_kind() { + use ValueKind::*; + let cases = [ + ("text as int64", frame("34"), Int64, String), + ("a fraction as uint64", frame(34.5f64), UInt64, Float64), + ("300 as int8", frame(300i64), Int8, Int64), + ("an integer as string", frame(34i64), String, Int64), + ("an integer as date", frame(0i32), Date, Int32), + ("a scalar as array", frame(34i64), Array, Int64), + ("a scalar as object", frame("a"), Object, String), + ("an integer as json", frame(1i64), Json, Int64), + ("a boolean as json", frame(true), Json, Bool), + ]; + for (what, value, kind, given) in &cases { + let error = refused(value, Some(*kind)).await; + assert_value_refusal(&error, Reason::FieldType, Found::Kind(*given), what); + } + } + + #[tokio::test] + async fn text_that_is_not_a_json_document() { + let cases = [ + ("not JSON", r#"{"a": "#, Reason::JsonSyntax), + ( + "a repeated member", + r#"{"a":1,"a":2}"#, + Reason::JsonDuplicateKey, + ), + ( + "an integer outside 64 bits", + "18446744073709551616", + Reason::JsonIntegerRange, + ), + ]; + for (what, text, reason) in cases { + for (crossing, given) in [ + (frame(text), ValueKind::String), + (frame(text.as_bytes().to_vec()), ValueKind::Bytes), + ] { + let error = refused(&crossing, Some(ValueKind::Json)).await; + assert_value_refusal(&error, reason, Found::Kind(given), what); + } + } + } + + /// A refusal names the kind of the value to encrypt, and contains no + /// part of the value. + #[tokio::test] + async fn without_any_of_the_value_in_the_error() { + let secret = "sk_live_4242424242"; + let cases = [ + (frame(vec![secret]), None), + (frame(secret), Some(ValueKind::Int64)), + ( + frame(format!(r#"{{"key": "{secret}""#)), + Some(ValueKind::Json), + ), + ]; + for (value, kind) in &cases { + let error = refused(value, *kind).await; + let shown = format!( + "{error} {error:?} {:?}", + error.help().map(|h| h.to_string()) + ); + assert!( + !shown.contains(secret) && !shown.contains("4242"), + "the refusal under {kind:?} shows the value: {shown}" + ); + } + } +} + +mod encrypt_with_no_declared_kind { + use super::*; + + /// A scalar of a logical type that this build does not define. The frame + /// and the leaf record the id of the type, and no kind names it. + fn unknown_logical() -> OwnedFrame { + let unknown = Logical::from_wire(200, 9).expect("an id no build knows yet"); + frame(Raw(Some(unknown), Physical::Int(Int::I32(7)))) + } + + /// The leaf format records a logical type that this build does not + /// define. So an older build can store a value of a newer type. The + /// value is one scalar. `encrypt` seals it as it arrived. + #[tokio::test] + async fn seals_a_scalar_of_an_unknown_logical_type_as_it_arrived() { + let cipher = common::stack_cipher().await; + let keyset = cipher.default_keyset(); + let value = unknown_logical(); + assert_eq!(value.frame().kind(), None, "no kind names the type"); + let sealed = value::encrypt(&keyset, value.frame(), None) + .expect("a scalar of an unknown logical type is one scalar") + .await + .expect("it seals"); + let opened = value::decrypt(&keyset, sealed.clone(), None) + .await + .expect("it opens with no declared kind"); + assert_eq!( + opened.frame(), + value.frame(), + "the value opens with its type id" + ); + + // The ciphertext opens as no declared kind, and as no Rust type. + let as_int = value::decrypt(&keyset, sealed.clone(), Some(ValueKind::Int32)).await; + assert!( + matches!(as_int, Err(Error::OpenedType { expected: "int32" })), + "an unknown logical type is not an int32, got: {as_int:?}" + ); + let typed = keyset.decrypt::(sealed).await; + assert!( + matches!(typed, Err(Error::OpenedType { .. })), + "no Rust type reads an unknown logical type, got: {typed:?}" + ); + } + + #[tokio::test] + async fn refuses_an_unknown_logical_type_under_a_declared_kind() { + for kind in [ValueKind::Int32, ValueKind::Date, ValueKind::Json] { + let error = refused(&unknown_logical(), Some(kind)).await; + assert_value_refusal( + &error, + Reason::FieldType, + Found::Unknown, + &format!("an unknown logical type as {kind}"), + ); + } + } + + /// A known logical type over a value that the type does not admit never + /// reaches `encrypt`, because no frame can contain one. The frame + /// writer refuses to write it. The frame reader refuses bytes that spell + /// it. + #[test] + fn a_logical_type_over_a_value_it_does_not_admit_is_not_a_frame() { + let short_uuid = Raw(Some(Logical::Uuid), Physical::Bytes(&[7; 15])); + assert!( + OwnedFrame::of(short_uuid).is_err(), + "the writer must refuse a UUID of fifteen bytes" + ); + // The frame of a real UUID, with one byte removed from the payload and + // from the length. + let uuid = frame(Raw(Some(Logical::Uuid), Physical::Bytes(&[7; 16]))); + let mut bytes = uuid.frame().as_bytes().to_vec(); + let length = bytes.len() - 16 - 4; + assert_eq!( + bytes[length..length + 4], + 16u32.to_le_bytes(), + "the payload's length sits before the payload" + ); + bytes[length..length + 4].copy_from_slice(&15u32.to_le_bytes()); + let _ = bytes.pop(); + assert!( + vitaminc_aead::Frame::parse(&bytes).is_err(), + "the reader must refuse a UUID of fifteen bytes" + ); + + let out_of_range = Raw(Some(Logical::Date), Physical::Int(Int::I64(i64::MAX))); + assert!( + OwnedFrame::of(out_of_range).is_err(), + "the writer must refuse a date outside the range" + ); + } + + #[tokio::test] + async fn seals_a_scalar_at_the_width_it_arrived_with() { + let cipher = common::stack_cipher().await; + let keyset = cipher.default_keyset(); + let sealed = value::encrypt(&keyset, int(Int::U8(7)).frame(), None) + .expect("a uint8 is one scalar") + .await + .expect("it seals"); + let opened = value::decrypt(&keyset, sealed, None) + .await + .expect("it opens"); + assert_eq!( + opened.frame().kind(), + Some(ValueKind::UInt8), + "no declared kind converts nothing" + ); + } +} + +mod encrypt_with_a_context { + use super::*; + + #[tokio::test] + async fn binds_the_ciphertext_to_it() { + let cipher = common::stack_cipher().await; + let keyset = cipher.default_keyset(); + let sealed = value::encrypt_with_context( + &keyset, + frame("ada@example.com").frame(), + None, + ("users", "email"), + ) + .expect("one scalar") + .await + .expect("it seals"); + + let without = value::decrypt(&keyset, sealed.clone(), None).await; + assert!( + matches!(without, Err(Error::Aead)), + "the empty context must not open it, got: {without:?}" + ); + let other = + value::decrypt_with_context(&keyset, sealed.clone(), None, ("users", "name")).await; + assert!( + matches!(other, Err(Error::Aead)), + "another context must not open it, got: {other:?}" + ); + let opened = value::decrypt_with_context(&keyset, sealed, None, ("users", "email")) + .await + .expect("the same context opens it"); + assert_eq!( + opened.frame(), + frame("ada@example.com").frame(), + "the value under its context" + ); + } + + /// The call shows the context that it will use, as the typed call does. + #[tokio::test] + async fn runs_under_the_context_the_typed_call_runs_under() { + let cipher = common::stack_cipher().await; + let keyset = cipher.default_keyset(); + let run_time = + value::encrypt_with_context(&keyset, frame(34i64).frame(), None, ("users", "age")) + .expect("one scalar"); + let typed = keyset.encrypt_with_context(34i64, ("users", "age")); + assert_eq!( + run_time.context(), + typed.context(), + "the two calls name different contexts" + ); + let run_time = value::encrypt(&keyset, frame(34i64).frame(), None).expect("one scalar"); + let typed = keyset.encrypt(34i64); + assert_eq!( + run_time.context(), + typed.context(), + "the two calls name different empty contexts" + ); + } +} + +/// The run-time interface has no batch call. A binding makes one call for +/// each value, and merges the calls with `Pending::all`. The merged call +/// sends one key request. +mod many_values_merged_with_pending_all { + use super::*; + + #[tokio::test] + async fn seal_and_open_in_one_key_request_each_and_keep_their_order() { + let (cipher, generates, retrieves) = common::counting_cipher().await; + let keyset = cipher.default_keyset(); + // Each value has its own declared kind. The last value also has its own + // context. + let values = [frame(1.0f64), frame("two"), frame(true), frame(4i64)]; + let kinds = [ + Some(ValueKind::UInt32), + Some(ValueKind::String), + None, + Some(ValueKind::Int64), + ]; + let mut calls = Vec::new(); + for (value, kind) in values.iter().zip(kinds).take(3) { + calls.push(value::encrypt(&keyset, value.frame(), kind).expect("one scalar")); + } + calls.push( + value::encrypt_with_context(&keyset, values[3].frame(), kinds[3], ("users", "n")) + .expect("one scalar"), + ); + assert_eq!( + generates.load(Ordering::SeqCst), + 0, + "a call requests no key until it is awaited" + ); + let sealed = stack_encrypt::Pending::all(&keyset, calls) + .await + .expect("the merged call seals"); + assert_eq!(sealed.len(), 4, "one ciphertext for each value"); + assert_eq!( + generates.load(Ordering::SeqCst), + 1, + "one key request seals the batch" + ); + + retrieves.store(0, Ordering::SeqCst); + let mut calls = Vec::new(); + for (ciphertext, kind) in sealed.iter().cloned().zip(kinds).take(3) { + calls.push(value::decrypt(&keyset, ciphertext, kind)); + } + calls.push(value::decrypt_with_context( + &keyset, + sealed[3].clone(), + kinds[3], + ("users", "n"), + )); + let opened = stack_encrypt::Pending::all(&keyset, calls) + .await + .expect("the merged call opens"); + assert_eq!( + retrieves.load(Ordering::SeqCst), + 1, + "one key request opens the batch" + ); + let expected = [frame(1u32), frame("two"), frame(true), frame(4i64)]; + assert_eq!( + opened.len(), + expected.len(), + "one frame for each ciphertext" + ); + for (position, (opened, expected)) in opened.iter().zip(&expected).enumerate() { + assert_eq!( + opened.frame(), + expected.frame(), + "the value at position {position} is in its call's place" + ); + } + + // A value sealed under a context opens only under that context. + let without = value::decrypt(&keyset, sealed[3].clone(), kinds[3]).await; + assert!( + matches!(without, Err(Error::Aead)), + "the empty context must not open a value sealed under one, got: {without:?}" + ); + } + + #[tokio::test] + async fn a_refused_value_stops_the_batch_before_any_key_request() { + let (cipher, generates, _) = common::counting_cipher().await; + let keyset = cipher.default_keyset(); + let values = [frame("a"), OwnedFrame::null(), frame(vec!["b"])]; + let calls: Result, dynamic::Error> = values + .iter() + .map(|value| value::encrypt(&keyset, value.frame(), None)) + .collect(); + let error = match calls { + Err(error) => error, + Ok(_) => panic!("a batch holding a null was taken"), + }; + assert_value_refusal( + &error, + Reason::NotAScalar, + Found::Null, + "the first refused value", + ); + assert_eq!( + generates.load(Ordering::SeqCst), + 0, + "a batch with a refused value requests no data key" + ); + } + + #[tokio::test] + async fn a_value_of_another_kind_fails_the_merged_decrypt() { + let cipher = common::stack_cipher().await; + let keyset = cipher.default_keyset(); + let sealed = [ + keyset.encrypt(1i64).await.expect("it seals"), + keyset.encrypt(String::from("two")).await.expect("it seals"), + keyset.encrypt(3i64).await.expect("it seals"), + ]; + let open_all = |kind: Option| { + let calls = sealed + .iter() + .cloned() + .map(|ciphertext| value::decrypt(&keyset, ciphertext, kind)) + .collect(); + stack_encrypt::Pending::all(&keyset, calls) + }; + let opened = open_all(Some(ValueKind::Int64)).await; + assert!( + matches!(opened, Err(Error::OpenedType { expected: "int64" })), + "a batch holding text must not open as int64, got: {opened:?}" + ); + let opened = open_all(None) + .await + .expect("with no declared kind each value opens as it was sealed"); + assert_eq!( + opened + .iter() + .map(|value| value.frame().kind()) + .collect::>(), + [ + Some(ValueKind::Int64), + Some(ValueKind::String), + Some(ValueKind::Int64) + ], + "each value keeps its own kind" + ); + } +} + +mod decrypt { + use super::*; + + #[tokio::test] + async fn returns_the_value_as_it_was_sealed_with_no_declared_kind() { + let cipher = common::stack_cipher().await; + let keyset = cipher.default_keyset(); + let sealed = keyset.encrypt(34u64).await.expect("it seals"); + let opened = value::decrypt(&keyset, sealed, None) + .await + .expect("it opens"); + assert_eq!(opened.frame(), frame(34u64).frame(), "the sealed value"); + } + + #[tokio::test] + async fn returns_a_value_of_the_declared_kind_and_converts_nothing() { + let cipher = common::stack_cipher().await; + let keyset = cipher.default_keyset(); + let sealed = keyset.encrypt(34u64).await.expect("it seals"); + let opened = value::decrypt(&keyset, sealed.clone(), Some(ValueKind::UInt64)) + .await + .expect("a uint64 opens as uint64"); + assert_eq!(opened.frame(), frame(34u64).frame(), "the sealed value"); + + // An integer of another width is another kind. `decrypt` converts + // nothing, as a typed field of a record converts nothing when it opens. + let narrower = value::decrypt(&keyset, sealed, Some(ValueKind::UInt32)).await; + assert!( + matches!(narrower, Err(Error::OpenedType { expected: "uint32" })), + "a uint64 must not open as uint32, got: {narrower:?}" + ); + } + + /// A refusal names the kind that was expected. A refusal never says + /// what the value opened as. + #[tokio::test] + async fn refuses_another_kind_without_saying_what_the_value_is() { + let cipher = common::stack_cipher().await; + let keyset = cipher.default_keyset(); + let sealed = keyset + .encrypt(String::from("sk_live_4242424242")) + .await + .expect("it seals"); + let error = value::decrypt(&keyset, sealed, Some(ValueKind::Int64)) + .await + .expect_err("text must not open as int64"); + assert!( + matches!(error, Error::OpenedType { expected: "int64" }), + "expected OpenedType naming int64, got: {error:?}" + ); + let shown = format!( + "{error} {error:?} {:?}", + error.help().map(|h| h.to_string()) + ); + assert!( + !shown.contains("string") && !shown.contains("String") && !shown.contains("4242"), + "the refusal says what the value opened as: {shown}" + ); + } + + #[tokio::test] + async fn refuses_an_array_or_an_object_kind_before_any_key_request() { + let (cipher, _, retrieves) = common::counting_cipher().await; + let keyset = cipher.default_keyset(); + let sealed = keyset.encrypt(34u64).await.expect("it seals"); + for (kind, name) in [(ValueKind::Array, "array"), (ValueKind::Object, "object")] { + let one = value::decrypt(&keyset, sealed.clone(), Some(kind)).await; + assert!( + matches!(one, Err(Error::OpenedType { expected }) if expected == name), + "a ciphertext must not open as {name}, got: {one:?}" + ); + } + assert_eq!( + retrieves.load(Ordering::SeqCst), + 0, + "a kind no ciphertext holds is refused with no key request" + ); + } + + #[tokio::test] + async fn opens_a_null_only_with_no_declared_kind() { + let cipher = common::stack_cipher().await; + let keyset = cipher.default_keyset(); + let tree = keyset + .encrypt_tree(None::, ("users", "age")) + .await + .expect("a null seals as a tree of one leaf"); + let CipherText::Single(leaf) = tree else { + panic!("a null seals as one leaf"); + }; + let sealed = Ciphertext::from(leaf); + let opened = value::decrypt_with_context(&keyset, sealed.clone(), None, ("users", "age")) + .await + .expect("a null leaf opens with no declared kind"); + assert!( + opened.frame().is_null(), + "a null leaf opens as the null frame" + ); + + let declared = + value::decrypt_with_context(&keyset, sealed, Some(ValueKind::Int64), ("users", "age")) + .await; + assert!( + matches!(declared, Err(Error::OpenedType { expected: "int64" })), + "a null is not a value of the declared kind, got: {declared:?}" + ); + } + + #[tokio::test] + async fn opens_only_its_own_keysets_ciphertext_through_a_keyset() { + let (cipher, _, retrieves) = common::counting_cipher().await; + let other = cipher.keyset(IdentifiedBy::Name("another-keyset".to_owned().into())); + let sealed = value::encrypt(&other, frame("elsewhere").frame(), None) + .expect("one scalar") + .await + .expect("it seals under the other keyset"); + retrieves.store(0, Ordering::SeqCst); + + let keyset = cipher.default_keyset(); + let foreign = value::decrypt(&keyset, sealed.clone(), None).await; + assert!( + matches!(foreign, Err(Error::ForeignKeyset { .. })), + "a keyset must not open another keyset's ciphertext, got: {foreign:?}" + ); + assert_eq!( + retrieves.load(Ordering::SeqCst), + 0, + "a foreign ciphertext is refused before any key is retrieved" + ); + + let opened = value::decrypt(&cipher, sealed, None) + .await + .expect("the cipher opens a ciphertext of any of its keysets"); + assert_eq!(opened.frame(), frame("elsewhere").frame(), "the value"); + } +} + +mod decrypt_a_json_document { + use super::*; + + /// The frame that a `json` value opens as: its JSON text as a bytes value. + fn document(text: &str) -> OwnedFrame { + frame(text.as_bytes().to_vec()) + } + + #[tokio::test] + async fn returns_the_documents_text_in_a_bytes_leaf() { + let cipher = common::stack_cipher().await; + let keyset = cipher.default_keyset(); + let sealed = keyset + .encrypt(JsonPlaintext::from(json!({"name": "Ada", "n": [1.5, -2]}))) + .await + .expect("a document seals"); + let opened = value::decrypt(&keyset, sealed.clone(), Some(ValueKind::Json)) + .await + .expect("a document opens as json"); + assert_eq!( + opened.frame(), + document(r#"{"n":[1.5,-2],"name":"Ada"}"#).frame(), + "the document's text, in a bytes leaf" + ); + assert_eq!( + opened.frame(), + dynamic::json_frame(&json!({"name": "Ada", "n": [1.5, -2]})) + .expect("a document frames") + .frame(), + "the frame a record's json field opens as" + ); + + // With no declared kind, the leaf comes back as it was sealed: as text. + let as_sealed = value::decrypt(&keyset, sealed, None) + .await + .expect("it opens"); + assert_eq!( + as_sealed.frame().kind(), + Some(ValueKind::String), + "a document is sealed as a text leaf" + ); + } + + #[tokio::test] + async fn round_trips_what_encrypt_sealed_as_json() { + let cipher = common::stack_cipher().await; + let keyset = cipher.default_keyset(); + let sealed = value::encrypt( + &keyset, + document(r#"{ "a" : [ 1 , null ] }"#).frame(), + Some(ValueKind::Json), + ) + .expect("a document") + .await + .expect("it seals"); + let opened = value::decrypt(&keyset, sealed.clone(), Some(ValueKind::Json)) + .await + .expect("it opens as json"); + assert_eq!( + opened.frame(), + document(r#"{"a":[1,null]}"#).frame(), + "the document, as the engine writes it" + ); + let typed: JsonPlaintext = keyset + .decrypt(sealed) + .await + .expect("the typed call opens it"); + assert_eq!( + typed.value(), + &json!({"a": [1, null]}), + "the typed document" + ); + } + + #[tokio::test] + async fn refuses_a_value_that_is_not_a_document() { + let cipher = common::stack_cipher().await; + let keyset = cipher.default_keyset(); + let not_documents = [ + ( + "text that is not JSON", + keyset.encrypt(String::from("{not json")).await, + ), + ("an integer", keyset.encrypt(7i64).await), + // The typed document reads only a text leaf. `decrypt` as `json` does the + // same. + ( + "JSON text in a bytes leaf", + keyset.encrypt(b"{}".to_vec()).await, + ), + ]; + for (what, sealed) in not_documents { + let sealed = sealed.expect("it seals"); + let opened = value::decrypt(&keyset, sealed, Some(ValueKind::Json)).await; + assert!( + matches!(opened, Err(Error::OpenedType { expected: "json" })), + "{what} must not open as json, got: {opened:?}" + ); + } + } + + /// `json` is a declared kind, and the engine stores a document as text. + /// So a string and a document have one stored form. A kind check cannot + /// distinguish them. + #[tokio::test] + async fn opens_a_string_that_holds_json_text_and_returns_it_as_the_engine_writes_it() { + let cipher = common::stack_cipher().await; + let keyset = cipher.default_keyset(); + let cases = [ + ("42", "42"), + (r#""ada""#, r#""ada""#), + ( + r#"{ "b" : [ 1 , null ], "a" : true }"#, + r#"{"a":true,"b":[1,null]}"#, + ), + ]; + for (sealed_text, opened_text) in cases { + let sealed = keyset + .encrypt(String::from(sealed_text)) + .await + .expect("a string seals"); + let opened = value::decrypt(&keyset, sealed.clone(), Some(ValueKind::Json)) + .await + .unwrap_or_else(|error| { + panic!("the string {sealed_text} holds JSON text and opens as json: {error}") + }); + assert_eq!( + opened.frame(), + document(opened_text).frame(), + "the string {sealed_text} opens as json to the text the engine writes" + ); + // The same ciphertext still opens as the string that was sealed. + let as_string = value::decrypt(&keyset, sealed, Some(ValueKind::String)) + .await + .expect("a string opens as string"); + assert_eq!( + as_string.frame(), + frame(sealed_text).frame(), + "the string {sealed_text} opens as string unchanged" + ); + } + } + + #[tokio::test] + async fn opens_a_sealed_document_as_a_string() { + let cipher = common::stack_cipher().await; + let keyset = cipher.default_keyset(); + let sealed = keyset + .encrypt(JsonPlaintext::from(json!({"name": "Ada", "n": [1.5, -2]}))) + .await + .expect("a document seals"); + let opened = value::decrypt(&keyset, sealed, Some(ValueKind::String)) + .await + .expect("a document is stored as text, so it opens as string"); + assert_eq!( + opened.frame(), + frame(r#"{"n":[1.5,-2],"name":"Ada"}"#).frame(), + "the frame holds the JSON text that was sealed, in a text leaf" + ); + } +} diff --git a/packages/stack-encrypt/tests/single_value_conformance.rs b/packages/stack-encrypt/tests/single_value_conformance.rs new file mode 100644 index 000000000..2db20a990 --- /dev/null +++ b/packages/stack-encrypt/tests/single_value_conformance.rs @@ -0,0 +1,728 @@ +//! The runner for the shared single-value conformance profile. +//! +//! The profile encrypts one value as one ciphertext through the run-time +//! interface. The runner compares each result with the typed interface and +//! with the frozen artifacts. See +//! `conformance/stack-encrypt/single-value-contract.md`. +// The typed `Uuid` reference needs the `uuid` feature. The `dynamic` +// feature does not turn `uuid` on. +#![cfg(all(feature = "dynamic", feature = "uuid"))] +mod common; + +use std::collections::{BTreeMap, BTreeSet}; +use std::path::PathBuf; +use std::sync::atomic::Ordering; + +use common::conformance::{value, Input}; +use common::frames::{frame, object, owned}; +use common::leaves::{kept_cipher, parts}; +use common::{hex, unhex, CountingSource, DeterministicSource}; +use miette::Diagnostic as _; +use serde::{Deserialize, Serialize}; +use stack_encrypt::dynamic::{self, frame::OwnedFrame, value as single, ValueKind}; +use stack_encrypt::json::JsonPlaintext; +use stack_encrypt::kms::{DataKeySource, IndexKeySource}; +use stack_encrypt::value::{Date, Decimal, Timestamp, Uuid}; +use stack_encrypt::{ + AsProtectedRef as _, CipherRef, Ciphertext, ContextPiece, Decrypt as _, Encrypt as _, Error, + IntoContext, KeysetCipher, Pending, StackCipher, +}; +use vitaminc_aead::frame::{Frame, PASSTHROUGH}; +use vitaminc_aead::plaintext::{FixedType, Width}; + +const PROFILE: &str = "single-value-v1"; + +/// The values that an input of type `shape` can name. The `{type, text}` +/// form cannot spell these values. A name outside this list is a corpus +/// error. +const SHAPES: [&str; 5] = [ + "array", + "empty_array", + "object", + "passthrough", + "typed_null", +]; + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Corpus { + version: u32, + profile: String, + seed: String, + required_capabilities: Vec, + cases: Vec, + batches: Vec, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Case { + id: String, + /// The name of the declared kind, or empty for none. + kind: String, + /// The parts of the context, or empty for the empty context. + context: Vec, + input: Input, + /// The value in the ciphertext, where it differs from the input. That is + /// a number converted to the declared kind, or the compact JSON text of a + /// document. + stored: Option, + /// Kinds that the ciphertext must not decrypt as. + refused_as: Option>, + /// Kinds that the ciphertext must decrypt as, other than the declared + /// kind. Each has the value that the ciphertext decrypts to. + opens_as: Option>, + expected_error: Option, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct OpensAs { + kind: String, + value: Input, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Batch { + id: String, + /// The kind declared for each input, in order: a name, or empty for + /// none. + kinds: Vec, + context: Vec, + inputs: Vec, + /// The values in the ciphertexts, where they differ from the inputs. + stored: Option>, + expected_error: Option, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct ExpectedError { + code: String, + reason: String, + /// The kind of the value to encrypt, as the payload field `found` names + /// it. + found: String, +} + +#[derive(Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +struct Artifacts { + version: u32, + profile: String, + producer: String, + cases: BTreeMap, +} + +#[derive(Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +struct Artifact { + /// The frame of the input: the value written as bytes. + frame: String, + /// The plaintext that the leaf is sealed with: its tag and payload. + /// Absent for a refused case. + #[serde(skip_serializing_if = "Option::is_none")] + leaf: Option, + /// A ciphertext of the value, frozen. Absent for a refused case. + #[serde(skip_serializing_if = "Option::is_none")] + ciphertext: Option, +} + +fn root() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../conformance/stack-encrypt/v1") +} + +/// The value that an input of type `shape` names. +fn shape(name: &str) -> OwnedFrame { + assert!( + SHAPES.contains(&name), + "{name}: not a shape the profile names" + ); + match name { + "array" => frame(vec!["a", "b"]), + "empty_array" => frame(Vec::::new()), + "object" => object(vec![("a", frame(1u32))]), + "passthrough" => { + let mut bytes = vec![PASSTHROUGH]; + bytes.extend_from_slice(frame("clear").frame().as_bytes()); + owned(&bytes) + } + _ => OwnedFrame::typed_null(FixedType::plain(Width::I64).expect("a fixed type")), + } +} + +/// The frame that an input names: a shape, or a value in the +/// `{type, text}` form of the corpus. +fn input(input: &Input) -> OwnedFrame { + match input.kind.as_str() { + "shape" => shape(&input.text), + _ => value(input), + } +} + +fn declared(kind: &str) -> Option { + (!kind.is_empty()).then(|| kind.parse().expect("a kind's name")) +} + +/// The context of a case, as a binding passes one: a frame of its parts. +fn piece(parts: &[String]) -> ContextPiece<'static> { + let frame = recipher_frame::serde::to_vec(&parts).expect("a context frames"); + dynamic::context(frame.as_protected_ref()) + .expect("a context of two text parts") + .into_inner() +} + +/// The run-time encrypt. An empty context uses the form with no context. Any +/// other context uses the form with a context. +fn seal<'a, K: 'static>( + keyset: &'a KeysetCipher<'_, K>, + value: Frame<'_>, + kind: Option, + context: &[String], +) -> Result, dynamic::Error> { + if context.is_empty() { + single::encrypt(keyset, value, kind) + } else { + single::encrypt_with_context(keyset, value, kind, piece(context)) + } +} + +/// A batch, as a binding encrypts one. The binding makes one single-value +/// call for each value, each with its own declared kind. The binding then +/// merges the calls into one key request. A refused value refuses the whole +/// batch. No call is merged. +fn seal_all<'a, K: 'static>( + keyset: &'a KeysetCipher<'_, K>, + values: &[OwnedFrame], + kinds: &[Option], + context: &[String], +) -> Result, K>, dynamic::Error> { + let calls = values + .iter() + .zip(kinds) + .map(|(value, kind)| seal(keyset, value.frame(), *kind, context)) + .collect::, _>>()?; + Ok(Pending::all(keyset, calls)) +} + +fn open<'a, K: 'static>( + cipher: impl Into>, + ciphertext: Ciphertext, + kind: Option, + context: &[String], +) -> Pending<'a, OwnedFrame, K> { + if context.is_empty() { + single::decrypt(cipher, ciphertext, kind) + } else { + single::decrypt_with_context(cipher, ciphertext, kind, piece(context)) + } +} + +/// A batch, as a binding decrypts one. The binding makes one single-value +/// call for each ciphertext, each with its own declared kind. The binding +/// then merges the calls into one key request. +fn open_all<'a, K: 'static>( + keyset: &'a KeysetCipher<'_, K>, + ciphertexts: Vec, + kinds: &[Option], + context: &[String], +) -> Pending<'a, Vec, K> { + let calls = ciphertexts + .into_iter() + .zip(kinds) + .map(|(ciphertext, kind)| open(keyset, ciphertext, *kind, context)) + .collect(); + Pending::all(keyset, calls) +} + +/// The context that the leaf of `ciphertext` is sealed under. Opening the +/// leaf with a kept key needs this context. +fn sealed_under(context: &[String]) -> ContextPiece<'static> { + if context.is_empty() { + ().into_context() + } else { + piece(context) + } +} + +/// The Rust type that the typed interface uses for each kind. `$run` +/// receives the type for `name`. The match is `None` for the one kind that +/// no Rust type spells: a lone 8-bit unsigned integer. +macro_rules! with_rust_type { + ($name:expr, $run:ident) => { + match $name { + "bool" => Some($run!(bool)), + "int8" => Some($run!(i8)), + "int16" => Some($run!(i16)), + "int32" => Some($run!(i32)), + "int64" => Some($run!(i64)), + "int128" => Some($run!(i128)), + "uint16" => Some($run!(u16)), + "uint32" => Some($run!(u32)), + "uint64" => Some($run!(u64)), + "uint128" => Some($run!(u128)), + "float32" => Some($run!(f32)), + "float64" => Some($run!(f64)), + "string" => Some($run!(String)), + "bytes" => Some($run!(Vec)), + "date" => Some($run!(Date)), + "timestamp" => Some($run!(Timestamp)), + "decimal" => Some($run!(Decimal)), + "uuid" => Some($run!(Uuid)), + "json" => Some($run!(JsonPlaintext)), + "uint8" => None, + other => panic!("{other}: no typed form is listed for this kind"), + } + }; +} + +/// The ciphertext that the typed call makes for the value in `stored`, as +/// the Rust type that `name` names. +async fn typed_seal( + keyset: &KeysetCipher<'_, K>, + name: &str, + stored: &OwnedFrame, + context: &[String], +) -> Option +where + K: DataKeySource + IndexKeySource + Sync + 'static, +{ + macro_rules! seal_as { + ($ty:ty) => {{ + let value: $ty = stored + .visit(<$ty>::sink()) + .expect("the stored value as its Rust type"); + if context.is_empty() { + keyset.encrypt(value).await + } else { + keyset.encrypt_with_context(value, piece(context)).await + } + .expect("the typed call seals") + }}; + } + with_rust_type!(name, seal_as) +} + +/// The value that the typed call decrypts `ciphertext` to, as the Rust type +/// that `name` names. The value is written as a frame. +async fn typed_open( + keyset: &KeysetCipher<'_, K>, + name: &str, + ciphertext: Ciphertext, + context: &[String], +) -> Option +where + K: DataKeySource + IndexKeySource + Sync + 'static, +{ + macro_rules! open_as { + ($ty:ty) => {{ + let value: $ty = if context.is_empty() { + keyset.decrypt(ciphertext).await + } else { + keyset + .decrypt_with_context(ciphertext, piece(context)) + .await + } + .expect("the typed call opens"); + frame(&value) + }}; + } + with_rust_type!(name, open_as) +} + +/// A cipher over the seeded source, with its `(generate, retrieve)` call +/// counters. +async fn counting( + seed: [u8; 32], +) -> ( + StackCipher>, + std::sync::Arc, + std::sync::Arc, +) { + let source = CountingSource::over(DeterministicSource::new(seed)); + let (generates, retrieves) = source.counters(); + let cipher = StackCipher::builder() + .kms(source) + .init() + .await + .expect("build cipher"); + (cipher, generates, retrieves) +} + +fn assert_refusal(id: &str, error: &dynamic::Error, expected: &ExpectedError) { + assert_eq!( + error.code().map(|code| code.to_string()).as_deref(), + Some(expected.code.as_str()), + "{id}: the diagnostic code" + ); + assert_eq!( + error.reason().map(|reason| reason.as_str()), + Some(expected.reason.as_str()), + "{id}: the reason" + ); + assert_eq!( + error.found().map(|found| found.as_str()), + Some(expected.found.as_str()), + "{id}: the kind of the value" + ); + assert_eq!(error.field(), None, "{id}: a single value names no field"); +} + +fn is_forbidden(result: &Result) -> bool { + matches!( + result, + Err(Error::Kms(stack_kms::Error::RetrieveKey( + stack_kms::RetrieveKeyError::RequestFailed(error) + ))) if matches!(error.kind, zerokms_protocol::ViturRequestErrorKind::Forbidden) + ) +} + +/// One accepted case. The run-time call must seal what the typed call seals +/// and what the artifact froze. Every reader must open the result. +async fn accepted( + seed: [u8; 32], + case: &Case, + value: &OwnedFrame, + artifact: &mut Artifact, + baseline: Option<&Artifact>, + kept: Option<&Artifact>, +) { + let id = &case.id; + let kind = declared(&case.kind); + let stored_input = case.stored.as_ref().unwrap_or(&case.input); + let stored = input(stored_input); + let context = &case.context; + + let (cipher, keys) = kept_cipher(seed).await; + let keyset = cipher.default_keyset(); + let fresh = seal(&keyset, value.frame(), kind, context) + .unwrap_or_else(|error| panic!("{id}: the value is refused: {error}")) + .await + .unwrap_or_else(|error| panic!("{id}: the value does not seal: {error}")); + let fresh_parts = parts(&keys, fresh.clone(), sealed_under(context)); + + // The typed call, over a new source of the same seed. The typed call + // then gets the data key that the run-time call was given. + let typed_name = if case.kind == "json" { + "json" + } else { + stored_input.kind.as_str() + }; + let (typed_cipher, typed_keys) = kept_cipher(seed).await; + let typed = typed_seal(&typed_cipher.default_keyset(), typed_name, &stored, context).await; + if let Some(typed) = &typed { + assert_eq!( + fresh_parts, + parts(&typed_keys, typed.clone(), sealed_under(context)), + "{id}: the run-time ciphertext differs from the typed one in a part that is not the nonce" + ); + } + + artifact.leaf = Some(fresh_parts.leaf.clone()); + artifact.ciphertext = Some(hex(&typed.unwrap_or_else(|| fresh.clone()).to_bytes())); + // An update keeps the frozen ciphertext of a case whose leaf has not + // changed. So a ciphertext stays frozen from one update to the next. The + // checks below test the kept ciphertext against the current engine. + if let Some(kept) = kept.filter(|kept| kept.leaf == artifact.leaf && kept.ciphertext.is_some()) + { + artifact.ciphertext.clone_from(&kept.ciphertext); + } + let reference: &Artifact = baseline.unwrap_or(artifact); + assert_eq!( + artifact.leaf, reference.leaf, + "{id}: the plaintext the leaf is sealed with" + ); + let frozen = Ciphertext::from_bytes(&unhex( + reference + .ciphertext + .as_deref() + .unwrap_or_else(|| panic!("{id}: an accepted case has a frozen ciphertext")), + )) + .unwrap_or_else(|error| panic!("{id}: the frozen ciphertext does not parse: {error}")); + assert_eq!( + parts(&keys, frozen.clone(), sealed_under(context)), + fresh_parts, + "{id}: the frozen ciphertext differs from a fresh one in a part that is not the nonce" + ); + + // With the `json` kind, a document decrypts as its text in a bytes value. + let opened_as_declared = if case.kind == "json" { + frame(stored_input.text.as_bytes().to_vec()) + } else { + input(stored_input) + }; + // No case seals under this context. + let wrong = ["conformance".to_owned(), "wrong".to_owned()]; + assert_ne!( + context[..], + wrong[..], + "{id}: a case uses the wrong context" + ); + for (origin, ciphertext) in [("fresh", fresh), ("frozen", frozen)] { + let opened = open(&keyset, ciphertext.clone(), None, context) + .await + .unwrap_or_else(|error| panic!("{id}: the {origin} ciphertext does not open: {error}")); + assert_eq!( + opened.frame(), + stored.frame(), + "{id}: the {origin} ciphertext opens to another value" + ); + if let Some(kind) = kind { + let opened = open(&keyset, ciphertext.clone(), Some(kind), context) + .await + .unwrap_or_else(|error| { + panic!("{id}: the {origin} ciphertext does not open as {kind}: {error}") + }); + assert_eq!( + opened.frame(), + opened_as_declared.frame(), + "{id}: the {origin} ciphertext opens as {kind} to another value" + ); + } + if let Some(opened) = typed_open(&keyset, typed_name, ciphertext.clone(), context).await { + assert_eq!( + opened.frame(), + stored.frame(), + "{id}: the typed call reads another value from the {origin} ciphertext" + ); + } + for also in case.opens_as.iter().flatten() { + let opened = open(&keyset, ciphertext.clone(), declared(&also.kind), context) + .await + .unwrap_or_else(|error| { + panic!( + "{id}: the {origin} ciphertext does not open as {}: {error}", + also.kind + ) + }); + assert_eq!( + opened.frame(), + input(&also.value).frame(), + "{id}: the {origin} ciphertext opens as {} to another value", + also.kind + ); + } + for name in case.refused_as.iter().flatten() { + let other = declared(name); + let refused = open(&keyset, ciphertext.clone(), other, context).await; + assert!( + matches!(&refused, Err(Error::OpenedType { expected }) if expected == name), + "{id}: the {origin} ciphertext must not open as {name}, got: {refused:?}" + ); + } + let refused = open(&keyset, ciphertext, None, &wrong).await; + assert!( + is_forbidden(&refused), + "{id}: the {origin} ciphertext must not open under another context, got: {refused:?}" + ); + } +} + +#[tokio::test] +async fn shared_single_value_profile() { + let update = common::fixture_updates_requested_or_panic(); + let corpus: Corpus = serde_json::from_str(include_str!( + "../../../conformance/stack-encrypt/v1/single-value-v1.cases.json" + )) + .expect("the cases file"); + assert_eq!(corpus.version, 1, "the corpus format version"); + assert_eq!(corpus.profile, PROFILE, "the profile"); + assert_eq!( + corpus.required_capabilities, + ["single-value", "value-kinds", "context-binding", "refusals"], + "the capabilities a runner needs" + ); + let seed: [u8; 32] = unhex(&corpus.seed).try_into().expect("a 32-byte seed"); + assert!(!corpus.cases.is_empty(), "the profile has cases"); + let ids: BTreeSet<&str> = corpus + .cases + .iter() + .map(|case| case.id.as_str()) + .chain(corpus.batches.iter().map(|batch| batch.id.as_str())) + .collect(); + assert_eq!( + ids.len(), + corpus.cases.len() + corpus.batches.len(), + "case IDs are distinct" + ); + assert!(!ids.contains(""), "no case ID is empty"); + + let path = root().join("single-value-v1.expected.rust-native.json"); + let baseline: Option = (!update).then(|| { + let artifacts: Artifacts = + serde_json::from_slice(&std::fs::read(&path).expect("the expected file")) + .expect("the expected file parses"); + assert_eq!(artifacts.version, 1, "the artifacts' format version"); + assert_eq!(artifacts.profile, PROFILE, "the artifacts' profile"); + assert!( + artifacts.producer.starts_with("rust-native"), + "the artifacts' producer: {}", + artifacts.producer + ); + assert_eq!( + artifacts + .cases + .keys() + .map(String::as_str) + .collect::>(), + corpus + .cases + .iter() + .map(|case| case.id.as_str()) + .collect::>(), + "the artifacts hold exactly the cases" + ); + artifacts + }); + + // On an update, the artifacts already written, if there are any. + let previous: Option = update + .then(|| std::fs::read(&path).ok()) + .flatten() + .and_then(|bytes| serde_json::from_slice(&bytes).ok()); + + let mut output = BTreeMap::new(); + for case in &corpus.cases { + eprintln!("single value: {}", case.id); + let value = input(&case.input); + let mut artifact = Artifact { + frame: hex(value.frame().as_bytes()), + leaf: None, + ciphertext: None, + }; + let reference = baseline + .as_ref() + .map(|artifacts| &artifacts.cases[&case.id]); + if let Some(reference) = reference { + assert_eq!( + artifact.frame, reference.frame, + "{}: the input's frame", + case.id + ); + } + match &case.expected_error { + Some(expected) => { + assert!( + case.stored.is_none() && case.refused_as.is_none() && case.opens_as.is_none(), + "{}: a refused case stores nothing", + case.id + ); + let (cipher, generates, retrieves) = counting(seed).await; + let keyset = cipher.default_keyset(); + let error = match seal(&keyset, value.frame(), declared(&case.kind), &case.context) + { + Err(error) => error, + Ok(_) => panic!( + "{}: the value is taken where a refusal is expected", + case.id + ), + }; + assert_refusal(&case.id, &error, expected); + assert_eq!( + ( + generates.load(Ordering::SeqCst), + retrieves.load(Ordering::SeqCst) + ), + (0, 0), + "{}: a refused value makes no key request", + case.id + ); + if let Some(reference) = reference { + assert!( + reference.leaf.is_none() && reference.ciphertext.is_none(), + "{}: a refused case has no frozen ciphertext", + case.id + ); + } + } + None => { + let kept = previous + .as_ref() + .and_then(|artifacts| artifacts.cases.get(&case.id)) + .filter(|kept| kept.frame == artifact.frame); + accepted(seed, case, &value, &mut artifact, reference, kept).await; + } + } + let _ = output.insert(case.id.clone(), artifact); + } + + for batch in &corpus.batches { + eprintln!("single value: {}", batch.id); + let id = &batch.id; + let kinds: Vec> = batch.kinds.iter().map(|kind| declared(kind)).collect(); + let values: Vec = batch.inputs.iter().map(input).collect(); + assert_eq!( + kinds.len(), + values.len(), + "{id}: one declared kind for each input" + ); + let (cipher, generates, retrieves) = counting(seed).await; + let keyset = cipher.default_keyset(); + let sealed = match ( + seal_all(&keyset, &values, &kinds, &batch.context), + &batch.expected_error, + ) { + (Err(error), Some(expected)) => { + assert_refusal(id, &error, expected); + assert_eq!( + generates.load(Ordering::SeqCst), + 0, + "{id}: a refused batch makes no key request" + ); + continue; + } + (Err(error), None) => panic!("{id}: the batch is refused: {error}"), + (Ok(_), Some(_)) => panic!("{id}: the batch is taken where a refusal is expected"), + (Ok(pending), None) => pending + .await + .unwrap_or_else(|error| panic!("{id}: the batch does not seal: {error}")), + }; + let requests = usize::from(!values.is_empty()); + assert_eq!( + sealed.len(), + values.len(), + "{id}: one ciphertext for each value" + ); + assert_eq!( + generates.load(Ordering::SeqCst), + requests, + "{id}: the batch seals in one key request" + ); + let opened = open_all(&keyset, sealed, &kinds, &batch.context) + .await + .unwrap_or_else(|error| panic!("{id}: the batch does not open: {error}")); + assert_eq!( + retrieves.load(Ordering::SeqCst), + requests, + "{id}: the batch opens in one key request" + ); + let stored = batch.stored.as_ref().unwrap_or(&batch.inputs); + assert_eq!( + opened.len(), + stored.len(), + "{id}: one value for each ciphertext" + ); + for (position, (opened, expected)) in opened.iter().zip(stored).enumerate() { + assert_eq!( + opened.frame(), + input(expected).frame(), + "{id}: the value at position {position}" + ); + } + } + + if update { + let artifacts = Artifacts { + version: 1, + profile: PROFILE.into(), + producer: format!("rust-native/stack-encrypt-{}", env!("CARGO_PKG_VERSION")), + cases: output, + }; + std::fs::write( + &path, + serde_json::to_string_pretty(&artifacts).expect("the artifacts as JSON") + "\n", + ) + .expect("write the expected file"); + } +} diff --git a/packages/stack-encrypt/tests/ui/opaque_blob_decrypt_requires_default.stderr b/packages/stack-encrypt/tests/ui/opaque_blob_decrypt_requires_default.stderr index 9121fd18c..568c19603 100644 --- a/packages/stack-encrypt/tests/ui/opaque_blob_decrypt_requires_default.stderr +++ b/packages/stack-encrypt/tests/ui/opaque_blob_decrypt_requires_default.stderr @@ -1,9 +1,18 @@ -error[E0277]: the trait bound `OpaqueBlob: OpaqueDecode` is not satisfied +error[E0277]: `OpaqueBlob` cannot be decrypted from one `Ciphertext` --> tests/ui/opaque_blob_decrypt_requires_default.rs:16:50 | 16 | let _refused: OpaqueBlob = keyset.decrypt(ct).await.unwrap(); - | ^^^^^^^ the trait `OpaqueDecode` is not implemented for `OpaqueBlob` - | + | ^^^^^^^ one `Ciphertext` decrypts into one owned value + | + = help: the trait `OpaqueDecode` is not implemented for `OpaqueBlob` + = note: one value is a scalar, such as a `String`, a `bool`, a float, a `Vec`, or a fixed-width integer other than `u8`. The docs of `OpaqueDecode` list every type that is accepted. + = note: an `Option` or a `Protected` of a scalar is one value too. So is a newtype that derives `Decrypt` over a scalar. + = note: for a date, a timestamp, a decimal, or a UUID, use `value::Date`, `value::Timestamp`, `value::Decimal`, or `value::Uuid`. A `uuid::Uuid`, a `rust_decimal::Decimal`, and the jiff types do not implement `Zeroize`. + = note: the type must also implement `Zeroize`, so that a decrypted value can be wiped when a later decrypt in the same call fails. + = note: the type must also be `Send` and `'static`. A `'static` type borrows no data. + = note: to decrypt a `Vec` into a `Vec`, with one element from each `Ciphertext`, use `DecryptFrom`. + = note: to decrypt a sequence, a map, or a struct that derives `Decrypt`, use `keyset.decrypt_tree`. `keyset.encrypt_tree` makes the tree of ciphertexts that it reads. + = note: to decrypt a whole `Deserialize` value from one `Ciphertext`, decrypt into `OpaqueBlob`. `T` must also implement `Default` and `Zeroize`. help: the trait `OpaqueDecode` is implemented for `OpaqueBlob` --> src/blob.rs | diff --git a/packages/stack-encrypt/tests/ui/opaque_blob_requires_zeroize.stderr b/packages/stack-encrypt/tests/ui/opaque_blob_requires_zeroize.stderr index ad432f03d..06cfc11f6 100644 --- a/packages/stack-encrypt/tests/ui/opaque_blob_requires_zeroize.stderr +++ b/packages/stack-encrypt/tests/ui/opaque_blob_requires_zeroize.stderr @@ -157,12 +157,21 @@ note: required by a bound in `OpaqueBlob` | pub struct OpaqueBlob(Zeroizing); | ^^^^^^^ required by this bound in `OpaqueBlob` -error[E0277]: the trait bound `OpaqueBlob: OpaqueDecode` is not satisfied +error[E0277]: `OpaqueBlob` cannot be decrypted from one `Ciphertext` --> tests/ui/opaque_blob_requires_zeroize.rs:18:48 | 18 | let _refused: OpaqueBlob = keyset.decrypt(ct).await.unwrap(); - | ^^^^^^^ the trait `OpaqueDecode` is not implemented for `OpaqueBlob` - | + | ^^^^^^^ one `Ciphertext` decrypts into one owned value + | + = help: the trait `OpaqueDecode` is not implemented for `OpaqueBlob` + = note: one value is a scalar, such as a `String`, a `bool`, a float, a `Vec`, or a fixed-width integer other than `u8`. The docs of `OpaqueDecode` list every type that is accepted. + = note: an `Option` or a `Protected` of a scalar is one value too. So is a newtype that derives `Decrypt` over a scalar. + = note: for a date, a timestamp, a decimal, or a UUID, use `value::Date`, `value::Timestamp`, `value::Decimal`, or `value::Uuid`. A `uuid::Uuid`, a `rust_decimal::Decimal`, and the jiff types do not implement `Zeroize`. + = note: the type must also implement `Zeroize`, so that a decrypted value can be wiped when a later decrypt in the same call fails. + = note: the type must also be `Send` and `'static`. A `'static` type borrows no data. + = note: to decrypt a `Vec` into a `Vec`, with one element from each `Ciphertext`, use `DecryptFrom`. + = note: to decrypt a sequence, a map, or a struct that derives `Decrypt`, use `keyset.decrypt_tree`. `keyset.encrypt_tree` makes the tree of ciphertexts that it reads. + = note: to decrypt a whole `Deserialize` value from one `Ciphertext`, decrypt into `OpaqueBlob`. `T` must also implement `Default` and `Zeroize`. help: the trait `OpaqueDecode` is implemented for `OpaqueBlob` --> src/blob.rs | diff --git a/packages/stack-encrypt/tests/ui/owned_collection_elements.stderr b/packages/stack-encrypt/tests/ui/owned_collection_elements.stderr index 32a9624ab..632b71be3 100644 --- a/packages/stack-encrypt/tests/ui/owned_collection_elements.stderr +++ b/packages/stack-encrypt/tests/ui/owned_collection_elements.stderr @@ -86,24 +86,26 @@ help: the following other types implement trait `Scalar` = note: required for `stack_encrypt::Ciphertext` to implement `EncryptTarget>` = note: this error originates in the macro `scalar` (in Nightly builds, run with -Z macro-backtrace for more info) -error[E0277]: the trait bound `u8: vitaminc_aead::typed::FromScalar` is not satisfied +error[E0277]: `u8` cannot be decrypted from one `Ciphertext` --> tests/ui/owned_collection_elements.rs:15:13 | 15 | let _ = Vec::::decrypt_from(column, keyset); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `vitaminc_aead::typed::FromScalar` is not implemented for `u8` + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ one `Ciphertext` decrypts into one owned value | - = help: the following other types implement trait `vitaminc_aead::typed::FromScalar`: - f32 - f64 - i128 - i16 - i32 - i64 - i8 - u128 - and $N others - = note: required for `u8` to implement `Decrypt` - = note: required for `u8` to implement `OpaqueDecode` + = help: the trait `OpaqueDecode` is not implemented for `u8` + = note: one value is a scalar, such as a `String`, a `bool`, a float, a `Vec`, or a fixed-width integer other than `u8`. The docs of `OpaqueDecode` list every type that is accepted. + = note: an `Option` or a `Protected` of a scalar is one value too. So is a newtype that derives `Decrypt` over a scalar. + = note: for a date, a timestamp, a decimal, or a UUID, use `value::Date`, `value::Timestamp`, `value::Decimal`, or `value::Uuid`. A `uuid::Uuid`, a `rust_decimal::Decimal`, and the jiff types do not implement `Zeroize`. + = note: the type must also implement `Zeroize`, so that a decrypted value can be wiped when a later decrypt in the same call fails. + = note: the type must also be `Send` and `'static`. A `'static` type borrows no data. + = note: to decrypt a `Vec` into a `Vec`, with one element from each `Ciphertext`, use `DecryptFrom`. + = note: to decrypt a sequence, a map, or a struct that derives `Decrypt`, use `keyset.decrypt_tree`. `keyset.encrypt_tree` makes the tree of ciphertexts that it reads. + = note: to decrypt a whole `Deserialize` value from one `Ciphertext`, decrypt into `OpaqueBlob`. `T` must also implement `Default` and `Zeroize`. +help: the trait `OpaqueDecode` is implemented for `OpaqueBlob` + --> src/blob.rs + | + | impl OpaqueDecode for OpaqueBlob {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ = note: required for `stack_encrypt::Ciphertext` to implement `DecryptSource` = note: 1 redundant requirement hidden = note: required for `Vec` to implement `DecryptSource>` diff --git a/packages/stack-encrypt/tests/ui/pass/scalar_decrypt_targets.rs b/packages/stack-encrypt/tests/ui/pass/scalar_decrypt_targets.rs new file mode 100644 index 000000000..b3caed3b7 --- /dev/null +++ b/packages/stack-encrypt/tests/ui/pass/scalar_decrypt_targets.rs @@ -0,0 +1,104 @@ +//! The targets that one `Ciphertext` decrypts into. Each must compile: +//! +//! - every scalar +//! - a `Protected` of a scalar, and a nullable scalar +//! - a JSON document +//! - the date, timestamp, decimal, and UUID values +//! - a derived newtype of a scalar, with no marker impl written for it +//! - an opaque blob, and a frame +//! +//! `tests/ui/scalar_decrypt_into_a_container.rs` pins the targets that must +//! not compile. +use stack_encrypt::dynamic::frame::OwnedFrame; +use stack_encrypt::json::JsonPlaintext; +use stack_encrypt::value::{Date, Decimal, Timestamp, Uuid}; +use stack_encrypt::{ + Ciphertext, Decrypt, DecryptFrom, KeysetCipher, OpaqueBlob, OpaqueDecode, Protected, + StackCipher, +}; +use stack_kms::FakeDataKeySource; + +/// A newtype that derives `Decrypt` over a scalar decrypts from one +/// ciphertext with no extra code. +#[derive(Decrypt, zeroize::Zeroize)] +struct Email(String); + +/// The same is true for a newtype of an integer, of another newtype, and of +/// a nullable scalar. +#[derive(Decrypt, zeroize::Zeroize)] +struct UserId(u64); +#[derive(Decrypt, zeroize::Zeroize)] +struct PrimaryEmail(Email); +#[derive(Decrypt, zeroize::Zeroize)] +struct Nickname(Option); + +/// A whole value stored as one blob decrypts through `OpaqueBlob`. +/// `OpaqueBlob` has its own impl of `OpaqueDecode`. +#[derive(Default, serde::Deserialize, zeroize::Zeroize)] +struct Profile { + name: String, +} + +fn opens() {} + +fn targets() { + opens::(); + opens::(); + opens::(); + opens::(); + opens::(); + opens::(); + opens::(); + opens::(); + opens::(); + opens::(); + opens::(); + opens::(); + opens::(); + opens::>(); + opens::<[u8; 16]>(); + opens::(); + opens::(); + opens::(); + opens::(); + opens::(); + opens::>(); + opens::>>(); + opens::>(); + opens::>(); + opens::>(); + opens::>>(); + opens::>>(); + opens::(); + opens::(); + opens::(); + opens::(); + opens::(); + opens::>(); + opens::>(); +} + +async fn calls( + cipher: &StackCipher, + keyset: &KeysetCipher<'_, FakeDataKeySource>, + ciphertext: Ciphertext, +) -> Result<(), stack_encrypt::Error> { + let _: i64 = keyset.decrypt(ciphertext.clone()).await?; + let _: Protected = keyset + .decrypt_with_context(ciphertext.clone(), ("users", "email")) + .await?; + let _ = keyset.decrypt::>(ciphertext.clone()).await?; + let _ = Vec::::decrypt_from(ciphertext.clone(), keyset).await?; + let _ = OwnedFrame::decrypt_from(ciphertext.clone(), cipher).await?; + let _ = Email::decrypt_from(ciphertext.clone(), cipher).await?; + let _: UserId = keyset.decrypt(ciphertext.clone()).await?; + // A column of ciphertexts is a `Vec`, with one scalar in + // each ciphertext. + let _ = Vec::::decrypt_from(vec![ciphertext], keyset).await?; + Ok(()) +} + +fn main() { + let _ = targets; + let _ = calls; +} diff --git a/packages/stack-encrypt/tests/ui/scalar_decrypt_into_a_container.rs b/packages/stack-encrypt/tests/ui/scalar_decrypt_into_a_container.rs new file mode 100644 index 000000000..a26885e7a --- /dev/null +++ b/packages/stack-encrypt/tests/ui/scalar_decrypt_into_a_container.rs @@ -0,0 +1,27 @@ +//! A `Ciphertext` contains one scalar. So its target must be built from one +//! scalar. A target that needs a container does not compile. These tests +//! cover a sequence, a map, a derived struct, a derived newtype of a +//! sequence, and a protected sequence. +//! `tests/ui/pass/scalar_decrypt_targets.rs` pins the targets that compile. +use std::collections::{BTreeMap, HashMap}; + +use stack_encrypt::{Ciphertext, Decrypt, DecryptFrom, KeysetCipher, Protected}; + +#[derive(Decrypt, zeroize::Zeroize)] +struct Account { + id: u64, +} + +#[derive(Decrypt, zeroize::Zeroize)] +struct Tags(Vec); + +fn unsupported(keyset: &KeysetCipher<'_, K>, ciphertext: Ciphertext) { + let _ = keyset.decrypt::>(ciphertext.clone()); + let _ = keyset.decrypt::>(ciphertext.clone()); + let _ = keyset.decrypt::(ciphertext.clone()); + let _ = keyset.decrypt::(ciphertext.clone()); + let _ = keyset.decrypt::>>(ciphertext.clone()); + let _ = keyset.decrypt_with_context::>(ciphertext.clone(), "users/tags"); + let _ = Vec::::decrypt_from(ciphertext, keyset); +} +fn main() {} diff --git a/packages/stack-encrypt/tests/ui/scalar_decrypt_into_a_container.stderr b/packages/stack-encrypt/tests/ui/scalar_decrypt_into_a_container.stderr new file mode 100644 index 000000000..317aea2d8 --- /dev/null +++ b/packages/stack-encrypt/tests/ui/scalar_decrypt_into_a_container.stderr @@ -0,0 +1,185 @@ +error[E0277]: `Vec` cannot be decrypted from one `Ciphertext` + --> tests/ui/scalar_decrypt_into_a_container.rs:19:30 + | +19 | let _ = keyset.decrypt::>(ciphertext.clone()); + | ^^^^^^^^^^^ one `Ciphertext` decrypts into one owned value + | + = help: the trait `OpaqueDecode` is not implemented for `Vec` + = note: one value is a scalar, such as a `String`, a `bool`, a float, a `Vec`, or a fixed-width integer other than `u8`. The docs of `OpaqueDecode` list every type that is accepted. + = note: an `Option` or a `Protected` of a scalar is one value too. So is a newtype that derives `Decrypt` over a scalar. + = note: for a date, a timestamp, a decimal, or a UUID, use `value::Date`, `value::Timestamp`, `value::Decimal`, or `value::Uuid`. A `uuid::Uuid`, a `rust_decimal::Decimal`, and the jiff types do not implement `Zeroize`. + = note: the type must also implement `Zeroize`, so that a decrypted value can be wiped when a later decrypt in the same call fails. + = note: the type must also be `Send` and `'static`. A `'static` type borrows no data. + = note: to decrypt a `Vec` into a `Vec`, with one element from each `Ciphertext`, use `DecryptFrom`. + = note: to decrypt a sequence, a map, or a struct that derives `Decrypt`, use `keyset.decrypt_tree`. `keyset.encrypt_tree` makes the tree of ciphertexts that it reads. + = note: to decrypt a whole `Deserialize` value from one `Ciphertext`, decrypt into `OpaqueBlob`. `T` must also implement `Default` and `Zeroize`. +help: the trait `OpaqueDecode` is implemented for `OpaqueBlob` + --> src/blob.rs + | + | impl OpaqueDecode for OpaqueBlob {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +note: required by a bound in `stack_encrypt::scalar::>::decrypt` + --> src/scalar.rs + | + | pub fn decrypt(&self, ciphertext: Ciphertext) -> Pending<'_, P, K> { + | ^^^^^^^^^^^^ required by this bound in `stack_encrypt::scalar::>::decrypt` + +error[E0277]: `BTreeMap` cannot be decrypted from one `Ciphertext` + --> tests/ui/scalar_decrypt_into_a_container.rs:20:30 + | +20 | let _ = keyset.decrypt::>(ciphertext.clone()); + | ^^^^^^^^^^^^^^^^^^^^^ one `Ciphertext` decrypts into one owned value + | + = help: the trait `OpaqueDecode` is not implemented for `BTreeMap` + = note: one value is a scalar, such as a `String`, a `bool`, a float, a `Vec`, or a fixed-width integer other than `u8`. The docs of `OpaqueDecode` list every type that is accepted. + = note: an `Option` or a `Protected` of a scalar is one value too. So is a newtype that derives `Decrypt` over a scalar. + = note: for a date, a timestamp, a decimal, or a UUID, use `value::Date`, `value::Timestamp`, `value::Decimal`, or `value::Uuid`. A `uuid::Uuid`, a `rust_decimal::Decimal`, and the jiff types do not implement `Zeroize`. + = note: the type must also implement `Zeroize`, so that a decrypted value can be wiped when a later decrypt in the same call fails. + = note: the type must also be `Send` and `'static`. A `'static` type borrows no data. + = note: to decrypt a `Vec` into a `Vec`, with one element from each `Ciphertext`, use `DecryptFrom`. + = note: to decrypt a sequence, a map, or a struct that derives `Decrypt`, use `keyset.decrypt_tree`. `keyset.encrypt_tree` makes the tree of ciphertexts that it reads. + = note: to decrypt a whole `Deserialize` value from one `Ciphertext`, decrypt into `OpaqueBlob`. `T` must also implement `Default` and `Zeroize`. +help: the trait `OpaqueDecode` is implemented for `OpaqueBlob` + --> src/blob.rs + | + | impl OpaqueDecode for OpaqueBlob {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +note: required by a bound in `stack_encrypt::scalar::>::decrypt` + --> src/scalar.rs + | + | pub fn decrypt(&self, ciphertext: Ciphertext) -> Pending<'_, P, K> { + | ^^^^^^^^^^^^ required by this bound in `stack_encrypt::scalar::>::decrypt` + +error[E0277]: `Account` cannot be decrypted from one `Ciphertext` + --> tests/ui/scalar_decrypt_into_a_container.rs:21:30 + | +21 | let _ = keyset.decrypt::(ciphertext.clone()); + | ^^^^^^^ one `Ciphertext` decrypts into one owned value + | +help: the trait `OpaqueDecode` is not implemented for `Account` + --> tests/ui/scalar_decrypt_into_a_container.rs:11:1 + | +11 | struct Account { + | ^^^^^^^^^^^^^^ + = note: one value is a scalar, such as a `String`, a `bool`, a float, a `Vec`, or a fixed-width integer other than `u8`. The docs of `OpaqueDecode` list every type that is accepted. + = note: an `Option` or a `Protected` of a scalar is one value too. So is a newtype that derives `Decrypt` over a scalar. + = note: for a date, a timestamp, a decimal, or a UUID, use `value::Date`, `value::Timestamp`, `value::Decimal`, or `value::Uuid`. A `uuid::Uuid`, a `rust_decimal::Decimal`, and the jiff types do not implement `Zeroize`. + = note: the type must also implement `Zeroize`, so that a decrypted value can be wiped when a later decrypt in the same call fails. + = note: the type must also be `Send` and `'static`. A `'static` type borrows no data. + = note: to decrypt a `Vec` into a `Vec`, with one element from each `Ciphertext`, use `DecryptFrom`. + = note: to decrypt a sequence, a map, or a struct that derives `Decrypt`, use `keyset.decrypt_tree`. `keyset.encrypt_tree` makes the tree of ciphertexts that it reads. + = note: to decrypt a whole `Deserialize` value from one `Ciphertext`, decrypt into `OpaqueBlob`. `T` must also implement `Default` and `Zeroize`. +help: the trait `OpaqueDecode` is implemented for `OpaqueBlob` + --> src/blob.rs + | + | impl OpaqueDecode for OpaqueBlob {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +note: required by a bound in `stack_encrypt::scalar::>::decrypt` + --> src/scalar.rs + | + | pub fn decrypt(&self, ciphertext: Ciphertext) -> Pending<'_, P, K> { + | ^^^^^^^^^^^^ required by this bound in `stack_encrypt::scalar::>::decrypt` + +error[E0277]: `Tags` cannot be decrypted from one `Ciphertext` + --> tests/ui/scalar_decrypt_into_a_container.rs:22:30 + | +22 | let _ = keyset.decrypt::(ciphertext.clone()); + | ^^^^ one `Ciphertext` decrypts into one owned value + | +help: the trait `OpaqueDecode` is not implemented for `Tags` + --> tests/ui/scalar_decrypt_into_a_container.rs:16:1 + | +16 | struct Tags(Vec); + | ^^^^^^^^^^^ + = note: one value is a scalar, such as a `String`, a `bool`, a float, a `Vec`, or a fixed-width integer other than `u8`. The docs of `OpaqueDecode` list every type that is accepted. + = note: an `Option` or a `Protected` of a scalar is one value too. So is a newtype that derives `Decrypt` over a scalar. + = note: for a date, a timestamp, a decimal, or a UUID, use `value::Date`, `value::Timestamp`, `value::Decimal`, or `value::Uuid`. A `uuid::Uuid`, a `rust_decimal::Decimal`, and the jiff types do not implement `Zeroize`. + = note: the type must also implement `Zeroize`, so that a decrypted value can be wiped when a later decrypt in the same call fails. + = note: the type must also be `Send` and `'static`. A `'static` type borrows no data. + = note: to decrypt a `Vec` into a `Vec`, with one element from each `Ciphertext`, use `DecryptFrom`. + = note: to decrypt a sequence, a map, or a struct that derives `Decrypt`, use `keyset.decrypt_tree`. `keyset.encrypt_tree` makes the tree of ciphertexts that it reads. + = note: to decrypt a whole `Deserialize` value from one `Ciphertext`, decrypt into `OpaqueBlob`. `T` must also implement `Default` and `Zeroize`. +help: the trait `OpaqueDecode` is implemented for `OpaqueBlob` + --> src/blob.rs + | + | impl OpaqueDecode for OpaqueBlob {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +note: required by a bound in `stack_encrypt::scalar::>::decrypt` + --> src/scalar.rs + | + | pub fn decrypt(&self, ciphertext: Ciphertext) -> Pending<'_, P, K> { + | ^^^^^^^^^^^^ required by this bound in `stack_encrypt::scalar::>::decrypt` + +error[E0277]: `Protected>` cannot be decrypted from one `Ciphertext` + --> tests/ui/scalar_decrypt_into_a_container.rs:23:30 + | +23 | let _ = keyset.decrypt::>>(ciphertext.clone()); + | ^^^^^^^^^^^^^^^^^^^ one `Ciphertext` decrypts into one owned value + | + = help: the trait `OpaqueDecode` is not implemented for `Protected>` + = note: one value is a scalar, such as a `String`, a `bool`, a float, a `Vec`, or a fixed-width integer other than `u8`. The docs of `OpaqueDecode` list every type that is accepted. + = note: an `Option` or a `Protected` of a scalar is one value too. So is a newtype that derives `Decrypt` over a scalar. + = note: for a date, a timestamp, a decimal, or a UUID, use `value::Date`, `value::Timestamp`, `value::Decimal`, or `value::Uuid`. A `uuid::Uuid`, a `rust_decimal::Decimal`, and the jiff types do not implement `Zeroize`. + = note: the type must also implement `Zeroize`, so that a decrypted value can be wiped when a later decrypt in the same call fails. + = note: the type must also be `Send` and `'static`. A `'static` type borrows no data. + = note: to decrypt a `Vec` into a `Vec`, with one element from each `Ciphertext`, use `DecryptFrom`. + = note: to decrypt a sequence, a map, or a struct that derives `Decrypt`, use `keyset.decrypt_tree`. `keyset.encrypt_tree` makes the tree of ciphertexts that it reads. + = note: to decrypt a whole `Deserialize` value from one `Ciphertext`, decrypt into `OpaqueBlob`. `T` must also implement `Default` and `Zeroize`. +help: the trait `OpaqueDecode` is implemented for `OpaqueBlob` + --> src/blob.rs + | + | impl OpaqueDecode for OpaqueBlob {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +note: required by a bound in `stack_encrypt::scalar::>::decrypt` + --> src/scalar.rs + | + | pub fn decrypt(&self, ciphertext: Ciphertext) -> Pending<'_, P, K> { + | ^^^^^^^^^^^^ required by this bound in `stack_encrypt::scalar::>::decrypt` + +error[E0277]: `HashMap` cannot be decrypted from one `Ciphertext` + --> tests/ui/scalar_decrypt_into_a_container.rs:24:43 + | +24 | let _ = keyset.decrypt_with_context::>(ciphertext.clone(), "users/tags"); + | ^^^^^^^^^^^^^^^^^^^^^^^ one `Ciphertext` decrypts into one owned value + | + = help: the trait `OpaqueDecode` is not implemented for `HashMap` + = note: one value is a scalar, such as a `String`, a `bool`, a float, a `Vec`, or a fixed-width integer other than `u8`. The docs of `OpaqueDecode` list every type that is accepted. + = note: an `Option` or a `Protected` of a scalar is one value too. So is a newtype that derives `Decrypt` over a scalar. + = note: for a date, a timestamp, a decimal, or a UUID, use `value::Date`, `value::Timestamp`, `value::Decimal`, or `value::Uuid`. A `uuid::Uuid`, a `rust_decimal::Decimal`, and the jiff types do not implement `Zeroize`. + = note: the type must also implement `Zeroize`, so that a decrypted value can be wiped when a later decrypt in the same call fails. + = note: the type must also be `Send` and `'static`. A `'static` type borrows no data. + = note: to decrypt a `Vec` into a `Vec`, with one element from each `Ciphertext`, use `DecryptFrom`. + = note: to decrypt a sequence, a map, or a struct that derives `Decrypt`, use `keyset.decrypt_tree`. `keyset.encrypt_tree` makes the tree of ciphertexts that it reads. + = note: to decrypt a whole `Deserialize` value from one `Ciphertext`, decrypt into `OpaqueBlob`. `T` must also implement `Default` and `Zeroize`. +help: the trait `OpaqueDecode` is implemented for `OpaqueBlob` + --> src/blob.rs + | + | impl OpaqueDecode for OpaqueBlob {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +note: required by a bound in `stack_encrypt::scalar::>::decrypt_with_context` + --> src/scalar.rs + | + | pub fn decrypt_with_context<'c, P: OpaqueDecode>( + | ^^^^^^^^^^^^ required by this bound in `stack_encrypt::scalar::>::decrypt_with_context` + +error[E0277]: `Vec` cannot be decrypted from one `Ciphertext` + --> tests/ui/scalar_decrypt_into_a_container.rs:25:13 + | +25 | let _ = Vec::::decrypt_from(ciphertext, keyset); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ one `Ciphertext` decrypts into one owned value + | + = help: the trait `OpaqueDecode` is not implemented for `Vec` + = note: one value is a scalar, such as a `String`, a `bool`, a float, a `Vec`, or a fixed-width integer other than `u8`. The docs of `OpaqueDecode` list every type that is accepted. + = note: an `Option` or a `Protected` of a scalar is one value too. So is a newtype that derives `Decrypt` over a scalar. + = note: for a date, a timestamp, a decimal, or a UUID, use `value::Date`, `value::Timestamp`, `value::Decimal`, or `value::Uuid`. A `uuid::Uuid`, a `rust_decimal::Decimal`, and the jiff types do not implement `Zeroize`. + = note: the type must also implement `Zeroize`, so that a decrypted value can be wiped when a later decrypt in the same call fails. + = note: the type must also be `Send` and `'static`. A `'static` type borrows no data. + = note: to decrypt a `Vec` into a `Vec`, with one element from each `Ciphertext`, use `DecryptFrom`. + = note: to decrypt a sequence, a map, or a struct that derives `Decrypt`, use `keyset.decrypt_tree`. `keyset.encrypt_tree` makes the tree of ciphertexts that it reads. + = note: to decrypt a whole `Deserialize` value from one `Ciphertext`, decrypt into `OpaqueBlob`. `T` must also implement `Default` and `Zeroize`. +help: the trait `OpaqueDecode` is implemented for `OpaqueBlob` + --> src/blob.rs + | + | impl OpaqueDecode for OpaqueBlob {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + = note: required for `stack_encrypt::Ciphertext` to implement `DecryptSource>` diff --git a/packages/stack-encrypt/tests/ui/scalar_decrypt_target_requires_zeroize.rs b/packages/stack-encrypt/tests/ui/scalar_decrypt_target_requires_zeroize.rs new file mode 100644 index 000000000..a1569f532 --- /dev/null +++ b/packages/stack-encrypt/tests/ui/scalar_decrypt_target_requires_zeroize.rs @@ -0,0 +1,15 @@ +//! One scalar builds a newtype that derives `Decrypt` over a `String`. A +//! `Ciphertext` still does not decrypt into the newtype, because the newtype +//! does not implement `Zeroize`. The same is true of a `uuid::Uuid`: the +//! error points to `value::Uuid`. +use stack_encrypt::{Ciphertext, Decrypt, KeysetCipher}; + +#[derive(Decrypt)] +struct Email(String); + +fn refused(keyset: &KeysetCipher<'_, K>, ciphertext: Ciphertext) { + let _ = keyset.decrypt::(ciphertext.clone()); + let _ = keyset.decrypt::(ciphertext); +} + +fn main() {} diff --git a/packages/stack-encrypt/tests/ui/scalar_decrypt_target_requires_zeroize.stderr b/packages/stack-encrypt/tests/ui/scalar_decrypt_target_requires_zeroize.stderr new file mode 100644 index 000000000..c177655b2 --- /dev/null +++ b/packages/stack-encrypt/tests/ui/scalar_decrypt_target_requires_zeroize.stderr @@ -0,0 +1,55 @@ +error[E0277]: `Email` cannot be decrypted from one `Ciphertext` + --> tests/ui/scalar_decrypt_target_requires_zeroize.rs:11:30 + | +11 | let _ = keyset.decrypt::(ciphertext.clone()); + | ^^^^^ one `Ciphertext` decrypts into one owned value + | +help: the trait `OpaqueDecode` is not implemented for `Email` + --> tests/ui/scalar_decrypt_target_requires_zeroize.rs:8:1 + | + 8 | struct Email(String); + | ^^^^^^^^^^^^ + = note: one value is a scalar, such as a `String`, a `bool`, a float, a `Vec`, or a fixed-width integer other than `u8`. The docs of `OpaqueDecode` list every type that is accepted. + = note: an `Option` or a `Protected` of a scalar is one value too. So is a newtype that derives `Decrypt` over a scalar. + = note: for a date, a timestamp, a decimal, or a UUID, use `value::Date`, `value::Timestamp`, `value::Decimal`, or `value::Uuid`. A `uuid::Uuid`, a `rust_decimal::Decimal`, and the jiff types do not implement `Zeroize`. + = note: the type must also implement `Zeroize`, so that a decrypted value can be wiped when a later decrypt in the same call fails. + = note: the type must also be `Send` and `'static`. A `'static` type borrows no data. + = note: to decrypt a `Vec` into a `Vec`, with one element from each `Ciphertext`, use `DecryptFrom`. + = note: to decrypt a sequence, a map, or a struct that derives `Decrypt`, use `keyset.decrypt_tree`. `keyset.encrypt_tree` makes the tree of ciphertexts that it reads. + = note: to decrypt a whole `Deserialize` value from one `Ciphertext`, decrypt into `OpaqueBlob`. `T` must also implement `Default` and `Zeroize`. +help: the trait `OpaqueDecode` is implemented for `OpaqueBlob` + --> src/blob.rs + | + | impl OpaqueDecode for OpaqueBlob {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +note: required by a bound in `stack_encrypt::scalar::>::decrypt` + --> src/scalar.rs + | + | pub fn decrypt(&self, ciphertext: Ciphertext) -> Pending<'_, P, K> { + | ^^^^^^^^^^^^ required by this bound in `stack_encrypt::scalar::>::decrypt` + +error[E0277]: `uuid::Uuid` cannot be decrypted from one `Ciphertext` + --> tests/ui/scalar_decrypt_target_requires_zeroize.rs:12:30 + | +12 | let _ = keyset.decrypt::(ciphertext); + | ^^^^^^^^^^ one `Ciphertext` decrypts into one owned value + | + = help: the trait `OpaqueDecode` is not implemented for `uuid::Uuid` + = note: one value is a scalar, such as a `String`, a `bool`, a float, a `Vec`, or a fixed-width integer other than `u8`. The docs of `OpaqueDecode` list every type that is accepted. + = note: an `Option` or a `Protected` of a scalar is one value too. So is a newtype that derives `Decrypt` over a scalar. + = note: for a date, a timestamp, a decimal, or a UUID, use `value::Date`, `value::Timestamp`, `value::Decimal`, or `value::Uuid`. A `uuid::Uuid`, a `rust_decimal::Decimal`, and the jiff types do not implement `Zeroize`. + = note: the type must also implement `Zeroize`, so that a decrypted value can be wiped when a later decrypt in the same call fails. + = note: the type must also be `Send` and `'static`. A `'static` type borrows no data. + = note: to decrypt a `Vec` into a `Vec`, with one element from each `Ciphertext`, use `DecryptFrom`. + = note: to decrypt a sequence, a map, or a struct that derives `Decrypt`, use `keyset.decrypt_tree`. `keyset.encrypt_tree` makes the tree of ciphertexts that it reads. + = note: to decrypt a whole `Deserialize` value from one `Ciphertext`, decrypt into `OpaqueBlob`. `T` must also implement `Default` and `Zeroize`. +help: the trait `OpaqueDecode` is implemented for `OpaqueBlob` + --> src/blob.rs + | + | impl OpaqueDecode for OpaqueBlob {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +note: required by a bound in `stack_encrypt::scalar::>::decrypt` + --> src/scalar.rs + | + | pub fn decrypt(&self, ciphertext: Ciphertext) -> Pending<'_, P, K> { + | ^^^^^^^^^^^^ required by this bound in `stack_encrypt::scalar::>::decrypt` diff --git a/packages/stack-encrypt/tests/value_bytes.rs b/packages/stack-encrypt/tests/value_bytes.rs index 93660f76f..57967889e 100644 --- a/packages/stack-encrypt/tests/value_bytes.rs +++ b/packages/stack-encrypt/tests/value_bytes.rs @@ -28,34 +28,24 @@ mod common; -use std::borrow::Cow; -use std::cell::RefCell; -use std::collections::HashMap; use std::path::PathBuf; -use std::sync::{Arc, Mutex}; +use std::sync::Arc; use common::conformance::{value, Input}; use common::frames::{frame, object}; -use common::{hex, DeterministicSource}; +use common::hex; +use common::leaves::{kept_cipher, reveal, Kept, KeptKeys}; use serde_json::{json, Map, Value as Json}; use stack_encrypt::dynamic::{self, frame::OwnedFrame, record}; use stack_encrypt::json::JsonPlaintext; use stack_encrypt::sem::EqualityTerm; use stack_encrypt::target::{equality, Borrowed, CallerContext}; use stack_encrypt::value::{Date, Decimal, Timestamp, Uuid as UuidValue}; -use stack_encrypt::{AsProtectedRef as _, CipherText, SealedValue, StackCipher, StackCipherText}; -use stack_kms::{ - DataKey, DataKeySource, DataKeyWithTag, GenerateKeyPayload, IdentifiedBy, IndexKey, - IndexKeySource, RetrieveKeyPayload, UnverifiedContext, -}; +use stack_encrypt::{AsProtectedRef as _, CipherText, StackCipher}; use uuid::Uuid; use vitaminc_aead::plaintext::{FixedType, Float, Int, Logical, Physical, Raw, TimeUnit, Width}; -use vitaminc_aead::seal::Cipher; -use vitaminc_aead::{ - Context, Encrypt, Frame, FrameWriter, IntoContext, LocalCipherText, Unspecified, -}; -use vitaminc_encrypt::{Aes256Cipher, Key as AesKey}; -use vitaminc_protected::{Buffer, Controlled as _, Protected}; +use vitaminc_aead::{Encrypt, Frame}; +use vitaminc_protected::{Buffer, Controlled as _}; const SEED: [u8; 32] = *b"stack-encrypt value bytes v1 "; @@ -66,142 +56,9 @@ fn fixture_path() -> PathBuf { PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/value_bytes_v1.json") } -// ============================================================================= -// Opening a sealed leaf to the plaintext sealed in it -// ============================================================================= - -/// [`DeterministicSource`], keeping each data key it generates by its IV, -/// so a test can open the leaves sealed under them without the engine. -struct KeptKeys { - inner: DeterministicSource, - keys: Arc, [u8; 32]>>>, -} - -impl stack_kms::KeySourceKind for KeptKeys { - type Kind = stack_kms::OwnIdentity; -} - -impl DataKeySource for KeptKeys { - async fn generate_keys( - &self, - payloads: Vec>, - keyset_id: Option, - unverified_context: Option>, - ) -> Result, stack_kms::Error> { - let keys = self - .inner - .generate_keys(payloads, keyset_id, unverified_context) - .await?; - let mut kept = self.keys.lock().unwrap(); - for key in &keys { - let _ = kept.insert(key.key.iv.to_vec(), *key.key.key()); - } - Ok(keys) - } - - async fn retrieve_keys( - &self, - payloads: Vec>, - keyset_id: Option, - unverified_context: Option<&UnverifiedContext>, - ) -> Result, stack_kms::Error> { - self.inner - .retrieve_keys(payloads, keyset_id, unverified_context) - .await - } -} - -impl IndexKeySource for KeptKeys { - async fn load_index_key( - &self, - keyset_id: Option, - ) -> Result<(Uuid, IndexKey), stack_kms::Error> { - self.inner.load_index_key(keyset_id).await - } -} - -/// A cipher over the kept keys, and the keys. -async fn cipher() -> ( - StackCipher, - Arc, [u8; 32]>>>, -) { - let keys = Arc::default(); - let cipher = StackCipher::builder() - .kms(KeptKeys { - inner: DeterministicSource::new(SEED), - keys: Arc::clone(&keys), - }) - .init() - .await - .expect("build cipher"); - (cipher, keys) -} - -/// A vitaminc cipher that opens a stored leaf with its kept key, under the -/// AAD the engine binds a leaf to (`stack-encrypt/leaf`, the format version, -/// the keyset, the AAD of the leaf's place and the key tag, as a PAE), and -/// keeps each plaintext it opened, in walk order. -struct Reveal<'k> { - keys: &'k HashMap, [u8; 32]>, - opened: RefCell>, -} - -impl Cipher for Reveal<'_> { - type Leaf = SealedValue; - type Error = Unspecified; - - fn seal(&self, _: Protected>, _: &Context<'_>) -> Result { - Err(Unspecified) - } - - fn open( - &self, - leaf: SealedValue, - aad: &Context<'_>, - ) -> Result>, Unspecified> { - let (keyset_id, iv, tag, ciphertext) = leaf.into_parts(); - let key = self.keys.get(iv.as_slice()).ok_or(Unspecified)?; - let aad = Context::pae(&[ - b"stack-encrypt/leaf", - &[SealedValue::FORMAT_VERSION], - keyset_id.as_bytes(), - aad.as_bytes(), - &tag, - ]); - let cipher = Aes256Cipher::new(&AesKey::from(*key))?; - let plaintext = cipher.open(LocalCipherText::from(ciphertext), &aad)?; - self.opened.borrow_mut().push(hex(plaintext.risky_ref())); - Ok(plaintext) - } -} - -/// The plaintext of every leaf of `tree`, sealed under `context`, in walk -/// order: a scalar's tagged bytes, a typed null's padded bytes, and an empty -/// container's marker as the empty string. -fn reveal<'c>( - keys: &Mutex, [u8; 32]>>, - tree: StackCipherText, - context: impl IntoContext<'c>, -) -> Vec { - let keys = keys.lock().unwrap(); - let reveal = Reveal { - keys: &keys, - opened: RefCell::default(), - }; - let mut out = Buffer::default(); - vitaminc_aead::decrypt_into( - &reveal, - tree, - context.into_context(), - FrameWriter::new(&mut out), - ) - .unwrap_or_else(|_| { - panic!( - "the leaves open under their kept keys: if every case fails here, \ - the AAD `Reveal` builds no longer mirrors `leaf_aad` in src/cipher.rs" - ) - }); - reveal.opened.into_inner() +/// A cipher over the kept keys of [`SEED`], and the keys. +async fn cipher() -> (StackCipher, Arc) { + kept_cipher(SEED).await } fn context_label() -> String { @@ -216,7 +73,7 @@ fn context_label() -> String { /// the leaf `encrypt_tree` seals it as. async fn typed( cipher: &StackCipher, - keys: &Mutex, [u8; 32]>>, + keys: &Kept, frame_of: T, sealed: T, ) -> Json { @@ -290,10 +147,7 @@ fn document() -> JsonPlaintext { JsonPlaintext::from(json!({"a": [1, "x"], "b": null})) } -async fn typed_section( - cipher: &StackCipher, - keys: &Mutex, [u8; 32]>>, -) -> Json { +async fn typed_section(cipher: &StackCipher, keys: &Kept) -> Json { let mut out = Map::new(); macro_rules! pin { ($name:literal, $value:expr) => { @@ -368,7 +222,7 @@ fn plan(spec: &Json) -> Result { /// refusal's code and reason. async fn seal_row( cipher: &StackCipher, - keys: &Mutex, [u8; 32]>>, + keys: &Kept, spec: Json, row: impl Encrypt, ) -> Json { @@ -440,10 +294,7 @@ const KINDS: &[(&str, &str)] = &[ ("bytes", "00ff10"), ]; -async fn dynamic_section( - cipher: &StackCipher, - keys: &Mutex, [u8; 32]>>, -) -> Json { +async fn dynamic_section(cipher: &StackCipher, keys: &Kept) -> Json { let mut out = Map::new(); for (kind, text) in KINDS { let value = value(&input(kind, text)); @@ -540,7 +391,7 @@ fn typed_null(ty: FixedType) -> Vec { async fn host_row_outcome( cipher: &StackCipher, - keys: &Mutex, [u8; 32]>>, + keys: &Kept, spec: Json, field_frame: &[u8], ) -> Json { @@ -581,10 +432,7 @@ fn envelope(logical: u8, parameter: u8, int64: &[u8; 8]) -> Vec { out } -async fn host_section( - cipher: &StackCipher, - keys: &Mutex, [u8; 32]>>, -) -> Json { +async fn host_section(cipher: &StackCipher, keys: &Kept) -> Json { let to = |raw: Raw<'_>| { vitaminc_aead::to_frame(raw) .expect("a host frame") @@ -680,10 +528,7 @@ async fn host_section( /// A typed null a host sends (Go's `vcvalue.TypedNull`, or a nil pointer to /// a fixed-width type), against each null policy of a typed field, an /// untyped field, and inside an untyped value. -async fn typed_null_section( - cipher: &StackCipher, - keys: &Mutex, [u8; 32]>>, -) -> Json { +async fn typed_null_section(cipher: &StackCipher, keys: &Kept) -> Json { let int32 = typed_null(FixedType::new(None, Width::I32).expect("a fixed type")); let int64 = typed_null(FixedType::new(None, Width::I64).expect("a fixed type")); let mut out = Map::new(); @@ -745,10 +590,7 @@ async fn typed_null_section( // A JSON document // ============================================================================= -async fn json_section( - cipher: &StackCipher, - keys: &Mutex, [u8; 32]>>, -) -> Json { +async fn json_section(cipher: &StackCipher, keys: &Kept) -> Json { let text = r#"{"a":[1,"x"],"b":null}"#; let opened = dynamic::json_frame(&json!({"a": [1, "x"], "b": null})).expect("a document"); let as_text = frame(String::from(text)); diff --git a/packages/vitaminc-aead/CHANGELOG.md b/packages/vitaminc-aead/CHANGELOG.md index f03bb0d49..69a8e68c2 100644 --- a/packages/vitaminc-aead/CHANGELOG.md +++ b/packages/vitaminc-aead/CHANGELOG.md @@ -16,6 +16,21 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ### Added +- `ScalarTarget` (also `typed::ScalarTarget`): a trait for a decrypt target that is built from one scalar. + `ScalarTarget` is the decrypt-side counterpart of `Scalar`. + Code that decrypts exactly one leaf bounds its target on `ScalarTarget`, so a target that needs a sequence or a map does not compile. + No one can implement `ScalarTarget` directly: a target has it when its sink implements `TakesScalar`. + So every `FromScalar` type is a `ScalarTarget`, and a fieldless enum that derives `Decrypt` is one too. + An `Option` of a `ScalarTarget`, a newtype that derives `Decrypt` over one, and `OwnedFrame` are also `ScalarTarget`s. + So is a `Protected` of a scalar, or of an `Option` of a scalar. + A `Vec` other than `Vec`, a map, a derived struct with named fields, and a newtype of one of those are not `ScalarTarget`s. + The compile error for a target that is not a `ScalarTarget` names the target, and says what a scalar target is. + Nothing in this crate bounds on `ScalarTarget`, so no existing code changes. +- `TakesScalar` (also `typed::TakesScalar`): a trait for a sink that builds its value from one scalar. + `ScalarSink`, `ScalarProtected`, and `OwnedFrameSink` implement it. + `Optional`, `ProtectedOptional`, `Wrapped`, and `Wrap` implement it over a sink that implements it. + A hand-written sink opts in with an empty impl. + That impl makes the target of the sink a `ScalarTarget`. - `plaintext::ValueKind`: what a value is, without the value, with the text name a schema spells it with (`"int32"`, `"timestamp"`, `"object"`, `"json"`, …). It covers every scalar, an array, an object and a JSON document. `ValueKind::Uuid` (`"uuid"`) is a UUID: `Logical::Uuid` over sixteen bytes. Its zero is sixteen zero bytes, its null is a typed null as long as a UUID leaf, and it holds only a UUID. diff --git a/packages/vitaminc-aead/src/frame/owned.rs b/packages/vitaminc-aead/src/frame/owned.rs index 384972d67..8f0494a47 100644 --- a/packages/vitaminc-aead/src/frame/owned.rs +++ b/packages/vitaminc-aead/src/frame/owned.rs @@ -9,7 +9,7 @@ use crate::plaintext::{ Encrypt, EncryptRef, FixedType, Logical, MapSink, Physical, SeqSink, Sink, SourceError, }; use crate::tags; -use crate::typed::{DecodeError, Decrypt}; +use crate::typed::{DecodeError, Decrypt, TakesScalar}; /// One value as a transport frame, in a [`Buffer`] of its own: a value /// kept past the call that wrote it, and what a ciphertext opens into. @@ -170,6 +170,10 @@ impl From for DecodeError { /// written. pub struct OwnedFrameSink(()); +/// One scalar always builds a frame: the frame of that scalar, or the null +/// frame. So one leaf can be decrypted into an [`OwnedFrame`]. +impl TakesScalar for OwnedFrameSink {} + /// A container an [`OwnedFrameSink`] is opening: a sequence or a map /// written in place into the frame's buffer, which it owns until it ends. /// A map refuses a repeated key, without naming it. diff --git a/packages/vitaminc-aead/src/lib.rs b/packages/vitaminc-aead/src/lib.rs index 88dc2a298..64e044960 100644 --- a/packages/vitaminc-aead/src/lib.rs +++ b/packages/vitaminc-aead/src/lib.rs @@ -77,7 +77,10 @@ pub use seal::{AsyncCipher, Cipher, Node, Opened, Pending}; pub use shape::{Refusal, Unencryptable}; // Decryption: typed targets, and sinks of any kind. #[doc(inline)] -pub use typed::{decrypt, decrypt_async, DecodeError, Decrypt, DecryptProtected, FromScalar}; +pub use typed::{ + decrypt, decrypt_async, DecodeError, Decrypt, DecryptProtected, FromScalar, ScalarTarget, + TakesScalar, +}; #[doc(inline)] pub use walk::{decrypt_into, decrypt_into_async, decrypt_to_frame, walk, DecryptError}; // The frame: a value as transport bytes, and back. diff --git a/packages/vitaminc-aead/src/typed.rs b/packages/vitaminc-aead/src/typed.rs index 600e9792c..4ac8ae934 100644 --- a/packages/vitaminc-aead/src/typed.rs +++ b/packages/vitaminc-aead/src/typed.rs @@ -15,6 +15,16 @@ //! kind, and never reads it as a zero. `HashMap` and `BTreeMap` //! read a map, each value through `T`'s sink. //! +//! [`ScalarTarget`] is implemented for each target that is built from one +//! scalar. Those are the scalar targets and +//! [`OwnedFrame`](crate::OwnedFrame). An `Option`, a `Protected`, and a +//! derived newtype of a scalar target are also built from one scalar. +//! +//! Code that decrypts exactly one leaf bounds its target on `ScalarTarget`. +//! A target that needs a container then does not compile. No one implements +//! `ScalarTarget` directly: a target has it when its sink implements +//! [`TakesScalar`]. +//! //! `Protected` is a target for every `T` that implements //! [`DecryptProtected`]: any scalar target that can be wiped, and a //! `Vec` or `Option` of such targets, nested to any depth. A @@ -265,6 +275,232 @@ impl Decrypt for T { } } +/// A decrypt target that is built from one scalar. +/// +/// `ScalarTarget` is the decrypt-side counterpart of +/// [`Scalar`](crate::Scalar). A leaf is one encrypted scalar or one +/// encrypted null. A leaf is never a sequence or a map. So code that +/// decrypts exactly one leaf bounds its target on this trait. A target that +/// needs a sequence or a map then fails to compile. +/// +/// With a bound on [`Decrypt`] alone, such a target would compile. The code +/// would then decrypt the leaf and return an error afterwards. +/// +/// # How a target gets this trait +/// +/// You cannot implement this trait yourself. A sink is the builder that a +/// target names in [`Decrypt::Sink`]. The decrypt code passes each decrypted +/// value to the sink, and the sink builds the target. A target is a +/// `ScalarTarget` when its sink implements [`TakesScalar`]. +/// +/// So these targets are `ScalarTarget`s with no code of their own: +/// +/// - Every [`FromScalar`] type, such as `bool`, the fixed-width integers +/// except `u8`, the floats, `String`, `Vec`, and `[u8; N]`. +/// - The other `FromScalar` types of this crate: the date, timestamp, +/// decimal, and UUID values. The jiff, `rust_decimal`, and uuid types +/// behind their features are `FromScalar` types too. +/// - A fieldless enum that derives `Decrypt`, and any type of your own that +/// implements `FromScalar`. +/// - A newtype that derives `Decrypt` over a `ScalarTarget`, such as +/// `struct Email(String)`. +/// - `Option` of a `ScalarTarget`. A null leaf builds `None`. +/// - `Protected` of a `FromScalar` type that can be wiped, and +/// `Protected>` of such a type. +/// - [`OwnedFrame`](crate::OwnedFrame). One leaf always builds a frame of +/// one scalar. +/// +/// These targets are not `ScalarTarget`s, because each needs a container: +/// +/// - A `Vec` other than `Vec`. +/// - A `HashMap` or a `BTreeMap`. +/// - A struct that derives `Decrypt` with named fields. +/// - A newtype or an `Option` of one of those. +/// +/// ``` +/// use vitaminc_aead::{Decrypt, Encrypt, OwnedFrame, ScalarTarget}; +/// use vitaminc_protected::Protected; +/// +/// /// Opens exactly one leaf. +/// fn opens_one_leaf() -> T::Sink { +/// T::sink() +/// } +/// +/// let _ = opens_one_leaf::(); +/// let _ = opens_one_leaf::>(); +/// let _ = opens_one_leaf::>(); +/// let _ = opens_one_leaf::>(); +/// let _ = opens_one_leaf::(); +/// +/// // A derived newtype of a scalar is a `ScalarTarget` with no extra code. +/// #[derive(Decrypt, Debug, PartialEq)] +/// struct Email(String); +/// +/// let email = "ada@example.com".visit(opens_one_leaf::())?; +/// assert_eq!(email, Email(String::from("ada@example.com"))); +/// # Ok::<(), vitaminc_aead::DecodeError>(()) +/// ``` +/// +/// A `Vec` needs a sequence, so it does not compile: +/// +/// ```compile_fail,E0277 +/// use vitaminc_aead::ScalarTarget; +/// fn opens_one_leaf() {} +/// opens_one_leaf::>(); +/// ``` +/// +/// A target with a hand-written sink is a `ScalarTarget` when that sink +/// implements [`TakesScalar`]. +#[diagnostic::on_unimplemented( + message = "`{Self}` is not built from one scalar", + label = "this decrypt target is not a `ScalarTarget`", + note = "a scalar target is a `FromScalar` type, such as `String`, `i64`, or `Vec`. An \ + `Option` or a `Protected` of one is a scalar target too. So is a newtype that \ + derives `Decrypt` over one.", + note = "a sequence, a map, and a struct with named fields each need a container. So none of \ + them is a scalar target.", + note = "a target with a hand-written sink is a scalar target when that sink implements \ + `TakesScalar`." +)] +pub trait ScalarTarget: Decrypt + sealed::SinkTakesScalar {} + +/// The only impl of [`ScalarTarget`]: for a target whose sink implements +/// [`TakesScalar`]. +// `do_not_recommend` makes the compiler report a refused target against +// `ScalarTarget`, and name the target. Without the attribute, the compiler +// reports the bound on the sink, and names the sink. +#[diagnostic::do_not_recommend] +impl ScalarTarget for T where T::Sink: TakesScalar {} + +mod sealed { + use super::{Decrypt, TakesScalar}; + + /// Stops code outside this crate from implementing + /// [`ScalarTarget`](super::ScalarTarget). + /// + /// The blanket impl of `ScalarTarget` does not stop that alone. Take a + /// crate that defines a type and the sink of that type, where the sink + /// does not implement `TakesScalar`. The compiler can prove that the + /// blanket impl does not apply to that type. So the compiler accepts a + /// second impl of `ScalarTarget` for the type. The sink that + /// `#[derive(Decrypt)]` generates for a struct with named fields is such + /// a sink. + /// + /// `SinkTakesScalar` is a supertrait of `ScalarTarget`. Code outside this + /// module cannot name `SinkTakesScalar`, so that code cannot implement + /// it. The only impl is for a target whose sink implements `TakesScalar`. + /// So the compiler rejects the second impl of `ScalarTarget`. + #[diagnostic::on_unimplemented( + message = "`ScalarTarget` cannot be implemented for `{Self}`", + label = "the sink of this target does not implement `TakesScalar`", + note = "a target is a `ScalarTarget` when its sink, `Decrypt::Sink`, implements \ + `TakesScalar`. No other impl is accepted." + )] + pub trait SinkTakesScalar {} + + // `do_not_recommend` makes the compiler report a refused impl of + // `ScalarTarget` against `SinkTakesScalar`. The message above then says + // why the impl is refused. + #[diagnostic::do_not_recommend] + impl SinkTakesScalar for T where T::Sink: TakesScalar {} +} + +/// A sink that builds its value from one scalar. +/// +/// A target is a [`ScalarTarget`] when its sink implements this trait. These +/// sinks of this crate implement it, because each reads a scalar: +/// +/// - [`ScalarSink`] and [`ScalarProtected`]. +/// - [`Optional`] and [`ProtectedOptional`] over a sink that implements it. +/// - [`Wrapped`] and [`Wrap`] over a sink that implements it. +/// - [`OwnedFrameSink`](crate::frame::OwnedFrameSink). +/// +/// These sinks do not implement it, because each needs a container: +/// [`List`], [`Dict`], and the protected list. The sink that +/// `#[derive(Decrypt)]` generates for a struct with named fields does not +/// implement it either. +/// +/// So a target whose sink is in the first list needs no extra code. The sink +/// of a derived newtype is [`Wrapped`] over the sink of the inner type. That +/// sink implements `TakesScalar` exactly when the inner sink does. +/// +/// # A sink written by hand +/// +/// Implement this trait only for a sink of your own whose +/// [`scalar`](Sink::scalar) method can succeed. The compiler does not check +/// that. A sink that implements this trait and returns an error for every +/// scalar still compiles. Decrypting into the target of that sink then fails +/// for every leaf. +/// +/// ``` +/// use vitaminc_aead::typed::{Never, TakesScalar}; +/// use vitaminc_aead::{ +/// DecodeError, Decrypt, Encrypt, EncryptRef, FixedType, Logical, Physical, ScalarTarget, +/// Sink, +/// }; +/// +/// /// A flag stored as the text `yes` or `no`. +/// #[derive(Debug, PartialEq)] +/// struct Flag(bool); +/// +/// struct FlagSink; +/// +/// impl Sink for FlagSink { +/// type Ok = Flag; +/// type Error = DecodeError; +/// type Seq = Never; +/// type Map = Never; +/// +/// fn scalar(self, ty: Option, value: Physical<'_>) -> Result { +/// match (ty, value) { +/// (None, Physical::Text("yes")) => Ok(Flag(true)), +/// (None, Physical::Text("no")) => Ok(Flag(false)), +/// _ => Err(DecodeError::Expected("flag")), +/// } +/// } +/// fn typed_null(self, _: FixedType) -> Result { +/// Err(DecodeError::Expected("flag")) +/// } +/// fn seq(self, _: Option) -> Result, DecodeError> { +/// Err(DecodeError::Expected("flag")) +/// } +/// fn map(self, _: Option) -> Result, DecodeError> { +/// Err(DecodeError::Expected("flag")) +/// } +/// fn passthrough(self, _: &P) -> Result { +/// Err(DecodeError::Expected("flag")) +/// } +/// } +/// +/// impl Decrypt for Flag { +/// type Sink = FlagSink; +/// fn sink() -> FlagSink { +/// FlagSink +/// } +/// } +/// +/// // The sink builds a `Flag` from one scalar, so `Flag` is a +/// // `ScalarTarget`. +/// impl TakesScalar for FlagSink {} +/// +/// fn opens_one_leaf() -> T::Sink { +/// T::sink() +/// } +/// assert_eq!("yes".visit(opens_one_leaf::())?, Flag(true)); +/// # Ok::<(), DecodeError>(()) +/// ``` +#[diagnostic::on_unimplemented( + message = "`{Self}` does not build its value from one scalar", + label = "this sink does not implement `TakesScalar`", + note = "the sinks of this crate that read one scalar implement `TakesScalar`. The sinks that \ + need a sequence or a map do not.", + note = "implement `TakesScalar` for a sink of your own only when its `scalar` method can \ + succeed." +)] +pub trait TakesScalar: Sink {} + +impl TakesScalar for ScalarSink {} + /// A sink nothing is ever walked into: the element and entry type of a /// container sink that hands out none, such as [`Never`] and the map sink /// of a derived struct with no fields. Uninhabited, so it cannot be built. @@ -812,6 +1048,12 @@ impl, W: Rewrap> Sink for Wrapped { } } +/// `Wrapped` passes a scalar to the inner sink and rewraps the result. So +/// `Wrapped` builds its value from one scalar exactly when the inner sink +/// does. That is why a derived newtype of a scalar target is a scalar +/// target. +impl + TakesScalar, W: Rewrap> TakesScalar for Wrapped {} + /// A container sink whose `end` passes its result through `W`. pub struct WrappedEnd(Q, PhantomData); @@ -1064,6 +1306,10 @@ impl Decrypt for Option { } } +/// A null builds `None`. Any other scalar builds `Some` of the value that +/// the sink of `T` builds. +impl TakesScalar for Optional where T::Sink: TakesScalar {} + /// A type that can be decrypted straight into `Protected`: it names /// the sink that builds the wrapped value. /// @@ -1107,6 +1353,8 @@ impl DecryptProtected for T { /// containers and passthrough, as [`ScalarSink`] does. pub struct ScalarProtected(PhantomData); +impl TakesScalar for ScalarProtected {} + impl Sink for ScalarProtected { type Ok = Protected; type Error = DecodeError; @@ -1232,6 +1480,10 @@ impl DecryptProtected for Option { /// The sink for `Protected>`. pub struct ProtectedOptional(T::ProtectedSink); +/// A null builds a protected `None`. Any other scalar builds a protected +/// `Some` of the value that the protected sink of `T` builds. +impl TakesScalar for ProtectedOptional where T::ProtectedSink: TakesScalar {} + impl Sink for ProtectedOptional { type Ok = Protected>; type Error = DecodeError; @@ -1311,6 +1563,16 @@ where } } +/// `Wrap` passes a scalar to the inner sink and moves the result into +/// `Protected`. So `Wrap` builds its value from one scalar exactly when the +/// inner sink does. +impl TakesScalar for Wrap +where + S: Sink + TakesScalar, + S::Ok: Zeroize, +{ +} + /// A container sink whose result is moved into `Protected` at its end. pub struct WrapEnd(Q); diff --git a/packages/vitaminc-aead/tests/scalar_target.rs b/packages/vitaminc-aead/tests/scalar_target.rs new file mode 100644 index 000000000..b5553a41c --- /dev/null +++ b/packages/vitaminc-aead/tests/scalar_target.rs @@ -0,0 +1,343 @@ +//! Tests of `ScalarTarget`: the trait of a decrypt target that is built from +//! one scalar. `ScalarTarget` is the decrypt-side counterpart of `Scalar`. +//! +//! No target implements `ScalarTarget` itself. A target has it when its sink +//! implements `TakesScalar`: when the sink builds its value from one scalar. +//! +//! The trait is only useful if it agrees with what the sinks do. So these +//! tests take every kind of target that has the trait. Each test passes one +//! scalar to the sink of the target, and checks what the sink builds. +//! +//! The compile-fail tests are in `tests/ui/scalar_target/`. Those tests +//! check that a target that needs a container does not have the trait. The +//! targets are a sequence, a map, a derived struct, a newtype of a sequence, +//! and a protected sequence. The same tests check that no one can implement +//! the trait for such a target directly. + +use vitaminc_aead::plaintext::Raw; +use vitaminc_aead::{ + Decrypt, Encrypt, FixedType, FromScalar, Logical, OwnedFrame, Physical, ScalarTarget, + ValueKind, Width, +}; +use vitaminc_protected::{Controlled, Protected}; + +/// The bound that code asks for when it decrypts exactly one leaf. The bound +/// says that one scalar builds the target. This function then checks that +/// the scalar `source` builds it. +fn built_by_one_scalar(source: impl Encrypt) -> T { + source + .visit(T::sink()) + .expect("one scalar builds a scalar target") +} + +/// A null, as a leaf contains one. +fn null() -> Raw<'static> { + Raw(None, Physical::Null) +} + +#[test] +fn every_built_in_scalar_target_is_built_by_one_scalar() { + assert!(built_by_one_scalar::(true), "bool"); + assert_eq!(built_by_one_scalar::(-8i8), -8, "i8"); + assert_eq!(built_by_one_scalar::(-16i16), -16, "i16"); + assert_eq!(built_by_one_scalar::(-32i32), -32, "i32"); + assert_eq!(built_by_one_scalar::(-64i64), -64, "i64"); + assert_eq!(built_by_one_scalar::(-128i128), -128, "i128"); + assert_eq!(built_by_one_scalar::(16u16), 16, "u16"); + assert_eq!(built_by_one_scalar::(32u32), 32, "u32"); + assert_eq!(built_by_one_scalar::(64u64), 64, "u64"); + assert_eq!(built_by_one_scalar::(128u128), 128, "u128"); + assert_eq!(built_by_one_scalar::(1.5f32), 1.5, "f32"); + assert_eq!(built_by_one_scalar::(2.5f64), 2.5, "f64"); + assert_eq!(built_by_one_scalar::("hi"), "hi", "String"); + assert_eq!( + built_by_one_scalar::>(vec![1u8, 2]), + [1, 2], + "Vec is one byte leaf, not a sequence" + ); + assert_eq!( + built_by_one_scalar::<[u8; 3]>([1u8, 2, 3]), + [1, 2, 3], + "[u8; N]" + ); +} + +#[test] +fn an_option_is_built_by_a_null_or_by_a_scalar() { + assert_eq!( + built_by_one_scalar::>(null()), + None, + "a plain null builds None" + ); + let typed_null = OwnedFrame::typed_null(FixedType::plain(Width::I64).expect("a fixed type")); + assert_eq!( + built_by_one_scalar::>(&typed_null), + None, + "a typed null builds None" + ); + assert_eq!( + built_by_one_scalar::>(34i64), + Some(34), + "a scalar builds Some" + ); + assert_eq!( + built_by_one_scalar::>>("hi"), + Some(Some(String::from("hi"))), + "a nested option" + ); +} + +#[test] +fn a_protected_scalar_target_is_built_by_one_scalar() { + let text = built_by_one_scalar::>("hi"); + assert_eq!(text.risky_ref(), "hi", "Protected"); + let bytes = built_by_one_scalar::>>(vec![9u8, 8]); + assert_eq!(bytes.risky_ref(), &[9, 8], "Protected>"); + let absent = built_by_one_scalar::>>(null()); + assert_eq!( + absent.risky_ref(), + &None, + "Protected> of a null" + ); + let present = built_by_one_scalar::>>(34i64); + assert_eq!( + present.map(|value| *value.risky_ref()), + Some(34), + "Option> of a scalar" + ); +} + +#[test] +fn an_owned_frame_is_built_by_any_scalar_and_by_a_null() { + let text = built_by_one_scalar::("hi"); + assert_eq!( + text.frame().kind(), + Some(ValueKind::String), + "a text scalar" + ); + let date = built_by_one_scalar::(Raw( + Some(Logical::Date), + Physical::Int(vitaminc_aead::Int::I32(19_782)), + )); + assert_eq!(date.frame().kind(), Some(ValueKind::Date), "a date scalar"); + let absent = built_by_one_scalar::(null()); + assert!(absent.frame().is_null(), "a null builds the null frame"); + let present = built_by_one_scalar::>(7u16); + assert_eq!( + present.map(|frame| frame.frame().kind()), + Some(Some(ValueKind::UInt16)), + "Option of a scalar" + ); +} + +/// A hand-written scalar target has the trait because it implements +/// `FromScalar`. +#[test] +fn a_hand_written_scalar_target_carries_the_marker() { + #[derive(Debug, PartialEq)] + struct Percent(u8); + impl FromScalar for Percent { + const EXPECTED: &'static str = "percentage"; + fn from_scalar(ty: Option, value: Physical<'_>) -> Option { + let n = u32::from_scalar(ty, value)?; + u8::try_from(n).ok().filter(|n| *n <= 100).map(Percent) + } + } + assert_eq!( + built_by_one_scalar::(42u32), + Percent(42), + "a FromScalar type" + ); +} + +/// A derived newtype reads what its inner type reads. The sink of the +/// newtype wraps the sink of the inner type. So the newtype is a scalar +/// target with no code of its own. +#[test] +fn a_derived_newtype_of_a_scalar_target_is_one_as_it_is() { + #[derive(Decrypt, Debug, PartialEq)] + struct Email(String); + assert_eq!( + built_by_one_scalar::("ada@example.com"), + Email(String::from("ada@example.com")), + "a derived newtype of a string" + ); + + #[derive(Decrypt, Debug, PartialEq)] + struct UserId(u64); + assert_eq!( + built_by_one_scalar::(42u64), + UserId(42), + "a derived newtype of an integer" + ); + + // A newtype of a newtype, and a nullable newtype. + #[derive(Decrypt, Debug, PartialEq)] + struct Primary(Email); + assert_eq!( + built_by_one_scalar::("ada@example.com"), + Primary(Email(String::from("ada@example.com"))), + "a derived newtype of a derived newtype" + ); + assert_eq!( + built_by_one_scalar::>(null()), + None, + "an Option of a derived newtype reads a null" + ); + + #[derive(Decrypt, Debug, PartialEq)] + struct MaybeId(Option); + assert_eq!( + built_by_one_scalar::(null()), + MaybeId(None), + "a derived newtype of an Option reads a null" + ); +} + +/// A newtype decrypts into `Protected` when its author implements +/// `DecryptProtected` for it. `Wrap` moves the value that the newtype's own +/// sink builds into `Protected`. `Wrap` builds its value from one scalar +/// when that sink does. +#[test] +fn a_protected_newtype_is_a_scalar_target_through_wrap() { + use vitaminc_aead::typed::Wrap; + use vitaminc_aead::DecryptProtected; + use zeroize::Zeroize; + + #[derive(Decrypt, Zeroize)] + struct Email(String); + impl DecryptProtected for Email { + type ProtectedSink = Wrap<::Sink>; + fn protected_sink() -> Self::ProtectedSink { + Wrap(Email::sink()) + } + } + let email = built_by_one_scalar::>("ada@example.com"); + assert_eq!( + email.risky_ref().0, + "ada@example.com", + "a protected derived newtype" + ); +} + +/// A target with a sink of its own is a scalar target when that sink +/// implements `TakesScalar`. +#[test] +fn a_hand_written_sink_opts_in_by_its_marker() { + use vitaminc_aead::typed::{Never, TakesScalar}; + use vitaminc_aead::{DecodeError, EncryptRef, Sink}; + + #[derive(Debug, PartialEq)] + struct Flag(bool); + struct FlagSink; + impl Sink for FlagSink { + type Ok = Flag; + type Error = DecodeError; + type Seq = Never; + type Map = Never; + fn scalar(self, ty: Option, value: Physical<'_>) -> Result { + match (ty, value) { + (None, Physical::Text("yes")) => Ok(Flag(true)), + (None, Physical::Text("no")) => Ok(Flag(false)), + _ => Err(DecodeError::Expected("flag")), + } + } + fn typed_null(self, _: FixedType) -> Result { + Err(DecodeError::Expected("flag")) + } + fn seq(self, _: Option) -> Result, DecodeError> { + Err(DecodeError::Expected("flag")) + } + fn map(self, _: Option) -> Result, DecodeError> { + Err(DecodeError::Expected("flag")) + } + fn passthrough(self, _: &P) -> Result { + Err(DecodeError::Expected("flag")) + } + } + impl Decrypt for Flag { + type Sink = FlagSink; + fn sink() -> FlagSink { + FlagSink + } + } + impl TakesScalar for FlagSink {} + assert_eq!( + built_by_one_scalar::("no"), + Flag(false), + "a target whose own sink is marked" + ); +} + +/// A derived fieldless enum reads an int leaf through `FromScalar`. So the +/// enum is a scalar target with no impl of its own. +#[test] +fn a_derived_fieldless_enum_carries_the_marker() { + #[derive(Encrypt, Decrypt, Debug, PartialEq, Clone, Copy)] + enum Status { + Active = 1, + Closed = 2, + } + assert_eq!( + built_by_one_scalar::(Status::Closed), + Status::Closed, + "a fieldless enum" + ); + assert_eq!( + built_by_one_scalar::(Status::Active), + Status::Active, + "the other variant" + ); +} + +#[cfg(feature = "jiff")] +#[test] +fn the_date_and_timestamp_targets_are_built_by_one_scalar() { + let date = jiff::civil::Date::constant(2024, 2, 29); + assert_eq!( + built_by_one_scalar::(date), + date, + "jiff date" + ); + let wiped = built_by_one_scalar::(date); + assert_eq!(wiped.to_jiff(), date, "this crate's Date"); + let instant = jiff::Timestamp::new(1_700_000_000, 0).expect("valid"); + assert_eq!( + built_by_one_scalar::(instant), + instant, + "jiff timestamp" + ); + let stamp = built_by_one_scalar::(instant); + assert_eq!(stamp.to_jiff(), instant, "this crate's Timestamp"); +} + +#[cfg(feature = "rust_decimal")] +#[test] +fn the_decimal_targets_are_built_by_one_scalar() { + let value = rust_decimal::Decimal::new(1234, 2); + assert_eq!( + built_by_one_scalar::(value), + value, + "rust_decimal" + ); + let wiped = built_by_one_scalar::(value); + assert_eq!(wiped.to_decimal(), value, "this crate's Decimal"); +} + +#[cfg(feature = "uuid")] +#[test] +fn the_uuid_targets_are_built_by_one_scalar() { + let id = uuid::Uuid::from_bytes([7; 16]); + assert_eq!(built_by_one_scalar::(id), id, "uuid"); + let wiped = built_by_one_scalar::(id); + assert_eq!(wiped.to_uuid(), id, "this crate's Uuid"); +} + +// `trybuild` starts rustc and reads the filesystem. Neither can run inside +// Miri's isolated interpreter. +#[cfg(not(miri))] +#[test] +fn containers_are_not_scalar_targets() { + let tests = trybuild::TestCases::new(); + tests.compile_fail("tests/ui/scalar_target/*.rs"); +} diff --git a/packages/vitaminc-aead/tests/ui/scalar_target/derived_newtype_of_a_container.rs b/packages/vitaminc-aead/tests/ui/scalar_target/derived_newtype_of_a_container.rs new file mode 100644 index 000000000..37507ff0b --- /dev/null +++ b/packages/vitaminc-aead/tests/ui/scalar_target/derived_newtype_of_a_container.rs @@ -0,0 +1,13 @@ +//! A derived newtype reads what its inner type reads. A newtype of a +//! sequence needs a sequence, so one scalar does not build it. + +use vitaminc_aead::{Decrypt, ScalarTarget}; + +#[derive(Decrypt)] +struct Tags(Vec); + +fn opens_one_leaf() {} + +fn main() { + opens_one_leaf::(); +} diff --git a/packages/vitaminc-aead/tests/ui/scalar_target/derived_newtype_of_a_container.stderr b/packages/vitaminc-aead/tests/ui/scalar_target/derived_newtype_of_a_container.stderr new file mode 100644 index 000000000..392a7de21 --- /dev/null +++ b/packages/vitaminc-aead/tests/ui/scalar_target/derived_newtype_of_a_container.stderr @@ -0,0 +1,19 @@ +error[E0277]: `Tags` is not built from one scalar + --> tests/ui/scalar_target/derived_newtype_of_a_container.rs:12:22 + | +12 | opens_one_leaf::(); + | ^^^^ this decrypt target is not a `ScalarTarget` + | +help: the trait `ScalarTarget` is not implemented for `Tags` + --> tests/ui/scalar_target/derived_newtype_of_a_container.rs:7:1 + | + 7 | struct Tags(Vec); + | ^^^^^^^^^^^ + = note: a scalar target is a `FromScalar` type, such as `String`, `i64`, or `Vec`. An `Option` or a `Protected` of one is a scalar target too. So is a newtype that derives `Decrypt` over one. + = note: a sequence, a map, and a struct with named fields each need a container. So none of them is a scalar target. + = note: a target with a hand-written sink is a scalar target when that sink implements `TakesScalar`. +note: required by a bound in `opens_one_leaf` + --> tests/ui/scalar_target/derived_newtype_of_a_container.rs:9:22 + | + 9 | fn opens_one_leaf() {} + | ^^^^^^^^^^^^ required by this bound in `opens_one_leaf` diff --git a/packages/vitaminc-aead/tests/ui/scalar_target/derived_struct_needs_a_map.rs b/packages/vitaminc-aead/tests/ui/scalar_target/derived_struct_needs_a_map.rs new file mode 100644 index 000000000..30740c98a --- /dev/null +++ b/packages/vitaminc-aead/tests/ui/scalar_target/derived_struct_needs_a_map.rs @@ -0,0 +1,15 @@ +//! A derived struct reads a map with one leaf for each field. So one scalar +//! does not build it, even when the struct has a single field. + +use vitaminc_aead::{Decrypt, ScalarTarget}; + +#[derive(Decrypt)] +struct Account { + id: u64, +} + +fn opens_one_leaf() {} + +fn main() { + opens_one_leaf::(); +} diff --git a/packages/vitaminc-aead/tests/ui/scalar_target/derived_struct_needs_a_map.stderr b/packages/vitaminc-aead/tests/ui/scalar_target/derived_struct_needs_a_map.stderr new file mode 100644 index 000000000..e9d66e3da --- /dev/null +++ b/packages/vitaminc-aead/tests/ui/scalar_target/derived_struct_needs_a_map.stderr @@ -0,0 +1,19 @@ +error[E0277]: `Account` is not built from one scalar + --> tests/ui/scalar_target/derived_struct_needs_a_map.rs:14:22 + | +14 | opens_one_leaf::(); + | ^^^^^^^ this decrypt target is not a `ScalarTarget` + | +help: the trait `ScalarTarget` is not implemented for `Account` + --> tests/ui/scalar_target/derived_struct_needs_a_map.rs:7:1 + | + 7 | struct Account { + | ^^^^^^^^^^^^^^ + = note: a scalar target is a `FromScalar` type, such as `String`, `i64`, or `Vec`. An `Option` or a `Protected` of one is a scalar target too. So is a newtype that derives `Decrypt` over one. + = note: a sequence, a map, and a struct with named fields each need a container. So none of them is a scalar target. + = note: a target with a hand-written sink is a scalar target when that sink implements `TakesScalar`. +note: required by a bound in `opens_one_leaf` + --> tests/ui/scalar_target/derived_struct_needs_a_map.rs:11:22 + | +11 | fn opens_one_leaf() {} + | ^^^^^^^^^^^^ required by this bound in `opens_one_leaf` diff --git a/packages/vitaminc-aead/tests/ui/scalar_target/hand_written_impl_for_a_derived_struct.rs b/packages/vitaminc-aead/tests/ui/scalar_target/hand_written_impl_for_a_derived_struct.rs new file mode 100644 index 000000000..6e162e0cf --- /dev/null +++ b/packages/vitaminc-aead/tests/ui/scalar_target/hand_written_impl_for_a_derived_struct.rs @@ -0,0 +1,15 @@ +//! No one implements `ScalarTarget` directly. The sink of a derived struct +//! is generated beside the struct. That sink reads a map, so it does not +//! implement `TakesScalar`. So the compiler rejects an impl of +//! `ScalarTarget` for the struct. + +use vitaminc_aead::{Decrypt, ScalarTarget}; + +#[derive(Decrypt)] +struct Account { + id: u64, +} + +impl ScalarTarget for Account {} + +fn main() {} diff --git a/packages/vitaminc-aead/tests/ui/scalar_target/hand_written_impl_for_a_derived_struct.stderr b/packages/vitaminc-aead/tests/ui/scalar_target/hand_written_impl_for_a_derived_struct.stderr new file mode 100644 index 000000000..6235cd78a --- /dev/null +++ b/packages/vitaminc-aead/tests/ui/scalar_target/hand_written_impl_for_a_derived_struct.stderr @@ -0,0 +1,20 @@ +error[E0277]: `ScalarTarget` cannot be implemented for `Account` + --> tests/ui/scalar_target/hand_written_impl_for_a_derived_struct.rs:13:23 + | +13 | impl ScalarTarget for Account {} + | ^^^^^^^ the sink of this target does not implement `TakesScalar` + | +help: the trait `typed::sealed::SinkTakesScalar` is not implemented for `Account` + --> tests/ui/scalar_target/hand_written_impl_for_a_derived_struct.rs:9:1 + | + 9 | struct Account { + | ^^^^^^^^^^^^^^ + = note: a target is a `ScalarTarget` when its sink, `Decrypt::Sink`, implements `TakesScalar`. No other impl is accepted. +note: required by a bound in `ScalarTarget` + --> src/typed.rs + | + | pub trait ScalarTarget: Decrypt + sealed::SinkTakesScalar {} + | ^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `ScalarTarget` + = note: `ScalarTarget` is a "sealed trait", because to implement it you also need to implement `vitaminc_aead::typed::sealed::SinkTakesScalar`, which is not accessible; this is usually done to force you to use one of the provided types that already implement it + = help: the following type implements the trait: + T diff --git a/packages/vitaminc-aead/tests/ui/scalar_target/hand_written_impl_for_a_newtype.rs b/packages/vitaminc-aead/tests/ui/scalar_target/hand_written_impl_for_a_newtype.rs new file mode 100644 index 000000000..c81d5de90 --- /dev/null +++ b/packages/vitaminc-aead/tests/ui/scalar_target/hand_written_impl_for_a_newtype.rs @@ -0,0 +1,13 @@ +//! No one implements `ScalarTarget` directly. A target is a `ScalarTarget` +//! when its sink implements `TakesScalar`. The sink of a derived newtype is +//! defined in vitaminc-aead. So an impl of `ScalarTarget` for a newtype of a +//! sequence conflicts with the blanket impl. + +use vitaminc_aead::{Decrypt, ScalarTarget}; + +#[derive(Decrypt)] +struct Tags(Vec); + +impl ScalarTarget for Tags {} + +fn main() {} diff --git a/packages/vitaminc-aead/tests/ui/scalar_target/hand_written_impl_for_a_newtype.stderr b/packages/vitaminc-aead/tests/ui/scalar_target/hand_written_impl_for_a_newtype.stderr new file mode 100644 index 000000000..9b29f712a --- /dev/null +++ b/packages/vitaminc-aead/tests/ui/scalar_target/hand_written_impl_for_a_newtype.stderr @@ -0,0 +1,10 @@ +error[E0119]: conflicting implementations of trait `ScalarTarget` for type `Tags` + --> tests/ui/scalar_target/hand_written_impl_for_a_newtype.rs:11:1 + | +11 | impl ScalarTarget for Tags {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = note: conflicting implementation in crate `vitaminc_aead`: + - impl ScalarTarget for T + where T: Decrypt, ::Sink: TakesScalar, ::Sink: ?Sized; + = note: upstream crates may add a new impl of trait `vitaminc_aead::TakesScalar` for type `::Sink` in future versions diff --git a/packages/vitaminc-aead/tests/ui/scalar_target/map_needs_a_map.rs b/packages/vitaminc-aead/tests/ui/scalar_target/map_needs_a_map.rs new file mode 100644 index 000000000..05add3dde --- /dev/null +++ b/packages/vitaminc-aead/tests/ui/scalar_target/map_needs_a_map.rs @@ -0,0 +1,13 @@ +//! A map target reads a map with one leaf for each value. So one scalar does +//! not build it. + +use std::collections::{BTreeMap, HashMap}; + +use vitaminc_aead::ScalarTarget; + +fn opens_one_leaf() {} + +fn main() { + opens_one_leaf::>(); + opens_one_leaf::>(); +} diff --git a/packages/vitaminc-aead/tests/ui/scalar_target/map_needs_a_map.stderr b/packages/vitaminc-aead/tests/ui/scalar_target/map_needs_a_map.stderr new file mode 100644 index 000000000..af0e5f3f3 --- /dev/null +++ b/packages/vitaminc-aead/tests/ui/scalar_target/map_needs_a_map.stderr @@ -0,0 +1,31 @@ +error[E0277]: `HashMap` is not built from one scalar + --> tests/ui/scalar_target/map_needs_a_map.rs:11:22 + | +11 | opens_one_leaf::>(); + | ^^^^^^^^^^^^^^^^^^^^ this decrypt target is not a `ScalarTarget` + | + = help: the trait `ScalarTarget` is not implemented for `HashMap` + = note: a scalar target is a `FromScalar` type, such as `String`, `i64`, or `Vec`. An `Option` or a `Protected` of one is a scalar target too. So is a newtype that derives `Decrypt` over one. + = note: a sequence, a map, and a struct with named fields each need a container. So none of them is a scalar target. + = note: a target with a hand-written sink is a scalar target when that sink implements `TakesScalar`. +note: required by a bound in `opens_one_leaf` + --> tests/ui/scalar_target/map_needs_a_map.rs:8:22 + | + 8 | fn opens_one_leaf() {} + | ^^^^^^^^^^^^ required by this bound in `opens_one_leaf` + +error[E0277]: `BTreeMap` is not built from one scalar + --> tests/ui/scalar_target/map_needs_a_map.rs:12:22 + | +12 | opens_one_leaf::>(); + | ^^^^^^^^^^^^^^^^^^^^^ this decrypt target is not a `ScalarTarget` + | + = help: the trait `ScalarTarget` is not implemented for `BTreeMap` + = note: a scalar target is a `FromScalar` type, such as `String`, `i64`, or `Vec`. An `Option` or a `Protected` of one is a scalar target too. So is a newtype that derives `Decrypt` over one. + = note: a sequence, a map, and a struct with named fields each need a container. So none of them is a scalar target. + = note: a target with a hand-written sink is a scalar target when that sink implements `TakesScalar`. +note: required by a bound in `opens_one_leaf` + --> tests/ui/scalar_target/map_needs_a_map.rs:8:22 + | + 8 | fn opens_one_leaf() {} + | ^^^^^^^^^^^^ required by this bound in `opens_one_leaf` diff --git a/packages/vitaminc-aead/tests/ui/scalar_target/vec_needs_a_sequence.rs b/packages/vitaminc-aead/tests/ui/scalar_target/vec_needs_a_sequence.rs new file mode 100644 index 000000000..421196fe4 --- /dev/null +++ b/packages/vitaminc-aead/tests/ui/scalar_target/vec_needs_a_sequence.rs @@ -0,0 +1,12 @@ +//! A `Vec` of a scalar target reads a sequence with one leaf for each +//! element. So one scalar does not build it. `Vec` is different: it is +//! the bytes scalar, so one scalar builds it. + +use vitaminc_aead::ScalarTarget; + +fn opens_one_leaf() {} + +fn main() { + opens_one_leaf::>(); + opens_one_leaf::>(); +} diff --git a/packages/vitaminc-aead/tests/ui/scalar_target/vec_needs_a_sequence.stderr b/packages/vitaminc-aead/tests/ui/scalar_target/vec_needs_a_sequence.stderr new file mode 100644 index 000000000..f26994858 --- /dev/null +++ b/packages/vitaminc-aead/tests/ui/scalar_target/vec_needs_a_sequence.stderr @@ -0,0 +1,15 @@ +error[E0277]: `Vec` is not built from one scalar + --> tests/ui/scalar_target/vec_needs_a_sequence.rs:11:22 + | +11 | opens_one_leaf::>(); + | ^^^^^^^^^^^ this decrypt target is not a `ScalarTarget` + | + = help: the trait `ScalarTarget` is not implemented for `Vec` + = note: a scalar target is a `FromScalar` type, such as `String`, `i64`, or `Vec`. An `Option` or a `Protected` of one is a scalar target too. So is a newtype that derives `Decrypt` over one. + = note: a sequence, a map, and a struct with named fields each need a container. So none of them is a scalar target. + = note: a target with a hand-written sink is a scalar target when that sink implements `TakesScalar`. +note: required by a bound in `opens_one_leaf` + --> tests/ui/scalar_target/vec_needs_a_sequence.rs:7:22 + | + 7 | fn opens_one_leaf() {} + | ^^^^^^^^^^^^ required by this bound in `opens_one_leaf` diff --git a/packages/vitaminc-aead/tests/ui/scalar_target/wrapped_container_is_not_a_scalar_target.rs b/packages/vitaminc-aead/tests/ui/scalar_target/wrapped_container_is_not_a_scalar_target.rs new file mode 100644 index 000000000..69b1d8e60 --- /dev/null +++ b/packages/vitaminc-aead/tests/ui/scalar_target/wrapped_container_is_not_a_scalar_target.rs @@ -0,0 +1,15 @@ +//! `Option` and `Protected` are scalar targets only when the type they wrap +//! is one. A `Vec` reads a sequence. So one scalar does not build an +//! `Option` of it, a `Protected` of it, or a `Protected` of an `Option` of +//! it. + +use vitaminc_aead::ScalarTarget; +use vitaminc_protected::Protected; + +fn opens_one_leaf() {} + +fn main() { + opens_one_leaf::>>(); + opens_one_leaf::>>(); + opens_one_leaf::>>>(); +} diff --git a/packages/vitaminc-aead/tests/ui/scalar_target/wrapped_container_is_not_a_scalar_target.stderr b/packages/vitaminc-aead/tests/ui/scalar_target/wrapped_container_is_not_a_scalar_target.stderr new file mode 100644 index 000000000..f2c493d8d --- /dev/null +++ b/packages/vitaminc-aead/tests/ui/scalar_target/wrapped_container_is_not_a_scalar_target.stderr @@ -0,0 +1,47 @@ +error[E0277]: `Option>` is not built from one scalar + --> tests/ui/scalar_target/wrapped_container_is_not_a_scalar_target.rs:12:22 + | +12 | opens_one_leaf::>>(); + | ^^^^^^^^^^^^^^^^ this decrypt target is not a `ScalarTarget` + | + = help: the trait `ScalarTarget` is not implemented for `Option>` + = note: a scalar target is a `FromScalar` type, such as `String`, `i64`, or `Vec`. An `Option` or a `Protected` of one is a scalar target too. So is a newtype that derives `Decrypt` over one. + = note: a sequence, a map, and a struct with named fields each need a container. So none of them is a scalar target. + = note: a target with a hand-written sink is a scalar target when that sink implements `TakesScalar`. +note: required by a bound in `opens_one_leaf` + --> tests/ui/scalar_target/wrapped_container_is_not_a_scalar_target.rs:9:22 + | + 9 | fn opens_one_leaf() {} + | ^^^^^^^^^^^^ required by this bound in `opens_one_leaf` + +error[E0277]: `Protected>` is not built from one scalar + --> tests/ui/scalar_target/wrapped_container_is_not_a_scalar_target.rs:13:22 + | +13 | opens_one_leaf::>>(); + | ^^^^^^^^^^^^^^^^^^^ this decrypt target is not a `ScalarTarget` + | + = help: the trait `ScalarTarget` is not implemented for `Protected>` + = note: a scalar target is a `FromScalar` type, such as `String`, `i64`, or `Vec`. An `Option` or a `Protected` of one is a scalar target too. So is a newtype that derives `Decrypt` over one. + = note: a sequence, a map, and a struct with named fields each need a container. So none of them is a scalar target. + = note: a target with a hand-written sink is a scalar target when that sink implements `TakesScalar`. +note: required by a bound in `opens_one_leaf` + --> tests/ui/scalar_target/wrapped_container_is_not_a_scalar_target.rs:9:22 + | + 9 | fn opens_one_leaf() {} + | ^^^^^^^^^^^^ required by this bound in `opens_one_leaf` + +error[E0277]: `Protected>>` is not built from one scalar + --> tests/ui/scalar_target/wrapped_container_is_not_a_scalar_target.rs:14:22 + | +14 | opens_one_leaf::>>>(); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ this decrypt target is not a `ScalarTarget` + | + = help: the trait `ScalarTarget` is not implemented for `Protected>>` + = note: a scalar target is a `FromScalar` type, such as `String`, `i64`, or `Vec`. An `Option` or a `Protected` of one is a scalar target too. So is a newtype that derives `Decrypt` over one. + = note: a sequence, a map, and a struct with named fields each need a container. So none of them is a scalar target. + = note: a target with a hand-written sink is a scalar target when that sink implements `TakesScalar`. +note: required by a bound in `opens_one_leaf` + --> tests/ui/scalar_target/wrapped_container_is_not_a_scalar_target.rs:9:22 + | + 9 | fn opens_one_leaf() {} + | ^^^^^^^^^^^^ required by this bound in `opens_one_leaf` diff --git a/scripts/__tests__/stack-conformance-ci.test.mjs b/scripts/__tests__/stack-conformance-ci.test.mjs index 2b6febf4f..c26286286 100644 --- a/scripts/__tests__/stack-conformance-ci.test.mjs +++ b/scripts/__tests__/stack-conformance-ci.test.mjs @@ -31,7 +31,7 @@ function goSelection(script) { } describe('shared Stack Encrypt conformance is required in CI', () => { - it('the conformance task runs all profiles in both languages', () => { + it('the conformance task runs every profile that has both runners in both languages', () => { const script = readFileSync( join(REPO_ROOT, 'scripts/stack-conformance.sh'), 'utf8', @@ -64,6 +64,21 @@ describe('shared Stack Encrypt conformance is required in CI', () => { } }) + it('the conformance task runs the single-value profile in Rust, which has no Go runner yet', () => { + const script = conformanceScript() + expect(script).toMatch( + /cargo nextest run[^\n]*--test single_value_conformance/, + ) + // When the Go runner is written, add it to `coreGoTests`, move the + // assertion above into the test of both languages, and delete this one. + const selected = goSelection(script) + expect(coreGoTests.some((test) => /SingleValue/.test(test))).toBe(false) + expect(selected.test('TestSingleValueConformance')).toBe(false) + expect(readRepo('conformance/stack-encrypt/README.md')).toMatch( + /single-value-v1\.cases\.json[^\n]*pending/, + ) + }) + it('selects exactly the core runners and indexed fixture tests', () => { const index = JSON.parse( readRepo('conformance/stack-encrypt/v1/fixture-enrollment.json'), diff --git a/scripts/stack-conformance.sh b/scripts/stack-conformance.sh index df2bc5039..600ba556c 100644 --- a/scripts/stack-conformance.sh +++ b/scripts/stack-conformance.sh @@ -19,7 +19,7 @@ go_tests=$(node scripts/stack-conformance-selection.mjs) artifacts=$(mktemp -d) trap 'rm -rf "$artifacts"' EXIT -mise x --env test -- cargo nextest run --locked -p stack-encrypt --all-features --test conformance --test declarations --test runtime_conformance --test read_conformance --test context_conformance --test record_lowering --test plan_grammar --test value_kinds --test query_operators --test fixture_safety --test value_conformance --test query_refusal_conformance --test raw_frame_conformance --test exchange_conformance --test binding_conformance +mise x --env test -- cargo nextest run --locked -p stack-encrypt --all-features --test conformance --test declarations --test runtime_conformance --test read_conformance --test context_conformance --test record_lowering --test plan_grammar --test value_kinds --test query_operators --test fixture_safety --test value_conformance --test query_refusal_conformance --test raw_frame_conformance --test exchange_conformance --test binding_conformance --test single_value_conformance ( cd languages/golang STACK_CONFORMANCE_OUTPUT="$artifacts/go.json" CGO_ENABLED=0 \