diff --git a/Cargo.lock b/Cargo.lock index 283ca69ad..db09c2cc1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2482,6 +2482,15 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe" +[[package]] +name = "orderable-bytes" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c7d30b72ffca73d9936fe5fc80a9c9520c73f5b4f64839a810211903d5ace3c" +dependencies = [ + "rust_decimal", +] + [[package]] name = "ore-rs" version = "0.12.0" @@ -2721,7 +2730,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b570b25f7617e43d59005d0990ccb79e950a423952cea19671b7a876da390adf" dependencies = [ "anyhow", - "itertools 0.10.5", + "itertools 0.13.0", "proc-macro2", "quote", "syn 2.0.114", @@ -3665,7 +3674,6 @@ dependencies = [ "uuid", "vitaminc 0.10.0", "vitaminc-aead 0.10.0", - "vitaminc-encrypt 0.10.0", "vitaminc-hmac", "vitaminc-normalize", "vitaminc-ore", @@ -4511,10 +4519,10 @@ checksum = "35042fb7a81d72dc43c53fec835e61027f18b4d01cc0f7e12d6c6a6ffbf3bfb9" dependencies = [ "vitaminc-aead 0.5.1", "vitaminc-context 0.5.1", - "vitaminc-encrypt 0.5.1", + "vitaminc-encrypt", "vitaminc-protected 0.5.1", "vitaminc-random 0.5.1", - "vitaminc-traits 0.5.1", + "vitaminc-traits", ] [[package]] @@ -4525,10 +4533,8 @@ checksum = "60ae27c0d0e6980d2f30683384ed591a9dafa943b18faaa6bfb456757b5e10ef" dependencies = [ "vitaminc-aead 0.10.0", "vitaminc-context 0.10.0", - "vitaminc-encrypt 0.10.0", "vitaminc-protected 0.10.0", "vitaminc-random 0.10.0", - "vitaminc-traits 0.10.0", ] [[package]] @@ -4550,9 +4556,9 @@ dependencies = [ name = "vitaminc-aead" version = "0.10.0" dependencies = [ + "aes-gcm", + "aws-lc-rs", "bytes", - "futures-executor", - "futures-util", "jiff", "quickcheck", "quickcheck_macros", @@ -4567,6 +4573,7 @@ dependencies = [ "vitaminc-prf", "vitaminc-protected 0.10.0", "vitaminc-random 0.10.0", + "wasm-bindgen-test", "zeroize", ] @@ -4628,20 +4635,6 @@ dependencies = [ "zeroize", ] -[[package]] -name = "vitaminc-encrypt" -version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e68d89e2587529db55a10fa59cb11be8a7505b4af473c8a0bec238c803190ec5" -dependencies = [ - "aes-gcm", - "aws-lc-rs", - "vitaminc-aead 0.10.0", - "vitaminc-protected 0.10.0", - "vitaminc-random 0.10.0", - "zeroize", -] - [[package]] name = "vitaminc-hmac" version = "0.10.0" @@ -4658,12 +4651,16 @@ dependencies = [ [[package]] name = "vitaminc-normalize" version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e333da8bb30eab39cc2c790cb860843229a0a06aefb807f4ce069a92a2e17e8d" dependencies = [ + "jiff", + "orderable-bytes", + "quickcheck", + "quickcheck_macros", + "rust_decimal", "thiserror 2.0.18", "unicode-general-category", "unicode-normalization", + "uuid", "vitaminc-aead 0.10.0", "vitaminc-protected 0.10.0", ] @@ -4826,22 +4823,6 @@ dependencies = [ "zeroize", ] -[[package]] -name = "vitaminc-traits" -version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "31fba5af175073f24768a8b06dd054ad696c7e6051dda1316c3814043a36d8e0" -dependencies = [ - "anyhow", - "bytes", - "rmp-serde", - "serde", - "thiserror 2.0.18", - "vitaminc-protected 0.10.0", - "vitaminc-random 0.10.0", - "zeroize", -] - [[package]] name = "wait-timeout" version = "0.2.1" diff --git a/Cargo.toml b/Cargo.toml index eb443de30..cc33f0cd3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -23,6 +23,8 @@ members = [ "packages/vitaminc-aead", "packages/recipher-frame", "packages/vitaminc-aead-derive", + # SPIKE: see the patch table at the end. + "packages/vitaminc-normalize", "languages/typescript/packages/auth", "languages/typescript/packages/profile", "languages/typescript/packages/stack-auth-wasm", @@ -155,14 +157,13 @@ web-time = "1.1" zeroize = { version = "1.8.1", features = ["derive"] } # This is needed because lock_api 0.4.6 was breaking things and the branch forces the use of 0.4.12 temp-env = { git = "https://github.com/cipherstash/temp-env", branch = "main" } -vitaminc = { version = "0.10.0", features = ["random", "protected", "encrypt"] } +vitaminc = { version = "0.10.0", features = ["random", "protected"] } # The AEAD crates live in this repository (packages/vitaminc-aead*, # packages/recipher-frame). vitaminc-aead = { path = "./packages/vitaminc-aead", version = "0.10.0" } # The transport frame and ciphertext codec every language binding carries # across its FFI boundary. Optional in stack-encrypt (the `dynamic` feature). recipher-frame = { path = "./packages/recipher-frame", version = "0.10.0" } -vitaminc-encrypt = "0.10.0" vitaminc-hmac = "0.10.0" # Normalized equality terms (Unicode 16 NFC text, one integer encoding for # every width), which `vitaminc-prf`'s `normalize` feature derives over. @@ -186,3 +187,7 @@ vitaminc-protected = "0.10.0" [patch.crates-io] vitaminc-aead = { path = "./packages/vitaminc-aead" } vitaminc-aead-derive = { path = "./packages/vitaminc-aead-derive" } +# SPIKE, not for merging. A copy of the published vitaminc-normalize 0.10.0, +# so that the spike can show what that crate has to change. The crate lives +# in cipherstash/vitaminc, and the real change is a release from there. +vitaminc-normalize = { path = "./packages/vitaminc-normalize" } diff --git a/conformance/vitaminc-aead/README.md b/conformance/vitaminc-aead/README.md index 8733a66cf..e0b14634e 100644 --- a/conformance/vitaminc-aead/README.md +++ b/conformance/vitaminc-aead/README.md @@ -23,10 +23,9 @@ After editing it, run `pnpm run code:fix` before committing. | `normalized` | yes | yes | yes | A valid value that reads back as a different canonical value | | `malformed` | yes | yes | yes | Bytes every decoder must refuse | | `ciphertext_malformed` | yes | no | yes | Ciphertext transport bytes the codec must refuse | -| `leaf_type_aad` | yes | no | no | The `LeafTypeAad` context bytes for a (base, kind, logical) triple | -Node has no ciphertext transport codec, and neither binding exposes -`LeafTypeAad`, so those two sections are asserted where the code is. A new +Node has no ciphertext transport codec, so that section is asserted where +the code is. A new section is consumed by every language that has the code it describes; the table above is the record of who asserts what, so keep it current. @@ -51,10 +50,6 @@ language writes back) and `reencode_value` (the host value it reads as). `ciphertext_malformed`: `transport` bytes of a ciphertext tree. -`leaf_type_aad`: `base`, `kind` (the physical kind), an optional `logical` -`{id, param}`, and the `context` bytes; its `rule` spells out the encoding so -another language can build the bytes from the corpus alone. - ## Host projections Rust re-encodes every valid vector byte for byte. A host language whose @@ -65,15 +60,14 @@ than skipping the row: re-encodes as Float64. A timestamp that is a whole number of milliseconds is read as a `Date`, and re-encodes as the `Timestamp(Millis)` envelope. A finer timestamp is read as an `RcTimestamp`, and re-encodes in the - nanosecond shorthand. As for Go, the timestamp projection is safe for two - reasons. `LeafTypeAad` binds the kind and the logical id, but not the - unit. The equality terms put every unit in one timestamp domain. + nanosecond shorthand. As for Go, the timestamp projection is safe: no + context binds a timestamp's unit, and the equality terms put every unit + in one timestamp domain. - `go_reencode`: Go has two projections. `undefined` becomes nil and re-encodes as null. A timestamp in the envelope (seconds, milliseconds or microseconds) is read as a `time.Time` and re-encodes in the nanosecond - shorthand, which is safe because `LeafTypeAad` binds the kind and the - logical id but not the unit, and the equality terms put every unit in one - timestamp domain. + shorthand, which is safe because no context binds a timestamp's unit, and + the equality terms put every unit in one timestamp domain. - `js: "refused"`: Node has no value for this row and refuses it. Today that is the `unknown-logical` envelope, a Node limitation tracked in #446, not a rule of the format; Rust and Go read and re-encode it unchanged. diff --git a/conformance/vitaminc-aead/value-conformance.json b/conformance/vitaminc-aead/value-conformance.json index 30e19d3a4..954e40fd0 100644 --- a/conformance/vitaminc-aead/value-conformance.json +++ b/conformance/vitaminc-aead/value-conformance.json @@ -713,98 +713,5 @@ "transport": "03010000000204000000deadbeef", "rule": "ADR 0001 section 3: CT_NONE is refused wherever it appears" } - ], - "leaf_type_aad": { - "rule": "LeafTypeAad (ADR 0001 section 3): the context is PAE(domain, base, kind, id) under the vitaminc-context encoding, where PAE is a u64-le count then each element as a u64-le length and its bytes, and each element is itself a typed piece: a PAE of two parts, the u64-le-prefixed label vitaminc/context/value/v1 and the u64-le-prefixed type label then the payload. The domain is bytes/v1 over vitaminc/aead/leaf-type/v2; the base is utf8/v1 over the base string; the kind is u8-le/v1 over the physical kind byte (null 0, bool 1, int 2, float 3, text 4, bytes 5; a cross-language commitment, never renumbered); the id is u8-le/v1 over the logical id byte, 0 for no logical type. The parameter is not bound: two vectors with the same base, kind and id and different parameters have the same context.", - "vectors": [ - { - "name": "int-date", - "base": "ctx", - "kind": "int", - "logical": { - "id": 2, - "param": 0 - }, - "context": "04000000000000006c0000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f62797465732f76311a00000000000000766974616d696e632f616561642f6c6561662d747970652f7632540000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f76310300000000000000637478530000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f75382d6c652f7631010000000000000002530000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f75382d6c652f7631010000000000000002" - }, - { - "name": "text-no-logical", - "base": "ctx", - "kind": "text", - "context": "04000000000000006c0000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f62797465732f76311a00000000000000766974616d696e632f616561642f6c6561662d747970652f7632540000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f76310300000000000000637478530000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f75382d6c652f7631010000000000000004530000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f75382d6c652f7631010000000000000000" - }, - { - "name": "bytes-uuid", - "base": "schema", - "kind": "bytes", - "logical": { - "id": 5, - "param": 0 - }, - "context": "04000000000000006c0000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f62797465732f76311a00000000000000766974616d696e632f616561642f6c6561662d747970652f7632570000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f76310600000000000000736368656d61530000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f75382d6c652f7631010000000000000005530000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f75382d6c652f7631010000000000000005" - }, - { - "name": "int-timestamp-millis", - "base": "events", - "kind": "int", - "logical": { - "id": 3, - "param": 1 - }, - "context": "04000000000000006c0000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f62797465732f76311a00000000000000766974616d696e632f616561642f6c6561662d747970652f7632570000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f763106000000000000006576656e7473530000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f75382d6c652f7631010000000000000002530000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f75382d6c652f7631010000000000000003" - }, - { - "name": "int-decimal-scale-2", - "base": "price", - "kind": "int", - "logical": { - "id": 4, - "param": 2 - }, - "context": "04000000000000006c0000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f62797465732f76311a00000000000000766974616d696e632f616561642f6c6561662d747970652f7632560000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f763105000000000000007072696365530000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f75382d6c652f7631010000000000000002530000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f75382d6c652f7631010000000000000004" - }, - { - "name": "null-undefined", - "base": "ctx", - "kind": "null", - "logical": { - "id": 1, - "param": 0 - }, - "context": "04000000000000006c0000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f62797465732f76311a00000000000000766974616d696e632f616561642f6c6561662d747970652f7632540000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f76310300000000000000637478530000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f75382d6c652f7631010000000000000000530000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f75382d6c652f7631010000000000000001" - }, - { - "name": "bool-no-logical", - "base": "ctx", - "kind": "bool", - "context": "04000000000000006c0000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f62797465732f76311a00000000000000766974616d696e632f616561642f6c6561662d747970652f7632540000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f76310300000000000000637478530000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f75382d6c652f7631010000000000000001530000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f75382d6c652f7631010000000000000000" - }, - { - "name": "float-no-logical", - "base": "ctx", - "kind": "float", - "context": "04000000000000006c0000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f62797465732f76311a00000000000000766974616d696e632f616561642f6c6561662d747970652f7632540000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f76310300000000000000637478530000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f75382d6c652f7631010000000000000003530000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f75382d6c652f7631010000000000000000" - }, - { - "name": "int-decimal-scale-0", - "base": "price", - "kind": "int", - "logical": { - "id": 4, - "param": 0 - }, - "context": "04000000000000006c0000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f62797465732f76311a00000000000000766974616d696e632f616561642f6c6561662d747970652f7632560000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f763105000000000000007072696365530000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f75382d6c652f7631010000000000000002530000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f75382d6c652f7631010000000000000004" - }, - { - "name": "int-timestamp-nanos", - "base": "events", - "kind": "int", - "logical": { - "id": 3, - "param": 3 - }, - "context": "04000000000000006c0000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f62797465732f76311a00000000000000766974616d696e632f616561642f6c6561662d747970652f7632570000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f763106000000000000006576656e7473530000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f75382d6c652f7631010000000000000002530000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f75382d6c652f7631010000000000000003" - } - ] - } + ] } diff --git a/languages/golang/auth/guest/Cargo.lock b/languages/golang/auth/guest/Cargo.lock index a3cee53c5..9d08f1ab5 100644 --- a/languages/golang/auth/guest/Cargo.lock +++ b/languages/golang/auth/guest/Cargo.lock @@ -2262,10 +2262,10 @@ checksum = "35042fb7a81d72dc43c53fec835e61027f18b4d01cc0f7e12d6c6a6ffbf3bfb9" dependencies = [ "vitaminc-aead 0.5.1", "vitaminc-context 0.5.1", - "vitaminc-encrypt 0.5.1", + "vitaminc-encrypt", "vitaminc-protected 0.5.1", "vitaminc-random 0.5.1", - "vitaminc-traits 0.5.1", + "vitaminc-traits", ] [[package]] @@ -2274,12 +2274,8 @@ version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "60ae27c0d0e6980d2f30683384ed591a9dafa943b18faaa6bfb456757b5e10ef" dependencies = [ - "vitaminc-aead 0.10.0", - "vitaminc-context 0.10.0", - "vitaminc-encrypt 0.10.0", "vitaminc-protected 0.10.0", "vitaminc-random 0.10.0", - "vitaminc-traits 0.10.0", ] [[package]] @@ -2302,7 +2298,6 @@ name = "vitaminc-aead" version = "0.10.0" dependencies = [ "bytes", - "futures-util", "serde", "thiserror 2.0.20", "vitaminc-aead-derive 0.10.0", @@ -2366,20 +2361,6 @@ dependencies = [ "zeroize", ] -[[package]] -name = "vitaminc-encrypt" -version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e68d89e2587529db55a10fa59cb11be8a7505b4af473c8a0bec238c803190ec5" -dependencies = [ - "aes-gcm", - "aws-lc-rs", - "vitaminc-aead 0.10.0", - "vitaminc-protected 0.10.0", - "vitaminc-random 0.10.0", - "zeroize", -] - [[package]] name = "vitaminc-protected" version = "0.5.1" @@ -2505,22 +2486,6 @@ dependencies = [ "zeroize", ] -[[package]] -name = "vitaminc-traits" -version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "31fba5af175073f24768a8b06dd054ad696c7e6051dda1316c3814043a36d8e0" -dependencies = [ - "anyhow", - "bytes", - "rmp-serde", - "serde", - "thiserror 2.0.20", - "vitaminc-protected 0.10.0", - "vitaminc-random 0.10.0", - "zeroize", -] - [[package]] name = "wasi" version = "0.11.1+wasi-snapshot-preview1" diff --git a/languages/golang/encrypt/guest/Cargo.lock b/languages/golang/encrypt/guest/Cargo.lock index 2c958fc08..35a4abd16 100644 --- a/languages/golang/encrypt/guest/Cargo.lock +++ b/languages/golang/encrypt/guest/Cargo.lock @@ -2272,7 +2272,6 @@ dependencies = [ "uuid", "vitaminc 0.10.0", "vitaminc-aead 0.10.0", - "vitaminc-encrypt 0.10.0", "vitaminc-hmac", "vitaminc-normalize", "vitaminc-ore", @@ -2826,10 +2825,10 @@ checksum = "35042fb7a81d72dc43c53fec835e61027f18b4d01cc0f7e12d6c6a6ffbf3bfb9" dependencies = [ "vitaminc-aead 0.5.1", "vitaminc-context 0.5.1", - "vitaminc-encrypt 0.5.1", + "vitaminc-encrypt", "vitaminc-protected 0.5.1", "vitaminc-random 0.5.1", - "vitaminc-traits 0.5.1", + "vitaminc-traits", ] [[package]] @@ -2838,12 +2837,8 @@ version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "60ae27c0d0e6980d2f30683384ed591a9dafa943b18faaa6bfb456757b5e10ef" dependencies = [ - "vitaminc-aead 0.10.0", - "vitaminc-context 0.10.0", - "vitaminc-encrypt 0.10.0", "vitaminc-protected 0.10.0", "vitaminc-random 0.10.0", - "vitaminc-traits 0.10.0", ] [[package]] @@ -2865,8 +2860,9 @@ dependencies = [ name = "vitaminc-aead" version = "0.10.0" dependencies = [ + "aes-gcm", + "aws-lc-rs", "bytes", - "futures-util", "jiff", "rust_decimal", "serde", @@ -2932,20 +2928,6 @@ dependencies = [ "zeroize", ] -[[package]] -name = "vitaminc-encrypt" -version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e68d89e2587529db55a10fa59cb11be8a7505b4af473c8a0bec238c803190ec5" -dependencies = [ - "aes-gcm", - "aws-lc-rs", - "vitaminc-aead 0.10.0", - "vitaminc-protected 0.10.0", - "vitaminc-random 0.10.0", - "zeroize", -] - [[package]] name = "vitaminc-hmac" version = "0.10.0" @@ -2962,8 +2944,6 @@ dependencies = [ [[package]] name = "vitaminc-normalize" version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e333da8bb30eab39cc2c790cb860843229a0a06aefb807f4ce069a92a2e17e8d" dependencies = [ "thiserror 2.0.20", "unicode-general-category", @@ -3130,22 +3110,6 @@ dependencies = [ "zeroize", ] -[[package]] -name = "vitaminc-traits" -version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "31fba5af175073f24768a8b06dd054ad696c7e6051dda1316c3814043a36d8e0" -dependencies = [ - "anyhow", - "bytes", - "rmp-serde", - "serde", - "thiserror 2.0.20", - "vitaminc-protected 0.10.0", - "vitaminc-random 0.10.0", - "zeroize", -] - [[package]] name = "wasi" version = "0.11.1+wasi-snapshot-preview1" diff --git a/languages/golang/encrypt/guest/Cargo.toml b/languages/golang/encrypt/guest/Cargo.toml index c501fb6c6..82d78db9a 100644 --- a/languages/golang/encrypt/guest/Cargo.toml +++ b/languages/golang/encrypt/guest/Cargo.toml @@ -104,3 +104,6 @@ strip = true [patch.crates-io] vitaminc-aead = { path = "../../../../packages/vitaminc-aead" } vitaminc-aead-derive = { path = "../../../../packages/vitaminc-aead-derive" } +# SPIKE, not for merging: the copy of vitaminc-normalize the root +# workspace patches in (see its [patch.crates-io]). +vitaminc-normalize = { path = "../../../../packages/vitaminc-normalize" } diff --git a/languages/golang/encrypt/guest/src/lib.rs b/languages/golang/encrypt/guest/src/lib.rs index 36e33a811..2b52938ce 100644 --- a/languages/golang/encrypt/guest/src/lib.rs +++ b/languages/golang/encrypt/guest/src/lib.rs @@ -80,7 +80,7 @@ //! `stack_guest_abi`'s, and [`io`] is how this guest's steps cross; //! [`abi`]'s module docs give this guest's contract on top of them. //! -//! On wasm32 `vitaminc-encrypt` uses its pure-Rust (RustCrypto `aes-gcm`) +//! On wasm32 vitaminc-aead's `aes` cipher uses its pure-Rust (RustCrypto `aes-gcm`) //! backend; the trade-offs are documented there. Values cross the boundary //! as vitaminc transport frames and ciphertext trees in vitaminc's //! ciphertext codec (`recipher_frame` — FFI encodings, not a storage diff --git a/languages/golang/encrypt/guest/tests/native_ops.rs b/languages/golang/encrypt/guest/tests/native_ops.rs index f84c86e1c..32509ccb9 100644 --- a/languages/golang/encrypt/guest/tests/native_ops.rs +++ b/languages/golang/encrypt/guest/tests/native_ops.rs @@ -25,8 +25,7 @@ mod support; use stack_encrypt::dynamic::frame::{decode_ciphertext, encode_ciphertext}; use stack_encrypt::sem::{DefaultMatch, EqualityTerm, MatchTerms, OpeTerm, OreTerm}; use stack_encrypt::{ - nonempty, CipherText, EncryptInto, Label, Node, PassthroughFrame, PendingStackCipherText, - SealedValue, StackCipher, + nonempty, CipherText, EncryptInto, Label, Node, PassthroughFrame, SealedValue, StackCipher, }; use stack_encrypt::{AuditMetadata, Controlled, Protected}; use stack_encrypt_guest::ops::{self, TERM_EQUALITY, TERM_MATCH, TERM_OPE, TERM_ORE}; @@ -1018,12 +1017,7 @@ fn a_natively_sealed_field_under_an_extended_context_opens_through_a_plan() { let cipher = cipher(); let keyset = cipher.default_keyset(); let native = nonempty!("users").with("age").with(7u64); - let sealed = block_on( - PendingStackCipherText::plan(Tree::UInt32(34), native) - .expect("plan") - .into_pending(&keyset, native), - ) - .expect("seal"); + let sealed = block_on(keyset.encrypt_tree(Tree::UInt32(34), native)).expect("seal"); let CipherText::Single(leaf) = sealed else { panic!("a scalar seals to a single leaf"); }; diff --git a/languages/typescript/packages/recipher-js/Cargo.lock b/languages/typescript/packages/recipher-js/Cargo.lock index eb3a9efb8..c1b9ab544 100644 --- a/languages/typescript/packages/recipher-js/Cargo.lock +++ b/languages/typescript/packages/recipher-js/Cargo.lock @@ -3135,7 +3135,6 @@ dependencies = [ "uuid", "vitaminc 0.10.0", "vitaminc-aead 0.10.0", - "vitaminc-encrypt 0.10.0", "vitaminc-hmac", "vitaminc-normalize", "vitaminc-ore", @@ -3747,10 +3746,10 @@ checksum = "35042fb7a81d72dc43c53fec835e61027f18b4d01cc0f7e12d6c6a6ffbf3bfb9" dependencies = [ "vitaminc-aead 0.5.1", "vitaminc-context 0.5.1", - "vitaminc-encrypt 0.5.1", + "vitaminc-encrypt", "vitaminc-protected 0.5.1", "vitaminc-random 0.5.1", - "vitaminc-traits 0.5.1", + "vitaminc-traits", ] [[package]] @@ -3759,12 +3758,8 @@ version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "60ae27c0d0e6980d2f30683384ed591a9dafa943b18faaa6bfb456757b5e10ef" dependencies = [ - "vitaminc-aead 0.10.0", - "vitaminc-context 0.10.0", - "vitaminc-encrypt 0.10.0", "vitaminc-protected 0.10.0", "vitaminc-random 0.10.0", - "vitaminc-traits 0.10.0", ] [[package]] @@ -3786,8 +3781,9 @@ dependencies = [ name = "vitaminc-aead" version = "0.10.0" dependencies = [ + "aes-gcm", + "aws-lc-rs", "bytes", - "futures-util", "jiff", "rust_decimal", "serde", @@ -3853,20 +3849,6 @@ dependencies = [ "zeroize", ] -[[package]] -name = "vitaminc-encrypt" -version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e68d89e2587529db55a10fa59cb11be8a7505b4af473c8a0bec238c803190ec5" -dependencies = [ - "aes-gcm", - "aws-lc-rs", - "vitaminc-aead 0.10.0", - "vitaminc-protected 0.10.0", - "vitaminc-random 0.10.0", - "zeroize", -] - [[package]] name = "vitaminc-hmac" version = "0.10.0" @@ -3883,8 +3865,6 @@ dependencies = [ [[package]] name = "vitaminc-normalize" version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e333da8bb30eab39cc2c790cb860843229a0a06aefb807f4ce069a92a2e17e8d" dependencies = [ "thiserror 2.0.21", "unicode-general-category", @@ -4051,22 +4031,6 @@ dependencies = [ "zeroize", ] -[[package]] -name = "vitaminc-traits" -version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "31fba5af175073f24768a8b06dd054ad696c7e6051dda1316c3814043a36d8e0" -dependencies = [ - "anyhow", - "bytes", - "rmp-serde", - "serde", - "thiserror 2.0.21", - "vitaminc-protected 0.10.0", - "vitaminc-random 0.10.0", - "zeroize", -] - [[package]] name = "walkdir" version = "2.5.1" diff --git a/languages/typescript/packages/recipher-js/Cargo.toml b/languages/typescript/packages/recipher-js/Cargo.toml index 85f4883f8..8c33a33bd 100644 --- a/languages/typescript/packages/recipher-js/Cargo.toml +++ b/languages/typescript/packages/recipher-js/Cargo.toml @@ -27,3 +27,6 @@ repository = "https://github.com/cipherstash/stack" [patch.crates-io] vitaminc-aead = { path = "../../../../packages/vitaminc-aead" } vitaminc-aead-derive = { path = "../../../../packages/vitaminc-aead-derive" } +# SPIKE, not for merging: the copy of vitaminc-normalize the root +# workspace patches in (see its [patch.crates-io]). +vitaminc-normalize = { path = "../../../../packages/vitaminc-normalize" } diff --git a/languages/typescript/packages/recipher-js/value-napi/tests/addon/Cargo.lock b/languages/typescript/packages/recipher-js/value-napi/tests/addon/Cargo.lock index fdd0c938b..9d19e9507 100644 --- a/languages/typescript/packages/recipher-js/value-napi/tests/addon/Cargo.lock +++ b/languages/typescript/packages/recipher-js/value-napi/tests/addon/Cargo.lock @@ -890,7 +890,6 @@ dependencies = [ "recipher-value-napi", "serde_json", "vitaminc-aead", - "vitaminc-encrypt", "vitaminc-protected", ] @@ -1128,8 +1127,9 @@ checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" name = "vitaminc-aead" version = "0.10.0" dependencies = [ + "aes-gcm", + "aws-lc-rs", "bytes", - "futures-util", "jiff", "rust_decimal", "serde", @@ -1160,20 +1160,6 @@ dependencies = [ "vitaminc-protected", ] -[[package]] -name = "vitaminc-encrypt" -version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e68d89e2587529db55a10fa59cb11be8a7505b4af473c8a0bec238c803190ec5" -dependencies = [ - "aes-gcm", - "aws-lc-rs", - "vitaminc-aead", - "vitaminc-protected", - "vitaminc-random", - "zeroize", -] - [[package]] name = "vitaminc-protected" version = "0.10.0" diff --git a/languages/typescript/packages/recipher-js/value-napi/tests/addon/Cargo.toml b/languages/typescript/packages/recipher-js/value-napi/tests/addon/Cargo.toml index eb1609c99..54162f5e1 100644 --- a/languages/typescript/packages/recipher-js/value-napi/tests/addon/Cargo.toml +++ b/languages/typescript/packages/recipher-js/value-napi/tests/addon/Cargo.toml @@ -18,9 +18,8 @@ napi-derive = "3" serde_json = "1" # For a refusal's code. The code is the refusal's diagnostic code. miette = "7.5.0" -vitaminc-aead = { version = "0.10.0", features = ["rust_decimal"] } +vitaminc-aead = { version = "0.10.0", features = ["rust_decimal", "aes"] } recipher-value-napi = { path = "../.." } -vitaminc-encrypt = "0.10.0" vitaminc-protected = "0.10.0" [build-dependencies] diff --git a/languages/typescript/packages/recipher-js/value-napi/tests/addon/src/lib.rs b/languages/typescript/packages/recipher-js/value-napi/tests/addon/src/lib.rs index 9221257f4..f23b3faa7 100644 --- a/languages/typescript/packages/recipher-js/value-napi/tests/addon/src/lib.rs +++ b/languages/typescript/packages/recipher-js/value-napi/tests/addon/src/lib.rs @@ -13,7 +13,8 @@ use vitaminc_aead::{ EncryptError, Float, Frame, Int, Logical, MapSink, Node, PassthroughFrame, Physical, SeqSink, Sink, TimeUnit, }; -use vitaminc_encrypt::{Aes256Cipher, Key, LocalCipherText}; +use vitaminc_aead::aes::{Aes256Cipher, Key}; +use vitaminc_aead::LocalCipherText; use vitaminc_protected::{Controlled, Protected}; /// The wrapper classes, exported so JavaScript can make instances with @@ -92,9 +93,6 @@ fn encrypt_error(error: EncryptError) -> Error { EncryptError::Source(source) => JsFault::from_source(&source), EncryptError::Shape(shape) => Error::new(Status::InvalidArg, format!("encrypt: {shape}")), EncryptError::Cipher(_) => Error::new(Status::GenericFailure, "encrypt: cipher failed"), - EncryptError::Count(count) => { - Error::new(Status::GenericFailure, format!("encrypt: {count}")) - } } } diff --git a/languages/typescript/packages/recipher-js/value-napi/tests/testdata/value-conformance.json b/languages/typescript/packages/recipher-js/value-napi/tests/testdata/value-conformance.json index 30e19d3a4..954e40fd0 100644 --- a/languages/typescript/packages/recipher-js/value-napi/tests/testdata/value-conformance.json +++ b/languages/typescript/packages/recipher-js/value-napi/tests/testdata/value-conformance.json @@ -713,98 +713,5 @@ "transport": "03010000000204000000deadbeef", "rule": "ADR 0001 section 3: CT_NONE is refused wherever it appears" } - ], - "leaf_type_aad": { - "rule": "LeafTypeAad (ADR 0001 section 3): the context is PAE(domain, base, kind, id) under the vitaminc-context encoding, where PAE is a u64-le count then each element as a u64-le length and its bytes, and each element is itself a typed piece: a PAE of two parts, the u64-le-prefixed label vitaminc/context/value/v1 and the u64-le-prefixed type label then the payload. The domain is bytes/v1 over vitaminc/aead/leaf-type/v2; the base is utf8/v1 over the base string; the kind is u8-le/v1 over the physical kind byte (null 0, bool 1, int 2, float 3, text 4, bytes 5; a cross-language commitment, never renumbered); the id is u8-le/v1 over the logical id byte, 0 for no logical type. The parameter is not bound: two vectors with the same base, kind and id and different parameters have the same context.", - "vectors": [ - { - "name": "int-date", - "base": "ctx", - "kind": "int", - "logical": { - "id": 2, - "param": 0 - }, - "context": "04000000000000006c0000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f62797465732f76311a00000000000000766974616d696e632f616561642f6c6561662d747970652f7632540000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f76310300000000000000637478530000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f75382d6c652f7631010000000000000002530000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f75382d6c652f7631010000000000000002" - }, - { - "name": "text-no-logical", - "base": "ctx", - "kind": "text", - "context": "04000000000000006c0000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f62797465732f76311a00000000000000766974616d696e632f616561642f6c6561662d747970652f7632540000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f76310300000000000000637478530000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f75382d6c652f7631010000000000000004530000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f75382d6c652f7631010000000000000000" - }, - { - "name": "bytes-uuid", - "base": "schema", - "kind": "bytes", - "logical": { - "id": 5, - "param": 0 - }, - "context": "04000000000000006c0000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f62797465732f76311a00000000000000766974616d696e632f616561642f6c6561662d747970652f7632570000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f76310600000000000000736368656d61530000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f75382d6c652f7631010000000000000005530000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f75382d6c652f7631010000000000000005" - }, - { - "name": "int-timestamp-millis", - "base": "events", - "kind": "int", - "logical": { - "id": 3, - "param": 1 - }, - "context": "04000000000000006c0000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f62797465732f76311a00000000000000766974616d696e632f616561642f6c6561662d747970652f7632570000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f763106000000000000006576656e7473530000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f75382d6c652f7631010000000000000002530000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f75382d6c652f7631010000000000000003" - }, - { - "name": "int-decimal-scale-2", - "base": "price", - "kind": "int", - "logical": { - "id": 4, - "param": 2 - }, - "context": "04000000000000006c0000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f62797465732f76311a00000000000000766974616d696e632f616561642f6c6561662d747970652f7632560000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f763105000000000000007072696365530000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f75382d6c652f7631010000000000000002530000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f75382d6c652f7631010000000000000004" - }, - { - "name": "null-undefined", - "base": "ctx", - "kind": "null", - "logical": { - "id": 1, - "param": 0 - }, - "context": "04000000000000006c0000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f62797465732f76311a00000000000000766974616d696e632f616561642f6c6561662d747970652f7632540000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f76310300000000000000637478530000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f75382d6c652f7631010000000000000000530000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f75382d6c652f7631010000000000000001" - }, - { - "name": "bool-no-logical", - "base": "ctx", - "kind": "bool", - "context": "04000000000000006c0000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f62797465732f76311a00000000000000766974616d696e632f616561642f6c6561662d747970652f7632540000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f76310300000000000000637478530000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f75382d6c652f7631010000000000000001530000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f75382d6c652f7631010000000000000000" - }, - { - "name": "float-no-logical", - "base": "ctx", - "kind": "float", - "context": "04000000000000006c0000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f62797465732f76311a00000000000000766974616d696e632f616561642f6c6561662d747970652f7632540000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f76310300000000000000637478530000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f75382d6c652f7631010000000000000003530000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f75382d6c652f7631010000000000000000" - }, - { - "name": "int-decimal-scale-0", - "base": "price", - "kind": "int", - "logical": { - "id": 4, - "param": 0 - }, - "context": "04000000000000006c0000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f62797465732f76311a00000000000000766974616d696e632f616561642f6c6561662d747970652f7632560000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f763105000000000000007072696365530000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f75382d6c652f7631010000000000000002530000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f75382d6c652f7631010000000000000004" - }, - { - "name": "int-timestamp-nanos", - "base": "events", - "kind": "int", - "logical": { - "id": 3, - "param": 3 - }, - "context": "04000000000000006c0000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f62797465732f76311a00000000000000766974616d696e632f616561642f6c6561662d747970652f7632570000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311800000000000000766974616d696e632f636f6e746578742f757466382f763106000000000000006576656e7473530000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f75382d6c652f7631010000000000000002530000000000000003000000000000001900000000000000766974616d696e632f636f6e746578742f76616c75652f76311900000000000000766974616d696e632f636f6e746578742f75382d6c652f7631010000000000000003" - } - ] - } + ] } diff --git a/packages/eql/Cargo.lock b/packages/eql/Cargo.lock index 53fef182a..502fed6f5 100644 --- a/packages/eql/Cargo.lock +++ b/packages/eql/Cargo.lock @@ -1227,7 +1227,6 @@ dependencies = [ "tokio", "uuid", "vitaminc-aead 0.10.0", - "vitaminc-encrypt 0.10.0", "vitaminc-protected 0.10.0", "zeroize", ] @@ -4235,7 +4234,6 @@ dependencies = [ "uuid", "vitaminc 0.10.0", "vitaminc-aead 0.10.0", - "vitaminc-encrypt 0.10.0", "vitaminc-hmac", "vitaminc-normalize", "vitaminc-ore", @@ -5048,12 +5046,8 @@ version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "60ae27c0d0e6980d2f30683384ed591a9dafa943b18faaa6bfb456757b5e10ef" dependencies = [ - "vitaminc-aead 0.10.0", - "vitaminc-context 0.10.0", - "vitaminc-encrypt 0.10.0", "vitaminc-protected 0.10.0", "vitaminc-random 0.10.0", - "vitaminc-traits 0.10.0", ] [[package]] @@ -5088,8 +5082,9 @@ dependencies = [ name = "vitaminc-aead" version = "0.10.0" dependencies = [ + "aes-gcm", + "aws-lc-rs", "bytes", - "futures-util", "jiff", "rust_decimal", "serde", @@ -5169,20 +5164,6 @@ dependencies = [ "zeroize", ] -[[package]] -name = "vitaminc-encrypt" -version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e68d89e2587529db55a10fa59cb11be8a7505b4af473c8a0bec238c803190ec5" -dependencies = [ - "aes-gcm", - "aws-lc-rs", - "vitaminc-aead 0.10.0", - "vitaminc-protected 0.10.0", - "vitaminc-random 0.10.0", - "zeroize", -] - [[package]] name = "vitaminc-hmac" version = "0.10.0" @@ -5199,8 +5180,6 @@ dependencies = [ [[package]] name = "vitaminc-normalize" version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e333da8bb30eab39cc2c790cb860843229a0a06aefb807f4ce069a92a2e17e8d" dependencies = [ "thiserror 2.0.20", "unicode-general-category", @@ -5434,22 +5413,6 @@ dependencies = [ "zeroize", ] -[[package]] -name = "vitaminc-traits" -version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "31fba5af175073f24768a8b06dd054ad696c7e6051dda1316c3814043a36d8e0" -dependencies = [ - "anyhow", - "bytes", - "rmp-serde", - "serde", - "thiserror 2.0.20", - "vitaminc-protected 0.10.0", - "vitaminc-random 0.10.0", - "zeroize", -] - [[package]] name = "vsimd" version = "0.8.0" diff --git a/packages/eql/Cargo.toml b/packages/eql/Cargo.toml index 72314769c..5c8f52216 100644 --- a/packages/eql/Cargo.toml +++ b/packages/eql/Cargo.toml @@ -42,3 +42,6 @@ unused_imports = "deny" [patch.crates-io] vitaminc-aead = { path = "../vitaminc-aead" } vitaminc-aead-derive = { path = "../vitaminc-aead-derive" } +# SPIKE, not for merging: the copy of vitaminc-normalize the root +# workspace patches in (see its [patch.crates-io]). +vitaminc-normalize = { path = "../vitaminc-normalize" } diff --git a/packages/eql/tests/encryption/Cargo.toml b/packages/eql/tests/encryption/Cargo.toml index 5265d9886..3f6fbc8c9 100644 --- a/packages/eql/tests/encryption/Cargo.toml +++ b/packages/eql/tests/encryption/Cargo.toml @@ -50,11 +50,10 @@ stack-encrypt = { path = "../../../stack-encrypt", default-features = false, fea # `plaintext::Sink`, for a plaintext type with its own `Encrypt` impl; and # jiff's and rust_decimal's own sources, which seal the leaf a date, # timestamp or decimal from any other producer seals. -vitaminc-aead = { version = "0.10.0", features = ["jiff", "rust_decimal"] } -# The AES cipher and protected buffer of the leaves stack-encrypt seals: +vitaminc-aead = { version = "0.10.0", features = ["jiff", "rust_decimal", "aes"] } +# `aes` is the AES cipher of the leaves stack-encrypt seals: # tests/opaque_json_bytes.rs opens a stored leaf with a kept test key to pin # the plaintext that was sealed. -vitaminc-encrypt = "0.10.0" vitaminc-protected = "0.10.0" jiff = "1.0.0" rust_decimal = { version = "1", default-features = false, features = ["std"] } diff --git a/packages/eql/tests/encryption/tests/heap_hygiene.rs b/packages/eql/tests/encryption/tests/heap_hygiene.rs index 0d5520fb0..a701ac976 100644 --- a/packages/eql/tests/encryption/tests/heap_hygiene.rs +++ b/packages/eql/tests/encryption/tests/heap_hygiene.rs @@ -10,13 +10,6 @@ //! indexed, when the value is refused or fails to open, and when the //! pending work is dropped before its keys arrive. stack-encrypt's //! `tests/heap_hygiene.rs` holds its dynamic paths the same way. -//! -//! One free is excluded by name: vitaminc-encrypt 0.6.0's aws-lc backend -//! (`backend::aws_lc::CipherKey::seal`, native builds only) frees an unwiped -//! plaintext buffer on every seal; that is vitaminc's to fix. It is counted -//! and printed, never silent, and every other free on those paths is still -//! watched. The spy recognises these frees by their backtrace, so a build -//! without symbols fails rather than passes. //! //! Unix only: the spy scans a freed block with libc's `memmem`, not as a @@ -55,16 +48,8 @@ thread_local! { /// threads, and the findings below are one set. static GATE: Mutex<()> = Mutex::new(()); -/// The marked frees seen, as backtraces; and how many each exclusion took. +/// The marked frees seen, as backtraces. static FOUND: Mutex> = Mutex::new(Vec::new()); -static EXCLUDED: Mutex<[usize; 1]> = Mutex::new([0; 1]); - -/// The frames whose frees are excluded, each with what it is (see the module -/// docs): vitaminc's aws-lc seal. -const EXCLUSIONS: [(&str, &str); 1] = [( - "vitaminc_encrypt::backend::aws_lc::CipherKey::seal", - "vitaminc's aws-lc seal", -)]; /// Whether the `len` bytes at `ptr` hold [`MARK`]. A freed block can hold /// bytes Rust never initialised (a `Vec`'s spare capacity, a struct's @@ -112,21 +97,10 @@ unsafe impl GlobalAlloc for Spy { if holds_mark(ptr, layout.size()) { BUSY.with(|busy| busy.set(true)); let trace = std::backtrace::Backtrace::force_capture().to_string(); - // Symbol demangling differs by platform: Linux writes - // `<…::CipherKey>::seal`, macOS `…::CipherKey::seal`. Match - // with the angle brackets dropped. - let plain = trace.replace(['<', '>'], ""); - if let Some(at) = EXCLUSIONS - .iter() - .position(|(frame, _)| plain.contains(frame)) - { - EXCLUDED.lock().unwrap()[at] += 1; - } else { - FOUND - .lock() - .unwrap() - .push(format!("{} bytes freed unwiped:\n{trace}", layout.size())); - } + FOUND + .lock() + .unwrap() + .push(format!("{} bytes freed unwiped:\n{trace}", layout.size())); BUSY.with(|busy| busy.set(false)); } } @@ -163,17 +137,10 @@ fn allocations_of(size: usize, what: &str, f: impl FnOnce()) -> usize { /// [`watched`], for a caller already holding [`GATE`]. fn watched_in_gate(what: &str, f: impl FnOnce() -> T) -> T { FOUND.lock().unwrap().clear(); - *EXCLUDED.lock().unwrap() = [0; 1]; WATCHING.with(|on| on.set(true)); let out = f(); WATCHING.with(|on| on.set(false)); let found = std::mem::take(&mut *FOUND.lock().unwrap()); - let excluded = std::mem::take(&mut *EXCLUDED.lock().unwrap()); - for ((_, name), skipped) in EXCLUSIONS.iter().zip(excluded) { - if skipped > 0 { - eprintln!("{what}: skipped {skipped} unwiped frees in {name}"); - } - } assert!( found.is_empty(), "{what}: {} heap blocks were freed with plaintext in them:\n{}", diff --git a/packages/eql/tests/encryption/tests/opaque_json_bytes.rs b/packages/eql/tests/encryption/tests/opaque_json_bytes.rs index 073b0717b..888a88023 100644 --- a/packages/eql/tests/encryption/tests/opaque_json_bytes.rs +++ b/packages/eql/tests/encryption/tests/opaque_json_bytes.rs @@ -36,7 +36,7 @@ use stack_kms::{ 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_aead::aes::{Aes256Cipher, Key as AesKey}; use vitaminc_protected::{Buffer, Controlled as _, Protected}; const SEED: [u8; 32] = *b"eql opaque json bytes v1 "; diff --git a/packages/eql/tests/timing/ore_block_v2/ctgen/Cargo.lock b/packages/eql/tests/timing/ore_block_v2/ctgen/Cargo.lock index 02b9d1d35..b9a06dfc1 100644 --- a/packages/eql/tests/timing/ore_block_v2/ctgen/Cargo.lock +++ b/packages/eql/tests/timing/ore_block_v2/ctgen/Cargo.lock @@ -180,30 +180,6 @@ version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c" -[[package]] -name = "futures-core" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" - -[[package]] -name = "futures-task" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" - -[[package]] -name = "futures-util" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" -dependencies = [ - "futures-core", - "futures-task", - "pin-project-lite", - "slab", -] - [[package]] name = "generic-array" version = "0.14.7" @@ -428,12 +404,6 @@ dependencies = [ "zeroize", ] -[[package]] -name = "pin-project-lite" -version = "0.2.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" - [[package]] name = "ppv-lite86" version = "0.2.21" @@ -586,12 +556,6 @@ dependencies = [ "digest", ] -[[package]] -name = "slab" -version = "0.4.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" - [[package]] name = "subtle" version = "2.6.1" @@ -746,7 +710,6 @@ name = "vitaminc-aead" version = "0.10.0" dependencies = [ "bytes", - "futures-util", "serde", "thiserror 2.0.21", "vitaminc-aead-derive", @@ -791,8 +754,6 @@ dependencies = [ [[package]] name = "vitaminc-normalize" version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e333da8bb30eab39cc2c790cb860843229a0a06aefb807f4ce069a92a2e17e8d" dependencies = [ "thiserror 2.0.21", "unicode-general-category", diff --git a/packages/eql/tests/timing/ore_block_v2/ctgen/Cargo.toml b/packages/eql/tests/timing/ore_block_v2/ctgen/Cargo.toml index c6d868b09..4b1518c1d 100644 --- a/packages/eql/tests/timing/ore_block_v2/ctgen/Cargo.toml +++ b/packages/eql/tests/timing/ore_block_v2/ctgen/Cargo.toml @@ -30,3 +30,6 @@ hex = "0.4" [patch.crates-io] vitaminc-aead = { path = "../../../../../vitaminc-aead" } vitaminc-aead-derive = { path = "../../../../../vitaminc-aead-derive" } +# SPIKE, not for merging: the copy of vitaminc-normalize the root +# workspace patches in (see its [patch.crates-io]). +vitaminc-normalize = { path = "../../../../../vitaminc-normalize" } diff --git a/packages/recipher-frame/tests/conformance.rs b/packages/recipher-frame/tests/conformance.rs index 3fc1db676..5f9be9de5 100644 --- a/packages/recipher-frame/tests/conformance.rs +++ b/packages/recipher-frame/tests/conformance.rs @@ -5,25 +5,21 @@ //! pass. Building each date and timestamp with jiff also shows that every //! value another binding seals opens as a jiff value in Rust. Every //! malformed vector is refused, every normalized vector reads -//! and writes back as its canonical bytes, every malformed ciphertext is -//! refused by the ciphertext codec, and every leaf-type AAD vector has the -//! context bytes it pins. +//! and writes back as its canonical bytes, and every malformed ciphertext +//! is refused by the ciphertext codec. //! //! `vitaminc-aead`'s ADR 0001 section 3 //! (`packages/vitaminc-aead/docs/adr/0001-describe-plaintext-once-and-consume-it-with-sinks.md`) //! decides the cases the corpus carries beyond the //! original tag table: the `0xF3` envelope, no `CT_NONE`, a leap second -//! refused, a decimal negative zero read as zero, and `LeafTypeAad` under -//! its new label. Each such vector states its rule. +//! refused, and a decimal negative zero read as zero. Each such vector +//! states its rule. use std::collections::BTreeMap; use recipher_frame::{decode_ciphertext, to_frame, Frame}; use vitaminc_aead::plaintext::kinds::jiff as conv; -use vitaminc_aead::{ - Encrypt, Float, Int, IntoAad, Kind, KnownLogical, LeafTypeAad, Logical, Physical, Raw, - TimeUnit, UnknownLogicalId, -}; +use vitaminc_aead::{Encrypt, Float, Int, Logical, Physical, Raw, TimeUnit}; use vitaminc_protected::Controlled; fn unhex(text: &str) -> Vec { @@ -238,82 +234,3 @@ fn every_malformed_ciphertext_is_refused() { ); } } - -#[test] -fn every_leaf_type_aad_vector_has_its_context_bytes() { - let corpus = corpus(); - let section = &corpus["leaf_type_aad"]; - assert!(section["rule"].is_string()); - let rows = section["vectors"].as_array().expect("vectors"); - assert!(rows.len() >= 2, "with and without a logical id"); - let mut seen_without = false; - let mut seen_kinds = std::collections::BTreeSet::new(); - // (base, kind, id) -> context: the parameter is not bound, so two - // vectors that differ only in it must share one context. - let mut by_binding: BTreeMap<(String, String, u64), (Vec, u64)> = BTreeMap::new(); - // Bindings shared by two vectors with different parameters. - let mut shared_across_params = 0; - for row in rows { - let name = &row["name"]; - let base = row["base"].as_str().expect("base"); - let kind = match row["kind"].as_str().expect("kind") { - "null" => Kind::Null, - "bool" => Kind::Bool, - "int" => Kind::Int, - "float" => Kind::Float, - "text" => Kind::Text, - "bytes" => Kind::Bytes, - other => panic!("{name}: unknown kind {other}"), - }; - // The context binds the logical id and not its parameter, so the - // row's `param` plays no part here (see the rule on each row). - let id = row["logical"]["id"] - .as_u64() - .map(|id| u8::try_from(id).expect("a one-byte id")); - seen_without |= id.is_none(); - let context = match id { - None => LeafTypeAad::physical(base, kind), - Some(id) => match KnownLogical::from_id(id) { - Some(known) => { - assert_eq!(known.kind(), kind, "{name}: a known id over the wrong kind"); - LeafTypeAad::logical(base, known) - } - None => { - let unknown = UnknownLogicalId::new(id) - .unwrap_or_else(|| panic!("{name}: {id} is a known id")); - LeafTypeAad::unknown(base, kind, unknown) - } - }, - } - .into_aad(); - let expected = unhex(row["context"].as_str().expect("context")); - assert_eq!(context.as_bytes(), expected, "{name}"); - seen_kinds.insert(row["kind"].as_str().expect("kind").to_owned()); - let id = row["logical"]["id"].as_u64().unwrap_or(0); - let binding = ( - base.to_owned(), - row["kind"].as_str().expect("kind").to_owned(), - id, - ); - let param = row["logical"]["param"].as_u64().unwrap_or(0); - if let Some((other, other_param)) = by_binding.insert(binding, (expected.clone(), param)) { - assert_eq!( - other, expected, - "{name}: the parameter must not change the context" - ); - if other_param != param { - shared_across_params += 1; - } - } - } - assert!(seen_without); - // Every kind byte of the cross-language commitment is pinned. - assert_eq!( - seen_kinds.into_iter().collect::>(), - ["bool", "bytes", "float", "int", "null", "text"] - ); - assert!( - shared_across_params >= 1, - "at least one pair of vectors that differ only in the parameter" - ); -} diff --git a/packages/stack-auth/fuzz/Cargo.lock b/packages/stack-auth/fuzz/Cargo.lock index c445c934d..913c40795 100644 --- a/packages/stack-auth/fuzz/Cargo.lock +++ b/packages/stack-auth/fuzz/Cargo.lock @@ -3173,12 +3173,12 @@ version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "35042fb7a81d72dc43c53fec835e61027f18b4d01cc0f7e12d6c6a6ffbf3bfb9" dependencies = [ - "vitaminc-aead 0.5.1", - "vitaminc-context 0.5.1", - "vitaminc-encrypt 0.5.1", + "vitaminc-aead", + "vitaminc-context", + "vitaminc-encrypt", "vitaminc-protected 0.5.1", "vitaminc-random 0.5.1", - "vitaminc-traits 0.5.1", + "vitaminc-traits", ] [[package]] @@ -3187,12 +3187,8 @@ version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "60ae27c0d0e6980d2f30683384ed591a9dafa943b18faaa6bfb456757b5e10ef" dependencies = [ - "vitaminc-aead 0.10.0", - "vitaminc-context 0.10.0", - "vitaminc-encrypt 0.10.0", "vitaminc-protected 0.10.0", "vitaminc-random 0.10.0", - "vitaminc-traits 0.10.0", ] [[package]] @@ -3203,28 +3199,13 @@ checksum = "62cacd4dae485e98cfe5407e919187a8468dd933ea4234be5115b7d13a30f3c6" dependencies = [ "bytes", "serde", - "vitaminc-aead-derive 0.5.1", - "vitaminc-context 0.5.1", + "vitaminc-aead-derive", + "vitaminc-context", "vitaminc-protected 0.5.1", "vitaminc-random 0.5.1", "zeroize", ] -[[package]] -name = "vitaminc-aead" -version = "0.10.0" -dependencies = [ - "bytes", - "futures-util", - "serde", - "thiserror 2.0.18", - "vitaminc-aead-derive 0.10.0", - "vitaminc-context 0.10.0", - "vitaminc-protected 0.10.0", - "vitaminc-random 0.10.0", - "zeroize", -] - [[package]] name = "vitaminc-aead-derive" version = "0.5.1" @@ -3236,15 +3217,6 @@ dependencies = [ "syn 3.0.3", ] -[[package]] -name = "vitaminc-aead-derive" -version = "0.10.0" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.3", -] - [[package]] name = "vitaminc-context" version = "0.5.1" @@ -3255,16 +3227,6 @@ dependencies = [ "vitaminc-protected 0.5.1", ] -[[package]] -name = "vitaminc-context" -version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "431a7fb023688dba855e52b9c4e44c942418dde8ea08a2b115cf6a7f762fa5b9" -dependencies = [ - "mutants", - "vitaminc-protected 0.10.0", -] - [[package]] name = "vitaminc-encrypt" version = "0.5.1" @@ -3273,26 +3235,12 @@ checksum = "9fbd0e1748055e381e02033e08af385de879c4dcf32e0f6739ac0c0cf0c6f13d" dependencies = [ "aes-gcm", "aws-lc-rs", - "vitaminc-aead 0.5.1", + "vitaminc-aead", "vitaminc-protected 0.5.1", "vitaminc-random 0.5.1", "zeroize", ] -[[package]] -name = "vitaminc-encrypt" -version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e68d89e2587529db55a10fa59cb11be8a7505b4af473c8a0bec238c803190ec5" -dependencies = [ - "aes-gcm", - "aws-lc-rs", - "vitaminc-aead 0.10.0", - "vitaminc-protected 0.10.0", - "vitaminc-random 0.10.0", - "zeroize", -] - [[package]] name = "vitaminc-protected" version = "0.5.1" @@ -3418,22 +3366,6 @@ dependencies = [ "zeroize", ] -[[package]] -name = "vitaminc-traits" -version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "31fba5af175073f24768a8b06dd054ad696c7e6051dda1316c3814043a36d8e0" -dependencies = [ - "anyhow", - "bytes", - "rmp-serde", - "serde", - "thiserror 2.0.18", - "vitaminc-protected 0.10.0", - "vitaminc-random 0.10.0", - "zeroize", -] - [[package]] name = "walkdir" version = "2.5.0" @@ -4272,3 +4204,11 @@ name = "zmij" version = "1.0.20" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4de98dfa5d5b7fef4ee834d0073d560c9ca7b6c46a71d058c48db7960f8cfaf7" + +[[patch.unused]] +name = "vitaminc-aead" +version = "0.10.0" + +[[patch.unused]] +name = "vitaminc-aead-derive" +version = "0.10.0" diff --git a/packages/stack-encrypt/CONTEXT.md b/packages/stack-encrypt/CONTEXT.md index a075c0d8e..49478287b 100644 --- a/packages/stack-encrypt/CONTEXT.md +++ b/packages/stack-encrypt/CONTEXT.md @@ -173,7 +173,7 @@ parts joined by `/` (`users/email`; a nested list is parenthesised, so one text part can never read as two, and an empty part inside a list is the bare `b64:`. Rendered by one function, `Descriptor::from_piece`, and **frozen**: a change re-keys everything. Finer than the encodings for a -pre-encoded `Aad` (opaque bytes) and coarser for shapes that render alike +pre-encoded `Context` (opaque bytes) and coarser for shapes that render alike (`7i64` and `7u64`): seal and open must present the context in the same shape. The descriptor is derived, never authored: nothing takes a descriptor string from a caller. diff --git a/packages/stack-encrypt/Cargo.toml b/packages/stack-encrypt/Cargo.toml index 4f617651a..28d770c1c 100644 --- a/packages/stack-encrypt/Cargo.toml +++ b/packages/stack-encrypt/Cargo.toml @@ -40,8 +40,7 @@ stack-encrypt-jsonpath = { path = "../stack-encrypt-jsonpath", version = "0.3.0" # `NonEmpty::with`, `From for NonEmpty` (#314) and the parts view # (#318), all of which this crate relies on. All five must share one # version or the aead crate is duplicated. -vitaminc-aead = { workspace = true } -vitaminc-encrypt = { workspace = true } +vitaminc-aead = { workspace = true, features = ["aes"] } vitaminc-hmac = { workspace = true } # Equality terms derive over `vitaminc-normalize`'s encoding of a value # (the workspace turns on vitaminc-prf's `normalize` feature): one term per diff --git a/packages/stack-encrypt/fuzz/Cargo.lock b/packages/stack-encrypt/fuzz/Cargo.lock index 923524166..8490ebbce 100644 --- a/packages/stack-encrypt/fuzz/Cargo.lock +++ b/packages/stack-encrypt/fuzz/Cargo.lock @@ -2210,7 +2210,6 @@ dependencies = [ "uuid", "vitaminc 0.10.0", "vitaminc-aead 0.10.0", - "vitaminc-encrypt 0.10.0", "vitaminc-hmac", "vitaminc-normalize", "vitaminc-ore", @@ -2714,10 +2713,10 @@ checksum = "35042fb7a81d72dc43c53fec835e61027f18b4d01cc0f7e12d6c6a6ffbf3bfb9" dependencies = [ "vitaminc-aead 0.5.1", "vitaminc-context 0.5.1", - "vitaminc-encrypt 0.5.1", + "vitaminc-encrypt", "vitaminc-protected 0.5.1", "vitaminc-random 0.5.1", - "vitaminc-traits 0.5.1", + "vitaminc-traits", ] [[package]] @@ -2726,12 +2725,8 @@ version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "60ae27c0d0e6980d2f30683384ed591a9dafa943b18faaa6bfb456757b5e10ef" dependencies = [ - "vitaminc-aead 0.10.0", - "vitaminc-context 0.10.0", - "vitaminc-encrypt 0.10.0", "vitaminc-protected 0.10.0", "vitaminc-random 0.10.0", - "vitaminc-traits 0.10.0", ] [[package]] @@ -2753,8 +2748,9 @@ dependencies = [ name = "vitaminc-aead" version = "0.10.0" dependencies = [ + "aes-gcm", + "aws-lc-rs", "bytes", - "futures-util", "jiff", "rust_decimal", "serde", @@ -2820,20 +2816,6 @@ dependencies = [ "zeroize", ] -[[package]] -name = "vitaminc-encrypt" -version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e68d89e2587529db55a10fa59cb11be8a7505b4af473c8a0bec238c803190ec5" -dependencies = [ - "aes-gcm", - "aws-lc-rs", - "vitaminc-aead 0.10.0", - "vitaminc-protected 0.10.0", - "vitaminc-random 0.10.0", - "zeroize", -] - [[package]] name = "vitaminc-hmac" version = "0.10.0" @@ -2850,8 +2832,6 @@ dependencies = [ [[package]] name = "vitaminc-normalize" version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e333da8bb30eab39cc2c790cb860843229a0a06aefb807f4ce069a92a2e17e8d" dependencies = [ "thiserror 2.0.18", "unicode-general-category", @@ -3018,22 +2998,6 @@ dependencies = [ "zeroize", ] -[[package]] -name = "vitaminc-traits" -version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "31fba5af175073f24768a8b06dd054ad696c7e6051dda1316c3814043a36d8e0" -dependencies = [ - "anyhow", - "bytes", - "rmp-serde", - "serde", - "thiserror 2.0.18", - "vitaminc-protected 0.10.0", - "vitaminc-random 0.10.0", - "zeroize", -] - [[package]] name = "wasi" version = "0.11.1+wasi-snapshot-preview1" diff --git a/packages/stack-encrypt/fuzz/Cargo.toml b/packages/stack-encrypt/fuzz/Cargo.toml index e91082049..744601377 100644 --- a/packages/stack-encrypt/fuzz/Cargo.toml +++ b/packages/stack-encrypt/fuzz/Cargo.toml @@ -89,3 +89,6 @@ resolver = "2" [patch.crates-io] vitaminc-aead = { path = "../../vitaminc-aead" } vitaminc-aead-derive = { path = "../../vitaminc-aead-derive" } +# SPIKE, not for merging: the copy of vitaminc-normalize the root +# workspace patches in (see its [patch.crates-io]). +vitaminc-normalize = { path = "../../vitaminc-normalize" } diff --git a/packages/stack-encrypt/src/cipher.rs b/packages/stack-encrypt/src/cipher.rs index b6d2c0fe7..d7629199c 100644 --- a/packages/stack-encrypt/src/cipher.rs +++ b/packages/stack-encrypt/src/cipher.rs @@ -3,45 +3,40 @@ //! //! `StackCipher` belongs to one ZeroKMS client; a [`KeysetCipher`] — the //! cipher bound to one of that client's keysets — seals values whose -//! per-leaf keys are ZeroKMS data keys, minted under that keyset, rather +//! per-leaf keys are ZeroKMS data keys, generated under that keyset, rather //! than one fixed key. The value side is vitaminc's: a value describes -//! itself once ([`Encrypt`]), vitaminc plans it into a tree of pending -//! leaves, each with its tagged plaintext and the AAD its place derives, -//! and a bytes-only [`Cipher`] seals and opens one leaf at a time. The -//! result is a ciphertext tree ([`StackCipherText`], the analog of -//! `AesCipherText`) whose leaves ([`SealedValue`]) each carry the ZeroKMS -//! metadata for their own data key — the keyset it was minted under -//! included, which is why decrypting needs no keyset named and lives on the -//! client's `StackCipher`. +//! itself once ([`Encrypt`]), and one walk stages it for encryption as a +//! tree of plaintext leaves (`Node`). The result of the seal is +//! a tree of the same shape ([`StackCipherText`]) whose leaves +//! ([`SealedValue`]) each record the ZeroKMS metadata of their own data +//! key. The keyset the key was generated under is part of that metadata, +//! which is why decrypting needs no keyset named and is on the client's +//! `StackCipher`. //! -//! ## Batching the key fetch +//! ## One key for each leaf, fetched together //! -//! Data-key generation/retrieval is an async ZeroKMS round-trip, and each -//! leaf needs its own key, so the keys are fetched for the whole tree -//! before any leaf is sealed or opened. The AES work stays in vitaminc's -//! synchronous walk: +//! Generating or retrieving a data key is an async ZeroKMS round trip, and +//! each leaf needs its own key. So the keys for a whole tree are fetched +//! first, in one request, and the AES work is done afterwards, with the +//! keys in hand and nothing awaited: //! -//! * **Encrypt** — [`PendingStackCipherText::plan`] walks the value into -//! vitaminc's pending tree and does no I/O. A single -//! [`PendingStackCipherText::into_pending`] (or the [`KeysetCipher::encrypt_tree`] -//! convenience) then batches **one** `generate_keys` call for the whole -//! tree, under the handle's keyset, and seals every leaf through -//! `MintedKeys`, the sealing half of this crate's [`Cipher`], one key per -//! leaf in walk order. -//! * **Decrypt** — [`StackCipher::decrypt`] batches **one** `retrieve_keys` -//! call per keyset the leaves were sealed under and zips each key onto -//! its leaf. vitaminc's [`decrypt`](vitaminc_aead::decrypt) then opens -//! every leaf through `BoundKeys`, the opening half, and walks the opened -//! tree into the value's [`Decrypt`] sink. +//! * **Encrypt.** [`KeysetCipher::encrypt_tree`] walks the value, with no +//! I/O, and asks for one data key for each leaf. When the keys arrive, +//! `seal_tree` seals every leaf in one pass, each under the next key. +//! * **Decrypt.** [`StackCipher::decrypt`] asks for each leaf's data key, +//! in one request for each keyset the leaves were sealed under. When the +//! keys arrive, `open_tree` opens every leaf in one pass, each under the +//! next key, and walks the opened tree into the value's [`Decrypt`] +//! sink. //! -//! Neither half is vitaminc's `AsyncCipher`. Its `seal_many` batches the -//! leaves of one document, but a ZeroKMS request names the descriptor of -//! the context the whole tree is sealed under, which a leaf's derived AAD -//! does not carry, and the target layer merges the key requests of many -//! documents (the fields of a record, the rows of a column) into one call -//! (RFC 0002). So the fetch is the target layer's -//! [`Pending`](crate::target::Pending), and the cipher vitaminc drives is -//! the synchronous one. +//! Every leaf has its own key, so every leaf has its own cipher: an +//! `Aes256Cipher`, built from that leaf's data key. Nothing in this crate +//! is a cipher for a whole tree. +//! +//! The fetch is the target layer's [`Pending`](crate::target::Pending): a +//! list of requests that can be joined with the requests of other values +//! (the fields of a record, the rows of a column) before any is sent, so +//! they share one ZeroKMS call. //! //! ## AAD derivation //! @@ -64,7 +59,7 @@ //! Each leaf ([`SealedValue`]) stores the ZeroKMS keyset id, `iv` and key //! `tag` — enough to retrieve the data key — plus a vitaminc //! [`LocalCipherText`] sealed under that key by -//! [`vitaminc_encrypt::Aes256Cipher`] (AES-256-GCM via vitaminc's backend: +//! [`vitaminc_aead::aes::Aes256Cipher`] (AES-256-GCM via vitaminc's backend: //! `aws-lc-rs` on native, RustCrypto on wasm32; vitaminc's own random nonce //! and versioned leaf layout). The leaf AAD is the labelled derivation //! `leaf_aad` (private): @@ -76,8 +71,7 @@ //! rules, and one re-pointed at another keyset fails instead of asking that //! keyset for a key it never minted. The `tag` is always bound, so the //! ciphertext is cryptographically tied to its ZeroKMS data key (key -//! binding); a caller AAD (e.g. a [`ContextTag`](vitaminc_aead::ContextTag)) -//! adds a further binding layer. +//! binding); the caller's context adds a further binding layer. //! Every data key is requested under a ZeroKMS **descriptor**: the context //! the tree is sealed under, rendered as a string by //! [`Descriptor`]. ZeroKMS HMACs the descriptor into the @@ -91,7 +85,6 @@ //! concatenation). A compatibility module can be added later to read existing //! records as customers of `cipherstash-client` migrate. -use std::cell::RefCell; use std::num::NonZeroUsize; use std::sync::{Arc, Mutex, OnceLock, PoisonError}; use std::time::Duration; @@ -103,12 +96,12 @@ use stack_kms::{EnvKeyProvider, KeyProvider, StackKms, StackKmsBuilder}; #[cfg(all(feature = "http", not(target_arch = "wasm32")))] use stack_kms::{FallbackKeyProvider, ProfileKeyProvider}; use uuid::Uuid; -use vitaminc_aead::seal::seal_all; +use vitaminc_aead::aes::{Aes256Cipher, Key as AesKey}; +use vitaminc_aead::seal::{open_with, OpenError}; use vitaminc_aead::{ - Cipher, CipherText, Context, DecodeError, Decrypt, DecryptError, Encrypt, IntoAad, IntoContext, - LocalCipherText, Node, Pending, Unspecified, + Cipher, Context, DecodeError, Decrypt, DecryptError, Encrypt, IntoAad, IntoContext, + LocalCipherText, Node, Plaintext, Unspecified, }; -use vitaminc_encrypt::{Aes256Cipher, Key as AesKey}; use vitaminc_protected::Protected; use crate::credential::KeySource; @@ -1484,11 +1477,7 @@ impl<K> KeysetCipher<'_, K> { T: Encrypt, A: IntoContext<'a>, { - let context = context.into_context(); - match PendingStackCipherText::plan(value, context.clone()) { - Ok(pending) => pending.into_pending(self, context), - Err(error) => crate::target::Pending::failed(self, error), - } + crate::target::encrypt_opaque(value, self, context) } /// Decrypt a tree of individually sealed leaves. @@ -1564,8 +1553,13 @@ where T: Decrypt + 's, { let context = aad.into_context().into_owned(); - crate::target::bind_pending(cipher_ref, ciphertext, Descriptor::of(context.clone())) - .try_map(move |keyed| open_keyed(keyed, context)) + let descriptor = Descriptor::of(context.clone()); + crate::target::open_pending( + cipher_ref, + ciphertext, + context.into_aad().into_owned(), + descriptor, + ) } impl<K> StackCipher<K> { @@ -1719,7 +1713,7 @@ pub struct SealedValue { /// ZeroKMS key tag: required to retrieve the key, and bound into the /// leaf's AAD so the ciphertext is tied to its data key. tag: Vec<u8>, - /// The leaf sealed by [`vitaminc_encrypt::Aes256Cipher`] under the data + /// The leaf sealed by [`vitaminc_aead::aes::Aes256Cipher`] under the data /// key: `version ‖ nonce ‖ ciphertext ‖ gcm_tag`. ciphertext: LocalCipherText, } @@ -1950,158 +1944,83 @@ impl TryFrom<SealedValueRepr> for SealedValue { } } -/// A leaf with its retrieved data key bound alongside. Produced by -/// [`bind_keys`] once the batched `retrieve_keys` call has returned; opened -/// by [`BoundKeys`] under the AAD vitaminc's walk derives for its place. -pub(crate) struct KeyedLeaf { - leaf: SealedValue, - key: DataKey, -} - -/// [`StackCipherText`] with a [`DataKey`] zipped onto every keyed leaf. -pub(crate) type KeyedCipherText = Node<KeyedLeaf>; +// ============================================================================= +// Sealing and opening a tree: one pass each, with the keys in hand +// ============================================================================= -/// Zip retrieved keys onto the tree in the same depth-first order the -/// target layer requested them (`retrieve_requests`), so each leaf carries -/// its own key and opening it makes no assumption about the order vitaminc -/// visits leaves in. -pub(crate) fn bind_keys( - ciphertext: StackCipherText, - keys: &mut impl Iterator<Item = DataKey>, -) -> Result<KeyedCipherText, Unspecified> { - fn bind( - leaf: SealedValue, - keys: &mut impl Iterator<Item = DataKey>, - ) -> Result<KeyedLeaf, Unspecified> { - let key = keys.next().ok_or(Unspecified)?; - Ok(KeyedLeaf { leaf, key }) - } - - match ciphertext { - CipherText::Single(leaf) => Ok(CipherText::Single(bind(leaf, keys)?)), - CipherText::EmptySequence(leaf) => Ok(CipherText::EmptySequence(bind(leaf, keys)?)), - CipherText::EmptyMap(leaf) => Ok(CipherText::EmptyMap(bind(leaf, keys)?)), - CipherText::Sequence(items) => { - let mut out = Vec::with_capacity(items.len()); - for item in items { - out.push(bind_keys(item, keys)?); - } - Ok(CipherText::Sequence(out)) - } - CipherText::Map(entries) => { - let mut out = Vec::with_capacity(entries.len()); - for (k, v) in entries { - out.push((k, bind_keys(v, keys)?)); - } - Ok(CipherText::Map(out)) - } - CipherText::Passthrough(value) => Ok(CipherText::Passthrough(value)), - } +/// Seal every leaf of a staged value: each under the next of +/// `sealing_keys`, the data keys ZeroKMS generated for it, and under the +/// AAD its place derives from `aad`. vitaminc derives the AAD and visits +/// the leaves. This crate decides only where each leaf's key comes from. A +/// leaf with no key left is refused. +pub(crate) fn seal_tree( + tree: Node<Plaintext>, + aad: &Context<'_>, + keyset_id: Uuid, + sealing_keys: &mut impl Iterator<Item = DataKeyWithTag>, +) -> Result<StackCipherText, Unspecified> { + tree.seal(aad, |plaintext, aad| { + let key = sealing_keys.next().ok_or(Unspecified)?; + seal_leaf(plaintext, aad, keyset_id, key) + }) } -// ============================================================================= -// Pending tree — planned synchronously, sealed asynchronously -// ============================================================================= +/// Why a leaf did not open. +enum LeafError { + /// The response held fewer keys than the tree has leaves. + NoKey, + /// The leaf did not authenticate. + Aead, +} -/// A value planned for sealing: vitaminc's tree of pending leaves, each -/// holding its tagged plaintext and the AAD its place in the value derives, -/// with no ZeroKMS I/O done yet. [`into_pending`](Self::into_pending) -/// turns it into a [`StackCipherText`]. +/// Open every leaf of a stored value, each under the next key of `keys` +/// and the AAD its place derives from `aad`. Every leaf is authenticated +/// before any plaintext is returned. /// -/// [`plan`](Self::plan) walks the value once, through vitaminc's -/// `EncryptSink`, which owns every container rule (element and entry AAD, -/// the empty markers, duplicate keys, a container with nothing sealed in -/// it). This crate decides only where each leaf's key comes from. -pub struct PendingStackCipherText(Node<Pending>); - -impl PendingStackCipherText { - /// Plan `value` for sealing under `context`. No key is requested. - /// - /// A value vitaminc refuses to encrypt as given (a map with a repeated - /// key, a container whose every child is a passthrough, a nesting deeper - /// than the transport carries) is [`Error::Aead`], as it is when the - /// value is sealed in one step. - pub fn plan<'a, P: Encrypt>(value: P, context: impl IntoAad<'a>) -> Result<Self, Error> { - vitaminc_aead::plan::<_, Unspecified, _>(value, context) - .map(Self) - .map_err(|_| Error::Aead) - } - - /// Number of leaves that need a ZeroKMS data key: every leaf, the empty - /// markers included; a passthrough needs none. - pub(crate) fn key_count(&self) -> usize { - fn count(node: &Node<Pending>) -> usize { - match node { - CipherText::Single(_) | CipherText::EmptySequence(_) | CipherText::EmptyMap(_) => 1, - CipherText::Sequence(items) => items.iter().map(count).sum(), - CipherText::Map(entries) => entries.iter().map(|(_, v)| count(v)).sum(), - CipherText::Passthrough(_) => 0, - } - } - count(&self.0) - } - - /// Seal the whole tree. The result is a - /// [`Pending`](crate::target::Pending). Awaiting it generates one data - /// key for each keyed leaf, then seals every leaf. All the keys come - /// from one batched ZeroKMS call, under the [`Descriptor`] of `context`. - /// A tree that has only passthrough leaves makes no call. - /// - /// `context` is the context the tree was planned under — the value passed to - /// [`plan`](Self::plan), in the same shape (see the - /// [descriptor docs](crate::descriptor)). The tree itself only carries - /// the *derived* per-leaf AADs, so the root is named here; nothing can - /// check that the two agree, which is why [`KeysetCipher::encrypt_tree`], which - /// does both steps from one value, is the form to prefer. - /// - /// Await the result. To send audit metadata with the key request, call - /// [`.audit(..)`](crate::Pending::audit) on the result first. - /// - /// A caller can have *several* trees that were planned independently, - /// such as one for each record field in a language binding. Merge them - /// with [`Pending::zip`](crate::target::Pending::zip) or - /// [`Pending::all`](crate::target::Pending::all). The whole assembly - /// then seals in **one** batched `generate_keys` call. - /// - /// This method settles through [`seal_pending`](crate::target), the - /// request carrier of the target layer. `encrypt_into_with_context` - /// into a `StackCipherText` settles through it too. So a tree is sealed - /// in one way, through one path to ZeroKMS. - /// - /// **Context contract.** The cipher-directed path deliberately accepts - /// *any* AAD, including none at all (`()`) — it mirrors - /// `Aes256Cipher`, where AAD-less sealing is a legitimate AEAD use, - /// opened symmetrically by [`StackCipher::decrypt`]. But a tree that - /// will be opened through the target layer's - /// [`DecryptSource`](crate::target::DecryptSource) — a per-field record - /// assembly in an FFI front-end, say — is bound by that layer's rule: it - /// opens only under a [`NonEmpty`](crate::NonEmpty) context, so seal - /// under one here (a `NonEmpty<T>` is an [`IntoContext`] like any other, and - /// encodes exactly as `T` does) or the ciphertext can never be read that - /// way. - pub fn into_pending<'c, 'a, K>( - self, - cipher: &'a KeysetCipher<'_, K>, - context: impl IntoContext<'c>, - ) -> crate::target::Pending<'a, StackCipherText, K> { - let context = context.into_context(); - crate::target::seal_pending(cipher, self, Descriptor::from_piece(&context)) - .under_context(context.clone().into_owned(), context.into_owned()) - } +/// Too few keys for the tree, or keys left over, both mean the requests +/// and the tree disagree about the tree's shape. That is a bug in this +/// crate and not a data error, so it is `ResponseShape` and never `Aead`, +/// which would read as tampering. +pub(crate) fn open_leaves( + tree: StackCipherText, + aad: &Context<'_>, + opening_keys: &mut impl Iterator<Item = DataKey>, +) -> Result<Node<Plaintext>, Error> { + let opened = open_with(tree, aad, |leaf, aad| { + let key = opening_keys.next().ok_or(LeafError::NoKey)?; + open_leaf(leaf, &key, aad).map_err(|_| LeafError::Aead) + }) + .map_err(|error| match error { + OpenError::Cipher(LeafError::NoKey) => Error::ResponseShape, + _ => Error::Aead, + })?; + Ok(opened) +} - /// Seal under `keyset_id`, drawing one key per leaf from `keys` in - /// vitaminc's walk order. A leaf with no key left is refused. - pub(crate) fn seal_with( - self, - keyset_id: Uuid, - mut keys: impl Iterator<Item = DataKeyWithTag>, - ) -> Result<StackCipherText, Unspecified> { - let minted = MintedKeys { - keyset_id, - keys: RefCell::new(&mut keys), - }; - seal_all(&minted, self.0).map_err(|_| Unspecified) +/// Open a stored value into `T`: [`open_leaves`], then the opened tree is +/// walked into `T`. +/// +/// A wrong key or AAD, a tampered leaf or marker, and a malformed tree are +/// [`Error::Aead`]. A tree that opens but holds a value that is not a `T` +/// is [`Error::OpenedType`]: every leaf authenticated, so it was sealed as +/// another type, not altered. +/// +/// Each leaf authenticates on its own, under its context and its place's +/// AAD (a map entry's key). Which entries a map holds and the order of a +/// sequence are deliberately not authenticated: stored values map to rows +/// and columns that a database returns in any order and a query selects in +/// part. A refusal of a container's shape is therefore `OpenedType` like any +/// other, not `Aead`. +pub(crate) fn open_tree<T: Decrypt>( + tree: StackCipherText, + aad: &Context<'_>, + opening_keys: &mut impl Iterator<Item = DataKey>, +) -> Result<T, Error> { + let opened = open_leaves(tree, aad, opening_keys)?; + if opening_keys.next().is_some() { + return Err(Error::ResponseShape); } + vitaminc_aead::walk(opened, T::sink()).map_err(|error| opened_error::<T>(error.with_cipher())) } // ============================================================================= @@ -2186,91 +2105,17 @@ fn seal_leaf( }) } -/// Open one keyed leaf under `aad`, returning its tagged plaintext. -fn open_leaf(keyed: KeyedLeaf, aad: &Context<'_>) -> Result<Protected<Vec<u8>>, Unspecified> { - let KeyedLeaf { leaf, key } = keyed; - let cipher = leaf_cipher(&key)?; +/// Open one leaf with its retrieved data key under `aad`, returning its +/// tagged plaintext. +fn open_leaf( + leaf: SealedValue, + key: &DataKey, + aad: &Context<'_>, +) -> Result<Protected<Vec<u8>>, Unspecified> { + let cipher = leaf_cipher(key)?; cipher.open(leaf.ciphertext, &leaf_aad(aad, leaf.keyset_id, &leaf.tag)) } -// ============================================================================= -// The vitaminc ciphers: one leaf at a time, keys already in hand -// ============================================================================= - -/// The sealing half of this crate's vitaminc [`Cipher`]: seals each leaf -/// under the next of a batch of data keys ZeroKMS has already generated, -/// in the order vitaminc's [`seal_all`] visits the leaves. -/// -/// The batch is fetched before the walk, in one `generate_keys` call per -/// pending (see [`PendingStackCipherText::into_pending`]), so the walk itself is -/// synchronous. A leaf for which no key is left is refused. -struct MintedKeys<'k, I> { - keyset_id: Uuid, - keys: RefCell<&'k mut I>, -} - -impl<I: Iterator<Item = DataKeyWithTag>> Cipher for MintedKeys<'_, I> { - type Leaf = SealedValue; - type Error = Unspecified; - - fn seal( - &self, - plaintext: Protected<Vec<u8>>, - aad: &Context<'_>, - ) -> Result<SealedValue, Unspecified> { - let key = self.keys.borrow_mut().next().ok_or(Unspecified)?; - seal_leaf(plaintext, aad, self.keyset_id, key) - } - - /// Opening goes through [`BoundKeys`], whose leaves carry their - /// retrieved keys. A minted key is never used to open. - fn open(&self, _: SealedValue, _: &Context<'_>) -> Result<Protected<Vec<u8>>, Unspecified> { - Err(Unspecified) - } -} - -/// The opening half of this crate's vitaminc [`Cipher`]: opens a leaf -/// whose retrieved data key [`bind_keys`] has already bound to it, under -/// the AAD vitaminc's walk derives for the leaf's place. vitaminc then -/// checks the empty markers and the container rules and hands each -/// scalar to the sink, so the decrypt side has one definition of the -/// per-node AAD, shared with every other vitaminc cipher. -pub(crate) struct BoundKeys; - -impl Cipher for BoundKeys { - type Leaf = KeyedLeaf; - type Error = Unspecified; - - /// Sealing goes through [`MintedKeys`]: a leaf is sealed under a key - /// generated for it, never one retrieved for another leaf. - fn seal(&self, _: Protected<Vec<u8>>, _: &Context<'_>) -> Result<KeyedLeaf, Unspecified> { - Err(Unspecified) - } - - fn open(&self, leaf: KeyedLeaf, aad: &Context<'_>) -> Result<Protected<Vec<u8>>, Unspecified> { - open_leaf(leaf, aad) - } -} - -/// Open a key-bound tree into `T` under `aad`. A wrong key or AAD, a -/// tampered leaf or marker, and a malformed tree are [`Error::Aead`]. A tree -/// that opens but holds a value that is not a `T` is [`Error::OpenedType`]: -/// every leaf authenticated, so it was sealed as another type, not altered. -/// -/// Each leaf authenticates on its own, under its context and its place's -/// AAD (a map entry's key). Which entries a map holds and the order of a -/// sequence are deliberately not authenticated: stored values map to rows -/// and columns that a database returns in any order and a query selects in -/// part. A refusal of a container's shape is therefore `OpenedType` like any -/// other, not `Aead`. Authenticating membership may suit other uses later; -/// it is not what this crate does. -pub(crate) fn open_keyed<'a, T: Decrypt>( - keyed: KeyedCipherText, - aad: impl IntoAad<'a>, -) -> Result<T, Error> { - vitaminc_aead::decrypt(&BoundKeys, keyed, aad).map_err(opened_error::<T>) -} - /// What a failed open is to the caller. Only the sink's refusal is told /// apart, and only by the type it wanted: the `DecodeError` itself can name /// a map key, which is not repeated. @@ -2768,29 +2613,6 @@ mod tests { } } - /// Each half of the cipher does one thing: a minted key never opens a - /// leaf, and a key bound to a leaf for opening never seals one. - #[test] - fn each_half_of_the_cipher_refuses_the_other_halfs_work() { - let leaf = - SealedValue::from_parts(Uuid::nil(), [0; 16], vec![1; 4], vec![2; 32]).expect("a leaf"); - let mut keys = std::iter::empty::<DataKeyWithTag>(); - let minted = MintedKeys { - keyset_id: Uuid::nil(), - keys: RefCell::new(&mut keys), - }; - let aad = Context::from_encoded(b"aad"); - assert!(minted.open(leaf, &aad).is_err(), "a minted key never opens"); - assert!( - minted.seal(Protected::new(vec![1]), &aad).is_err(), - "and seals nothing once the batch is spent" - ); - assert!( - BoundKeys.seal(Protected::new(vec![1]), &aad).is_err(), - "a bound key never seals" - ); - } - /// Byte-level pin for the [`leaf_aad`] derivation. This is part of the /// frozen leaf format: a change to the domain label, the version byte, /// the keyset id's place, the piece order, or the PAE framing makes diff --git a/packages/stack-encrypt/src/dynamic/record.rs b/packages/stack-encrypt/src/dynamic/record.rs index c754399ea..066aa154f 100644 --- a/packages/stack-encrypt/src/dynamic/record.rs +++ b/packages/stack-encrypt/src/dynamic/record.rs @@ -171,6 +171,8 @@ use crate::{ #[cfg(test)] use crate::{ContextPiece, NonEmpty}; +#[cfg(test)] +mod one_sink; mod plan; pub mod planned; mod source; diff --git a/packages/stack-encrypt/src/dynamic/record/one_sink.rs b/packages/stack-encrypt/src/dynamic/record/one_sink.rs new file mode 100644 index 000000000..418e5f376 --- /dev/null +++ b/packages/stack-encrypt/src/dynamic/record/one_sink.rs @@ -0,0 +1,1602 @@ +//! SPIKE, not for merging. A record walked once, by a sink this crate +//! defines, and sealed in one pass. +//! +//! Encrypting a record is two steps: +//! +//! 1. `source.visit(RecordSink::new(plan))` walks the record once. The sink +//! is built from the plan, so it sends each field to the sinks the plan +//! names for it. When the walk ends, the sink settles each field's +//! context. The result is an [`PendingRecord`]. +//! 2. [`seal_record`] asks for every data key in one request, then seals +//! every leaf and keys every term in one pass. +//! +//! Decrypting is [`open_record`]: one request for every data key, then one +//! pass that opens each field and writes it to the output. +//! +//! [`field_context`] is the one statement of a field's context. The walk and +//! the opening both call it. +use vitaminc_aead::frame::{FrameWriteError, FrameWriter, OwnedFrame}; +use vitaminc_aead::plaintext::{EncryptRef, Error as _, FixedType, SourceError}; +use vitaminc_aead::shape::Root; +use vitaminc_aead::{ + ContextPiece, EncryptError, EncryptSink, IntoAad, Node, Plaintext, Tee, Unspecified, +}; +use vitaminc_normalize::{Term, Terms}; +use vitaminc_protected::{AsProtectedRef as _, Buffer}; + +use super::plan::Context; +use super::*; +use crate::cipher::{open_leaves, seal_tree}; +use crate::dynamic::label::{join, IntoLabel as _}; +use crate::sem::equality_of_normalized; +use crate::sem::EqualityTerm; +use crate::target::declaration::{ + ciphertext, clear, equality, open_frame, run, Answers, Declaration, Fields, Here, Left, Open, + Right, +}; +use crate::target::DeclaredContext; +use crate::target::{retrieve_requests, AeadContext, CallerContext, CipherRef, Pending, Request}; +use crate::{CipherText, Descriptor, KeysetCipher, Label, NonEmpty, StackCipherText}; + +/// The one error type of the walk: every sink teed in it reports this. +type WalkError = EncryptError<Unspecified>; + +/// Why a value is not a record of the plan. It names no value. +#[derive(Debug, thiserror::Error)] +enum NotThisRecord { + #[error("the value is not a map of fields")] + NotAMap, + #[error("a field is not in the plan")] + UnknownField, + #[error("a field is given twice")] + RepeatedField, + #[error("a field of the plan is missing")] + MissingField, + #[error("the context field is missing, or is not a label")] + NoContext, + #[error("a field's context is not valid")] + Context, + #[error("the spike keys equality terms only")] + NotInTheSpike, +} + +fn refused(why: NotThisRecord) -> WalkError { + WalkError::source(SourceError::new(why)) +} + +/// The context `field` is sealed under and its terms are keyed under: the +/// record's context, then the field's identity, under the plan's scopes +/// and bindings. `base` is the record's context: the plan's own label, or +/// the value of the plan's context field. +fn field_context( + plan: &Plan, + field: &FieldPlan, + base: &Label, +) -> Result<ContextPiece<'static>, NotThisRecord> { + let label = join(base, field.identity()).map_err(|_| NotThisRecord::Context)?; + let piece = AeadContext::from(plan.declared_context().under(NonEmpty::from(label))).piece(); + Descriptor::from_piece(&piece) + .check() + .map_err(|_| NotThisRecord::Context)?; + Ok(piece) +} + +/// Whether the plan stores `field` in the clear and nothing else. +fn in_the_clear(field: &FieldPlan) -> bool { + field.outputs() == [Output::Passthrough] +} + +// ============================================================================= +// The walk +// ============================================================================= + +/// The sink that walks a record. It is built from the plan. +pub(crate) struct RecordSink<'p> { + plan: &'p Plan, +} + +impl<'p> RecordSink<'p> { + pub(crate) fn new(plan: &'p Plan) -> Self { + Self { plan } + } +} + +impl<'p> Sink for RecordSink<'p> { + type Ok = PendingRecord; + type Error = WalkError; + type Seq = NotASequence; + type Map = RecordFields<'p>; + + fn scalar(self, _: Option<Logical>, _: Physical<'_>) -> Result<PendingRecord, WalkError> { + Err(refused(NotThisRecord::NotAMap)) + } + + fn typed_null(self, _: FixedType) -> Result<PendingRecord, WalkError> { + Err(refused(NotThisRecord::NotAMap)) + } + + fn seq(self, _: Option<usize>) -> Result<NotASequence, WalkError> { + Err(refused(NotThisRecord::NotAMap)) + } + + fn map(self, _: Option<usize>) -> Result<RecordFields<'p>, WalkError> { + Ok(RecordFields { + plan: self.plan, + fields: Vec::new(), + }) + } + + fn passthrough<P: ?Sized + EncryptRef>(self, _: &P) -> Result<PendingRecord, WalkError> { + Err(refused(NotThisRecord::NotAMap)) + } +} + +/// A record is a map, so its sink has no sequence. Never built. The `Sink` +/// trait asks every sink to name a sequence type. +pub(crate) enum NotASequence {} + +impl SeqSink for NotASequence { + type Ok = PendingRecord; + type Error = WalkError; + type Element<'s> = Option<EncryptSink<Root, Unspecified>>; + + fn element(&mut self) -> Result<Self::Element<'_>, WalkError> { + match *self {} + } + + fn end(self) -> Result<PendingRecord, WalkError> { + match self {} + } +} + +/// One field while the record is walked: a place for each of the three +/// things the plan can ask of a field. +struct WalkedField { + name: String, + /// The value staged for encryption, for a field the plan seals. + sealed: Option<Node<Plaintext>>, + /// The value normalized, for a field the plan indexes. + terms: Vec<Term>, + /// The value as a frame, for a field the plan stores in the clear. + clear: Buffer, +} + +/// The fields of the record being walked. +pub(crate) struct RecordFields<'p> { + plan: &'p Plan, + fields: Vec<WalkedField>, +} + +/// The sink of one field: the sink that seals it, the sink that indexes it +/// and the sink that keeps it in the clear, each present if the plan says +/// so. Each writes into its place in the field's [`WalkedField`]. +type FieldSink<'s> = Tee< + Option<EncryptSink<&'s mut Option<Node<Plaintext>>, Unspecified>>, + Tee<Option<Terms<'s, WalkError>>, Option<FrameWriter<'s, WalkError>>>, +>; + +impl MapSink for RecordFields<'_> { + type Ok = PendingRecord; + type Error = WalkError; + type Entry<'s> + = FieldSink<'s> + where + Self: 's; + + fn entry(&mut self, key: &str) -> Result<FieldSink<'_>, WalkError> { + let declared = self + .plan + .fields() + .iter() + .find(|field| field.name() == key) + .ok_or_else(|| refused(NotThisRecord::UnknownField))?; + if self.fields.iter().any(|field| field.name == key) { + return Err(refused(NotThisRecord::RepeatedField)); + } + let indexes = declared.indexes(); + if indexes.iter().any(|index| *index != IndexSpec::Equality) { + return Err(refused(NotThisRecord::NotInTheSpike)); + } + self.fields.push(WalkedField { + name: key.to_owned(), + sealed: None, + terms: Vec::new(), + clear: Buffer::new(), + }); + let Some(WalkedField { + sealed, + terms, + clear, + .. + }) = self.fields.last_mut() + else { + return Err(refused(NotThisRecord::MissingField)); + }; + Ok(Tee( + declared.has_ciphertext().then(|| EncryptSink::into(sealed)), + Tee( + (!indexes.is_empty()).then(|| Terms::new(terms)), + in_the_clear(declared).then(|| FrameWriter::reporting(clear, 0)), + ), + )) + } + + /// Every field has been walked, so every value a context needs is + /// here: this is where each field's context is settled. + fn end(self) -> Result<PendingRecord, WalkError> { + let Self { plan, fields } = self; + if plan + .fields() + .iter() + .any(|declared| !fields.iter().any(|field| field.name == declared.name())) + { + return Err(refused(NotThisRecord::MissingField)); + } + let mut walked = Vec::with_capacity(fields.len()); + for field in fields { + let has_clear = !field.clear.as_protected_ref().risky_ref().is_empty(); + let clear = match has_clear { + true => Some( + OwnedFrame::from_buffer(field.clear) + .map_err(|_| refused(NotThisRecord::NotAMap))?, + ), + false => None, + }; + walked.push((field.name, field.sealed, field.terms, clear)); + } + let base = match plan.context_source() { + Context::Label(label) => label.clone(), + Context::Field(of) => walked + .iter() + .find(|(name, ..)| name == of) + .and_then(|(.., clear)| clear.as_ref()) + .and_then(|frame| frame.into_label().ok()) + .ok_or_else(|| refused(NotThisRecord::NoContext))?, + }; + let mut record = Vec::with_capacity(walked.len()); + for (name, sealed, terms, clear) in walked { + let declared = plan + .fields() + .iter() + .find(|field| field.name() == name) + .ok_or_else(|| refused(NotThisRecord::UnknownField))?; + let context = match in_the_clear(declared) { + true => None, + false => Some(field_context(plan, declared, &base).map_err(refused)?), + }; + record.push(PendingField { + name, + context, + sealed, + terms, + clear, + }); + } + Ok(PendingRecord { fields: record }) + } +} + +// ============================================================================= +// The record between the walk and the seal +// ============================================================================= + +/// A record staged for encryption: walked, with nothing sealed and no term +/// keyed. Every field has its context. +pub(crate) struct PendingRecord { + fields: Vec<PendingField>, +} + +struct PendingField { + name: String, + /// What the field is sealed under and its terms are keyed under. + /// `None` for a field stored in the clear. + context: Option<ContextPiece<'static>>, + sealed: Option<Node<Plaintext>>, + terms: Vec<Term>, + clear: Option<OwnedFrame>, +} + +// ============================================================================= +// The seal +// ============================================================================= + +/// Walk `source` as a record of `plan`, then seal it. +pub(crate) fn encrypt_record<'a, K>( + cipher: &'a KeysetCipher<'_, K>, + plan: &Plan, + source: impl Encrypt, +) -> Pending<'a, StackCipherText, K> { + match source.visit(RecordSink::new(plan)) { + Ok(record) => seal_record(cipher, record), + Err(_) => Pending::failed(cipher, crate::Error::Aead), + } +} + +/// Seal a walked record. One request asks for a data key for each leaf, +/// each under the descriptor of its field's context. Then one pass seals +/// every leaf, keys every term, and puts each field's outputs in a map of +/// their own, which is the shape a record is stored in. +pub(crate) fn seal_record<'a, K>( + cipher: &'a KeysetCipher<'_, K>, + record: PendingRecord, +) -> Pending<'a, StackCipherText, K> { + let mut requests = Vec::new(); + for field in &record.fields { + if let (Some(tree), Some(context)) = (&field.sealed, &field.context) { + let descriptor = Descriptor::from_piece(context); + requests.extend( + std::iter::repeat_with(|| Request::generate_under(descriptor.clone())) + .take(tree.leaf_count()), + ); + } + } + let known = cipher.loaded_state().cloned(); + if known.is_none() { + requests.push(Request::selected_keyset()); + } + Pending::request(cipher, requests, move |responses| { + let keyset = match known { + Some(keyset) => keyset, + None => responses.next_keyset()?, + }; + let mut sealing_keys = responses.drain_generated(); + let mut fields = Vec::with_capacity(record.fields.len()); + for field in record.fields { + let aad = field.context.map(|context| context.into_aad().into_owned()); + let mut outputs = Vec::new(); + if let (Some(tree), Some(aad)) = (field.sealed, &aad) { + let sealed = seal_tree(tree, aad, keyset.id, &mut sealing_keys)?; + outputs.push(("c".to_owned(), sealed)); + } + for term in field.terms { + let aad = aad.clone().ok_or(crate::Error::Aead)?; + let eq = equality_of_normalized(&keyset.prf, term.normalized, aad)?; + outputs.push(("eq".to_owned(), bytes_node(eq.as_bytes().to_vec())?)); + } + if let Some(clear) = field.clear { + outputs.push(("passthrough".to_owned(), passthrough_frame(clear.frame()))); + } + fields.push((field.name, CipherText::Map(outputs))); + } + Ok(CipherText::Map(fields)) + }) +} + +// ============================================================================= +// The open +// ============================================================================= + +/// One field of a stored record, ready to open. +enum StoredField { + Sealed { + name: String, + tree: StackCipherText, + context: ContextPiece<'static>, + }, + Clear { + name: String, + value: OwnedFrame, + }, +} + +/// Take one named output out of a stored field's outputs. +fn take(outputs: &mut Vec<(String, StackCipherText)>, key: &str) -> Option<StackCipherText> { + let at = outputs.iter().position(|(name, _)| name == key)?; + Some(outputs.swap_remove(at).1) +} + +/// The fields of a stored record that open, each with its context, in the +/// order of the plan. +fn stored_fields(plan: &Plan, record: StackCipherText) -> Result<Vec<StoredField>, crate::Error> { + let CipherText::Map(mut stored) = record else { + return Err(crate::Error::Aead); + }; + let mut clear = Vec::new(); + let mut sealed = Vec::new(); + for declared in plan.fields() { + let at = stored + .iter() + .position(|(name, _)| name == declared.name()) + .ok_or(crate::Error::Aead)?; + let (name, CipherText::Map(mut outputs)) = stored.swap_remove(at) else { + return Err(crate::Error::Aead); + }; + if in_the_clear(declared) { + let Some(CipherText::Passthrough(payload)) = take(&mut outputs, "passthrough") else { + return Err(crate::Error::Aead); + }; + let value = passthrough_value(&payload).ok_or(crate::Error::Aead)?; + clear.push((name, value)); + } else if declared.has_ciphertext() { + let tree = take(&mut outputs, "c").ok_or(crate::Error::Aead)?; + sealed.push((declared, name, tree)); + } + } + let base = match plan.context_source() { + Context::Label(label) => label.clone(), + Context::Field(of) => clear + .iter() + .find(|(name, _)| name == of) + .and_then(|(_, value)| value.into_label().ok()) + .ok_or(crate::Error::Aead)?, + }; + let mut fields = Vec::with_capacity(clear.len() + sealed.len()); + for (declared, name, tree) in sealed { + let context = field_context(plan, declared, &base).map_err(|_| crate::Error::Aead)?; + fields.push(StoredField::Sealed { + name, + tree, + context, + }); + } + fields.extend( + clear + .into_iter() + .map(|(name, value)| StoredField::Clear { name, value }), + ); + Ok(fields) +} + +/// Open a stored record of `plan`. One request retrieves every leaf's data +/// key, each under the descriptor of its field's context. Then one pass +/// opens each field and writes its value to the output frame. +pub(crate) fn open_record<'a, K>( + cipher_ref: impl Into<CipherRef<'a, K>>, + plan: &Plan, + record: StackCipherText, +) -> Pending<'a, OwnedFrame, K> { + let cipher_ref: CipherRef<'a, K> = cipher_ref.into(); + let fields = match stored_fields(plan, record) { + Ok(fields) => fields, + Err(error) => return Pending::failed(cipher_ref, error), + }; + let mut requests = Vec::new(); + for field in &fields { + if let StoredField::Sealed { tree, context, .. } = field { + requests.extend(retrieve_requests(tree, &Descriptor::from_piece(context))); + } + } + Pending::request(cipher_ref, requests, move |responses| { + let mut opening_keys = responses.drain_retrieved(); + let mut out = Buffer::new(); + let written = |_: FrameWriteError| crate::Error::Aead; + let mut map = Sink::map(FrameWriter::new(&mut out), Some(fields.len())).map_err(written)?; + for field in fields { + match field { + StoredField::Sealed { + name, + tree, + context, + } => { + let opened = open_leaves(tree, &context.into_aad(), &mut opening_keys)?; + vitaminc_aead::walk(opened, map.entry(&name).map_err(written)?) + .map_err(|_| crate::Error::Aead)?; + } + StoredField::Clear { name, value } => { + (&value) + .visit(map.entry(&name).map_err(written)?) + .map_err(written)?; + } + } + } + map.end().map_err(written)?; + if opening_keys.next().is_some() { + return Err(crate::Error::ResponseShape); + } + drop(opening_keys); + OwnedFrame::from_buffer(out).map_err(|_| crate::Error::Aead) + }) +} + +// ============================================================================= +// The same record, as a declaration the plan builds +// ============================================================================= + +/// What one field of a plan gives: its ciphertext, its equality term and +/// its value in the clear, each there if the plan asks for it. +type FieldOutputs = ( + (Option<StackCipherText>, Option<EqualityTerm>), + Option<OwnedFrame>, +); + +/// One field of a plan, as a declaration. The three things a plan can ask +/// of a field are each there or not, so every field has this one type. +fn planned( + field: &FieldPlan, +) -> Result< + impl Open<Output = FieldOutputs, Context = CallerContext> + + Answers<crate::op::Eq, Left<Right<Here>>, Query: Declaration<Output = Option<EqualityTerm>>>, + NotThisRecord, +> { + let indexes = field.indexes(); + if indexes.iter().any(|index| *index != IndexSpec::Equality) { + return Err(NotThisRecord::NotInTheSpike); + } + let sealed = field + .has_ciphertext() + .then(|| ciphertext().accepting::<CallerContext>()); + let term = (!indexes.is_empty()).then(equality); + let in_clear = in_the_clear(field).then(clear::<CallerContext>); + Ok(Declaration::zip(Declaration::zip(sealed, term), in_clear)) +} + +/// A field's outputs as the map a record stores for it. +fn stored_field(outputs: FieldOutputs) -> Result<StackCipherText, crate::Error> { + let ((sealed, term), in_clear) = outputs; + let mut nodes = Vec::new(); + if let Some(sealed) = sealed { + nodes.push(("c".to_owned(), sealed)); + } + if let Some(term) = term { + nodes.push(("eq".to_owned(), bytes_node(term.as_bytes().to_vec())?)); + } + if let Some(in_clear) = in_clear { + nodes.push(( + "passthrough".to_owned(), + passthrough_frame(in_clear.frame()), + )); + } + Ok(CipherText::Map(nodes)) +} + +/// The fields' outputs as the tree a record is stored in. +fn stored_record( + names: Vec<String>, + outputs: Vec<FieldOutputs>, +) -> Result<Vec<(String, StackCipherText)>, crate::Error> { + names + .into_iter() + .zip(outputs) + .map(|(name, outputs)| Ok((name, stored_field(outputs)?))) + .collect() +} + +/// A stored field's map, taken apart into the outputs the field's +/// declaration stores: the inverse of [`stored_field`]. +fn unstored_field(field: &FieldPlan, node: StackCipherText) -> Result<FieldOutputs, crate::Error> { + let CipherText::Map(mut outputs) = node else { + return Err(crate::Error::Aead); + }; + let sealed = match field.has_ciphertext() { + true => Some(take(&mut outputs, "c").ok_or(crate::Error::Aead)?), + false => None, + }; + let term = match field.indexes().is_empty() { + true => None, + false => { + let Some(CipherText::Passthrough(payload)) = take(&mut outputs, "eq") else { + return Err(crate::Error::Aead); + }; + let bytes = passthrough_bytes(&payload).ok_or(crate::Error::Aead)?; + Some(EqualityTerm::try_from(bytes.as_slice()).map_err(|_| crate::Error::Aead)?) + } + }; + let in_clear = match in_the_clear(field) { + true => { + let Some(CipherText::Passthrough(payload)) = take(&mut outputs, "passthrough") else { + return Err(crate::Error::Aead); + }; + Some(passthrough_value(&payload).ok_or(crate::Error::Aead)?) + } + false => None, + }; + Ok(((sealed, term), in_clear)) +} + +/// The declaration of a plan whose context is its own label: every field +/// is under the label, then its own identity. +fn fields_under_label( + plan: &Plan, + label: &Label, +) -> Result<impl Open<Output = Vec<FieldOutputs>, Context = DeclaredContext>, NotThisRecord> { + let fields = plan + .fields() + .iter() + .map(|field| { + let own = join(label, field.identity()).map_err(|_| NotThisRecord::Context)?; + Ok(planned(field)? + .under(NonEmpty::from(own)) + .entry(field.name().to_owned())) + }) + .collect::<Result<Fields<_>, NotThisRecord>>()?; + Ok(fields.record()) +} + +/// The declaration of a plan whose context is the value of the field +/// `of`: every other field is under that value, then its own identity. The +/// context field is kept in the clear, and is the second output. +fn fields_under_context_field( + plan: &Plan, + of: &str, +) -> Result< + impl Open<Output = (Vec<FieldOutputs>, OwnedFrame), Context = DeclaredContext>, + NotThisRecord, +> { + let fields = plan + .fields() + .iter() + .filter(|field| field.name() != of) + .map(|field| { + Ok(planned(field)? + .under_field(field.identity().to_owned()) + .entry(field.name().to_owned())) + }) + .collect::<Result<Fields<_>, NotThisRecord>>()?; + Ok(fields.context_from(of.to_owned()).record()) +} + +/// The names of a plan's fields, without the context field `of`. +fn names_without(plan: &Plan, of: Option<&str>) -> Vec<String> { + plan.fields() + .iter() + .map(FieldPlan::name) + .filter(|name| Some(*name) != of) + .map(str::to_owned) + .collect() +} + +/// Walk `source` as a record of `plan`, then seal it, through the +/// declaration the plan builds. +pub(crate) fn encrypt_declared<'a, K: 'static>( + cipher: &'a KeysetCipher<'_, K>, + plan: &Plan, + source: impl Encrypt, +) -> Pending<'a, StackCipherText, K> { + let context = plan.declared_context(); + match plan.context_source() { + Context::Label(label) => { + let Ok(fields) = fields_under_label(plan, label) else { + return Pending::failed(cipher, crate::Error::Aead); + }; + let names = names_without(plan, None); + let declaration = + fields.try_map(move |outputs| Ok(CipherText::Map(stored_record(names, outputs)?))); + run(cipher, declaration, source, context) + } + Context::Field(of) => { + let Ok(fields) = fields_under_context_field(plan, of) else { + return Pending::failed(cipher, crate::Error::Aead); + }; + let names = names_without(plan, Some(of)); + let of = of.clone(); + let declaration = fields.try_map(move |(outputs, context_field)| { + let mut record = stored_record(names, outputs)?; + record.push((of, stored_field(((None, None), Some(context_field)))?)); + Ok(CipherText::Map(record)) + }); + run(cipher, declaration, source, context) + } + } +} + +/// Open a stored record of `plan` into a frame, through the same +/// declaration the plan builds to seal one. The stored tree is taken apart +/// into the outputs the declaration stores. Then the declaration makes one +/// key request, and one pass opens each field into its entry of the frame. +pub(crate) fn decrypt_declared<'a, K: 'static>( + cipher_ref: impl Into<CipherRef<'a, K>>, + plan: &Plan, + record: StackCipherText, +) -> Pending<'a, OwnedFrame, K> { + let cipher_ref: CipherRef<'a, K> = cipher_ref.into(); + let CipherText::Map(mut stored) = record else { + return Pending::failed(cipher_ref, crate::Error::Aead); + }; + let mut outputs_of = |field: &FieldPlan| { + let at = stored + .iter() + .position(|(name, _)| name == field.name()) + .ok_or(crate::Error::Aead)?; + unstored_field(field, stored.swap_remove(at).1) + }; + let context = plan.declared_context(); + match plan.context_source() { + Context::Label(label) => { + let Ok(declaration) = fields_under_label(plan, label) else { + return Pending::failed(cipher_ref, crate::Error::Aead); + }; + let outputs = plan.fields().iter().map(&mut outputs_of).collect(); + match outputs { + Ok(outputs) => open_frame(cipher_ref, &declaration, outputs, context), + Err(error) => Pending::failed(cipher_ref, error), + } + } + Context::Field(of) => { + let Ok(declaration) = fields_under_context_field(plan, of) else { + return Pending::failed(cipher_ref, crate::Error::Aead); + }; + let mut others = Vec::new(); + let mut context_field = None; + for field in plan.fields() { + match (outputs_of(field), field.name() == of) { + (Ok(((None, None), Some(in_clear))), true) => context_field = Some(in_clear), + (Ok(outputs), false) => others.push(outputs), + (Ok(_), true) => return Pending::failed(cipher_ref, crate::Error::Aead), + (Err(error), _) => return Pending::failed(cipher_ref, error), + } + } + let Some(context_field) = context_field else { + return Pending::failed(cipher_ref, crate::Error::Aead); + }; + open_frame(cipher_ref, &declaration, (others, context_field), context) + } + } +} + +/// The term a query sends for `field = value`, through the declaration +/// the plan builds for that field. It is the field's own declaration, read +/// for the operator `Eq`, under the context the field is sealed under. +/// +/// A plan whose context is a field of each record is refused, as today: a +/// query has no record to read that field from. +pub(crate) fn query_declared<'a, K: 'static>( + cipher: &'a KeysetCipher<'_, K>, + plan: &Plan, + field: &str, + value: impl Encrypt, +) -> Pending<'a, EqualityTerm, K> { + let Context::Label(label) = plan.context_source() else { + return Pending::failed(cipher, crate::Error::Aead); + }; + let Some(field) = plan + .fields() + .iter() + .find(|declared| declared.name() == field) + else { + return Pending::failed(cipher, crate::Error::Aead); + }; + let (Ok(declaration), Ok(own)) = (planned(field), join(label, field.identity())) else { + return Pending::failed(cipher, crate::Error::Aead); + }; + let query = declaration + .query::<crate::op::Eq, _>() + .under(NonEmpty::from(own)) + // A field with no equality index answers no `Eq`. + .try_map(|term: Option<EqualityTerm>| term.ok_or(crate::Error::Aead)); + run(cipher, query, value, plan.declared_context()) +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +mod tests { + use std::collections::BTreeMap; + + use recipher_frame::serde::{from_slice, to_vec}; + + use super::*; + use crate::kms::FakeDataKeySource; + use crate::StackCipher; + + /// A record whose context comes from its own `tenant` field. + fn plan_with_a_context_field() -> Plan { + let declaration = to_vec(&serde_json::json!({ + "context_field": "tenant", + "tenant": { "context": ["tenant"], "outputs": ["passthrough"], "type": "string" }, + "email": { "context": ["email"], "outputs": ["c", "eq"], "type": "string" }, + "age": { "context": ["age"], "outputs": ["c"], "type": "uint64" }, + })) + .expect("a frame"); + Plan::from_frame(declaration.as_protected_ref()).expect("parses") + } + + /// A record whose context is the plan's own label. + fn plan_with_a_label() -> Plan { + let declaration = to_vec(&serde_json::json!({ + "email": { "context": ["users", "email"], "outputs": ["c", "eq"], "type": "string" }, + "age": { "context": ["users", "age"], "outputs": ["c"], "type": "uint64" }, + })) + .expect("a frame"); + Plan::from_frame(declaration.as_protected_ref()).expect("parses") + } + + /// A record with nothing to seal. + fn plan_with_no_sealed_field() -> Plan { + let declaration = to_vec(&serde_json::json!({ + "plan": { "context": ["users", "plan"], "outputs": ["passthrough"], "type": "string" }, + })) + .expect("a frame"); + Plan::from_frame(declaration.as_protected_ref()).expect("parses") + } + + const TENANT: &str = "tenants/acme"; + + /// `{ age, email, tenant }`. A map's keys are in order, so `tenant` is + /// the last entry the walk reaches. + fn row_with_tenant() -> OwnedFrame { + let fields = BTreeMap::from([ + ("email", OwnedFrame::of("ada@example.com").expect("a frame")), + ("tenant", OwnedFrame::of(TENANT).expect("a frame")), + ("age", OwnedFrame::of(36u64).expect("a frame")), + ]); + OwnedFrame::of(&fields).expect("a frame") + } + + fn row() -> OwnedFrame { + let fields = BTreeMap::from([ + ("email", OwnedFrame::of("ada@example.com").expect("a frame")), + ("age", OwnedFrame::of(36u64).expect("a frame")), + ]); + OwnedFrame::of(&fields).expect("a frame") + } + + fn output<'r>(record: &'r StackCipherText, field: &str, key: &str) -> &'r StackCipherText { + let CipherText::Map(fields) = record else { + panic!("a record is a map"); + }; + let (_, outputs) = fields + .iter() + .find(|(name, _)| name == field) + .expect("the field"); + let CipherText::Map(outputs) = outputs else { + panic!("a field is a map of outputs"); + }; + outputs + .iter() + .find(|(name, _)| name == key) + .map(|(_, node)| node) + .expect("the output") + } + + fn term_bytes(node: &StackCipherText) -> Vec<u8> { + let CipherText::Passthrough(payload) = node else { + panic!("a term is a passthrough node"); + }; + passthrough_bytes(payload).expect("bytes") + } + + fn decoded(frame: &OwnedFrame) -> BTreeMap<String, serde_json::Value> { + from_slice(frame.frame().as_bytes()).expect("a record") + } + + async fn a_cipher() -> StackCipher<FakeDataKeySource> { + StackCipher::builder() + .kms(FakeDataKeySource::new()) + .init() + .await + .expect("a cipher") + } + + mod given_a_record_whose_tenant_arrives_last { + use super::*; + + #[test] + fn one_walk_leaves_every_field_with_its_context() { + let plan = plan_with_a_context_field(); + + let record = row_with_tenant() + .visit(RecordSink::new(&plan)) + .map_err(|_| "refused") + .expect("one walk"); + + let seen: Vec<(&str, bool, bool, usize, bool)> = record + .fields + .iter() + .map(|field| { + ( + field.name.as_str(), + field.context.is_some(), + field.sealed.is_some(), + field.terms.len(), + field.clear.is_some(), + ) + }) + .collect(); + assert_eq!( + seen, + [ + ("age", true, true, 0, false), + ("email", true, true, 1, false), + ("tenant", false, false, 0, true), + ], + "each field: name, has a context, is sealed, its terms, is in the clear" + ); + } + + #[tokio::test] + async fn the_record_seals_in_one_pending_and_todays_decrypt_opens_it() { + let cipher = a_cipher().await; + let keyset = cipher.default_keyset(); + let plan = plan_with_a_context_field(); + + let pending = encrypt_record(&keyset, &plan, row_with_tenant()); + let key_requests = pending.key_count(); + let record = pending.await.expect("sealed"); + + let today = encrypt(&keyset, row_with_tenant(), &plan) + .expect("fits the plan") + .await + .expect("sealed"); + assert!( + (2..=3).contains(&key_requests), + "one data key for each of the two sealed values, and the keyset if it is not \ + loaded: {key_requests}" + ); + assert_eq!( + term_bytes(output(&record, "email", "eq")), + term_bytes(output(&today, "email", "eq")), + "the equality term from the one walk is today's term" + ); + + let opened = decrypt(&cipher, record, &plan, None) + .expect("fits the plan") + .await + .expect("today's decrypt opens the record the one sink sealed"); + let opened_today = decrypt(&cipher, today, &plan, None) + .expect("fits the plan") + .await + .expect("opens"); + assert_eq!( + opened.frame().as_bytes(), + opened_today.frame().as_bytes(), + "the record opens to the same plaintext as today's" + ); + } + + #[tokio::test] + async fn open_record_opens_what_todays_encrypt_stores() { + let cipher = a_cipher().await; + let keyset = cipher.default_keyset(); + let plan = plan_with_a_context_field(); + let today = encrypt(&keyset, row_with_tenant(), &plan) + .expect("fits the plan") + .await + .expect("sealed"); + + let opened = open_record(&cipher, &plan, today) + .await + .expect("one request, one pass"); + + assert_eq!( + decoded(&opened), + decoded(&row_with_tenant()), + "every field is back, the tenant included" + ); + } + + #[tokio::test] + async fn a_record_sealed_for_another_tenant_does_not_open_as_this_one() { + let cipher = a_cipher().await; + let keyset = cipher.default_keyset(); + let plan = plan_with_a_context_field(); + let sealed = encrypt_record(&keyset, &plan, row_with_tenant()) + .await + .expect("sealed"); + let CipherText::Map(mut fields) = sealed else { + panic!("a record is a map"); + }; + for (name, outputs) in &mut fields { + if name == "tenant" { + let other = OwnedFrame::of("tenants/other").expect("a frame"); + *outputs = CipherText::Map(vec![( + "passthrough".to_owned(), + passthrough_frame(other.frame()), + )]); + } + } + + let opened = open_record(&cipher, &plan, CipherText::Map(fields)).await; + + assert!( + opened.is_err(), + "the tenant is part of every other field's context" + ); + } + } + + mod given_the_same_record_as_a_declaration { + use super::*; + use crate::target::declaration::{ciphertext, indexed_equality, run, Declaration}; + use crate::target::DeclaredContext; + + /// The record of `plan_with_a_context_field`, written with the + /// combinators: what a plan would build at run time. Its output is + /// the tree a record is stored in. + fn the_declaration() -> impl Declaration<Output = StackCipherText, Context = DeclaredContext> + { + indexed_equality() + .under_field("email") + .entry("email") + .zip(ciphertext().under_field("age").entry("age")) + .context_from("tenant") + .record() + .map(|((email, age), tenant)| { + let eq = bytes_node(email.terms.as_bytes().to_vec()).expect("a term frames"); + let field = |outputs: Vec<(&str, StackCipherText)>| { + CipherText::Map( + outputs + .into_iter() + .map(|(key, node)| (key.to_owned(), node)) + .collect(), + ) + }; + CipherText::Map(vec![ + ("age".to_owned(), field(vec![("c", age)])), + ( + "email".to_owned(), + field(vec![("c", email.ciphertext), ("eq", eq)]), + ), + ( + "tenant".to_owned(), + field(vec![("passthrough", passthrough_frame(tenant.frame()))]), + ), + ]) + }) + } + + #[tokio::test] + async fn the_term_is_todays_term_though_the_tenant_arrives_last() { + let cipher = a_cipher().await; + let keyset = cipher.default_keyset(); + let plan = plan_with_a_context_field(); + + let record = run( + &keyset, + the_declaration(), + row_with_tenant(), + DeclaredContext::default(), + ) + .await + .expect("the declaration encrypts"); + let today = encrypt(&keyset, row_with_tenant(), &plan) + .expect("fits the plan") + .await + .expect("sealed"); + + assert_eq!( + term_bytes(output(&record, "email", "eq")), + term_bytes(output(&today, "email", "eq")), + "the declaration's equality term should be today's term" + ); + } + + #[tokio::test] + async fn todays_decrypt_opens_the_record() { + let cipher = a_cipher().await; + let keyset = cipher.default_keyset(); + let plan = plan_with_a_context_field(); + + let record = run( + &keyset, + the_declaration(), + row_with_tenant(), + DeclaredContext::default(), + ) + .await + .expect("the declaration encrypts"); + let today = encrypt(&keyset, row_with_tenant(), &plan) + .expect("fits the plan") + .await + .expect("sealed"); + + let opened = decrypt(&cipher, record, &plan, None) + .expect("fits the plan") + .await + .expect("today's decrypt opens the record the declaration sealed"); + let opened_today = decrypt(&cipher, today, &plan, None) + .expect("fits the plan") + .await + .expect("opens"); + assert_eq!( + opened.frame().as_bytes(), + opened_today.frame().as_bytes(), + "the record should open to the same plaintext as today's" + ); + } + + #[tokio::test] + async fn the_record_does_not_open_as_another_tenants() { + let cipher = a_cipher().await; + let keyset = cipher.default_keyset(); + let plan = plan_with_a_context_field(); + let sealed = run( + &keyset, + the_declaration(), + row_with_tenant(), + DeclaredContext::default(), + ) + .await + .expect("the declaration encrypts"); + let CipherText::Map(mut fields) = sealed else { + panic!("a record is a map"); + }; + for (name, outputs) in &mut fields { + if name == "tenant" { + let other = OwnedFrame::of("tenants/other").expect("a frame"); + *outputs = CipherText::Map(vec![( + "passthrough".to_owned(), + passthrough_frame(other.frame()), + )]); + } + } + + let opened = decrypt(&cipher, CipherText::Map(fields), &plan, None) + .expect("fits the plan") + .await; + + assert!( + opened.is_err(), + "the tenant should be part of every other field's context" + ); + } + + #[tokio::test] + async fn a_record_with_no_tenant_is_refused() { + let cipher = a_cipher().await; + let keyset = cipher.default_keyset(); + + let sealed = run( + &keyset, + the_declaration(), + row(), + DeclaredContext::default(), + ) + .await; + + assert!( + sealed.is_err(), + "a record with no context field should be refused" + ); + } + } + + mod given_a_declaration_the_plan_builds { + use super::*; + + /// Each field's name with the keys of its outputs, in name order. + fn shape(record: &StackCipherText) -> Vec<(String, Vec<String>)> { + let CipherText::Map(fields) = record else { + panic!("a record is a map"); + }; + let mut shape: Vec<(String, Vec<String>)> = fields + .iter() + .map(|(name, outputs)| { + let CipherText::Map(outputs) = outputs else { + panic!("a field is a map of outputs"); + }; + let mut keys: Vec<String> = + outputs.iter().map(|(key, _)| key.clone()).collect(); + keys.sort(); + (name.clone(), keys) + }) + .collect(); + shape.sort(); + shape + } + + /// Seal `row` both ways, and check the declaration's record against + /// today's: the same fields and outputs, the same equality term, + /// the same number of keys, and the same plaintext from today's + /// decrypt. + async fn is_todays_record(plan: Plan, row: OwnedFrame, term_of: Option<&str>) { + let cipher = a_cipher().await; + let keyset = cipher.default_keyset(); + + let declared = encrypt_declared(&keyset, &plan, &row); + let today = encrypt(&keyset, &row, &plan).expect("fits the plan"); + assert_eq!( + declared.key_count(), + today.key_count(), + "the declaration should ask for as many keys as today's path" + ); + let declared = declared.await.expect("the declaration seals"); + let today = today.await.expect("today's path seals"); + + assert_eq!( + shape(&declared), + shape(&today), + "the record should have today's fields and outputs" + ); + if let Some(field) = term_of { + assert_eq!( + term_bytes(output(&declared, field, "eq")), + term_bytes(output(&today, field, "eq")), + "the equality term should be today's term" + ); + } + let opened = decrypt(&cipher, declared, &plan, None) + .expect("fits the plan") + .await + .expect("today's decrypt opens the declaration's record"); + let opened_today = decrypt(&cipher, today, &plan, None) + .expect("fits the plan") + .await + .expect("opens"); + assert_eq!( + opened.frame().as_bytes(), + opened_today.frame().as_bytes(), + "the record should open to the same plaintext as today's" + ); + } + + #[tokio::test] + async fn a_plan_with_a_context_field_gives_todays_record() { + is_todays_record( + plan_with_a_context_field(), + row_with_tenant(), + Some("email"), + ) + .await; + } + + #[tokio::test] + async fn a_plan_with_a_label_gives_todays_record() { + is_todays_record(plan_with_a_label(), row(), Some("email")).await; + } + + #[tokio::test] + async fn a_plan_with_nothing_to_seal_gives_todays_record() { + let fields = BTreeMap::from([("plan", OwnedFrame::of("free").expect("a frame"))]); + let row = OwnedFrame::of(&fields).expect("a frame"); + + is_todays_record(plan_with_no_sealed_field(), row, None).await; + } + + #[tokio::test] + async fn a_field_the_plan_does_not_name_is_refused() { + let cipher = a_cipher().await; + let keyset = cipher.default_keyset(); + let fields = BTreeMap::from([ + ("email", OwnedFrame::of("ada@example.com").expect("a frame")), + ("age", OwnedFrame::of(36u64).expect("a frame")), + ("name", OwnedFrame::of("Ada").expect("a frame")), + ]); + let row = OwnedFrame::of(&fields).expect("a frame"); + + let sealed = encrypt_declared(&keyset, &plan_with_a_label(), &row).await; + + assert!( + sealed.is_err(), + "a field the plan does not name should be refused" + ); + } + + #[tokio::test] + async fn a_missing_field_is_refused() { + let cipher = a_cipher().await; + let keyset = cipher.default_keyset(); + let fields = + BTreeMap::from([("email", OwnedFrame::of("ada@example.com").expect("a frame"))]); + let row = OwnedFrame::of(&fields).expect("a frame"); + + let sealed = encrypt_declared(&keyset, &plan_with_a_label(), &row).await; + + assert!(sealed.is_err(), "a record with no age should be refused"); + } + } + + mod given_a_stored_record_and_the_plans_declaration { + use super::*; + + /// Open a record that today's path sealed, both ways, and check + /// the declaration against today's decrypt: the same number of + /// keys, and the same plaintext. + async fn opens_as_today(plan: Plan, row: OwnedFrame) { + let cipher = a_cipher().await; + let keyset = cipher.default_keyset(); + let seal = || async { + encrypt(&keyset, &row, &plan) + .expect("fits the plan") + .await + .expect("today's path seals") + }; + + let declared = decrypt_declared(&cipher, &plan, seal().await); + let today = decrypt(&cipher, seal().await, &plan, None).expect("fits the plan"); + assert_eq!( + declared.key_count(), + today.key_count(), + "the declaration should ask for as many keys as today's decrypt" + ); + let declared = declared.await.expect("the declaration opens"); + let today = today.await.expect("today's decrypt opens"); + + assert_eq!( + decoded(&declared), + decoded(&today), + "the declaration should open the record to today's plaintext" + ); + assert_eq!( + decoded(&declared), + decoded(&row), + "the plaintext should be the record that was sealed" + ); + } + + #[tokio::test] + async fn a_plan_with_a_context_field_opens_as_today() { + opens_as_today(plan_with_a_context_field(), row_with_tenant()).await; + } + + #[tokio::test] + async fn a_plan_with_a_label_opens_as_today() { + opens_as_today(plan_with_a_label(), row()).await; + } + + #[tokio::test] + async fn a_plan_with_nothing_to_seal_opens_as_today() { + let fields = BTreeMap::from([("plan", OwnedFrame::of("free").expect("a frame"))]); + let row = OwnedFrame::of(&fields).expect("a frame"); + + opens_as_today(plan_with_no_sealed_field(), row).await; + } + + #[tokio::test] + async fn one_declaration_seals_a_record_and_opens_it() { + let cipher = a_cipher().await; + let keyset = cipher.default_keyset(); + let plan = plan_with_a_context_field(); + + let sealed = encrypt_declared(&keyset, &plan, row_with_tenant()) + .await + .expect("the declaration seals"); + let opened = decrypt_declared(&cipher, &plan, sealed) + .await + .expect("the declaration opens what it sealed"); + + assert_eq!( + decoded(&opened), + decoded(&row_with_tenant()), + "the record should come back unchanged" + ); + } + + #[tokio::test] + async fn the_record_does_not_open_as_another_tenants() { + let cipher = a_cipher().await; + let keyset = cipher.default_keyset(); + let plan = plan_with_a_context_field(); + let sealed = encrypt_declared(&keyset, &plan, row_with_tenant()) + .await + .expect("the declaration seals"); + let CipherText::Map(mut fields) = sealed else { + panic!("a record is a map"); + }; + for (name, outputs) in &mut fields { + if name == "tenant" { + let other = OwnedFrame::of("tenants/other").expect("a frame"); + *outputs = CipherText::Map(vec![( + "passthrough".to_owned(), + passthrough_frame(other.frame()), + )]); + } + } + + let opened = decrypt_declared(&cipher, &plan, CipherText::Map(fields)).await; + + assert!( + opened.is_err(), + "the tenant should be part of every other field's context" + ); + } + + #[tokio::test] + async fn a_field_does_not_open_in_another_fields_place() { + let cipher = a_cipher().await; + let keyset = cipher.default_keyset(); + // Two fields of one type, so the plaintexts would fit each other. + let declaration = to_vec(&serde_json::json!({ + "first": { "context": ["users", "first"], "outputs": ["c"], "type": "string" }, + "last": { "context": ["users", "last"], "outputs": ["c"], "type": "string" }, + })) + .expect("a frame"); + let plan = Plan::from_frame(declaration.as_protected_ref()).expect("parses"); + let fields = BTreeMap::from([ + ("first", OwnedFrame::of("Ada").expect("a frame")), + ("last", OwnedFrame::of("Lovelace").expect("a frame")), + ]); + let row = OwnedFrame::of(&fields).expect("a frame"); + let sealed = encrypt_declared(&keyset, &plan, &row) + .await + .expect("the declaration seals"); + let CipherText::Map(mut stored) = sealed else { + panic!("a record is a map"); + }; + // Swap the two fields' outputs. + let (first, last) = stored.split_at_mut(1); + std::mem::swap(&mut first[0].1, &mut last[0].1); + + let opened = decrypt_declared(&cipher, &plan, CipherText::Map(stored)).await; + + assert!( + opened.is_err(), + "a field sealed under users/first should not open as users/last" + ); + } + } + + mod given_a_query_of_a_plans_field { + use super::*; + use crate::dynamic::{query_term, NoTargets, Op, Operand}; + + #[tokio::test] + async fn the_query_term_is_todays_query_term() { + let cipher = a_cipher().await; + let keyset = cipher.default_keyset(); + let plan = plan_with_a_label(); + + let term = query_declared(&keyset, &plan, "email", "ada@example.com") + .await + .expect("the declaration gives the query term"); + let today = query_term( + &keyset, + &plan, + "email", + Op::Eq, + "ada@example.com", + &NoTargets, + ) + .expect("fits the plan") + .await + .expect("today's query"); + + assert_eq!( + today.operand(), + &Operand::One(term.to_bytes()), + "the declaration's query term should be today's" + ); + } + + #[tokio::test] + async fn the_query_term_is_the_term_the_record_stores() { + let cipher = a_cipher().await; + let keyset = cipher.default_keyset(); + let plan = plan_with_a_label(); + + let stored = encrypt_declared(&keyset, &plan, row()) + .await + .expect("the declaration seals"); + let term = query_declared(&keyset, &plan, "email", "ada@example.com") + .await + .expect("the declaration gives the query term"); + + assert_eq!( + term_bytes(output(&stored, "email", "eq")), + term.to_bytes(), + "a query should send the term the record stores" + ); + } + + #[tokio::test] + async fn a_field_with_no_equality_index_answers_no_query() { + let cipher = a_cipher().await; + let keyset = cipher.default_keyset(); + let plan = plan_with_a_label(); + + let term = query_declared(&keyset, &plan, "age", 36u64).await; + let today = query_term(&keyset, &plan, "age", Op::Eq, 36u64, &NoTargets); + + assert!( + term.is_err(), + "age has no index, so it should answer no query" + ); + assert!(today.is_err(), "today's query should refuse it too"); + } + + #[tokio::test] + async fn a_plan_whose_context_is_a_field_is_refused() { + let cipher = a_cipher().await; + let keyset = cipher.default_keyset(); + let plan = plan_with_a_context_field(); + + let term = query_declared(&keyset, &plan, "email", "ada@example.com").await; + let today = query_term( + &keyset, + &plan, + "email", + Op::Eq, + "ada@example.com", + &NoTargets, + ); + + assert!( + term.is_err(), + "a query has no record to read the context field from" + ); + assert!(today.is_err(), "today's query should refuse it too"); + } + } + + mod given_a_record_under_the_plans_label { + use super::*; + + #[tokio::test] + async fn the_record_round_trips_through_the_one_sink() { + let cipher = a_cipher().await; + let keyset = cipher.default_keyset(); + let plan = plan_with_a_label(); + + let sealed = encrypt_record(&keyset, &plan, row()).await.expect("sealed"); + let opened = open_record(&cipher, &plan, sealed).await.expect("opened"); + + assert_eq!(decoded(&opened), decoded(&row()), "every field is back"); + } + + #[tokio::test] + async fn the_one_sink_and_todays_path_open_each_others_records() { + let cipher = a_cipher().await; + let keyset = cipher.default_keyset(); + let plan = plan_with_a_label(); + let ours = encrypt_record(&keyset, &plan, row()).await.expect("sealed"); + let today = encrypt(&keyset, row(), &plan) + .expect("fits the plan") + .await + .expect("sealed"); + + let ours_by_today = decrypt(&cipher, ours, &plan, None) + .expect("fits the plan") + .await + .expect("today's decrypt opens ours"); + let today_by_ours = open_record(&cipher, &plan, today) + .await + .expect("open_record opens today's"); + + assert_eq!( + decoded(&ours_by_today), + decoded(&today_by_ours), + "both directions give the same record" + ); + } + } + + mod given_a_record_with_nothing_to_seal { + use super::*; + + #[tokio::test] + async fn it_is_stored_and_read_back_with_no_rule_of_its_own() { + let cipher = a_cipher().await; + let keyset = cipher.default_keyset(); + let plan = plan_with_no_sealed_field(); + let fields = BTreeMap::from([("plan", OwnedFrame::of("free").expect("a frame"))]); + let source = OwnedFrame::of(&fields).expect("a frame"); + + let pending = encrypt_record(&keyset, &plan, &source); + let data_keys = pending.key_count(); + let sealed = pending.await.expect("stored"); + let opened = open_record(&cipher, &plan, sealed) + .await + .expect("read back"); + + assert!(data_keys <= 1, "no data key is asked for: {data_keys}"); + assert_eq!(decoded(&opened), decoded(&source), "the field is back"); + } + } + + mod given_a_value_that_is_not_the_plans_record { + use super::*; + + #[test] + fn a_field_the_plan_does_not_name_is_refused() { + let plan = plan_with_a_label(); + let fields = BTreeMap::from([ + ("email", OwnedFrame::of("ada@example.com").expect("a frame")), + ("age", OwnedFrame::of(36u64).expect("a frame")), + ("extra", OwnedFrame::of(1u64).expect("a frame")), + ]); + let source = OwnedFrame::of(&fields).expect("a frame"); + + let walked = source.visit(RecordSink::new(&plan)); + + assert!(walked.is_err(), "the walk stops at the field"); + } + + #[test] + fn a_missing_field_is_refused() { + let plan = plan_with_a_label(); + let fields = BTreeMap::from([("age", OwnedFrame::of(36u64).expect("a frame"))]); + let source = OwnedFrame::of(&fields).expect("a frame"); + + let walked = source.visit(RecordSink::new(&plan)); + + assert!(walked.is_err(), "the record lacks a field of the plan"); + } + + #[test] + fn a_scalar_is_refused() { + let plan = plan_with_a_label(); + + let walked = 7u32.visit(RecordSink::new(&plan)); + + assert!(walked.is_err(), "a record is a map of fields"); + } + } +} diff --git a/packages/stack-encrypt/src/json/cascade.rs b/packages/stack-encrypt/src/json/cascade.rs index 8cbb507a2..927a3a204 100644 --- a/packages/stack-encrypt/src/json/cascade.rs +++ b/packages/stack-encrypt/src/json/cascade.rs @@ -124,8 +124,8 @@ pub(crate) fn children_of( #[cfg(test)] mod tests { use super::*; + use vitaminc_aead::aes::{Aes256Cipher, Key}; use vitaminc_aead::{Cipher, Context, LocalCipherText}; - use vitaminc_encrypt::{Aes256Cipher, Key}; use vitaminc_protected::Protected; #[test] diff --git a/packages/stack-encrypt/src/json/derive.rs b/packages/stack-encrypt/src/json/derive.rs index b3e6944d8..ba15bdec4 100644 --- a/packages/stack-encrypt/src/json/derive.rs +++ b/packages/stack-encrypt/src/json/derive.rs @@ -15,8 +15,8 @@ use serde_json::{Map, Number, Value}; use sha2::{Digest, Sha256}; use uuid::Uuid; use vitaminc::random::SafeRand; +use vitaminc_aead::aes::{Aes256Cipher, Key as AesKey}; use vitaminc_aead::{Cipher, Context, IntoAad, IntoContext, LocalCipherText}; -use vitaminc_encrypt::{Aes256Cipher, Key as AesKey}; use vitaminc_hmac::HmacSha256Prf; use vitaminc_prf::{BlockVisitor, IntoPrfContext, PrfValue}; use vitaminc_protected::{AsProtectedRef, Controlled, Protected}; diff --git a/packages/stack-encrypt/src/json/mod.rs b/packages/stack-encrypt/src/json/mod.rs index 21aec47f7..21c92940f 100644 --- a/packages/stack-encrypt/src/json/mod.rs +++ b/packages/stack-encrypt/src/json/mod.rs @@ -88,7 +88,7 @@ //! # Nonces and tokens //! //! - **Nonces are random.** Every entry is sealed through the engine's one -//! AEAD path (`vitaminc-encrypt`'s `Aes256Cipher`, a fresh random 96-bit +//! AEAD path (vitaminc-aead's `Aes256Cipher`, a fresh random 96-bit //! nonce per seal, carried in the ciphertext), so there is one leaf //! cipher in the crate. Uniqueness under one document key is //! probabilistic rather than structural: at `N` entries the collision diff --git a/packages/stack-encrypt/src/lib.rs b/packages/stack-encrypt/src/lib.rs index 077268c39..bacfc2732 100644 --- a/packages/stack-encrypt/src/lib.rs +++ b/packages/stack-encrypt/src/lib.rs @@ -688,7 +688,7 @@ endpoint — are `StackKmsBuilder`'s, and the two keyset-cache knobs are //! //! A `KeysetCipher` seals through a vitaminc `Cipher`; everything vitaminc //! can encrypt remains available through [`KeysetCipher::encrypt_tree`]. Its data model, AAD derivations and -//! the leaf wire format are vitaminc's (`vitaminc_encrypt::Aes256Cipher`, AES-256-GCM under a random +//! the leaf wire format are vitaminc's (`vitaminc_aead::aes::Aes256Cipher`, AES-256-GCM under a random //! per-leaf nonce vitaminc generates itself). The ZeroKMS `iv` a [`SealedValue`] //! carries is *not* that nonce: it identifies the data key, and is sent back to //! ZeroKMS with the key `tag` to re-derive it — under the same [`Descriptor`] @@ -752,8 +752,8 @@ pub mod value; #[cfg(feature = "http")] pub use cipher::WithAuthStrategy; pub use cipher::{ - Error, LeafBytesError, NoKms, PendingStackCipherText, SealedValue, StackCipher, - StackCipherBuilder, StackCipherText, WithKeySource, + Error, LeafBytesError, NoKms, SealedValue, StackCipher, StackCipherBuilder, StackCipherText, + WithKeySource, }; pub use contexts::{ CallContexts, CallerShape, ContextTree, Contexts, FieldContext, Kind, LeafContext, Placeholder, @@ -789,8 +789,8 @@ pub use target::{ // `IntoAad` and `IntoPrfContext` are vitaminc's blankets over it, so both // derivations see the same bytes. pub use vitaminc_aead::{ - CipherText, Context, ContextPiece, ContextTag, DecodeError, Decrypt, Encrypt, EncryptRef, - IntoAad, IntoContext, Node, PassthroughFrame, ScalarTarget, Unspecified, + CipherText, Context, ContextPiece, DecodeError, Decrypt, Encrypt, EncryptRef, 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`], @@ -851,10 +851,6 @@ pub use vitaminc_aead::{ /// let _: Option<OreTerm<Vec<u8>>> = None; // bytes are not `Orderable` /// ``` pub use vitaminc_ore::Orderable; -// The vitaminc 0.4 names, deprecated there; re-exported for one transition so -// a caller that spelled them keeps compiling with a warning. -#[allow(deprecated)] -pub use vitaminc_aead::{Aad, AadPiece}; // Likewise the PRF context surface, so a caller who needs the PRF view of a // context has no direct `vitaminc-prf` dependency for it. diff --git a/packages/stack-encrypt/src/sem/mod.rs b/packages/stack-encrypt/src/sem/mod.rs index 149a592b1..38a6b6787 100644 --- a/packages/stack-encrypt/src/sem/mod.rs +++ b/packages/stack-encrypt/src/sem/mod.rs @@ -643,7 +643,7 @@ where /// bytes, under its `vitaminc-normalize` domain and the PAE-framed /// `[EQUALITY_DOMAIN, context]`. [`equality`] and the `dynamic` path, which /// normalizes the one scalar it walks to, both end here. -fn equality_of_normalized( +pub(crate) fn equality_of_normalized( prf: &HmacSha256Prf, normalized: Normalized, context: Context<'_>, diff --git a/packages/stack-encrypt/src/target/core.rs b/packages/stack-encrypt/src/target/core.rs index 4495daacc..18b9b499e 100644 --- a/packages/stack-encrypt/src/target/core.rs +++ b/packages/stack-encrypt/src/target/core.rs @@ -1,9 +1,12 @@ //! Canonical execution shared by the cipher-directed and declaration APIs. -use super::{CipherRef, Pending, Request, Responses}; -use crate::cipher::{bind_keys, open_keyed, KeyedCipherText, PendingStackCipherText}; +use super::{CipherRef, Pending, Request}; +use crate::cipher::{open_tree, seal_tree}; use crate::{Descriptor, Error, KeysetCipher, StackCipher, StackCipherText}; -use vitaminc_aead::{CipherText, Decrypt, Encrypt, IntoAad, IntoContext}; -use vitaminc_protected::NonEmpty; +use vitaminc_aead::seal::leaves; +use vitaminc_aead::shape::Root; +use vitaminc_aead::{ + Context, Decrypt, Encrypt, EncryptSink, IntoAad, IntoContext, Node, Plaintext, Unspecified, +}; /// Internal term operation. It is deliberately inaccessible to target authors. /// @@ -20,30 +23,19 @@ pub(crate) trait Term<S, K, Ctx>: Sized { Self: 'a; } -/// Seal `source` into the native tree. It is consumed, as Vitamin C's -/// by-value [`Encrypt`] walk consumes it: a caller holding only a borrow -/// clones before it gets here (see [`ConsumeSource`](super::ConsumeSource)), -/// and one holding the value hands it over without a copy. The walk happens -/// here, before any request exists, so the pending holds only the planned -/// leaves. -pub(crate) fn encrypt_native<'a, 'c, S: Encrypt, K, T: IntoContext<'c>>( - source: S, - cipher: &'a KeysetCipher<'_, K>, - context: NonEmpty<T>, -) -> Pending<'a, StackCipherText, K> { - encrypt_opaque(source, cipher, context) -} -/// The opening half of [`encrypt_native`]; the context is nonempty. -pub(crate) fn open_native<'a, 'c, P: Decrypt + Send + 'static, K, T: IntoContext<'c>>( - tree: StackCipherText, - cipher: &'a StackCipher<K>, - context: NonEmpty<T>, -) -> Pending<'a, P, K> { - open_opaque(tree, cipher, context) -} -/// [`encrypt_native`] for the opaque scalar operation, whose context may -/// be empty. Mapping its encrypted output preserves that policy. Structural -/// target operations use `encrypt_native` and retain its nonempty requirement. +/// Walk `source` and seal it under `context`. +/// +/// The walk consumes the source. A caller that has only a borrow clones +/// before it gets here (see [`ConsumeSource`](super::ConsumeSource)). A +/// caller that has the value hands it over without a copy. +/// +/// The walk happens here, before any request exists. So the result holds +/// only the staged value. +/// +/// The context may be empty: the opaque scalar operation allows that. An +/// operation that needs a context that is not empty passes a +/// [`NonEmpty`](crate::NonEmpty) one, as [`ciphertext`](super::ciphertext) +/// does. /// /// A refused context drops `source` as it is. Every caller passes a borrow, /// or checks the context first ([`ciphertext`](super::ciphertext) does), so @@ -60,9 +52,11 @@ pub(crate) fn encrypt_opaque<'a, 'c, S: Encrypt, K, T: IntoContext<'c>>( } let piece = context.clone().into_owned(); let aad = context.into_aad().into_owned(); - match PendingStackCipherText::plan(source, aad) { - Ok(tree) => seal_pending(cipher, tree, descriptor).under_context(piece.clone(), piece), - Err(error) => Pending::ready(cipher, Err(error)), + // The one walk of the value. It stages the value for encryption: + // nothing is sealed, and the sink holds no context. + match source.visit(EncryptSink::<Root, Unspecified>::new()) { + Ok(tree) => seal_pending(cipher, tree, aad, descriptor).under_context(piece.clone(), piece), + Err(_) => Pending::ready(cipher, Err(Error::Aead)), } } /// The opening half of [`encrypt_opaque`]. @@ -73,22 +67,17 @@ pub(crate) fn open_opaque<'a, 'c, P: Decrypt + Send + 'static, K, T: IntoContext ) -> Pending<'a, P, K> { let context = context.into_context(); let descriptor = Descriptor::from_piece(&context); - // Fast path, as in `seal_pending`; `dispatch` is the gate. - if let Err(e) = descriptor.check() { - return Pending::ready(cipher, Err(e)); - } - let requests = retrieve_requests(&tree, &descriptor); let piece = context.clone().into_owned(); let aad = context.into_aad().into_owned(); - Pending::request(cipher, requests, move |responses| { - let keyed = keyed_from_responses(tree, responses)?; - open_keyed(keyed, aad) - }) - .under_context(piece.clone(), piece) + open_pending(cipher, tree, aad, descriptor).under_context(piece.clone(), piece) } +/// Seal a walked value: one data key for each leaf, all generated in one +/// request under `descriptor`, then every leaf sealed in one pass under the +/// AAD its place derives from `aad`. pub(crate) fn seal_pending<'a, K>( cipher: &'a KeysetCipher<'_, K>, - tree: PendingStackCipherText, + tree: Node<Plaintext>, + aad: Context<'static>, descriptor: Descriptor, ) -> Pending<'a, StackCipherText, K> { // Fast path: refuse an over-long descriptor before a single request @@ -103,7 +92,7 @@ pub(crate) fn seal_pending<'a, K>( let known = cipher.loaded_state().map(|keyset| keyset.id); let mut requests: Vec<Request> = std::iter::repeat_with(|| Request::generate_under(descriptor.clone())) - .take(tree.key_count()) + .take(tree.leaf_count()) .collect(); if known.is_none() { requests.push(Request::selected_keyset()); @@ -113,75 +102,43 @@ pub(crate) fn seal_pending<'a, K>( Some(keyset_id) => keyset_id, None => responses.next_keyset()?.id, }; - tree.seal_with(keyset_id, responses.drain_generated()) - .map_err(Error::from) + let mut sealing_keys = responses.drain_generated(); + seal_tree(tree, &aad, keyset_id, &mut sealing_keys).map_err(Error::from) }) } -/// Retrieve every leaf's data key and bind it onto its leaf, ready for -/// [`open_keyed`]. -pub(crate) fn bind_pending<'a, K>( +/// Open a stored value into `T`: every leaf's data key retrieved in one +/// request under `descriptor`, then every leaf opened in one pass under the +/// AAD its place derives from `aad`. +pub(crate) fn open_pending<'a, T: Decrypt + 'a, K>( cipher_ref: impl Into<CipherRef<'a, K>>, - ciphertext: StackCipherText, + tree: StackCipherText, + aad: Context<'static>, descriptor: Descriptor, -) -> Pending<'a, KeyedCipherText, K> { +) -> Pending<'a, T, K> { let cipher_ref: CipherRef<'a, K> = cipher_ref.into(); // Fast path, as in `seal_pending`; `dispatch` is the gate. if let Err(e) = descriptor.check() { - return Pending::ready(cipher_ref, Err(e)); + return Pending::failed(cipher_ref, e); } - let requests = retrieve_requests(&ciphertext, &descriptor); + let requests = retrieve_requests(&tree, &descriptor); Pending::request(cipher_ref, requests, move |responses| { - keyed_from_responses(ciphertext, responses) + open_tree(tree, &aad, &mut responses.drain_retrieved()) }) } -fn keyed_from_responses( - ciphertext: StackCipherText, - responses: &mut Responses, -) -> Result<KeyedCipherText, Error> { - let mut keys = responses.drain_retrieved(); - // Too few keys for the tree, or keys left over once it is bound, both - // mean `retrieve_requests` and `bind_keys` disagreed about the tree's - // shape: a composition bug in this module, not a data error — so - // `ResponseShape`, never `Aead`, which would read as tampering. - let keyed = bind_keys(ciphertext, &mut keys).map_err(|_| Error::ResponseShape)?; - if keys.next().is_some() { - return Err(Error::ResponseShape); - } - Ok(keyed) -} - -fn retrieve_requests(ciphertext: &StackCipherText, descriptor: &Descriptor) -> Vec<Request> { - let mut out = Vec::new(); - collect_retrieve_requests(ciphertext, descriptor, &mut out); - out -} - -fn collect_retrieve_requests( - ciphertext: &StackCipherText, - descriptor: &Descriptor, - out: &mut Vec<Request>, -) { - match ciphertext { - CipherText::Single(leaf) | CipherText::EmptySequence(leaf) | CipherText::EmptyMap(leaf) => { - out.push(Request::retrieve_under( +/// One request for each leaf's data key, in the order vitaminc visits the +/// leaves when it opens them. +pub(crate) fn retrieve_requests(tree: &StackCipherText, descriptor: &Descriptor) -> Vec<Request> { + leaves(tree) + .into_iter() + .map(|leaf: &crate::SealedValue| { + Request::retrieve_under( *leaf.iv(), leaf.tag().to_vec(), descriptor.clone(), leaf.keyset_id(), - )); - } - CipherText::Sequence(items) => { - for item in items { - collect_retrieve_requests(item, descriptor, out); - } - } - CipherText::Map(entries) => { - for (_, value) in entries { - collect_retrieve_requests(value, descriptor, out); - } - } - CipherText::Passthrough(_) => {} - } + ) + }) + .collect() } diff --git a/packages/stack-encrypt/src/target/declaration.rs b/packages/stack-encrypt/src/target/declaration.rs new file mode 100644 index 000000000..1421f7124 --- /dev/null +++ b/packages/stack-encrypt/src/target/declaration.rs @@ -0,0 +1,2363 @@ +//! SPIKE, not for merging. The combinators, written as adapters over one +//! trait, as the standard library's iterator adapters are. +//! +//! A [`Declaration`] says how a value becomes a target, in two steps: +//! +//! 1. The value is walked once into the declaration's sink. The sink +//! stages what the target needs: the plaintext tree to seal, the +//! normalized scalar of a term. Nothing is sealed or keyed, and the +//! sink holds no context. +//! 2. The declaration's finishing step is handed what the walk staged, the +//! cipher and one context. It requests the keys, seals and keys, and +//! builds the target. +//! +//! [`ciphertext`], [`equality`], [`clear`] and [`json_document`] are the +//! declarations of one operation each. Every other declaration is built from them with the adapters, and +//! each adapter is a small struct that is a declaration too: +//! +//! | Adapter | The struct | Its sink | +//! |---|---|---| +//! | `a.zip(b)` | [`Zip`] | `Tee(a, b)`: both read the same value | +//! | `a.map(f)` | [`Map`] | `a`'s | +//! | `a.try_map(f)` | [`TryMap`] | `a`'s | +//! | `a.convert(to, from)` | [`Convert`] | `a`'s | +//! | `a.accepting::<C>()` | [`Accepting`] | `a`'s | +//! | `a.under(own)` | [`Under`] | `a`'s | +//! | `a.entry("email")` | [`Entry`] | a map sink that gives `a` the entry `email` | +//! | `a.record()` | [`Record`] | `a`'s, counting the entries | +//! | `Some(a)` or `None` | `Option<A>` | `a`'s, or none | +//! | `entries.collect()` | [`Fields`] | a map sink that gives each entry to its field | +//! | `a.under_field("email")` | [`UnderField`] | `a`'s | +//! | `a.context_from("tenant")` | [`ContextFrom`] | `Tee(a, ..)`: the fields, and the entry `tenant` | +//! +//! `under_field` and `context_from` are for a record whose context is the value +//! of one of its fields. The walk can reach that field last, so the +//! context is settled in the finishing step, when the walk is over. +//! +//! `entry` takes the place of `project`. A field of a record is not borrowed +//! from a struct. It is the entry of that name, taken as the record is +//! walked. So one declaration serves a Rust struct and a frame from a +//! language binding. +//! +//! A plaintext is encrypted as a collection is collected: +//! `plaintext.encrypt_into::<T>(..)` is `iter.collect::<B>()`, and +//! [`EncryptTarget<S>`] is `FromIterator<A>`. The impl of +//! `EncryptTarget<S>` says which plaintext types a target takes, so a +//! plaintext of another type does not compile. [`field`] carries that +//! check to each field of a record. +//! +//! A declaration also says how its target is opened again ([`Open`]), and +//! which term a query sends for an operator its index answers +//! ([`Answers`]). One declaration serves encrypt, decrypt and query. +//! +//! One context for each target is still a rule the compiler checks. +//! [`Declaration::zip`] asks both sides to name the same +//! [`Declaration::Context`], and [`Zip`] hands both the one value it was +//! handed. + +mod open; +mod query; + +#[allow(unused_imports)] +pub(crate) use open::{open, open_frame, Open}; +#[allow(unused_imports)] +pub(crate) use query::{Answers, Here, Left, Right}; + +use std::borrow::Cow; +use std::marker::PhantomData; + +use stack_kms::MaybeSend; +use vitaminc_aead::frame::{FrameWriter, OwnedFrame}; +use vitaminc_aead::plaintext::{ + Error as _, FixedType, Logical, MapSink, Physical, SeqSink, Sink, SourceError, ValueKind, +}; +use vitaminc_aead::shape::Root; +use vitaminc_aead::{ + Encrypt, EncryptError, EncryptRef, EncryptSink, IntoAad as _, IntoContext as _, Node, + Plaintext, Tee, Unspecified, +}; +use vitaminc_normalize::{Term, Terms}; +use vitaminc_protected::Buffer; + +use super::core::seal_pending; +use super::index::Encrypted; +use super::source::Source; +use super::{AeadContext, CallerContext, DeclaredContext, Pending}; +use crate::dynamic::{read_json, IntoLabel as _}; +use crate::json::{JsonDocument, JsonOptions, JsonPlaintext}; +use crate::sem::{EqualityTerm, TermError}; +use crate::{Descriptor, Error, KeysetCipher, Label, NonEmpty, StackCipherText}; + +/// The one error type of the walk: every sink teed in it reports this. +pub(crate) type WalkError = EncryptError<Unspecified>; + +fn refused(why: &'static str) -> WalkError { + WalkError::source(SourceError::msg(why)) +} + +// ============================================================================= +// The trait +// ============================================================================= + +/// How a value becomes a target: a sink for the one walk of the value, and +/// the step that finishes what the walk staged. +pub(crate) trait Declaration: Sized { + /// What this declaration builds. + type Output: MaybeSend + 'static; + /// What one walk leaves. Nothing in it is sealed or keyed. + type Staged: Default + 'static; + /// The sink a value is walked into. It writes into a [`Staged`]. + /// + /// [`Staged`]: Self::Staged + type Sink<'s>: Sink<Error = WalkError> + where + Self: 's; + /// The one context the finishing step is handed. + type Context: Clone + 'static; + + /// The sink that stages a value in `staged`. + fn sink<'s>(&'s self, staged: &'s mut Self::Staged) -> Self::Sink<'s>; + + /// Request the keys, seal and key what the walk staged, and build the + /// output, under `context`. + fn finish<'a, K: 'static>( + self, + staged: Self::Staged, + cipher: &'a KeysetCipher<'_, K>, + context: Self::Context, + ) -> Pending<'a, Self::Output, K>; + + /// This declaration and `other`, from one walk, under one context. + fn zip<B>(self, other: B) -> Zip<Self, B> + where + B: Declaration<Context = Self::Context>, + { + Zip(self, other) + } + + /// This declaration, with its output converted by `f`. + fn map<U, F>(self, f: F) -> Map<Self, F> + where + U: MaybeSend + 'static, + F: FnOnce(Self::Output) -> U + MaybeSend + 'static, + { + Map(self, f) + } + + /// This declaration, with its output converted by `f`, which can + /// refuse it. + fn try_map<U, F>(self, f: F) -> TryMap<Self, F> + where + U: MaybeSend + 'static, + F: FnOnce(Self::Output) -> Result<U, Error> + MaybeSend + 'static, + { + TryMap(self, f) + } + + /// This declaration, with its output converted by `to`, and `from` as + /// the inverse. Unlike [`map`](Self::map), the result still opens what + /// it stored: `from` takes the stored value apart again. + fn convert<U, F, G>(self, to: F, from: G) -> Convert<Self, F, G> + where + U: MaybeSend + 'static, + F: FnOnce(Self::Output) -> U + MaybeSend + 'static, + G: Fn(U) -> Self::Output, + { + Convert(self, to, from) + } + + /// The declaration of the term a query sends for the operator `Op`: + /// `field.query::<Eq, _>()`. It compiles only for a declaration with an + /// index that answers `Op`. + fn query<Op, At>(&self) -> <Self as Answers<Op, At>>::Query + where + Self: Answers<Op, At>, + { + self.query_declaration() + } + + /// This declaration, handed a context `C` that converts to the one it + /// needs. + fn accepting<C>(self) -> Accepting<Self, C> + where + C: Into<Self::Context> + Clone + 'static, + { + Accepting(self, PhantomData) + } + + /// This declaration under `own`, extended by the surrounding context. + fn under(self, own: NonEmpty<Label>) -> Under<Self> + where + Self::Context: From<CallerContext>, + { + Under(self, own) + } + + /// This declaration, for the entry `key` of a record. + fn entry(self, key: impl Into<Cow<'static, str>>) -> Entry<Self> { + Entry(self, key.into()) + } + + /// These fields as a whole record: an entry that no field takes is + /// refused. + fn record(self) -> Record<Self> + where + Self::Staged: FieldsSeen, + { + Record(self) + } + + /// This declaration under the record's context, then `identity`: a + /// field of a record whose context is read from the record. + fn under_field(self, identity: impl Into<Cow<'static, str>>) -> UnderField<Self> + where + Self::Context: From<CallerContext>, + { + UnderField(self, identity.into()) + } + + /// These fields, with the record's context read from the entry `key`. + /// That entry is kept in the clear, and is the second output. + fn context_from(self, key: impl Into<Cow<'static, str>>) -> ContextFrom<Self> + where + Self: Declaration<Context = RecordContext>, + { + ContextFrom(self, clear().entry(key)) + } +} + +/// Encrypt `source` as `declaration` says: one walk into its sink, then +/// its finishing step under `context`. +pub(crate) fn run<'a, D: Declaration, K: 'static>( + cipher: &'a KeysetCipher<'_, K>, + declaration: D, + source: impl Encrypt, + context: D::Context, +) -> Pending<'a, D::Output, K> { + let mut staged = D::Staged::default(); + // The sink borrows the declaration and `staged`, so the walk ends + // before either moves. + let walked = source.visit(declaration.sink(&mut staged)).is_ok(); + match walked { + true => declaration.finish(staged, cipher, context), + false => Pending::failed(cipher, Error::Aead), + } +} + +/// A target that is encrypted from a plaintext of type `S`. It is to +/// [`EncryptInto::encrypt_into`] what `FromIterator<A>` is to `collect`: +/// the impl says which plaintext types the target takes, so a plaintext of +/// another type does not compile. +pub(crate) trait EncryptTarget<S>: Sized + MaybeSend + 'static { + /// The context the declaration needs. + type Context: Clone + 'static; + + /// The declaration of this target. + fn declaration() -> impl Declaration<Output = Self, Context = Self::Context>; + + /// How a plaintext is walked for this target. A scalar is walked as + /// it is. A record names its fields here, with the names its + /// declaration takes them by. + fn source(plaintext: S) -> impl Encrypt; +} + +/// `plaintext.encrypt_into::<T>(..)`, for every plaintext a target takes: +/// as `collect::<B>()` is on every iterator. +pub(crate) trait EncryptInto: Sized { + /// Encrypt this plaintext into `T`, as `T` declares. + fn encrypt_into<'a, T, K>( + self, + cipher: &'a KeysetCipher<'_, K>, + context: T::Context, + ) -> Pending<'a, T, K> + where + T: EncryptTarget<Self>, + K: 'static, + { + run(cipher, T::declaration(), T::source(self), context) + } +} + +impl<S> EncryptInto for S {} + +/// The declaration of the target `T`, for the field of `P` that `select` +/// names. +/// +/// `select` is never called. It tells the compiler the type of the field, +/// and `T` must take a plaintext of that type. So a record whose target +/// does not fit its plaintext field does not compile. +pub(crate) fn field<P, S, T>( + _select: fn(&P) -> &S, +) -> impl Declaration<Output = T, Context = T::Context> +where + S: 'static, + T: EncryptTarget<&'static S>, +{ + T::declaration() +} + +// ============================================================================= +// The operations +// ============================================================================= + +/// Seal the value. The declaration [`ciphertext`] returns. +pub(crate) struct Ciphertext; + +/// Seal the value, under the [`AeadContext`] the declaration is handed. +pub(crate) fn ciphertext() -> Ciphertext { + Ciphertext +} + +impl Declaration for Ciphertext { + type Output = StackCipherText; + type Staged = Option<Node<Plaintext>>; + type Sink<'s> = EncryptSink<&'s mut Option<Node<Plaintext>>, Unspecified>; + type Context = AeadContext; + + fn sink<'s>(&'s self, staged: &'s mut Self::Staged) -> Self::Sink<'s> { + EncryptSink::into(staged) + } + + fn finish<'a, K: 'static>( + self, + staged: Self::Staged, + cipher: &'a KeysetCipher<'_, K>, + context: AeadContext, + ) -> Pending<'a, StackCipherText, K> { + let Some(tree) = staged else { + return Pending::failed(cipher, Error::Aead); + }; + match context.sealable() { + Ok(context) => { + let context = context.into_context(); + let descriptor = Descriptor::from_piece(&context); + let piece = context.clone().into_owned(); + let aad = context.into_aad().into_owned(); + seal_pending(cipher, tree, aad, descriptor).under_context(piece.clone(), piece) + } + Err(error) => Pending::failed(cipher, error), + } + } +} + +/// Derive the equality term of the value. The declaration [`equality`] +/// returns. +pub(crate) struct EqualityOf; + +/// Derive the equality term of the value, under the [`CallerContext`] the +/// declaration is handed. +pub(crate) fn equality() -> EqualityOf { + EqualityOf +} + +impl Declaration for EqualityOf { + type Output = EqualityTerm; + type Staged = Vec<Term>; + type Sink<'s> = Terms<'s, WalkError>; + type Context = CallerContext; + + fn sink<'s>(&'s self, staged: &'s mut Self::Staged) -> Self::Sink<'s> { + Terms::new(staged) + } + + fn finish<'a, K: 'static>( + self, + mut staged: Self::Staged, + cipher: &'a KeysetCipher<'_, K>, + context: CallerContext, + ) -> Pending<'a, EqualityTerm, K> { + // One term, at the root: the value is one scalar with an equality + // domain. The rule is `sem::normalized`'s. + let normalized = match (staged.pop(), staged.is_empty()) { + (Some(term), true) if term.path.steps().is_empty() => term.normalized, + _ => return Pending::failed(cipher, Error::from(TermError::NoEqualityTerm)), + }; + let (query, stored) = (context.query(), context.stored()); + match context.validated() { + Ok(context) => cipher + .equality_term_normalized(normalized, CallerContext::query_nonempty(context)) + .under_context(query, stored), + Err(error) => Pending::failed(cipher, error), + } + } +} + +/// Keep the value as a frame, in the clear. The declaration [`clear`] +/// returns. +pub(crate) struct Clear<C>(PhantomData<fn(C)>); + +/// Keep the value as a frame, in the clear: nothing is sealed, and the +/// context the declaration is handed is not used. +pub(crate) fn clear<C: Clone + 'static>() -> Clear<C> { + Clear(PhantomData) +} + +/// What [`Clear`] stages: the bytes of the frame. +pub(crate) struct ClearStaged(Buffer); + +impl Default for ClearStaged { + fn default() -> Self { + Self(Buffer::new()) + } +} + +impl<C: Clone + 'static> Declaration for Clear<C> { + type Output = OwnedFrame; + type Staged = ClearStaged; + type Sink<'s> = FrameWriter<'s, WalkError>; + type Context = C; + + fn sink<'s>(&'s self, staged: &'s mut Self::Staged) -> Self::Sink<'s> { + FrameWriter::reporting(&mut staged.0, 0) + } + + fn finish<'a, K: 'static>( + self, + staged: Self::Staged, + cipher: &'a KeysetCipher<'_, K>, + _: C, + ) -> Pending<'a, OwnedFrame, K> { + Pending::ready( + cipher, + OwnedFrame::from_buffer(staged.0).map_err(|_| Error::Aead), + ) + } +} + +/// Seal a JSON document under the JSON index. The declaration +/// [`json_document`] returns. +pub(crate) struct JsonIndex(JsonOptions); + +/// Seal a JSON document under the JSON index with `options`: what today's +/// [`json_document`](super::json_document) declares. +/// +/// The sink keeps the value as it is walked, and the value can be either +/// of two things: +/// +/// - JSON text, one scalar: what a [`JsonPlaintext`](crate::json::JsonPlaintext) +/// and a binding's JSON field are. The finishing step parses the text. +/// - A map or a sequence: a Rust struct, or a map from a binding. The +/// finishing step reads the document from its structure, so any value +/// that can be walked can be a JSON document. +/// +/// Then the finishing step does what the JSON index does today, with its +/// own walk of the document: it derives every term under the keyset, and +/// seals every entry. +pub(crate) fn json_document(options: JsonOptions) -> JsonIndex { + JsonIndex(options) +} + +impl Declaration for JsonIndex { + type Output = JsonDocument; + type Staged = ClearStaged; + type Sink<'s> = FrameWriter<'s, WalkError>; + type Context = CallerContext; + + fn sink<'s>(&'s self, staged: &'s mut Self::Staged) -> Self::Sink<'s> { + FrameWriter::reporting(&mut staged.0, 0) + } + + fn finish<'a, K: 'static>( + self, + staged: Self::Staged, + cipher: &'a KeysetCipher<'_, K>, + context: CallerContext, + ) -> Pending<'a, JsonDocument, K> { + let Ok(frame) = OwnedFrame::from_buffer(staged.0) else { + return Pending::failed(cipher, Error::Aead); + }; + let document = match frame.frame().kind() { + // A map or a sequence is the document's own structure. + Some(ValueKind::Object | ValueKind::Array) => { + recipher_frame::serde::from_slice::<serde_json::Value>(frame.frame().as_bytes()) + .map(JsonPlaintext::from) + .map_err(|_| Error::Aead) + } + // Anything else has to be JSON text. + _ => read_json(frame.frame()).map_err(|_| Error::Aead), + }; + let document = match document { + Ok(document) => document, + Err(error) => return Pending::failed(cipher, error), + }; + let (query, stored) = (context.query(), context.stored()); + match context.validated() { + Ok(context) => { + let (query_context, stored_context) = CallerContext::both_nonempty(context); + // The sealing wipes the document it is given. + crate::json::seal_pending( + Source::given(document.into_value()), + &self.0, + cipher, + query_context, + stored_context, + ) + .under_context(query, stored) + } + Err(error) => Pending::failed(cipher, error), + } + } +} + +/// Seal the value and derive its equality term, from one walk. The +/// ciphertext takes the AEAD half of the context the term takes. +/// +/// This is today's [`indexed`](super::indexed)`(Equality)`, composed the +/// same way. +pub(crate) fn indexed_equality( +) -> impl Open<Output = Encrypted<EqualityTerm>, Context = CallerContext> + + Answers<crate::op::Eq, Right<Here>, Query: Declaration<Output = EqualityTerm>> { + ciphertext() + .accepting::<CallerContext>() + .zip(equality()) + .convert( + |(ciphertext, terms)| Encrypted { ciphertext, terms }, + |stored: Encrypted<EqualityTerm>| (stored.ciphertext, stored.terms), + ) +} + +/// Any plaintext that can be walked. +impl<S: Encrypt> EncryptTarget<S> for Encrypted<EqualityTerm> { + type Context = CallerContext; + + fn declaration() -> impl Declaration<Output = Self, Context = CallerContext> { + indexed_equality() + } + + fn source(plaintext: S) -> impl Encrypt { + plaintext + } +} + +/// Any plaintext that can be walked. +impl<S: Encrypt> EncryptTarget<S> for StackCipherText { + type Context = AeadContext; + + fn declaration() -> impl Declaration<Output = Self, Context = AeadContext> { + ciphertext() + } + + fn source(plaintext: S) -> impl Encrypt { + plaintext + } +} + +// ============================================================================= +// The adapters +// ============================================================================= + +/// Two declarations from one walk, under one context. See +/// [`Declaration::zip`]. +pub(crate) struct Zip<A, B>(A, B); + +impl<A, B> Declaration for Zip<A, B> +where + A: Declaration, + B: Declaration<Context = A::Context>, +{ + type Output = (A::Output, B::Output); + type Staged = (A::Staged, B::Staged); + type Sink<'s> + = Tee<A::Sink<'s>, B::Sink<'s>> + where + Self: 's; + type Context = A::Context; + + fn sink<'s>(&'s self, staged: &'s mut Self::Staged) -> Self::Sink<'s> { + Tee(self.0.sink(&mut staged.0), self.1.sink(&mut staged.1)) + } + + fn finish<'a, K: 'static>( + self, + staged: Self::Staged, + cipher: &'a KeysetCipher<'_, K>, + context: Self::Context, + ) -> Pending<'a, Self::Output, K> { + self.0 + .finish(staged.0, cipher, context.clone()) + .zip(self.1.finish(staged.1, cipher, context)) + } +} + +/// A declaration with its output converted. See [`Declaration::map`]. +pub(crate) struct Map<A, F>(A, F); + +impl<A, U, F> Declaration for Map<A, F> +where + A: Declaration, + U: MaybeSend + 'static, + F: FnOnce(A::Output) -> U + MaybeSend + 'static, +{ + type Output = U; + type Staged = A::Staged; + type Sink<'s> + = A::Sink<'s> + where + Self: 's; + type Context = A::Context; + + fn sink<'s>(&'s self, staged: &'s mut Self::Staged) -> Self::Sink<'s> { + self.0.sink(staged) + } + + fn finish<'a, K: 'static>( + self, + staged: Self::Staged, + cipher: &'a KeysetCipher<'_, K>, + context: Self::Context, + ) -> Pending<'a, U, K> { + self.0.finish(staged, cipher, context).map(self.1) + } +} + +/// A declaration with its output converted by a function that can refuse +/// it. See [`Declaration::try_map`]. +pub(crate) struct TryMap<A, F>(A, F); + +impl<A, U, F> Declaration for TryMap<A, F> +where + A: Declaration, + U: MaybeSend + 'static, + F: FnOnce(A::Output) -> Result<U, Error> + MaybeSend + 'static, +{ + type Output = U; + type Staged = A::Staged; + type Sink<'s> + = A::Sink<'s> + where + Self: 's; + type Context = A::Context; + + fn sink<'s>(&'s self, staged: &'s mut Self::Staged) -> Self::Sink<'s> { + self.0.sink(staged) + } + + fn finish<'a, K: 'static>( + self, + staged: Self::Staged, + cipher: &'a KeysetCipher<'_, K>, + context: Self::Context, + ) -> Pending<'a, U, K> { + self.0.finish(staged, cipher, context).try_map(self.1) + } +} + +/// A declaration with its output converted, and the inverse beside it. See +/// [`Declaration::convert`]. +pub(crate) struct Convert<A, F, G>(A, F, G); + +impl<A, U, F, G> Declaration for Convert<A, F, G> +where + A: Declaration, + U: MaybeSend + 'static, + F: FnOnce(A::Output) -> U + MaybeSend + 'static, + G: Fn(U) -> A::Output, +{ + type Output = U; + type Staged = A::Staged; + type Sink<'s> + = A::Sink<'s> + where + Self: 's; + type Context = A::Context; + + fn sink<'s>(&'s self, staged: &'s mut Self::Staged) -> Self::Sink<'s> { + self.0.sink(staged) + } + + fn finish<'a, K: 'static>( + self, + staged: Self::Staged, + cipher: &'a KeysetCipher<'_, K>, + context: Self::Context, + ) -> Pending<'a, U, K> { + self.0.finish(staged, cipher, context).map(self.1) + } +} + +/// A declaration handed a context that converts to the one it needs. See +/// [`Declaration::accepting`]. +pub(crate) struct Accepting<A, C>(A, PhantomData<fn(C)>); + +impl<A, C> Declaration for Accepting<A, C> +where + A: Declaration, + C: Into<A::Context> + Clone + 'static, +{ + type Output = A::Output; + type Staged = A::Staged; + type Sink<'s> + = A::Sink<'s> + where + Self: 's; + type Context = C; + + fn sink<'s>(&'s self, staged: &'s mut Self::Staged) -> Self::Sink<'s> { + self.0.sink(staged) + } + + fn finish<'a, K: 'static>( + self, + staged: Self::Staged, + cipher: &'a KeysetCipher<'_, K>, + context: C, + ) -> Pending<'a, Self::Output, K> { + self.0.finish(staged, cipher, context.into()) + } +} + +/// A declaration under a context of its own. See [`Declaration::under`]. +pub(crate) struct Under<A>(A, NonEmpty<Label>); + +impl<A> Declaration for Under<A> +where + A: Declaration, + A::Context: From<CallerContext>, +{ + type Output = A::Output; + type Staged = A::Staged; + type Sink<'s> + = A::Sink<'s> + where + Self: 's; + type Context = DeclaredContext; + + fn sink<'s>(&'s self, staged: &'s mut Self::Staged) -> Self::Sink<'s> { + self.0.sink(staged) + } + + fn finish<'a, K: 'static>( + self, + staged: Self::Staged, + cipher: &'a KeysetCipher<'_, K>, + context: DeclaredContext, + ) -> Pending<'a, Self::Output, K> { + match context.checked_under(self.1) { + Ok(context) => self.0.finish(staged, cipher, context.into()), + Err(error) => Pending::failed(cipher, error), + } + } +} + +// ============================================================================= +// A record: `at` and `record` +// ============================================================================= + +/// A declaration for one entry of a record. See [`Declaration::entry`]. +pub(crate) struct Entry<A>(A, Cow<'static, str>); + +/// What [`Entry`] stages: what its declaration stages, and whether the walk +/// reached its entry. +pub(crate) struct EntryStaged<S> { + inner: S, + seen: bool, +} + +impl<S: Default> Default for EntryStaged<S> { + fn default() -> Self { + Self { + inner: S::default(), + seen: false, + } + } +} + +impl<A: Declaration> Declaration for Entry<A> { + type Output = A::Output; + type Staged = EntryStaged<A::Staged>; + type Sink<'s> + = EntrySink<'s, A> + where + Self: 's; + type Context = A::Context; + + fn sink<'s>(&'s self, staged: &'s mut Self::Staged) -> Self::Sink<'s> { + EntrySink { + declaration: &self.0, + key: &self.1, + staged, + } + } + + fn finish<'a, K: 'static>( + self, + staged: Self::Staged, + cipher: &'a KeysetCipher<'_, K>, + context: Self::Context, + ) -> Pending<'a, Self::Output, K> { + self.0.finish(staged.inner, cipher, context) + } +} + +/// The sink of [`Entry`]: a map, in which one entry is the declaration's. +pub(crate) struct EntrySink<'s, A: Declaration> { + declaration: &'s A, + key: &'s str, + staged: &'s mut EntryStaged<A::Staged>, +} + +impl<'s, A: Declaration> Sink for EntrySink<'s, A> { + type Ok = (); + type Error = WalkError; + type Seq = NotASequence; + type Map = Self; + + fn scalar(self, _: Option<Logical>, _: Physical<'_>) -> Result<(), WalkError> { + Err(refused("a record is a map")) + } + + fn typed_null(self, _: FixedType) -> Result<(), WalkError> { + Err(refused("a record is a map")) + } + + fn seq(self, _: Option<usize>) -> Result<NotASequence, WalkError> { + Err(refused("a record is a map")) + } + + fn map(self, _: Option<usize>) -> Result<Self, WalkError> { + Ok(self) + } + + fn passthrough<P: ?Sized + EncryptRef>(self, _: &P) -> Result<(), WalkError> { + Err(refused("a record is a map")) + } +} + +impl<'s, A: Declaration> MapSink for EntrySink<'s, A> { + type Ok = (); + type Error = WalkError; + /// The declaration's sink for its own entry, and no sink for any other. + type Entry<'e> + = Option<A::Sink<'e>> + where + Self: 'e; + + fn entry(&mut self, key: &str) -> Result<Self::Entry<'_>, WalkError> { + if key != self.key { + return Ok(None); + } + if self.staged.seen { + return Err(refused("a field is given twice")); + } + self.staged.seen = true; + Ok(Some(self.declaration.sink(&mut self.staged.inner))) + } + + fn end(self) -> Result<(), WalkError> { + match self.staged.seen { + true => Ok(()), + false => Err(refused("a field of the record is missing")), + } + } +} + +/// Never built. The `Sink` trait asks every sink to name a sequence type. +pub(crate) enum NotASequence {} + +impl SeqSink for NotASequence { + type Ok = (); + type Error = WalkError; + type Element<'s> = EncryptSink<Root, Unspecified>; + + fn element(&mut self) -> Result<Self::Element<'_>, WalkError> { + match *self {} + } + + fn end(self) -> Result<(), WalkError> { + match self {} + } +} + +/// How many fields the walk reached. [`Record`] compares it with the +/// number of entries the walk gave. +pub(crate) trait FieldsSeen { + fn fields_seen(&self) -> usize; +} + +impl<S> FieldsSeen for EntryStaged<S> { + fn fields_seen(&self) -> usize { + usize::from(self.seen) + } +} + +impl<A: FieldsSeen, B: FieldsSeen> FieldsSeen for (A, B) { + fn fields_seen(&self) -> usize { + self.0.fields_seen() + self.1.fields_seen() + } +} + +/// Fields as a whole record. See [`Declaration::record`]. +pub(crate) struct Record<A>(A); + +/// What [`Record`] stages: what its fields stage, and how many entries the +/// walk gave. +pub(crate) struct RecordStaged<S> { + fields: S, + entries: usize, +} + +impl<S: Default> Default for RecordStaged<S> { + fn default() -> Self { + Self { + fields: S::default(), + entries: 0, + } + } +} + +impl<A> Declaration for Record<A> +where + A: Declaration, + A::Staged: FieldsSeen, +{ + type Output = A::Output; + type Staged = RecordStaged<A::Staged>; + type Sink<'s> + = Counting<'s, A::Sink<'s>> + where + Self: 's; + type Context = A::Context; + + fn sink<'s>(&'s self, staged: &'s mut Self::Staged) -> Self::Sink<'s> { + Counting { + inner: self.0.sink(&mut staged.fields), + entries: &mut staged.entries, + } + } + + fn finish<'a, K: 'static>( + self, + staged: Self::Staged, + cipher: &'a KeysetCipher<'_, K>, + context: Self::Context, + ) -> Pending<'a, Self::Output, K> { + // A field given twice and a field that is missing were refused in + // the walk. So more entries than fields means an entry that no + // field took. + if staged.entries != staged.fields.fields_seen() { + return Pending::failed(cipher, Error::Aead); + } + self.0.finish(staged.fields, cipher, context) + } +} + +/// A sink that counts the entries of the map it is given, and hands +/// everything to `inner`. +pub(crate) struct Counting<'s, S> { + inner: S, + entries: &'s mut usize, +} + +impl<'s, S: Sink> Sink for Counting<'s, S> { + type Ok = S::Ok; + type Error = S::Error; + type Seq = S::Seq; + type Map = Counting<'s, S::Map>; + + fn scalar(self, ty: Option<Logical>, value: Physical<'_>) -> Result<S::Ok, S::Error> { + self.inner.scalar(ty, value) + } + + fn typed_null(self, ty: FixedType) -> Result<S::Ok, S::Error> { + self.inner.typed_null(ty) + } + + fn seq(self, len: Option<usize>) -> Result<S::Seq, S::Error> { + self.inner.seq(len) + } + + fn map(self, len: Option<usize>) -> Result<Self::Map, S::Error> { + Ok(Counting { + inner: self.inner.map(len)?, + entries: self.entries, + }) + } + + fn passthrough<P: ?Sized + EncryptRef>(self, value: &P) -> Result<S::Ok, S::Error> { + self.inner.passthrough(value) + } +} + +impl<'s, M: MapSink> MapSink for Counting<'s, M> { + type Ok = M::Ok; + type Error = M::Error; + type Entry<'e> + = M::Entry<'e> + where + Self: 'e; + + fn entry(&mut self, key: &str) -> Result<Self::Entry<'_>, M::Error> { + *self.entries += 1; + self.inner.entry(key) + } + + fn end(self) -> Result<M::Ok, M::Error> { + self.inner.end() + } +} + +// ============================================================================= +// A declaration built at run time: `Option` and `Fields` +// ============================================================================= + +/// A declaration that is there or not. A plan is data, so whether a field +/// has a ciphertext, a term or a clear value is known only at run time. +/// With `Option`, every field of a plan has one type. +impl<A: Declaration> Declaration for Option<A> { + type Output = Option<A::Output>; + type Staged = A::Staged; + type Sink<'s> + = Option<A::Sink<'s>> + where + Self: 's; + type Context = A::Context; + + fn sink<'s>(&'s self, staged: &'s mut Self::Staged) -> Self::Sink<'s> { + self.as_ref().map(|declaration| declaration.sink(staged)) + } + + fn finish<'a, K: 'static>( + self, + staged: Self::Staged, + cipher: &'a KeysetCipher<'_, K>, + context: Self::Context, + ) -> Pending<'a, Self::Output, K> { + match self { + Some(declaration) => declaration.finish(staged, cipher, context).map(Some), + None => Pending::ready(cipher, Ok(None)), + } + } +} + +/// The fields of a record, when their number is known only at run time. +/// It is collected from the fields' entries, as a `Vec` is collected from +/// an iterator: +/// +/// ```ignore +/// plan.fields().iter().map(|field| declare(field).entry(name)).collect::<Fields<_>>() +/// ``` +/// +/// `zip` cannot do this. Each `zip` makes a new type, so a loop cannot +/// build a record of a length it does not know. The entries of a `Fields` +/// all have one type. +pub(crate) struct Fields<A>(Vec<Entry<A>>); + +impl<A> FromIterator<Entry<A>> for Fields<A> { + fn from_iter<I: IntoIterator<Item = Entry<A>>>(entries: I) -> Self { + Self(entries.into_iter().collect()) + } +} + +impl<A: Declaration> Declaration for Fields<A> { + type Output = Vec<A::Output>; + type Staged = Vec<EntryStaged<A::Staged>>; + type Sink<'s> + = FieldsSink<'s, A> + where + Self: 's; + type Context = A::Context; + + fn sink<'s>(&'s self, staged: &'s mut Self::Staged) -> Self::Sink<'s> { + staged.clear(); + staged.resize_with(self.0.len(), EntryStaged::default); + FieldsSink { + entries: &self.0, + staged, + } + } + + fn finish<'a, K: 'static>( + self, + staged: Self::Staged, + cipher: &'a KeysetCipher<'_, K>, + context: Self::Context, + ) -> Pending<'a, Self::Output, K> { + let fields = self + .0 + .into_iter() + .zip(staged) + .map(|(entry, staged)| entry.finish(staged, cipher, context.clone())); + Pending::collect(cipher, fields) + } +} + +/// The sink of [`Fields`]: a map, in which each entry goes to the field of +/// that name. +pub(crate) struct FieldsSink<'s, A: Declaration> { + entries: &'s [Entry<A>], + staged: &'s mut Vec<EntryStaged<A::Staged>>, +} + +impl<'s, A: Declaration> Sink for FieldsSink<'s, A> { + type Ok = (); + type Error = WalkError; + type Seq = NotASequence; + type Map = Self; + + fn scalar(self, _: Option<Logical>, _: Physical<'_>) -> Result<(), WalkError> { + Err(refused("a record is a map")) + } + + fn typed_null(self, _: FixedType) -> Result<(), WalkError> { + Err(refused("a record is a map")) + } + + fn seq(self, _: Option<usize>) -> Result<NotASequence, WalkError> { + Err(refused("a record is a map")) + } + + fn map(self, _: Option<usize>) -> Result<Self, WalkError> { + Ok(self) + } + + fn passthrough<P: ?Sized + EncryptRef>(self, _: &P) -> Result<(), WalkError> { + Err(refused("a record is a map")) + } +} + +impl<'s, A: Declaration> MapSink for FieldsSink<'s, A> { + type Ok = (); + type Error = WalkError; + /// The sink of the field of that name, and no sink for a name that no + /// field has. + type Entry<'e> + = Option<A::Sink<'e>> + where + Self: 'e; + + fn entry(&mut self, key: &str) -> Result<Self::Entry<'_>, WalkError> { + let Some(at) = self.entries.iter().position(|entry| entry.1 == key) else { + return Ok(None); + }; + let (Some(entry), Some(staged)) = (self.entries.get(at), self.staged.get_mut(at)) else { + return Ok(None); + }; + if staged.seen { + return Err(refused("a field is given twice")); + } + staged.seen = true; + Ok(Some(entry.0.sink(&mut staged.inner))) + } + + fn end(self) -> Result<(), WalkError> { + match self.staged.iter().all(|staged| staged.seen) { + true => Ok(()), + false => Err(refused("a field of the record is missing")), + } + } +} + +impl<S> FieldsSeen for Vec<EntryStaged<S>> { + fn fields_seen(&self) -> usize { + self.iter().filter(|staged| staged.seen).count() + } +} + +// ============================================================================= +// A record whose context is one of its fields: `under_field` and `context_from` +// ============================================================================= + +/// The context a field is handed when its record's context is read from +/// the record: what the caller declared, and the value of the context +/// field. +#[derive(Clone)] +pub(crate) struct RecordContext { + declared: DeclaredContext, + base: Label, +} + +/// A declaration under the record's context, then its own identity. See +/// [`Declaration::under_field`]. +pub(crate) struct UnderField<A>(A, Cow<'static, str>); + +impl<A> Declaration for UnderField<A> +where + A: Declaration, + A::Context: From<CallerContext>, +{ + type Output = A::Output; + type Staged = A::Staged; + type Sink<'s> + = A::Sink<'s> + where + Self: 's; + type Context = RecordContext; + + fn sink<'s>(&'s self, staged: &'s mut Self::Staged) -> Self::Sink<'s> { + self.0.sink(staged) + } + + fn finish<'a, K: 'static>( + self, + staged: Self::Staged, + cipher: &'a KeysetCipher<'_, K>, + context: RecordContext, + ) -> Pending<'a, Self::Output, K> { + // The record's context, then this field's identity. + let Ok(label) = Label::new(context.base.segments().chain([&*self.1])) else { + return Pending::failed(cipher, Error::Aead); + }; + match context.declared.checked_under(NonEmpty::from(label)) { + Ok(context) => self.0.finish(staged, cipher, context.into()), + Err(error) => Pending::failed(cipher, error), + } + } +} + +/// Fields whose context is read from one entry of the record. See +/// [`Declaration::context_from`]. +pub(crate) struct ContextFrom<A>(A, Entry<Clear<()>>); + +impl<A> Declaration for ContextFrom<A> +where + A: Declaration<Context = RecordContext>, +{ + type Output = (A::Output, OwnedFrame); + type Staged = (A::Staged, EntryStaged<ClearStaged>); + type Sink<'s> + = Tee<A::Sink<'s>, EntrySink<'s, Clear<()>>> + where + Self: 's; + type Context = DeclaredContext; + + fn sink<'s>(&'s self, staged: &'s mut Self::Staged) -> Self::Sink<'s> { + Tee(self.0.sink(&mut staged.0), self.1.sink(&mut staged.1)) + } + + fn finish<'a, K: 'static>( + self, + staged: Self::Staged, + cipher: &'a KeysetCipher<'_, K>, + context: DeclaredContext, + ) -> Pending<'a, Self::Output, K> { + // The walk is over, so the context field has been read, wherever + // in the record it was. + let Ok(frame) = OwnedFrame::from_buffer(staged.1.inner.0) else { + return Pending::failed(cipher, Error::Aead); + }; + let Ok(base) = (&frame).into_label() else { + return Pending::failed(cipher, Error::Aead); + }; + let context = RecordContext { + declared: context, + base, + }; + self.0 + .finish(staged.0, cipher, context) + .map(move |fields| (fields, frame)) + } +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used)] +mod tests { + use super::*; + use crate::kms::FakeDataKeySource; + use crate::target::{indexed, Borrowed, DecryptFrom as _, Equality}; + use crate::{nonempty, StackCipher}; + + const EMAIL: &str = "ada@example.com"; + + fn context() -> CallerContext { + CallerContext::from(nonempty!("users").with("email")) + } + + async fn a_cipher() -> StackCipher<FakeDataKeySource> { + StackCipher::builder() + .kms(FakeDataKeySource::new()) + .init() + .await + .expect("a cipher") + } + + mod given_a_ciphertext_with_an_equality_term { + use super::*; + + #[tokio::test] + async fn the_term_is_todays_term() { + let cipher = a_cipher().await; + let keyset = cipher.default_keyset(); + let email = String::from(EMAIL); + + let new: Encrypted<EqualityTerm> = (&email) + .encrypt_into(&keyset, context()) + .await + .expect("the declaration encrypts"); + let today = keyset + .run( + indexed::<String, _, Borrowed, _>(Equality), + &email, + context(), + ) + .await + .expect("today's combinators encrypt"); + + assert_eq!( + new.terms, today.terms, + "the declaration's equality term should be today's term" + ); + } + + #[tokio::test] + async fn each_way_makes_the_same_requests_under_the_same_contexts() { + let cipher = a_cipher().await; + let keyset = cipher.default_keyset(); + let email = String::from(EMAIL); + + let new = (&email).encrypt_into::<Encrypted<EqualityTerm>, _>(&keyset, context()); + let today = keyset.run( + indexed::<String, _, Borrowed, _>(Equality), + &email, + context(), + ); + + assert_eq!( + new.key_count(), + today.key_count(), + "the declaration should ask for as many keys as today's combinators" + ); + assert_eq!( + format!("{:?}", new.context()), + format!("{:?}", today.context()), + "the declaration should report the contexts today's combinators report" + ); + } + + #[tokio::test] + async fn todays_decrypt_opens_the_ciphertext() { + let cipher = a_cipher().await; + let keyset = cipher.default_keyset(); + let email = String::from(EMAIL); + + let sealed: Encrypted<EqualityTerm> = (&email) + .encrypt_into(&keyset, context()) + .await + .expect("the declaration encrypts"); + let opened = String::decrypt_from_with_context(sealed, &cipher, context()) + .await + .expect("today's decrypt opens it"); + + assert_eq!(opened, EMAIL, "the plaintext should come back unchanged"); + } + + #[tokio::test] + async fn another_context_does_not_open_it() { + let cipher = a_cipher().await; + let keyset = cipher.default_keyset(); + let email = String::from(EMAIL); + + let sealed: Encrypted<EqualityTerm> = (&email) + .encrypt_into(&keyset, context()) + .await + .expect("the declaration encrypts"); + let other = CallerContext::from(nonempty!("users").with("name")); + let opened = String::decrypt_from_with_context(sealed, &cipher, other).await; + + assert!( + opened.is_err(), + "a ciphertext sealed under users/email should not open under users/name" + ); + } + } + + mod given_a_stored_ciphertext_with_its_term { + use super::*; + + async fn sealed_today( + keyset: &KeysetCipher<'_, FakeDataKeySource>, + ) -> Encrypted<EqualityTerm> { + let email = String::from(EMAIL); + keyset + .run( + indexed::<String, _, Borrowed, _>(Equality), + &email, + context(), + ) + .await + .expect("today's combinators encrypt") + } + + #[tokio::test] + async fn the_declaration_opens_what_todays_combinators_sealed() { + let cipher = a_cipher().await; + let keyset = cipher.default_keyset(); + let stored = sealed_today(&keyset).await; + + let opened: String = open(&cipher, &indexed_equality(), stored, context()) + .await + .expect("the declaration opens it"); + + assert_eq!(opened, EMAIL, "the plaintext should come back unchanged"); + } + + #[tokio::test] + async fn the_declaration_opens_what_it_sealed() { + let cipher = a_cipher().await; + let keyset = cipher.default_keyset(); + let email = String::from(EMAIL); + let stored: Encrypted<EqualityTerm> = (&email) + .encrypt_into(&keyset, context()) + .await + .expect("the declaration encrypts"); + + let opened: String = open(&cipher, &indexed_equality(), stored, context()) + .await + .expect("the declaration opens it"); + + assert_eq!(opened, EMAIL, "the plaintext should come back unchanged"); + } + + #[tokio::test] + async fn opening_asks_for_the_keys_todays_decrypt_asks_for() { + let cipher = a_cipher().await; + let keyset = cipher.default_keyset(); + + let new = open::<_, String, _>( + &cipher, + &indexed_equality(), + sealed_today(&keyset).await, + context(), + ); + let today = + String::decrypt_from_with_context(sealed_today(&keyset).await, &cipher, context()); + + assert_eq!( + new.key_count(), + today.key_count(), + "the declaration should ask for as many keys as today's decrypt" + ); + assert_eq!( + format!("{:?}", new.context()), + format!("{:?}", today.context()), + "the declaration should report the contexts today's decrypt reports" + ); + } + + #[tokio::test] + async fn another_context_does_not_open_it() { + let cipher = a_cipher().await; + let keyset = cipher.default_keyset(); + let stored = sealed_today(&keyset).await; + let other = CallerContext::from(nonempty!("users").with("name")); + + let opened = open::<_, String, _>(&cipher, &indexed_equality(), stored, other).await; + + assert!( + opened.is_err(), + "a ciphertext sealed under users/email should not open under users/name" + ); + } + } + + mod given_a_value_that_counts_its_walks { + use std::sync::atomic::{AtomicUsize, Ordering}; + use std::sync::Arc; + + use super::*; + + /// A text value that counts how many times it is walked. + struct Counted { + text: String, + walks: Arc<AtomicUsize>, + } + + impl EncryptRef for Counted { + const REF_DEPTH: Option<usize> = Some(0); + const REF_FIXED: Option<FixedType> = None; + + fn visit_ref<S: Sink>(&self, sink: S) -> Result<S::Ok, S::Error> { + self.walks.fetch_add(1, Ordering::SeqCst); + self.text.as_str().visit(sink) + } + } + + impl Encrypt for Counted { + fn visit<S: Sink>(self, sink: S) -> Result<S::Ok, S::Error> { + self.visit_ref(sink) + } + } + + fn counted() -> (Counted, Arc<AtomicUsize>) { + let walks = Arc::new(AtomicUsize::new(0)); + let value = Counted { + text: String::from(EMAIL), + walks: Arc::clone(&walks), + }; + (value, walks) + } + + #[tokio::test] + async fn the_declaration_walks_it_once() { + let cipher = a_cipher().await; + let keyset = cipher.default_keyset(); + let (value, walks) = counted(); + + value + .lend() + .encrypt_into::<Encrypted<EqualityTerm>, _>(&keyset, context()) + .await + .expect("the declaration encrypts"); + + assert_eq!( + walks.load(Ordering::SeqCst), + 1, + "the ciphertext and the term should come from one walk" + ); + } + + #[tokio::test] + async fn todays_combinators_walk_it_once_for_each_operation() { + let cipher = a_cipher().await; + let keyset = cipher.default_keyset(); + let (value, walks) = counted(); + + keyset + .run( + indexed::<Counted, _, Borrowed, _>(Equality), + &value, + context(), + ) + .await + .expect("today's combinators encrypt"); + + assert_eq!( + walks.load(Ordering::SeqCst), + 2, + "the ciphertext operation and the term operation should each walk the value" + ); + } + } + + mod given_a_record_of_two_fields { + use std::collections::BTreeMap; + + use vitaminc_aead::frame::OwnedFrame; + + use super::*; + use crate::Encryption; + + struct User { + email: String, + age: u32, + } + + // --------------------------------------------------------------- + // What a derive would write for `EncryptedUser`: the walk of the + // plaintext, and the declaration, from the same field names. + // --------------------------------------------------------------- + + /// A `User` walked as a map of its fields. + struct UserFields<'u>(&'u User); + + impl Encrypt for UserFields<'_> { + fn visit<S: Sink>(self, sink: S) -> Result<S::Ok, S::Error> { + let mut map = sink.map(Some(2))?; + (&self.0.email).visit(map.entry("email")?)?; + (&self.0.age).visit(map.entry("age")?)?; + map.end() + } + } + + #[derive(Debug)] + struct EncryptedUser { + email: Encrypted<EqualityTerm>, + age: StackCipherText, + } + + fn label(path: &str) -> NonEmpty<Label> { + NonEmpty::from(Label::parse(path).expect("a label")) + } + + impl<'u> EncryptTarget<&'u User> for EncryptedUser { + type Context = DeclaredContext; + + fn declaration() -> impl Declaration<Output = Self, Context = DeclaredContext> { + field(|user: &User| &user.email) + .under(label("users/email")) + .entry("email") + .zip( + field(|user: &User| &user.age) + .under(label("users/age")) + .entry("age"), + ) + .record() + .map(|(email, age)| EncryptedUser { email, age }) + } + + fn source(user: &'u User) -> impl Encrypt { + UserFields(user) + } + } + + /// The declaration alone, for a source that is not a `User`. + fn the_declaration() -> impl Declaration<Output = EncryptedUser, Context = DeclaredContext> + { + <EncryptedUser as EncryptTarget<&User>>::declaration() + } + + /// The record's declaration with the inverse of its last step, so + /// that it opens what it stored. A derive would write `convert` + /// where the declaration above has `map`. + fn the_two_way_declaration() -> impl Open<Output = EncryptedUser, Context = DeclaredContext> + { + indexed_equality() + .under(label("users/email")) + .entry("email") + .zip(ciphertext().under(label("users/age")).entry("age")) + .record() + .convert( + |(email, age)| EncryptedUser { email, age }, + |stored: EncryptedUser| (stored.email, stored.age), + ) + } + + /// The email field's declaration. A derive would write it once, and + /// use it for the record and for the field's queries. + fn the_email_field( + ) -> impl Open<Output = Encrypted<EqualityTerm>, Context = DeclaredContext> + + Answers<crate::op::Eq, Right<Here>, Query: Declaration<Output = EqualityTerm>> + { + indexed_equality().under(label("users/email")) + } + + #[tokio::test] + async fn a_query_of_a_field_sends_the_term_the_record_stores() { + let cipher = a_cipher().await; + let keyset = cipher.default_keyset(); + let record: EncryptedUser = (&user()) + .encrypt_into(&keyset, DeclaredContext::default()) + .await + .expect("the declaration encrypts"); + + let term = run( + &keyset, + the_email_field().query::<crate::op::Eq, _>(), + EMAIL, + DeclaredContext::default(), + ) + .await + .expect("the field answers Eq"); + + assert_eq!( + term, record.email.terms, + "a query should send the term the record stores" + ); + } + + #[tokio::test] + async fn a_query_of_a_field_sends_todays_query_term() { + let cipher = a_cipher().await; + let keyset = cipher.default_keyset(); + let email = String::from(EMAIL); + + let term = run( + &keyset, + the_email_field().query::<crate::op::Eq, _>(), + &email, + DeclaredContext::default(), + ) + .await + .expect("the field answers Eq"); + let today = keyset + .run( + crate::target::Index::<String>::query_operation::<_, Borrowed>(&Equality) + .under(label("users/email")), + &email, + DeclaredContext::default(), + ) + .await + .expect("today's query operation"); + + assert_eq!(term, today, "the query term should be today's"); + } + + // These do not compile: + // + // ciphertext().query::<crate::op::Eq, _>() + // error[E0277]: `Ciphertext: Answers<Eq, _>` is not satisfied + // + // the_email_field().query::<crate::op::Lt, _>() + // error[E0277]: `…: Answers<Lt, _>` is not satisfied + // + // equality().zip(equality()).query::<crate::op::Eq, _>() + // error[E0284]: type annotations needed: both sides answer `Eq` + + /// The plaintext a stored record opens to, as a Rust type. + #[derive(Debug, PartialEq, vitaminc_aead::Decrypt)] + struct OpenedUser { + email: String, + age: u32, + } + + #[tokio::test] + async fn the_declaration_opens_the_record_into_a_struct() { + let cipher = a_cipher().await; + let keyset = cipher.default_keyset(); + let record: EncryptedUser = (&user()) + .encrypt_into(&keyset, DeclaredContext::default()) + .await + .expect("the declaration encrypts"); + + let opened: OpenedUser = open( + &cipher, + &the_two_way_declaration(), + record, + DeclaredContext::default(), + ) + .await + .expect("the declaration opens the record"); + + assert_eq!( + opened, + OpenedUser { + email: String::from(EMAIL), + age: 36 + }, + "the record should come back as its plaintext" + ); + } + + #[tokio::test] + async fn the_declaration_opens_the_record_into_a_frame() { + let cipher = a_cipher().await; + let keyset = cipher.default_keyset(); + let record: EncryptedUser = (&user()) + .encrypt_into(&keyset, DeclaredContext::default()) + .await + .expect("the declaration encrypts"); + + let opened = open_frame( + &cipher, + &the_two_way_declaration(), + record, + DeclaredContext::default(), + ) + .await + .expect("the declaration opens the record"); + + let fields: BTreeMap<String, serde_json::Value> = + recipher_frame::serde::from_slice(opened.frame().as_bytes()).expect("a map"); + assert_eq!( + fields, + BTreeMap::from([ + (String::from("email"), serde_json::json!(EMAIL)), + (String::from("age"), serde_json::json!(36)), + ]), + "the frame should have each field under its name, and no term" + ); + } + + #[tokio::test] + async fn the_declaration_opens_what_todays_combinators_sealed() { + let cipher = a_cipher().await; + let keyset = cipher.default_keyset(); + let (email, age) = keyset + .run(todays_combinators(), &user(), DeclaredContext::default()) + .await + .expect("today's combinators encrypt"); + + let opened: OpenedUser = open( + &cipher, + &the_two_way_declaration(), + EncryptedUser { email, age }, + DeclaredContext::default(), + ) + .await + .expect("the declaration opens a record today's combinators sealed"); + + assert_eq!(opened.email, EMAIL, "the email should come back unchanged"); + assert_eq!(opened.age, 36, "the age should come back unchanged"); + } + + #[tokio::test] + async fn a_field_stored_in_another_fields_place_does_not_open() { + let cipher = a_cipher().await; + let keyset = cipher.default_keyset(); + let record: EncryptedUser = (&user()) + .encrypt_into(&keyset, DeclaredContext::default()) + .await + .expect("the declaration encrypts"); + // The age's ciphertext where the email's should be. + let moved = EncryptedUser { + email: Encrypted { + ciphertext: record.age, + terms: record.email.terms, + }, + age: record.email.ciphertext, + }; + + let opened = open_frame( + &cipher, + &the_two_way_declaration(), + moved, + DeclaredContext::default(), + ) + .await; + + assert!( + opened.is_err(), + "a ciphertext sealed under users/age should not open as users/email" + ); + } + + /// The same record, as today's combinators declare it. + fn todays_combinators<'s, K: 'static>( + ) -> Encryption<'s, User, (Encrypted<EqualityTerm>, StackCipherText), K, DeclaredContext> + { + indexed::<String, _, Borrowed, _>(Equality) + .under(label("users/email")) + .project(|user: &User| &user.email) + .zip( + crate::target::ciphertext::<u32, _, Borrowed>() + .under(label("users/age")) + .project(|user: &User| &user.age), + ) + } + + fn user() -> User { + User { + email: String::from(EMAIL), + age: 36, + } + } + + fn frame_of(fields: &[(&'static str, OwnedFrame)]) -> OwnedFrame { + let fields: BTreeMap<&str, &OwnedFrame> = + fields.iter().map(|(key, value)| (*key, value)).collect(); + OwnedFrame::of(&fields).expect("a frame") + } + + fn text(value: &str) -> OwnedFrame { + OwnedFrame::of(value).expect("a frame") + } + + fn number(value: u32) -> OwnedFrame { + OwnedFrame::of(value).expect("a frame") + } + + /// The same record as a value from a language binding: a frame. + fn a_frame() -> OwnedFrame { + frame_of(&[("email", text(EMAIL)), ("age", number(36))]) + } + + fn email_context() -> CallerContext { + CallerContext::from(label("users/email")) + } + + fn age_context() -> CallerContext { + CallerContext::from(label("users/age")) + } + + #[tokio::test] + async fn the_term_is_todays_term() { + let cipher = a_cipher().await; + let keyset = cipher.default_keyset(); + let user = user(); + + let record: EncryptedUser = (&user) + .encrypt_into(&keyset, DeclaredContext::default()) + .await + .expect("the declaration encrypts"); + let (email, _) = keyset + .run(todays_combinators(), &user, DeclaredContext::default()) + .await + .expect("today's combinators encrypt"); + + assert_eq!( + record.email.terms, email.terms, + "the record's equality term should be today's term" + ); + } + + #[tokio::test] + async fn each_way_makes_the_same_requests_under_the_same_contexts() { + let cipher = a_cipher().await; + let keyset = cipher.default_keyset(); + let user = user(); + + let new = (&user).encrypt_into::<EncryptedUser, _>(&keyset, DeclaredContext::default()); + let today = keyset.run(todays_combinators(), &user, DeclaredContext::default()); + + assert_eq!( + new.key_count(), + today.key_count(), + "the record should ask for as many keys as today's combinators" + ); + assert_eq!( + format!("{:?}", new.context()), + format!("{:?}", today.context()), + "the record should report the contexts today's combinators report" + ); + } + + #[tokio::test] + async fn todays_decrypt_opens_each_field_under_its_own_context() { + let cipher = a_cipher().await; + let keyset = cipher.default_keyset(); + + let record: EncryptedUser = (&user()) + .encrypt_into(&keyset, DeclaredContext::default()) + .await + .expect("the declaration encrypts"); + let email = String::decrypt_from_with_context(record.email, &cipher, email_context()) + .await + .expect("the email opens under users/email"); + let age = u32::decrypt_from_with_context(record.age, &cipher, age_context()) + .await + .expect("the age opens under users/age"); + + assert_eq!(email, EMAIL, "the email should come back unchanged"); + assert_eq!(age, 36, "the age should come back unchanged"); + } + + #[tokio::test] + async fn a_field_does_not_open_under_another_fields_context() { + let cipher = a_cipher().await; + let keyset = cipher.default_keyset(); + + let record: EncryptedUser = (&user()) + .encrypt_into(&keyset, DeclaredContext::default()) + .await + .expect("the declaration encrypts"); + let opened = + String::decrypt_from_with_context(record.email, &cipher, age_context()).await; + + assert!( + opened.is_err(), + "the email, sealed under users/email, should not open under users/age" + ); + } + + #[tokio::test] + async fn a_frame_from_a_binding_goes_through_the_same_declaration() { + let cipher = a_cipher().await; + let keyset = cipher.default_keyset(); + + let from_struct: EncryptedUser = (&user()) + .encrypt_into(&keyset, DeclaredContext::default()) + .await + .expect("the struct encrypts"); + let from_frame: EncryptedUser = run( + &keyset, + the_declaration(), + a_frame(), + DeclaredContext::default(), + ) + .await + .expect("the frame encrypts"); + + assert_eq!( + from_frame.email.terms, from_struct.email.terms, + "a frame and a struct with the same fields should give the same term" + ); + let age = u32::decrypt_from_with_context(from_frame.age, &cipher, age_context()) + .await + .expect("the frame's age opens under users/age"); + assert_eq!(age, 36, "the frame's age should come back unchanged"); + } + + #[tokio::test] + async fn a_frame_with_a_missing_field_is_refused() { + let cipher = a_cipher().await; + let keyset = cipher.default_keyset(); + let no_age = frame_of(&[("email", text(EMAIL))]); + + let missing = run( + &keyset, + the_declaration(), + no_age, + DeclaredContext::default(), + ) + .await; + + assert!(missing.is_err(), "a record with no age should be refused"); + } + + #[tokio::test] + async fn a_frame_with_an_unknown_field_is_refused() { + let cipher = a_cipher().await; + let keyset = cipher.default_keyset(); + let with_name = frame_of(&[ + ("email", text(EMAIL)), + ("age", number(36)), + ("name", text("Ada")), + ]); + + let unknown = run( + &keyset, + the_declaration(), + with_name, + DeclaredContext::default(), + ) + .await; + + assert!( + unknown.is_err(), + "a record with a field the declaration does not name should be refused" + ); + } + + #[tokio::test] + async fn fields_that_are_not_a_whole_record_ignore_an_unknown_field() { + let cipher = a_cipher().await; + let keyset = cipher.default_keyset(); + let with_name = frame_of(&[ + ("email", text(EMAIL)), + ("age", number(36)), + ("name", text("Ada")), + ]); + // The same fields, with no `record()` at the end. + let fields = indexed_equality() + .under(label("users/email")) + .entry("email") + .zip(ciphertext().under(label("users/age")).entry("age")); + + let sealed = run(&keyset, fields, with_name, DeclaredContext::default()).await; + + assert!( + sealed.is_ok(), + "without `record()`, an entry that no field takes should be ignored" + ); + } + } + + mod given_a_target_that_takes_text_only { + use super::*; + + /// A target that takes text and nothing else. Today's match index + /// is one: `Index<S> for Match` asks `S: AsRef<str>`. + #[derive(Debug)] + struct TextOnly(StackCipherText); + + impl<S: Encrypt + AsRef<str>> EncryptTarget<S> for TextOnly { + type Context = AeadContext; + + fn declaration() -> impl Declaration<Output = Self, Context = AeadContext> { + ciphertext().map(TextOnly) + } + + fn source(plaintext: S) -> impl Encrypt { + plaintext + } + } + + #[tokio::test] + async fn text_is_encrypted() { + let cipher = a_cipher().await; + let keyset = cipher.default_keyset(); + + let sealed = EMAIL + .encrypt_into::<TextOnly, _>(&keyset, AeadContext::from(context())) + .await; + + assert!( + sealed.is_ok(), + "text should be encrypted into a text target" + ); + } + + // A number does not compile: + // + // 36u32.encrypt_into::<TextOnly, _>(&keyset, ..) + // + // error[E0277]: the trait bound `u32: AsRef<str>` is not satisfied + // + // A record whose field is a number does not compile either, when + // the field's target is `TextOnly`: + // + // field(|user: &User| &user.age) // `User::age` is a `u32` + // .entry("age") + // .map(|age| Record { age }) // `Record::age` is a `TextOnly` + // + // error[E0277]: the trait bound `u32: AsRef<str>` is not satisfied + } + + mod given_a_json_document { + use std::collections::BTreeMap; + + use serde_json::json; + + use super::*; + use crate::json::JsonPlaintext; + + fn profile() -> serde_json::Value { + json!({"name": "ada", "tags": ["a", "b"], "age": 36}) + } + + fn label(path: &str) -> NonEmpty<Label> { + NonEmpty::from(Label::parse(path).expect("a label")) + } + + fn profile_context() -> CallerContext { + CallerContext::from(label("users/profile")) + } + + /// Every text value in `value`, in walk order. + fn texts(value: &serde_json::Value, out: &mut Vec<String>) { + match value { + serde_json::Value::String(text) => out.push(text.clone()), + serde_json::Value::Array(items) => items.iter().for_each(|item| texts(item, out)), + serde_json::Value::Object(fields) => { + fields.values().for_each(|field| texts(field, out)); + } + _ => {} + } + } + + /// The selectors of the document's selector set, in a fixed order. + /// A document stores its selectors in a random order. + fn selectors(document: &JsonDocument) -> Vec<String> { + let wire = serde_json::to_value(document).expect("a document serializes"); + let mut selectors = Vec::new(); + texts(&wire["q"], &mut selectors); + selectors.sort(); + selectors + } + + fn entries(document: &JsonDocument) -> usize { + let wire = serde_json::to_value(document).expect("a document serializes"); + wire["sv"].as_array().map_or(0, Vec::len) + } + + async fn todays(keyset: &KeysetCipher<'_, FakeDataKeySource>) -> JsonDocument { + let value = profile(); + keyset + .run( + crate::target::json_document::<_, Borrowed>(JsonOptions::default()), + &value, + profile_context(), + ) + .await + .expect("today's JSON index seals") + } + + #[tokio::test] + async fn the_declaration_gives_todays_selectors_and_entries() { + let cipher = a_cipher().await; + let keyset = cipher.default_keyset(); + + let new = run( + &keyset, + json_document(JsonOptions::default()), + JsonPlaintext::from(profile()), + profile_context(), + ) + .await + .expect("the declaration seals"); + let today = todays(&keyset).await; + + assert_eq!( + selectors(&new), + selectors(&today), + "the document should have today's selectors" + ); + assert_eq!( + entries(&new), + entries(&today), + "the document should have as many entries as today's" + ); + // name, tags, tags[0], tags[1], age, and the root: the document is + // stored as its tree of entries, and not as one ciphertext. + assert_eq!( + entries(&new), + 6, + "the document should have an entry for the root and for each node" + ); + } + + #[tokio::test] + async fn todays_decrypt_opens_the_document() { + let cipher = a_cipher().await; + let keyset = cipher.default_keyset(); + + let sealed = run( + &keyset, + json_document(JsonOptions::default()), + JsonPlaintext::from(profile()), + profile_context(), + ) + .await + .expect("the declaration seals"); + let opened = + JsonPlaintext::decrypt_from_with_context(sealed, &cipher, profile_context()) + .await + .expect("today's decrypt opens it"); + + assert_eq!( + opened.value(), + &profile(), + "the document should come back unchanged" + ); + } + + /// The same profile as a Rust struct, walked as a map of its fields. + struct Profile { + name: String, + tags: Vec<String>, + age: u32, + } + + impl Encrypt for &Profile { + fn visit<S: Sink>(self, sink: S) -> Result<S::Ok, S::Error> { + let mut map = sink.map(Some(3))?; + (&self.name).visit(map.entry("name")?)?; + (&self.tags).visit(map.entry("tags")?)?; + (&self.age).visit(map.entry("age")?)?; + map.end() + } + } + + #[tokio::test] + async fn a_struct_walked_as_a_map_is_todays_document() { + let cipher = a_cipher().await; + let keyset = cipher.default_keyset(); + let profile_struct = Profile { + name: String::from("ada"), + tags: vec![String::from("a"), String::from("b")], + age: 36, + }; + + let new = run( + &keyset, + json_document(JsonOptions::default()), + &profile_struct, + profile_context(), + ) + .await + .expect("the declaration seals a struct"); + let today = todays(&keyset).await; + + assert_eq!( + selectors(&new), + selectors(&today), + "a struct should have the selectors of the same document as JSON" + ); + assert_eq!( + entries(&new), + 6, + "the root and each node should have an entry" + ); + let opened = JsonPlaintext::decrypt_from_with_context(new, &cipher, profile_context()) + .await + .expect("today's decrypt opens it"); + assert_eq!( + opened.value(), + &profile(), + "the struct should come back as the same document" + ); + } + + #[tokio::test] + async fn a_map_from_a_binding_is_todays_document() { + let cipher = a_cipher().await; + let keyset = cipher.default_keyset(); + // The profile as a map of frames, and not as JSON text. + let tags = vec![String::from("a"), String::from("b")]; + let fields = BTreeMap::from([ + ("name", OwnedFrame::of("ada").expect("a frame")), + ("tags", OwnedFrame::of(&tags).expect("a frame")), + ("age", OwnedFrame::of(36u32).expect("a frame")), + ]); + let map = OwnedFrame::of(&fields).expect("a frame"); + + let new = run( + &keyset, + json_document(JsonOptions::default()), + map, + profile_context(), + ) + .await + .expect("the declaration seals a map"); + let today = todays(&keyset).await; + + assert_eq!( + selectors(&new), + selectors(&today), + "a map should have the selectors of the same document as JSON" + ); + } + + #[tokio::test] + async fn a_json_field_of_a_record_from_a_frame_is_todays_document() { + let cipher = a_cipher().await; + let keyset = cipher.default_keyset(); + // A record as a binding sends it: the profile is JSON text. + let fields = BTreeMap::from([ + ("email", OwnedFrame::of(EMAIL).expect("a frame")), + ( + "profile", + OwnedFrame::of(profile().to_string().as_str()).expect("a frame"), + ), + ]); + let row = OwnedFrame::of(&fields).expect("a frame"); + let declaration = indexed_equality() + .under(label("users/email")) + .entry("email") + .zip( + json_document(JsonOptions::default()) + .under(label("users/profile")) + .entry("profile"), + ) + .record(); + + let (email, document) = run(&keyset, declaration, row, DeclaredContext::default()) + .await + .expect("the record seals"); + let today = todays(&keyset).await; + + assert_eq!( + selectors(&document), + selectors(&today), + "the field's document should have today's selectors" + ); + let opened = + JsonPlaintext::decrypt_from_with_context(document, &cipher, profile_context()) + .await + .expect("today's decrypt opens the field's document"); + assert_eq!( + opened.value(), + &profile(), + "the field's document should come back unchanged" + ); + let opened = String::decrypt_from_with_context( + email, + &cipher, + CallerContext::from(label("users/email")), + ) + .await + .expect("the email beside it opens"); + assert_eq!(opened, EMAIL, "the email should come back unchanged"); + } + } + + mod given_a_value_that_is_not_one_scalar { + use super::*; + + #[tokio::test] + async fn the_equality_term_is_refused_as_today() { + let cipher = a_cipher().await; + let keyset = cipher.default_keyset(); + let list = vec![String::from("a"), String::from("b")]; + + let new = (&list) + .encrypt_into::<Encrypted<EqualityTerm>, _>(&keyset, context()) + .await; + let today = keyset + .run( + indexed::<Vec<String>, _, Borrowed, _>(Equality), + &list, + context(), + ) + .await; + + assert!( + new.is_err(), + "a list has no equality term, so the declaration should refuse it" + ); + assert!( + today.is_err(), + "a list has no equality term, so today's combinators should refuse it" + ); + } + } +} diff --git a/packages/stack-encrypt/src/target/declaration/open.rs b/packages/stack-encrypt/src/target/declaration/open.rs new file mode 100644 index 000000000..4c9be5e9b --- /dev/null +++ b/packages/stack-encrypt/src/target/declaration/open.rs @@ -0,0 +1,673 @@ +//! SPIKE, not for merging. The decrypt half of a declaration. +//! +//! A [`Declaration`] says how a value becomes a target. [`Open`] is a second +//! trait on the same declaration: it says how that target is opened again. +//! So one declaration serves encrypt and decrypt, and a record is declared +//! once. +//! +//! Opening is the encrypt steps in reverse: +//! +//! 1. The stored target is taken apart under the one context +//! ([`Open::retrieve`]). Each sealed tree gives its key requests. Nothing +//! is opened yet, and no key has arrived. +//! 2. With the keys, each tree is opened and its plaintext is walked into a +//! sink ([`Open::open_into`]). The sink is the plaintext's own: a frame +//! writer for a language binding, or the sink of a Rust type. +//! +//! So the plaintext goes from the opened leaves straight to where it is +//! kept. A record's fields are written as the entries of one map +//! ([`Open::open_entries`]), and no field is copied into a value of its +//! own first. +//! +//! Every adapter that only arranges or names things opens what it stored: +//! `zip`, `accepting`, `under`, `entry`, `record`, `under_field`, +//! `context_from`, `Option` and [`Fields`]. `map` and `try_map` do not: a +//! function has no inverse. [`Declaration::convert`] is `map` with the +//! inverse beside it, for a target that has to open. + +use stack_kms::DataKey; +use vitaminc_aead::frame::{FrameWriter, OwnedFrame}; +use vitaminc_aead::plaintext::{MapSink, Sink}; +use vitaminc_aead::{Context, ContextPiece, Decrypt, IntoAad as _, IntoContext as _}; +use vitaminc_protected::Buffer; + +use super::{ + Accepting, Ciphertext, Clear, ContextFrom, Convert, Declaration, Entry, EqualityOf, Fields, + Record, RecordContext, Under, UnderField, Zip, +}; +use crate::cipher::open_leaves; +use crate::dynamic::IntoLabel as _; +use crate::sem::EqualityTerm; +use crate::target::core::retrieve_requests; +use crate::target::{AeadContext, CallerContext, CipherRef, DeclaredContext, Pending, Request}; +use crate::{Descriptor, Error, Label, NonEmpty, StackCipherText}; +use stack_kms::MaybeSend; + +/// A sink refused the plaintext, or the stored value has another shape +/// than the declaration. The spike keeps one error for both. +fn refused<E>(_: E) -> Error { + Error::Aead +} + +/// What taking a stored target apart gives the call: the key requests, and +/// the context of each sealed tree, which the pending call reports. +#[derive(Default)] +pub(crate) struct Retrieval { + requests: Vec<Request>, + contexts: Vec<(ContextPiece<'static>, ContextPiece<'static>)>, +} + +/// The decrypt half of a declaration: how what it stored is opened again. +pub(crate) trait Open: Declaration { + /// What is kept between the key request and the opening: the sealed + /// trees, each with the AAD it opens under. + type Sealed: MaybeSend + 'static; + + /// Take `stored` apart under `context`. Add the key requests and the + /// context of every sealed tree to `retrieval`, and return what to open + /// when the keys arrive. Nothing is opened here. + fn retrieve( + &self, + stored: Self::Output, + context: Self::Context, + retrieval: &mut Retrieval, + ) -> Result<Self::Sealed, Error>; + + /// Whether `sealed` has a plaintext to give. A term has none. + fn opens(sealed: &Self::Sealed) -> bool; + + /// Open `sealed` with the next of `keys`, in the order + /// [`retrieve`](Self::retrieve) asked for them, and walk the plaintext + /// into `sink` as one value. + fn open_into<S: Sink, I: Iterator<Item = DataKey>>( + sealed: Self::Sealed, + keys: &mut I, + sink: S, + ) -> Result<S::Ok, Error>; + + /// The same, for the fields of a record: each plaintext is walked into + /// its entry of `map`, which is already open. + fn open_entries<M: MapSink, I: Iterator<Item = DataKey>>( + _sealed: Self::Sealed, + _keys: &mut I, + _map: &mut M, + ) -> Result<(), Error> { + // A value that is not a field of a record has no entry to write. + Err(Error::Aead) + } +} + +/// Take `stored` apart and make the one key request, then hand the keys to +/// `open`. +fn opening<'a, D, T, K, F>( + cipher_ref: impl Into<CipherRef<'a, K>>, + declaration: &D, + stored: D::Output, + context: D::Context, + open: F, +) -> Pending<'a, T, K> +where + D: Open, + T: 'a, + F: FnOnce(D::Sealed, &mut dyn Iterator<Item = DataKey>) -> Result<T, Error> + MaybeSend + 'a, +{ + let cipher_ref: CipherRef<'a, K> = cipher_ref.into(); + let mut retrieval = Retrieval::default(); + let sealed = match declaration.retrieve(stored, context, &mut retrieval) { + Ok(sealed) => sealed, + Err(error) => return Pending::failed(cipher_ref, error), + }; + let pending = Pending::request(cipher_ref, retrieval.requests, move |responses| { + let mut keys = responses.drain_retrieved(); + let opened = open(sealed, &mut keys)?; + // A key left over means the requests and the trees disagree. + match keys.next() { + Some(_) => Err(Error::ResponseShape), + None => Ok(opened), + } + }); + retrieval + .contexts + .into_iter() + .fold(pending, |pending, (query, stored)| { + pending.under_context(query, stored) + }) +} + +/// Open `stored` into a `T`, as `declaration` says: one key request, then +/// one pass that opens every leaf and walks it into `T`'s own sink. +pub(crate) fn open<'a, D, T, K>( + cipher_ref: impl Into<CipherRef<'a, K>>, + declaration: &D, + stored: D::Output, + context: D::Context, +) -> Pending<'a, T, K> +where + D: Open, + T: Decrypt + MaybeSend + 'a, +{ + opening( + cipher_ref, + declaration, + stored, + context, + |sealed, mut keys| D::open_into(sealed, &mut keys, T::sink()), + ) +} + +/// Open `stored` into a frame, for a language binding: one key request, +/// then one pass that opens every leaf and writes it to the frame. +pub(crate) fn open_frame<'a, D, K>( + cipher_ref: impl Into<CipherRef<'a, K>>, + declaration: &D, + stored: D::Output, + context: D::Context, +) -> Pending<'a, OwnedFrame, K> +where + D: Open, +{ + opening( + cipher_ref, + declaration, + stored, + context, + |sealed, mut keys| { + let mut out = Buffer::new(); + D::open_into(sealed, &mut keys, FrameWriter::new(&mut out))?; + OwnedFrame::from_buffer(out).map_err(refused) + }, + ) +} + +// ============================================================================= +// The operations +// ============================================================================= + +/// A ciphertext opens to the value that was sealed. +impl Open for Ciphertext { + type Sealed = (StackCipherText, Context<'static>); + + fn retrieve( + &self, + stored: StackCipherText, + context: AeadContext, + retrieval: &mut Retrieval, + ) -> Result<Self::Sealed, Error> { + let context = context.sealable()?.into_context(); + let descriptor = Descriptor::from_piece(&context); + descriptor.check()?; + retrieval + .requests + .extend(retrieve_requests(&stored, &descriptor)); + let piece = context.clone().into_owned(); + retrieval.contexts.push((piece.clone(), piece)); + Ok((stored, context.into_aad().into_owned())) + } + + fn opens(_: &Self::Sealed) -> bool { + true + } + + fn open_into<S: Sink, I: Iterator<Item = DataKey>>( + (tree, aad): Self::Sealed, + keys: &mut I, + sink: S, + ) -> Result<S::Ok, Error> { + let opened = open_leaves(tree, &aad, keys)?; + vitaminc_aead::walk(opened, sink).map_err(refused) + } +} + +/// A term is one-way: it stores nothing that opens. +impl Open for EqualityOf { + type Sealed = (); + + fn retrieve(&self, _: EqualityTerm, _: CallerContext, _: &mut Retrieval) -> Result<(), Error> { + Ok(()) + } + + fn opens(_: &()) -> bool { + false + } + + fn open_into<S: Sink, I: Iterator<Item = DataKey>>( + (): (), + _: &mut I, + _: S, + ) -> Result<S::Ok, Error> { + Err(Error::Aead) + } +} + +/// A value kept in the clear is given back as it is. +impl<C: Clone + 'static> Open for Clear<C> { + type Sealed = OwnedFrame; + + fn retrieve(&self, stored: OwnedFrame, _: C, _: &mut Retrieval) -> Result<OwnedFrame, Error> { + Ok(stored) + } + + fn opens(_: &OwnedFrame) -> bool { + true + } + + fn open_into<S: Sink, I: Iterator<Item = DataKey>>( + stored: OwnedFrame, + _: &mut I, + sink: S, + ) -> Result<S::Ok, Error> { + vitaminc_aead::Encrypt::visit(&stored, sink).map_err(refused) + } +} + +// ============================================================================= +// The adapters +// ============================================================================= + +/// As one value, a pair opens the side that has a plaintext: a ciphertext +/// beside its term opens the ciphertext. As the fields of a record, both +/// sides write their entries. +impl<A, B> Open for Zip<A, B> +where + A: Open, + B: Open<Context = A::Context>, +{ + type Sealed = (A::Sealed, B::Sealed); + + fn retrieve( + &self, + stored: Self::Output, + context: Self::Context, + retrieval: &mut Retrieval, + ) -> Result<Self::Sealed, Error> { + Ok(( + self.0.retrieve(stored.0, context.clone(), retrieval)?, + self.1.retrieve(stored.1, context, retrieval)?, + )) + } + + fn opens(sealed: &Self::Sealed) -> bool { + A::opens(&sealed.0) || B::opens(&sealed.1) + } + + fn open_into<S: Sink, I: Iterator<Item = DataKey>>( + sealed: Self::Sealed, + keys: &mut I, + sink: S, + ) -> Result<S::Ok, Error> { + match A::opens(&sealed.0) { + true => A::open_into(sealed.0, keys, sink), + false => B::open_into(sealed.1, keys, sink), + } + } + + fn open_entries<M: MapSink, I: Iterator<Item = DataKey>>( + sealed: Self::Sealed, + keys: &mut I, + map: &mut M, + ) -> Result<(), Error> { + A::open_entries(sealed.0, keys, map)?; + B::open_entries(sealed.1, keys, map) + } +} + +/// A converted declaration opens what the inverse gives back. +impl<A, U, F, G> Open for Convert<A, F, G> +where + A: Open, + U: MaybeSend + 'static, + F: FnOnce(A::Output) -> U + MaybeSend + 'static, + G: Fn(U) -> A::Output, +{ + type Sealed = A::Sealed; + + fn retrieve( + &self, + stored: U, + context: Self::Context, + retrieval: &mut Retrieval, + ) -> Result<Self::Sealed, Error> { + self.0.retrieve((self.2)(stored), context, retrieval) + } + + fn opens(sealed: &Self::Sealed) -> bool { + A::opens(sealed) + } + + fn open_into<S: Sink, I: Iterator<Item = DataKey>>( + sealed: Self::Sealed, + keys: &mut I, + sink: S, + ) -> Result<S::Ok, Error> { + A::open_into(sealed, keys, sink) + } + + fn open_entries<M: MapSink, I: Iterator<Item = DataKey>>( + sealed: Self::Sealed, + keys: &mut I, + map: &mut M, + ) -> Result<(), Error> { + A::open_entries(sealed, keys, map) + } +} + +impl<A, C> Open for Accepting<A, C> +where + A: Open, + C: Into<A::Context> + Clone + 'static, +{ + type Sealed = A::Sealed; + + fn retrieve( + &self, + stored: Self::Output, + context: C, + retrieval: &mut Retrieval, + ) -> Result<Self::Sealed, Error> { + self.0.retrieve(stored, context.into(), retrieval) + } + + fn opens(sealed: &Self::Sealed) -> bool { + A::opens(sealed) + } + + fn open_into<S: Sink, I: Iterator<Item = DataKey>>( + sealed: Self::Sealed, + keys: &mut I, + sink: S, + ) -> Result<S::Ok, Error> { + A::open_into(sealed, keys, sink) + } + + fn open_entries<M: MapSink, I: Iterator<Item = DataKey>>( + sealed: Self::Sealed, + keys: &mut I, + map: &mut M, + ) -> Result<(), Error> { + A::open_entries(sealed, keys, map) + } +} + +impl<A> Open for Under<A> +where + A: Open, + A::Context: From<CallerContext>, +{ + type Sealed = A::Sealed; + + fn retrieve( + &self, + stored: Self::Output, + context: DeclaredContext, + retrieval: &mut Retrieval, + ) -> Result<Self::Sealed, Error> { + let context = context.checked_under(self.1.clone())?; + self.0.retrieve(stored, context.into(), retrieval) + } + + fn opens(sealed: &Self::Sealed) -> bool { + A::opens(sealed) + } + + fn open_into<S: Sink, I: Iterator<Item = DataKey>>( + sealed: Self::Sealed, + keys: &mut I, + sink: S, + ) -> Result<S::Ok, Error> { + A::open_into(sealed, keys, sink) + } + + fn open_entries<M: MapSink, I: Iterator<Item = DataKey>>( + sealed: Self::Sealed, + keys: &mut I, + map: &mut M, + ) -> Result<(), Error> { + A::open_entries(sealed, keys, map) + } +} + +impl<A> Open for UnderField<A> +where + A: Open, + A::Context: From<CallerContext>, +{ + type Sealed = A::Sealed; + + fn retrieve( + &self, + stored: Self::Output, + context: RecordContext, + retrieval: &mut Retrieval, + ) -> Result<Self::Sealed, Error> { + let label = Label::new(context.base.segments().chain([&*self.1])).map_err(refused)?; + let context = context.declared.checked_under(NonEmpty::from(label))?; + self.0.retrieve(stored, context.into(), retrieval) + } + + fn opens(sealed: &Self::Sealed) -> bool { + A::opens(sealed) + } + + fn open_into<S: Sink, I: Iterator<Item = DataKey>>( + sealed: Self::Sealed, + keys: &mut I, + sink: S, + ) -> Result<S::Ok, Error> { + A::open_into(sealed, keys, sink) + } + + fn open_entries<M: MapSink, I: Iterator<Item = DataKey>>( + sealed: Self::Sealed, + keys: &mut I, + map: &mut M, + ) -> Result<(), Error> { + A::open_entries(sealed, keys, map) + } +} + +/// An entry opens its value into the entry of that name. +impl<A: Open> Open for Entry<A> { + type Sealed = (String, A::Sealed); + + fn retrieve( + &self, + stored: Self::Output, + context: Self::Context, + retrieval: &mut Retrieval, + ) -> Result<Self::Sealed, Error> { + Ok(( + self.1.clone().into_owned(), + self.0.retrieve(stored, context, retrieval)?, + )) + } + + fn opens((_, sealed): &Self::Sealed) -> bool { + A::opens(sealed) + } + + fn open_into<S: Sink, I: Iterator<Item = DataKey>>( + sealed: Self::Sealed, + keys: &mut I, + sink: S, + ) -> Result<S::Ok, Error> { + let mut map = sink.map(Some(1)).map_err(refused)?; + Self::open_entries(sealed, keys, &mut map)?; + map.end().map_err(refused) + } + + fn open_entries<M: MapSink, I: Iterator<Item = DataKey>>( + (key, sealed): Self::Sealed, + keys: &mut I, + map: &mut M, + ) -> Result<(), Error> { + // A field with nothing to open, such as one that is a term alone, + // has no entry in the plaintext. + if !A::opens(&sealed) { + return Ok(()); + } + A::open_into(sealed, keys, map.entry(&key).map_err(refused)?).map(|_| ()) + } +} + +/// A record opens to one map, with an entry for each field. +impl<A> Open for Record<A> +where + A: Open, + A::Staged: super::FieldsSeen, +{ + type Sealed = A::Sealed; + + fn retrieve( + &self, + stored: Self::Output, + context: Self::Context, + retrieval: &mut Retrieval, + ) -> Result<Self::Sealed, Error> { + self.0.retrieve(stored, context, retrieval) + } + + fn opens(sealed: &Self::Sealed) -> bool { + A::opens(sealed) + } + + fn open_into<S: Sink, I: Iterator<Item = DataKey>>( + sealed: Self::Sealed, + keys: &mut I, + sink: S, + ) -> Result<S::Ok, Error> { + let mut map = sink.map(None).map_err(refused)?; + A::open_entries(sealed, keys, &mut map)?; + map.end().map_err(refused) + } +} + +/// A declaration that is not there stored nothing. +impl<A: Open> Open for Option<A> { + type Sealed = Option<A::Sealed>; + + fn retrieve( + &self, + stored: Self::Output, + context: Self::Context, + retrieval: &mut Retrieval, + ) -> Result<Self::Sealed, Error> { + match (self, stored) { + (Some(declaration), Some(stored)) => { + declaration.retrieve(stored, context, retrieval).map(Some) + } + (None, None) => Ok(None), + // What is stored is not what the declaration stores. + _ => Err(Error::Aead), + } + } + + fn opens(sealed: &Self::Sealed) -> bool { + sealed.as_ref().is_some_and(A::opens) + } + + fn open_into<S: Sink, I: Iterator<Item = DataKey>>( + sealed: Self::Sealed, + keys: &mut I, + sink: S, + ) -> Result<S::Ok, Error> { + match sealed { + Some(sealed) => A::open_into(sealed, keys, sink), + None => Err(Error::Aead), + } + } +} + +/// The fields of a record open in their own order, each into its entry. +impl<A: Open> Open for Fields<A> { + type Sealed = Vec<<Entry<A> as Open>::Sealed>; + + fn retrieve( + &self, + stored: Self::Output, + context: Self::Context, + retrieval: &mut Retrieval, + ) -> Result<Self::Sealed, Error> { + if stored.len() != self.0.len() { + return Err(Error::Aead); + } + self.0 + .iter() + .zip(stored) + .map(|(entry, stored)| entry.retrieve(stored, context.clone(), retrieval)) + .collect() + } + + fn opens(sealed: &Self::Sealed) -> bool { + sealed.iter().any(<Entry<A> as Open>::opens) + } + + fn open_into<S: Sink, I: Iterator<Item = DataKey>>( + sealed: Self::Sealed, + keys: &mut I, + sink: S, + ) -> Result<S::Ok, Error> { + let mut map = sink.map(Some(sealed.len())).map_err(refused)?; + Self::open_entries(sealed, keys, &mut map)?; + map.end().map_err(refused) + } + + fn open_entries<M: MapSink, I: Iterator<Item = DataKey>>( + sealed: Self::Sealed, + keys: &mut I, + map: &mut M, + ) -> Result<(), Error> { + sealed + .into_iter() + .try_for_each(|entry| <Entry<A> as Open>::open_entries(entry, keys, map)) + } +} + +/// The context field is in the clear, so it is read before any key is +/// asked for, and the fields' contexts come from it. It is written back as +/// an entry of the record. +impl<A> Open for ContextFrom<A> +where + A: Open<Context = RecordContext>, +{ + type Sealed = (A::Sealed, <Entry<Clear<()>> as Open>::Sealed); + + fn retrieve( + &self, + (fields, context_field): Self::Output, + context: DeclaredContext, + retrieval: &mut Retrieval, + ) -> Result<Self::Sealed, Error> { + let base = (&context_field).into_label().map_err(refused)?; + let context = RecordContext { + declared: context, + base, + }; + Ok(( + self.0.retrieve(fields, context, retrieval)?, + self.1.retrieve(context_field, (), retrieval)?, + )) + } + + fn opens(_: &Self::Sealed) -> bool { + true + } + + fn open_into<S: Sink, I: Iterator<Item = DataKey>>( + sealed: Self::Sealed, + keys: &mut I, + sink: S, + ) -> Result<S::Ok, Error> { + let mut map = sink.map(None).map_err(refused)?; + Self::open_entries(sealed, keys, &mut map)?; + map.end().map_err(refused) + } + + fn open_entries<M: MapSink, I: Iterator<Item = DataKey>>( + (fields, context_field): Self::Sealed, + keys: &mut I, + map: &mut M, + ) -> Result<(), Error> { + A::open_entries(fields, keys, map)?; + <Entry<Clear<()>> as Open>::open_entries(context_field, keys, map) + } +} diff --git a/packages/stack-encrypt/src/target/declaration/query.rs b/packages/stack-encrypt/src/target/declaration/query.rs new file mode 100644 index 000000000..909bab551 --- /dev/null +++ b/packages/stack-encrypt/src/target/declaration/query.rs @@ -0,0 +1,162 @@ +//! SPIKE, not for merging. The query half of a declaration. +//! +//! A query sends the term that an index stores, so that the database can +//! compare the two. A declaration already says which index a field has and +//! which context the field's term is derived under. [`Answers`] reads the +//! query from it: the declaration of the term that one operator sends. +//! +//! So one declaration of a field serves three calls. It seals the field, +//! it opens the field ([`Open`](super::Open)), and it gives the query +//! term for an operator the field's index answers. +//! +//! Whether a field answers an operator is checked by the compiler. +//! `ciphertext().query::<Eq, _>()` does not compile, because a ciphertext +//! has no index. Two indexes that both answer one operator do not compile +//! either: the compiler cannot tell which one the query means. + +use std::marker::PhantomData; + +use super::{Accepting, Convert, Declaration, Entry, EqualityOf, Fields, Under, UnderField, Zip}; +use crate::op; +use crate::target::CallerContext; +use stack_kms::MaybeSend; + +/// Where in a declaration the index that answers is. The compiler works +/// this out. A caller writes `_`. +pub(crate) struct Here; +/// The index is in the left side of a [`Zip`]. +pub(crate) struct Left<At>(PhantomData<At>); +/// The index is in the right side of a [`Zip`]. +pub(crate) struct Right<At>(PhantomData<At>); + +/// A declaration with an index that answers the operator `Op`. +pub(crate) trait Answers<Op, At>: Declaration { + /// The declaration of the term a query sends for `Op`, under the + /// context this declaration derives its own term under. + type Query: Declaration<Context = Self::Context>; + + /// The declaration of the query term. + fn query_declaration(&self) -> Self::Query; +} + +/// An equality index answers `Eq` with the term it stores. +impl Answers<op::Eq, Here> for EqualityOf { + type Query = EqualityOf; + + fn query_declaration(&self) -> EqualityOf { + EqualityOf + } +} + +impl<Op, At, A, B> Answers<Op, Left<At>> for Zip<A, B> +where + A: Answers<Op, At>, + B: Declaration<Context = A::Context>, +{ + type Query = A::Query; + + fn query_declaration(&self) -> Self::Query { + self.0.query_declaration() + } +} + +impl<Op, At, A, B> Answers<Op, Right<At>> for Zip<A, B> +where + A: Declaration, + B: Answers<Op, At> + Declaration<Context = A::Context>, +{ + type Query = B::Query; + + fn query_declaration(&self) -> Self::Query { + self.1.query_declaration() + } +} + +/// The query keeps the context conversion. +impl<Op, At, A, C> Answers<Op, At> for Accepting<A, C> +where + A: Answers<Op, At>, + C: Into<A::Context> + Clone + 'static, +{ + type Query = Accepting<A::Query, C>; + + fn query_declaration(&self) -> Self::Query { + Accepting(self.0.query_declaration(), PhantomData) + } +} + +/// A conversion is of the stored target, so the query does not have it. +impl<Op, At, A, U, F, G> Answers<Op, At> for Convert<A, F, G> +where + A: Answers<Op, At>, + U: MaybeSend + 'static, + F: FnOnce(A::Output) -> U + MaybeSend + 'static, + G: Fn(U) -> A::Output, +{ + type Query = A::Query; + + fn query_declaration(&self) -> Self::Query { + self.0.query_declaration() + } +} + +/// The query term is derived under the field's own context, as the stored +/// term is. +impl<Op, At, A> Answers<Op, At> for Under<A> +where + A: Answers<Op, At>, + A::Context: From<CallerContext>, +{ + type Query = Under<A::Query>; + + fn query_declaration(&self) -> Self::Query { + Under(self.0.query_declaration(), self.1.clone()) + } +} + +impl<Op, At, A> Answers<Op, At> for UnderField<A> +where + A: Answers<Op, At>, + A::Context: From<CallerContext>, +{ + type Query = UnderField<A::Query>; + + fn query_declaration(&self) -> Self::Query { + UnderField(self.0.query_declaration(), self.1.clone()) + } +} + +/// A query's value is the value itself, and not an entry of a record. +impl<Op, At, A> Answers<Op, At> for Entry<A> +where + A: Answers<Op, At>, +{ + type Query = A::Query; + + fn query_declaration(&self) -> Self::Query { + self.0.query_declaration() + } +} + +/// A field of a plan has the index or it does not. The query term of a +/// field without it is `None`. +impl<Op, At, A> Answers<Op, At> for Option<A> +where + A: Answers<Op, At>, +{ + type Query = Option<A::Query>; + + fn query_declaration(&self) -> Self::Query { + self.as_ref().map(Answers::query_declaration) + } +} + +impl<A: Declaration> Fields<A> { + /// The declaration of the field `name`, for a query of that field. + pub(crate) fn field(&self, name: &str) -> Option<&A> { + self.0 + .iter() + .find(|entry| entry.1 == name) + .map(|entry| &entry.0) + } +} diff --git a/packages/stack-encrypt/src/target/mod.rs b/packages/stack-encrypt/src/target/mod.rs index 602be99f9..6a53c0cc2 100644 --- a/packages/stack-encrypt/src/target/mod.rs +++ b/packages/stack-encrypt/src/target/mod.rs @@ -162,6 +162,9 @@ mod collections; mod context; mod conversion; pub(crate) mod core; +#[cfg(feature = "dynamic")] +#[allow(dead_code)] +pub(crate) mod declaration; pub(crate) mod index; mod input; mod operations; @@ -170,7 +173,9 @@ mod request; mod source; pub mod transcode; -pub(crate) use self::core::{bind_pending, seal_pending}; +#[cfg(test)] +pub(crate) use self::core::retrieve_requests; +pub(crate) use self::core::{encrypt_opaque, open_pending}; pub use context::{ AeadContext, Bind, BindPart, CallerContext, CheckedInput, ContextFromField, DeclaredContext, Extends, NoBind, NoScope, Parts, Scope, ScopePart, Scopes, StoredParts, diff --git a/packages/stack-encrypt/src/target/operations.rs b/packages/stack-encrypt/src/target/operations.rs index 95810f036..63435c31a 100644 --- a/packages/stack-encrypt/src/target/operations.rs +++ b/packages/stack-encrypt/src/target/operations.rs @@ -18,7 +18,7 @@ use super::context::{ AeadContext, CallerContext, DeclaredContext, Extends, StoredContext, StoredParts, }; use super::conversion::{DecryptSource, EncryptTarget}; -use super::core::{encrypt_native, open_native, Term}; +use super::core::{encrypt_opaque, open_opaque, Term}; use super::input::{AcceptsContext, NoCallerContext, RequiredContext}; use super::source::{ Borrowed, ConsumeSource, Guarded, Held, Owned, Source, SourceMode, WipeSource, @@ -1074,8 +1074,8 @@ where Encryption { build: Box::new(move |source, cipher, cx: AeadContext| match cx.sealable() { Ok(ctx) => match source.into_held() { - Held::Lent(source) => encrypt_native(source.lend(), cipher, ctx), - Held::Given(source) => encrypt_native(source, cipher, ctx), + Held::Lent(source) => encrypt_opaque(source.lend(), cipher, ctx), + Held::Given(source) => encrypt_opaque(source, cipher, ctx), }, Err(e) => { M::wipe(source); @@ -1588,7 +1588,7 @@ pub fn open<P: crate::Decrypt + zeroize::Zeroize + Send + 'static, K: 'static>( ) -> Decryption<P, K> { let context = context.into(); Decryption::open(Box::new(move |cipher| match context.validated() { - Ok(ctx) => open_native(tree, cipher, ctx).wiping(), + Ok(ctx) => open_opaque(tree, cipher, ctx).wiping(), Err(e) => Pending::failed(cipher, e), })) } diff --git a/packages/stack-encrypt/tests/common/leaves.rs b/packages/stack-encrypt/tests/common/leaves.rs index 41a4a276d..b91e13b50 100644 --- a/packages/stack-encrypt/tests/common/leaves.rs +++ b/packages/stack-encrypt/tests/common/leaves.rs @@ -20,9 +20,9 @@ use stack_kms::{ IndexKeySource, RetrieveKeyPayload, UnverifiedContext, }; use uuid::Uuid; +use vitaminc_aead::aes::{Aes256Cipher, Key as AesKey}; 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}; diff --git a/packages/stack-encrypt/tests/heap_hygiene.rs b/packages/stack-encrypt/tests/heap_hygiene.rs index f83a550a5..e65fc12b5 100644 --- a/packages/stack-encrypt/tests/heap_hygiene.rs +++ b/packages/stack-encrypt/tests/heap_hygiene.rs @@ -18,12 +18,6 @@ //! guest's linear memory after the fact, where allocator metadata and reuse //! have already overwritten most freed chunks, so it cannot see one. //! -//! One free is excluded by name: vitaminc-encrypt 0.6.0's aws-lc backend -//! (`backend::aws_lc::CipherKey::seal`, native builds only) frees an unwiped -//! plaintext buffer on every seal. That is vitaminc's to fix, not this -//! crate's; the spy reports how many it skipped, and recognises them by -//! their backtrace, so a build without symbols fails rather than passes. -//! //! The stack is not watched, and is kept out of the picture: a future the //! operation boxes (`Pending`'s `IntoFuture`) is built on the stack and //! copied into its box with every byte it does not initialise, so a watch @@ -74,9 +68,8 @@ thread_local! { /// threads, and the findings below are one set. static GATE: Mutex<()> = Mutex::new(()); -/// The marked frees seen, as backtraces; and how many were vitaminc's. +/// The marked frees seen, as backtraces. static FOUND: Mutex<Vec<String>> = Mutex::new(Vec::new()); -static UPSTREAM: Mutex<usize> = Mutex::new(0); /// The data key the JSON tests' key source last handed out, which a freed /// block must not hold either (see [`json_index`]). Set outside any @@ -112,9 +105,6 @@ static TRACKING: AtomicBool = AtomicBool::new(false); static COUNT_SIZE: AtomicUsize = AtomicUsize::new(0); static COUNTED: AtomicUsize = AtomicUsize::new(0); -/// The vitaminc frame whose free is excluded (see the module docs). -const UPSTREAM_SEAL: &str = "vitaminc_encrypt::backend::aws_lc::CipherKey::seal"; - /// Whether the `len` bytes at `ptr` hold [`MARK`]. A freed block can hold /// bytes Rust never initialised (a `Vec`'s spare capacity, a struct's /// padding), and reading those through a `&[u8]` is undefined behaviour, so @@ -182,7 +172,7 @@ unsafe impl GlobalAlloc for Spy { // own lifetime: the system allocator hands memory out as its last // owner left it, and a block that is only partly written (a boxed // future's state, a `Vec`'s spare capacity) would otherwise show - // what an earlier, excluded free left there and be blamed for it. + // what an earlier free left there and be blamed for it. let ptr = System.alloc_zeroed(layout); if !ptr.is_null() && layout.size() == COUNT_SIZE.load(Ordering::SeqCst) @@ -217,17 +207,10 @@ unsafe impl GlobalAlloc for Spy { if holds_mark(ptr, layout.size()) || holds_key(ptr, layout.size()) { BUSY.with(|busy| busy.set(true)); let trace = std::backtrace::Backtrace::force_capture().to_string(); - // Symbol demangling differs by platform: Linux writes - // `<…::CipherKey>::seal`, macOS `…::CipherKey::seal`. Match - // with the angle brackets dropped. - if trace.replace(['<', '>'], "").contains(UPSTREAM_SEAL) { - *UPSTREAM.lock().unwrap() += 1; - } else { - FOUND - .lock() - .unwrap() - .push(format!("{} bytes freed unwiped:\n{trace}", layout.size())); - } + FOUND + .lock() + .unwrap() + .push(format!("{} bytes freed unwiped:\n{trace}", layout.size())); BUSY.with(|busy| busy.set(false)); } } @@ -271,7 +254,7 @@ fn watched<T>(what: &str, f: impl FnOnce() -> T) -> T { /// Take [`GATE`], which serializes every watch: the thread-local flags /// keep other threads' allocations out of a watch, but [`FOUND`], -/// [`UPSTREAM`], [`LIVE`] and [`TRACKING`] are shared, and a test running +/// [`LIVE`] and [`TRACKING`] are shared, and a test running /// alongside on another thread (plain `cargo test`) would otherwise reset /// or switch them off mid-watch. A test that panicked holding it (a /// `should_panic` control) poisons it; the state it guards is reset on @@ -283,16 +266,11 @@ fn gate() -> std::sync::MutexGuard<'static, ()> { /// [`watched`], for a caller already holding [`GATE`]. fn watched_in_gate<T>(what: &str, f: impl FnOnce() -> T) -> T { FOUND.lock().unwrap().clear(); - *UPSTREAM.lock().unwrap() = 0; scrub_stack(); WATCHING.with(|on| on.set(true)); let out = f(); WATCHING.with(|on| on.set(false)); let found = std::mem::take(&mut *FOUND.lock().unwrap()); - let upstream = std::mem::take(&mut *UPSTREAM.lock().unwrap()); - if upstream > 0 { - eprintln!("{what}: skipped {upstream} unwiped frees in vitaminc's aws-lc seal"); - } assert!( found.is_empty(), "{what}: {} heap blocks were freed with plaintext in them:\n{}", diff --git a/packages/stack-encrypt/tests/json_leakage/profile.rs b/packages/stack-encrypt/tests/json_leakage/profile.rs index 4801bcbb7..673b0acd8 100644 --- a/packages/stack-encrypt/tests/json_leakage/profile.rs +++ b/packages/stack-encrypt/tests/json_leakage/profile.rs @@ -49,7 +49,7 @@ pub use super::chain::Rule; /// What every entry's ciphertext adds to its plaintext: the frame's version /// byte, the 96-bit random nonce and the 128-bit GCM tag -/// (`vitaminc-encrypt`'s `Aes256Cipher`). The page's "less the AEAD's fixed +/// (vitaminc-aead's `Aes256Cipher`). The page's "less the AEAD's fixed /// overhead". pub const AEAD_OVERHEAD: usize = 1 + 12 + 16; diff --git a/packages/stack-encrypt/tests/json_leakage/simulator.rs b/packages/stack-encrypt/tests/json_leakage/simulator.rs index e6ffa8f0a..8f9fdf4e9 100644 --- a/packages/stack-encrypt/tests/json_leakage/simulator.rs +++ b/packages/stack-encrypt/tests/json_leakage/simulator.rs @@ -53,7 +53,7 @@ use super::profile::{ SentOrder, Step, StoredOrder, TokenName, TokenStep, }; -/// The version byte `vitaminc-encrypt` writes at the front of every +/// The version byte vitaminc-aead's `Aes256Cipher` writes at the front of every /// ciphertext: public framing, not leakage. pub const CIPHERTEXT_FRAME: u8 = 2; diff --git a/packages/stack-encrypt/tests/roundtrip.rs b/packages/stack-encrypt/tests/roundtrip.rs index 929c6c15f..d8af9d5af 100644 --- a/packages/stack-encrypt/tests/roundtrip.rs +++ b/packages/stack-encrypt/tests/roundtrip.rs @@ -6,7 +6,7 @@ use std::collections::HashMap; -use stack_encrypt::{CipherText, ContextTag, Encrypt, PassthroughFrame, SealedValue, StackCipher}; +use stack_encrypt::{CipherText, Encrypt, PassthroughFrame, SealedValue, StackCipher}; use stack_kms::FakeDataKeySource; use vitaminc_aead::plaintext::{MapSink, Sink}; use vitaminc_aead::Decrypt; @@ -223,39 +223,6 @@ async fn nested_vec_roundtrips() { assert_eq!(pt, nested); } -/// The context a `ContextTag` binds is an AAD like any other: a value -/// sealed under `ContextTag::aad(tag)` opens under the same, and only the -/// same, tag. -#[tokio::test] -async fn context_tag_binds_and_roundtrips() { - let cipher = cipher().await; - let keyset = cipher.default_keyset(); - let ct = keyset - .encrypt_tree("token".to_string(), ContextTag::aad("user:42")) - .await - .expect("encrypt"); - - // Matching context recovers the value. - let pt: String = cipher - .decrypt(ct, ContextTag::aad("user:42")) - .await - .expect("decrypt"); - assert_eq!(pt, "token"); -} - -#[tokio::test] -async fn context_tag_wrong_context_fails() { - let cipher = cipher().await; - let keyset = cipher.default_keyset(); - let ct = keyset - .encrypt_tree("token".to_string(), ContextTag::aad("user:42")) - .await - .expect("encrypt"); - - let result: Result<String, _> = cipher.decrypt(ct, ContextTag::aad("user:99")).await; - assert!(result.is_err(), "wrong context tag must not decrypt"); -} - #[tokio::test] async fn empty_vec_roundtrips() { // An empty sequence seals an authenticated marker, so emptiness is provable. diff --git a/packages/stack-kms/fuzz/Cargo.lock b/packages/stack-kms/fuzz/Cargo.lock index 389e4a957..c429c04ce 100644 --- a/packages/stack-kms/fuzz/Cargo.lock +++ b/packages/stack-kms/fuzz/Cargo.lock @@ -2375,12 +2375,12 @@ version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "35042fb7a81d72dc43c53fec835e61027f18b4d01cc0f7e12d6c6a6ffbf3bfb9" dependencies = [ - "vitaminc-aead 0.5.1", - "vitaminc-context 0.5.1", - "vitaminc-encrypt 0.5.1", + "vitaminc-aead", + "vitaminc-context", + "vitaminc-encrypt", "vitaminc-protected 0.5.1", "vitaminc-random 0.5.1", - "vitaminc-traits 0.5.1", + "vitaminc-traits", ] [[package]] @@ -2389,12 +2389,8 @@ version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "60ae27c0d0e6980d2f30683384ed591a9dafa943b18faaa6bfb456757b5e10ef" dependencies = [ - "vitaminc-aead 0.10.0", - "vitaminc-context 0.10.0", - "vitaminc-encrypt 0.10.0", "vitaminc-protected 0.10.0", "vitaminc-random 0.10.0", - "vitaminc-traits 0.10.0", ] [[package]] @@ -2405,28 +2401,13 @@ checksum = "62cacd4dae485e98cfe5407e919187a8468dd933ea4234be5115b7d13a30f3c6" dependencies = [ "bytes", "serde", - "vitaminc-aead-derive 0.5.1", - "vitaminc-context 0.5.1", + "vitaminc-aead-derive", + "vitaminc-context", "vitaminc-protected 0.5.1", "vitaminc-random 0.5.1", "zeroize", ] -[[package]] -name = "vitaminc-aead" -version = "0.10.0" -dependencies = [ - "bytes", - "futures-util", - "serde", - "thiserror 2.0.18", - "vitaminc-aead-derive 0.10.0", - "vitaminc-context 0.10.0", - "vitaminc-protected 0.10.0", - "vitaminc-random 0.10.0", - "zeroize", -] - [[package]] name = "vitaminc-aead-derive" version = "0.5.1" @@ -2438,15 +2419,6 @@ dependencies = [ "syn 3.0.3", ] -[[package]] -name = "vitaminc-aead-derive" -version = "0.10.0" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.3", -] - [[package]] name = "vitaminc-context" version = "0.5.1" @@ -2457,16 +2429,6 @@ dependencies = [ "vitaminc-protected 0.5.1", ] -[[package]] -name = "vitaminc-context" -version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "431a7fb023688dba855e52b9c4e44c942418dde8ea08a2b115cf6a7f762fa5b9" -dependencies = [ - "mutants", - "vitaminc-protected 0.10.0", -] - [[package]] name = "vitaminc-encrypt" version = "0.5.1" @@ -2475,26 +2437,12 @@ checksum = "9fbd0e1748055e381e02033e08af385de879c4dcf32e0f6739ac0c0cf0c6f13d" dependencies = [ "aes-gcm", "aws-lc-rs", - "vitaminc-aead 0.5.1", + "vitaminc-aead", "vitaminc-protected 0.5.1", "vitaminc-random 0.5.1", "zeroize", ] -[[package]] -name = "vitaminc-encrypt" -version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e68d89e2587529db55a10fa59cb11be8a7505b4af473c8a0bec238c803190ec5" -dependencies = [ - "aes-gcm", - "aws-lc-rs", - "vitaminc-aead 0.10.0", - "vitaminc-protected 0.10.0", - "vitaminc-random 0.10.0", - "zeroize", -] - [[package]] name = "vitaminc-protected" version = "0.5.1" @@ -2620,22 +2568,6 @@ dependencies = [ "zeroize", ] -[[package]] -name = "vitaminc-traits" -version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "31fba5af175073f24768a8b06dd054ad696c7e6051dda1316c3814043a36d8e0" -dependencies = [ - "anyhow", - "bytes", - "rmp-serde", - "serde", - "thiserror 2.0.18", - "vitaminc-protected 0.10.0", - "vitaminc-random 0.10.0", - "zeroize", -] - [[package]] name = "wasi" version = "0.11.1+wasi-snapshot-preview1" @@ -3263,3 +3195,11 @@ name = "zmij" version = "1.0.20" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4de98dfa5d5b7fef4ee834d0073d560c9ca7b6c46a71d058c48db7960f8cfaf7" + +[[patch.unused]] +name = "vitaminc-aead" +version = "0.10.0" + +[[patch.unused]] +name = "vitaminc-aead-derive" +version = "0.10.0" diff --git a/packages/vitaminc-aead/Cargo.toml b/packages/vitaminc-aead/Cargo.toml index 83f2d487a..ab0c8ea08 100644 --- a/packages/vitaminc-aead/Cargo.toml +++ b/packages/vitaminc-aead/Cargo.toml @@ -18,7 +18,7 @@ rust-version = "1.89.0" publish = false [package.metadata.docs.rs] -features = ["jiff", "rust_decimal", "uuid", "hlist"] +features = ["aes", "jiff", "rust_decimal", "uuid"] rustdoc-args = ["--cfg", "docsrs"] [dependencies] @@ -31,9 +31,6 @@ bytes = { version = "^1", features = ["serde"] } serde = { version = "1", features = ["derive"] } thiserror = "2.0.18" zeroize = { version = "1", features = ["derive"] } -# `stream::iter(..).buffered(..)` for the bounded per-leaf defaults of -# `AsyncCipher`'s `seal_many` and `open_many`. No runtime. -futures-util = { version = "0.3.31", default-features = false, features = ["alloc"] } # Optional `Encrypt` sources for logical types: a date and a timestamp, # a decimal, and a uuid. Each is a few lines over the core model. @@ -57,19 +54,27 @@ version = "1" default-features = false optional = true +# The AES-256-GCM cipher (`aes`): aws-lc-rs on native targets, RustCrypto's +# aes-gcm on wasm32. +[target.'cfg(not(target_arch = "wasm32"))'.dependencies.aws-lc-rs] +version = "1.17.0" +optional = true + +[dependencies.aes-gcm] +version = "0.10" +default-features = false +features = ["aes", "alloc", "zeroize"] +optional = true + [features] +# The AES-256-GCM `Cipher` and its key, in the `aes` module. +aes = ["dep:aws-lc-rs", "dep:aes-gcm"] +# Not an API. Forces the RustCrypto backend on native targets, so its tests +# run without a wasm toolchain. +_test-rust-crypto-backend = ["aes"] jiff = ["dep:jiff"] rust_decimal = ["dep:rust_decimal"] uuid = ["dep:uuid"] -# Opt-in HList-based ciphertext shape. Trades the dynamic `Cipher::Ok` enum -# (heap-allocated `Vec`s, `Box<dyn Any>` passthrough) for a per-call typed -# builder where the full structural shape is encoded in the type system — -# no heap nodes, no type erasure, statically-typed passthrough access. -# -# Best suited to native Rust performance-sensitive paths; the dynamic -# default remains preferable for wasm32 / JS bindings where bundle size -# and runtime-determined shapes matter more. -hlist = [] # Not an API. Makes `plaintext::render`, the path notation tests assert # against, reachable from sibling crates' tests. Only path-only # dev-dependencies turn it on, so no published build has it. @@ -86,6 +91,12 @@ quickcheck = "1.1.0" quickcheck_macros = "1.2.0" # Compile-fail tests for the derive macros' guards — see tests/derive_ui.rs. trybuild = "1.0.118" -futures-executor = "0.3.31" serde_json = "1" jiff = { version = "1.0.1", default-features = false } + +[target.'cfg(target_arch = "wasm32")'.dev-dependencies] +wasm-bindgen-test = "0.3" + +[[test]] +name = "aes_cipher" +required-features = ["aes"] diff --git a/packages/vitaminc-aead/README.md b/packages/vitaminc-aead/README.md index b2e785d9d..45161059e 100644 --- a/packages/vitaminc-aead/README.md +++ b/packages/vitaminc-aead/README.md @@ -26,16 +26,16 @@ This crate provides the data model and the traversals for encrypting structured ## Key Features - **One data model**: a value is described once, as an [`Encrypt`] that walks itself into a [`Sink`]. Encryption, decryption, the transport frame, index terms and host bindings are all sinks or sources of the same model, so there is no intermediate value type to convert through. -- **A cipher is `seal` and `open`**: the [`Cipher`] trait seals and opens one leaf; every rule about the *shape* of a value (how map entries are bound to their keys, how sequence elements are bound to their sequence but not to their index or count, how empty containers are authenticated, the refusal of a container with nothing sealed) lives once in the encrypting sink and the opening walk. [`AsyncCipher`] is the same for a cipher that has to be awaited, with batching hooks for a remote key service. +- **A cipher is `seal` and `open`**: the [`Cipher`] trait seals and opens one leaf; every rule about the *shape* of a value (how map entries are bound to their keys, how sequence elements are bound to their sequence but not to their index or count, how empty containers are authenticated, the refusal of a container with nothing sealed) lives once in the encrypting sink and the opening walk. - **Typed decryption names a sink**: a [`Decrypt`] target is any type that names the sink that builds it, so a ciphertext is decoded straight into a struct, a `Vec`, an `Option`, a `Protected<T>`, or a host value. Decoding is strict. - **Self-describing leaves**: every scalar seals as a tagged leaf (`[tag] ++ payload`), with an optional logical type (a date, a timestamp, a decimal, a UUID) over its physical kind, so a value encrypted from Rust, Go or JavaScript opens from any of them. -- **Flexible AAD handling**: the [`IntoAad`] trait lets strings, byte slices, integers, tuples, and `()` all be used as additional authenticated data, and [`ContextTag`] moves the obligation to supply it into the type system. +- **Flexible AAD handling**: the [`IntoAad`] trait lets strings, byte slices, integers, tuples, and `()` all be used as additional authenticated data. - **Protected types integration**: works with `vitaminc-protected` so sensitive plaintext stays wrapped through encrypt and decrypt. - **Side-channel-aware errors**: a cipher's [`Unspecified`] error reveals nothing about the cause of a failure. ## Usage -The examples below use a cipher that keeps the plaintext in the clear and authenticates the AAD, so they run without a key. A real one is `vitaminc_encrypt::Aes256Cipher`. +The examples below use a cipher that keeps the plaintext in the clear and authenticates the AAD, so they run without a key. A real one is `aes::Aes256Cipher`, built with the `aes` feature. ```rust # use vitaminc_aead::{Cipher, Context, Unspecified}; @@ -78,7 +78,7 @@ use vitaminc_aead::{Cipher, Context, Unspecified}; use vitaminc_protected::{Controlled, Protected}; /// Not a cipher: it stores the plaintext as it is, to show the trait -/// shape only. For real data, use `vitaminc_encrypt::Aes256Cipher`. +/// shape only. For real data, use `vitaminc_aead::aes::Aes256Cipher`. struct ClearTextForExamplesOnly; impl Cipher for ClearTextForExamplesOnly { @@ -101,8 +101,6 @@ impl Cipher for ClearTextForExamplesOnly { } ``` -A cipher that has to be awaited implements [`AsyncCipher`] instead, and drives [`encrypt_async`] and [`decrypt_async`]. The walk of the value finishes before the first await, so the future holds only the planned leaves and is `Send` even when the source is not. `seal_many` and `open_many` take every leaf of one document at once, for a provider with a batch API. - ### Encrypting data [`encrypt`] takes any [`Encrypt`] source. Built in: strings, bytes (`Vec<u8>`, `&[u8]`, `[u8; N]`), the integers `i8`, `i16`, `i32`, `i64`, `i128`, `u16`, `u32`, `u64` and `u128`, `f32` and `f64`, `bool`, `Option<T>`, `Vec<T>`, `HashMap<String, T>` and `BTreeMap<String, T>`, `Protected<T>` (walked by reference inside the wrapper), a `ProtectedRef` borrow from `as_protected_ref()` (walked as the `&Protected<T>` it came from), and, behind features, `jiff`, `rust_decimal` and `uuid` scalars. The result is a [`CipherText`] tree mirroring the value's shape: one sealed leaf per scalar, with the containers around them. Each source that is one leaf on its own also implements [`Scalar`], the bound for a caller that must seal exactly one leaf. @@ -266,14 +264,6 @@ the empty list is `None`, a list of two is `(a, b)`, `nonempty!(a).with(b).with( different contexts and so are `"ab"` and `b"ab"`. `ContextPiece` also implements `MaybeEmpty` by the same rule the static types use, so a tree can be wrapped in `NonEmpty`. -[`ContextTag`] pairs a value with a tag that is folded into the AAD whenever it is encrypted, so a -value that must always be sealed against its context (a user id, a column name) cannot be -encrypted without it; `ContextTag::context(tag).decrypt(..)` mirrors it on the way out. - -[`LeafTypeAad`] binds the column type a schema expects, its physical kind and logical type, into -the AAD at both ends, so a ciphertext written under one column type fails to open under another. -The binding is a declaration, not a check of the value, and it only works when both ends supply it. - ### Working with Protected Types The crate integrates with `vitaminc-protected` so sensitive plaintext stays wrapped. A `Protected<T>` @@ -403,20 +393,9 @@ Host bindings do not convert their values into a Rust value tree. [`Frame`] is a [`Tee`] runs two sinks over one walk. `vitaminc-normalize` uses it to produce equality terms beside encryption, so a document is walked once and every term exists before any cipher is called. -### Nonce Generation - -The crate provides nonce generation utilities for AEAD operations: +### AES-256-GCM -```rust -# fn main() -> Result<(), Box<dyn std::error::Error>> { -use vitaminc_aead::{NonceGenerator, RandomNonceGenerator}; - -// Create a random nonce generator for 12-byte nonces -let generator = RandomNonceGenerator::<12>::init()?; -let nonce = generator.generate()?; -# Ok(()) -# } -``` +With the `aes` feature, the `aes` module has the crate's cipher, `Aes256Cipher`, and its 32-byte `Key`. It seals each leaf as `version ‖ nonce ‖ ciphertext ‖ tag`, under a fresh random 96-bit nonce, and binds the wire version into the leaf's AAD. It uses `aws-lc-rs` on native targets and RustCrypto's `aes-gcm` on `wasm32`. Both produce the same bytes. ## Security Considerations @@ -438,7 +417,6 @@ No optional features are enabled by default. | `jiff` | Adds `jiff::civil::Date` and `jiff::Timestamp` as sources and decrypt targets, and `Date` and `Timestamp`, a date and a UTC instant that are wiped when dropped. The wire's range for dates and timestamps is jiff's, years -9999 to 9999, in every binding, so every value opens into a jiff type. | | `rust_decimal` | Adds `rust_decimal::Decimal` encoding and decoding, and the wipeable `Decimal`. | | `uuid` | Adds `uuid::Uuid` encoding and decoding, and the wipeable `Uuid`. | -| `hlist` | Exposes the static heterogeneous-list API in `hlist`. | ## Compatibility @@ -453,25 +431,20 @@ Vitamin C is brought to you by the team at [CipherStash](https://cipherstash.com License: MIT <!-- GitHub API links target the latest release; src/lib.rs resolves these for rustdoc. --> -[`AsyncCipher`]: https://docs.rs/vitaminc-aead/latest/vitaminc_aead/trait.AsyncCipher.html [`CipherText`]: https://docs.rs/vitaminc-aead/latest/vitaminc_aead/enum.CipherText.html [`Cipher`]: https://docs.rs/vitaminc-aead/latest/vitaminc_aead/trait.Cipher.html -[`ContextTag`]: https://docs.rs/vitaminc-aead/latest/vitaminc_aead/struct.ContextTag.html [`Decrypt`]: https://docs.rs/vitaminc-aead/latest/vitaminc_aead/trait.Decrypt.html [`Encrypt`]: https://docs.rs/vitaminc-aead/latest/vitaminc_aead/trait.Encrypt.html [`FrameWriter`]: https://docs.rs/vitaminc-aead/latest/vitaminc_aead/struct.FrameWriter.html [`Frame`]: https://docs.rs/vitaminc-aead/latest/vitaminc_aead/struct.Frame.html [`IntoAad`]: https://docs.rs/vitaminc-aead/latest/vitaminc_aead/trait.IntoAad.html -[`LeafTypeAad`]: https://docs.rs/vitaminc-aead/latest/vitaminc_aead/struct.LeafTypeAad.html [`PassthroughFrame`]: https://docs.rs/vitaminc-aead/latest/vitaminc_aead/struct.PassthroughFrame.html [`Scalar`]: https://docs.rs/vitaminc-aead/latest/vitaminc_aead/trait.Scalar.html [`Sink::passthrough`]: https://docs.rs/vitaminc-aead/latest/vitaminc_aead/trait.Sink.html#tymethod.passthrough [`Sink`]: https://docs.rs/vitaminc-aead/latest/vitaminc_aead/trait.Sink.html [`Tee`]: https://docs.rs/vitaminc-aead/latest/vitaminc_aead/struct.Tee.html [`Unspecified`]: https://docs.rs/vitaminc-aead/latest/vitaminc_aead/struct.Unspecified.html -[`decrypt_async`]: https://docs.rs/vitaminc-aead/latest/vitaminc_aead/fn.decrypt_async.html [`decrypt_into`]: https://docs.rs/vitaminc-aead/latest/vitaminc_aead/fn.decrypt_into.html [`decrypt`]: https://docs.rs/vitaminc-aead/latest/vitaminc_aead/fn.decrypt.html -[`encrypt_async`]: https://docs.rs/vitaminc-aead/latest/vitaminc_aead/fn.encrypt_async.html [`encrypt`]: https://docs.rs/vitaminc-aead/latest/vitaminc_aead/fn.encrypt.html [`to_frame`]: https://docs.rs/vitaminc-aead/latest/vitaminc_aead/fn.to_frame.html diff --git a/packages/vitaminc-aead/src/aad/leaf_type.rs b/packages/vitaminc-aead/src/aad/leaf_type.rs deleted file mode 100644 index be8b76ddc..000000000 --- a/packages/vitaminc-aead/src/aad/leaf_type.rs +++ /dev/null @@ -1,548 +0,0 @@ -//! Binding an expected leaf type into the AAD. -//! -//! [`LeafTypeAad`] is for a **schema-aware** caller, one that already knows -//! what type a field must hold. It binds that expectation into the AAD at -//! both ends, so a ciphertext of the wrong type fails authentication before -//! any plaintext is released. A type confusion becomes an ordinary AEAD -//! failure. -//! -//! Binding is opt-in, and stays so. If every leaf's type were bound by -//! default, a reader would need the type to open the data: a JavaScript or -//! Go reader with no schema, which decodes whatever the leaf's tag says, -//! could no longer open rows a Rust writer sealed. Self-describing data -//! that any binding can read is the default; a caller that holds a schema -//! on both sides adds this binding on top. -//! -//! The self-describing path never binds it. A sealed leaf carries its own -//! tag inside the AEAD, which is knowable only *after* decryption; AAD must -//! be known *before*, so it can only carry an expectation the caller -//! already holds. The two are complementary: the inner tag makes a value -//! self-describing, and this binding lets a schema enforce a type up front. -//! -//! The expectation a schema holds is "this column is a date", not "this -//! column is an int", so what is bound is the physical kind **and** the -//! logical id. An int's width is not part of it: width is a hint end to -//! end, and a column of `i32`s and a column of `i64`s are both int columns. -//! The logical type's parameter is not bound either: a decimal's scale -//! varies from value to value within one column, and binding it would -//! refuse `1.50` next to `1.5`. The parameter is still validated after -//! opening, by [`Logical::admits`](crate::plaintext::Logical::admits). -//! -//! A known logical type is stored as exactly one kind, so -//! [`LeafTypeAad::logical`] derives the kind from it rather than taking -//! one: a pair that disagrees, such as text bound as a date, cannot be -//! written, and a column with a logical type has one binding, not one per -//! kind a caller might pick. Only for a logical id this build does not know -//! ([`LeafTypeAad::unknown`]) does the caller name the kind, since nothing -//! here can know it. -//! -//! The binding is a declaration, not a check. Nothing compares it with the -//! value being sealed, so a writer that binds a date and seals text has -//! made a ciphertext that opens, as text, under the date binding and under -//! nothing else. What the binding authenticates is that writer and reader -//! agree on the type; what the value is, the leaf's own tag says. - -use std::borrow::Cow; - -use crate::plaintext::kinds::id; -use crate::{ContextPiece, IntoContext, Kind, KnownLogical, UnknownLogicalId}; - -/// Domain-separation label for the leaf-type binding. Leading the list -/// keeps the context disjoint from a caller binding `(base, kind, id)` as a -/// list of its own. Replaces `vitaminc/aead-value/leaf-type/v1`, which -/// bound the leaf tag alone; a ciphertext bound under that label does not -/// open under this one. -const LEAF_TYPE_DOMAIN: &[u8] = b"vitaminc/aead/leaf-type/v2"; - -/// A context that binds an expected leaf type onto a base context. -/// -/// Built on a base context (anything implementing [`IntoContext`], -/// typically the caller's schema context) by one of three constructors, -/// one per shape of column: -/// -/// - [`physical`](Self::physical): a [`Kind`] with no logical type; -/// - [`logical`](Self::logical): a [`KnownLogical`], over the one kind it is -/// stored as; -/// - [`unknown`](Self::unknown): an [`UnknownLogicalId`] from a newer build, -/// over a kind the caller names. -/// -/// None takes a logical type's parameter, which is never bound, and none -/// can pair a known logical type with a kind it is not stored as, so there -/// is nothing to check and nothing to fail. -/// -/// As a context it is the four-part list `(domain, base, kind, id)`, with -/// the base's own parts intact, the kind's wire byte as a `u8` leaf and -/// the id as a `u8` leaf, `0` for no logical type. The same binding must -/// be supplied on decrypt or authentication fails. -/// -/// ``` -/// use vitaminc_aead::{Kind, KnownLogical, LeafTypeAad, UnknownLogicalId}; -/// -/// // A column of plain integers, of any width. -/// let age = LeafTypeAad::physical(("users", "age"), Kind::Int); -/// // A column of dates, bound over int, the kind a date is stored as. -/// let signed_up = LeafTypeAad::logical(("users", "signed_up"), KnownLogical::Date); -/// // A column of decimals, of any scale. -/// let price = LeafTypeAad::logical(("orders", "price"), KnownLogical::Decimal); -/// // A column whose logical type is newer than this build. -/// let id = UnknownLogicalId::new(200).expect("above the last known id"); -/// let future = LeafTypeAad::unknown(("orders", "eta"), Kind::Int, id); -/// ``` -/// -/// A schema that stores each column's kind and logical id, as a -/// cross-language one does, picks the constructor from the id: -/// -/// ``` -/// use vitaminc_aead::{Kind, KnownLogical, LeafTypeAad, UnknownLogicalId}; -/// -/// fn column(name: &str, kind: Kind, logical_id: u8) -> LeafTypeAad<'_> { -/// if let Some(known) = KnownLogical::from_id(logical_id) { -/// // A known logical type brings its own kind. -/// LeafTypeAad::logical(name, known) -/// } else if let Some(unknown) = UnknownLogicalId::new(logical_id) { -/// LeafTypeAad::unknown(name, kind, unknown) -/// } else { -/// LeafTypeAad::physical(name, kind) -/// } -/// } -/// # let _ = column("price", Kind::Int, 4); -/// ``` -/// -/// The binding is associated data, not a secret, so it is `Debug` and -/// `Clone`: a caller can keep one per column and clone it for each row. -#[derive(Clone, Debug)] -pub struct LeafTypeAad<'a> { - base: ContextPiece<'a>, - kind: Kind, - id: u8, -} - -impl<'a> LeafTypeAad<'a> { - /// Bind `kind`, with no logical type, as the expected leaf type onto - /// `base`: a column of plain values of that kind. - pub fn physical(base: impl IntoContext<'a>, kind: Kind) -> Self { - Self::bind(base, kind, id::NONE) - } - - /// Bind `logical`, over the kind it is stored as - /// ([`KnownLogical::kind`]), as the expected leaf type onto `base`: a - /// column of that logical type, whatever each value's parameter, such - /// as a decimal's scale or a timestamp's unit. - pub fn logical(base: impl IntoContext<'a>, logical: KnownLogical) -> Self { - Self::bind(base, logical.kind(), logical.id()) - } - - /// Bind the logical id `logical`, from a build newer than this one, - /// over `kind` as the expected leaf type onto `base`. This build cannot - /// know what kind that logical type is stored as, so the caller names - /// it; it must be the kind the newer build derives, or the two do not - /// agree on the binding. - pub fn unknown(base: impl IntoContext<'a>, kind: Kind, logical: UnknownLogicalId) -> Self { - Self::bind(base, kind, logical.get()) - } - - fn bind(base: impl IntoContext<'a>, kind: Kind, id: u8) -> Self { - Self { - base: base.into_context(), - kind, - id, - } - } -} - -impl<'a> IntoContext<'a> for LeafTypeAad<'a> { - fn into_context(self) -> ContextPiece<'a> { - ContextPiece::List(vec![ - ContextPiece::Bytes(Cow::Borrowed(LEAF_TYPE_DOMAIN)), - self.base, - ContextPiece::U8(self.kind.to_wire()), - ContextPiece::U8(self.id), - ]) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::plaintext::record::{record, Event, Owned, Record}; - use crate::plaintext::{Int, Logical, Physical, Raw}; - use crate::seal::mock::{Leaf, Mock, Refused}; - use crate::{decrypt, decrypt_into, encrypt, Context, DecryptError, IntoAad, Node}; - - fn hex(bytes: &[u8]) -> String { - bytes.iter().map(|b| format!("{b:02x}")).collect() - } - - /// The exact bytes are the type-binding commitment: the list - /// `(domain, base, kind, id)` of typed parts. Changing them breaks - /// decryption of every schema-bound ciphertext. - #[test] - fn pins_the_context_bytes_with_no_logical_type() { - let bound = LeafTypeAad::physical("ctx", Kind::Int).into_aad(); - let expected = Context::pae(&[ - LEAF_TYPE_DOMAIN.into_aad().as_bytes(), - "ctx".into_aad().as_bytes(), - Kind::Int.to_wire().into_aad().as_bytes(), - 0u8.into_aad().as_bytes(), - ]); - assert_eq!(bound, expected); - // Four parts, each a typed leaf of the context encoding. - assert_eq!( - hex(bound.as_bytes()), - concat!( - "0400000000000000", - // The domain label, as bytes. - "6c00000000000000", - "0300000000000000", - "1900000000000000766974616d696e632f636f6e746578742f76616c75652f7631", - "1900000000000000766974616d696e632f636f6e746578742f62797465732f7631", - "1a00000000000000766974616d696e632f616561642f6c6561662d747970652f7632", - // The base, "ctx", as text. - "5400000000000000", - "0300000000000000", - "1900000000000000766974616d696e632f636f6e746578742f76616c75652f7631", - "1800000000000000766974616d696e632f636f6e746578742f757466382f7631", - "0300000000000000637478", - // The kind, int, as a u8. - "5300000000000000", - "0300000000000000", - "1900000000000000766974616d696e632f636f6e746578742f76616c75652f7631", - "1900000000000000766974616d696e632f636f6e746578742f75382d6c652f7631", - "010000000000000002", - // No logical type, as a u8. - "5300000000000000", - "0300000000000000", - "1900000000000000766974616d696e632f636f6e746578742f76616c75652f7631", - "1900000000000000766974616d696e632f636f6e746578742f75382d6c652f7631", - "010000000000000000", - ) - ); - } - - #[test] - fn pins_the_context_bytes_with_a_logical_type() { - let bound = LeafTypeAad::logical("ctx", KnownLogical::Date).into_aad(); - let expected = Context::pae(&[ - LEAF_TYPE_DOMAIN.into_aad().as_bytes(), - "ctx".into_aad().as_bytes(), - Kind::Int.to_wire().into_aad().as_bytes(), - id::DATE.into_aad().as_bytes(), - ]); - assert_eq!(bound, expected); - // The same four parts, with the date's id. - assert_eq!( - hex(bound.as_bytes()), - concat!( - "0400000000000000", - "6c00000000000000", - "0300000000000000", - "1900000000000000766974616d696e632f636f6e746578742f76616c75652f7631", - "1900000000000000766974616d696e632f636f6e746578742f62797465732f7631", - "1a00000000000000766974616d696e632f616561642f6c6561662d747970652f7632", - "5400000000000000", - "0300000000000000", - "1900000000000000766974616d696e632f636f6e746578742f76616c75652f7631", - "1800000000000000766974616d696e632f636f6e746578742f757466382f7631", - "0300000000000000637478", - "5300000000000000", - "0300000000000000", - "1900000000000000766974616d696e632f636f6e746578742f76616c75652f7631", - "1900000000000000766974616d696e632f636f6e746578742f75382d6c652f7631", - "010000000000000002", - "5300000000000000", - "0300000000000000", - "1900000000000000766974616d696e632f636f6e746578742f76616c75652f7631", - "1900000000000000766974616d696e632f636f6e746578742f75382d6c652f7631", - "010000000000000002", - ) - ); - } - - #[test] - fn keeps_the_base_parts_intact() { - let parts = LeafTypeAad::physical(("schema", 7u64), Kind::Text).into_context(); - assert_eq!( - parts.to_string(), - "(0x766974616d696e632f616561642f6c6561662d747970652f7632, (\"schema\", 7u64), 4u8, 0u8)" - ); - assert_eq!(parts.leaves().count(), 5); - } - - #[test] - fn differs_from_a_map_entry_and_from_a_bare_list() { - // The domain label keeps the binding disjoint from the map-entry - // derivation and from a caller binding `(base, kind, id)` as a list - // of their own. - let leaf = LeafTypeAad::physical("ctx", Kind::Int).into_aad(); - assert_ne!(leaf, "ctx".into_aad().for_map_entry("\x02")); - let bare = ContextPiece::List(vec![ - "ctx".into_context(), - ContextPiece::U8(Kind::Int.to_wire()), - ContextPiece::U8(0), - ]); - assert_ne!(leaf, bare.into_aad()); - } - - /// The four parts the binding is, built by hand. - fn parts(kind: Kind, id: u8) -> Context<'static> { - Context::pae(&[ - LEAF_TYPE_DOMAIN.into_aad().as_bytes(), - "ctx".into_aad().as_bytes(), - kind.to_wire().into_aad().as_bytes(), - id.into_aad().as_bytes(), - ]) - } - - const ALL_KINDS: [Kind; 6] = [ - Kind::Null, - Kind::Bool, - Kind::Int, - Kind::Float, - Kind::Text, - Kind::Bytes, - ]; - - /// Every binding a constructor can build is the list - /// `(domain, base, kind, id)`, byte for byte: each kind with id 0, each - /// known logical type over its kind and id, and every unknown id over - /// every kind. - #[test] - fn every_kind_and_logical_id_binds_its_four_parts() { - for kind in ALL_KINDS { - assert_eq!( - LeafTypeAad::physical("ctx", kind).into_aad(), - parts(kind, id::NONE), - "{kind:?}" - ); - } - let known = [ - (KnownLogical::Undefined, Kind::Null, id::UNDEFINED), - (KnownLogical::Date, Kind::Int, id::DATE), - (KnownLogical::Timestamp, Kind::Int, id::TIMESTAMP), - (KnownLogical::Decimal, Kind::Int, id::DECIMAL), - (KnownLogical::Uuid, Kind::Bytes, id::UUID), - ]; - // Every id this build knows is here. - assert_eq!( - known.map(|(_, _, id)| id), - core::array::from_fn(|i| i as u8 + 1) - ); - assert_eq!(usize::from(id::LAST_KNOWN), known.len()); - for (logical, kind, id) in known { - assert_eq!( - LeafTypeAad::logical("ctx", logical).into_aad(), - parts(kind, id), - "{logical:?}" - ); - } - for id in id::LAST_KNOWN + 1..=u8::MAX { - let unknown = UnknownLogicalId::new(id).expect("unknown"); - for kind in ALL_KINDS { - assert_eq!( - LeafTypeAad::unknown("ctx", kind, unknown).into_aad(), - parts(kind, id), - "{kind:?} with id {id}" - ); - } - } - } - - #[test] - fn is_sensitive_to_the_kind_and_the_id() { - let int = LeafTypeAad::physical("ctx", Kind::Int).into_aad(); - assert_ne!(int, LeafTypeAad::physical("ctx", Kind::Text).into_aad()); - assert_ne!( - int, - LeafTypeAad::logical("ctx", KnownLogical::Date).into_aad() - ); - assert_ne!( - LeafTypeAad::logical("ctx", KnownLogical::Date).into_aad(), - LeafTypeAad::logical("ctx", KnownLogical::Decimal).into_aad() - ); - let unknown = |id| UnknownLogicalId::new(id).expect("unknown"); - assert_ne!( - int, - LeafTypeAad::unknown("ctx", Kind::Int, unknown(200)).into_aad() - ); - assert_ne!( - LeafTypeAad::unknown("ctx", Kind::Int, unknown(200)).into_aad(), - LeafTypeAad::unknown("ctx", Kind::Int, unknown(201)).into_aad() - ); - assert_ne!( - LeafTypeAad::unknown("ctx", Kind::Int, unknown(200)).into_aad(), - LeafTypeAad::unknown("ctx", Kind::Text, unknown(200)).into_aad() - ); - } - - /// Every physical kind has a wire byte of its own, and a boolean column - /// binds like any other. - #[test] - fn every_kind_binds_differently() { - for (i, a) in ALL_KINDS.iter().enumerate() { - for b in &ALL_KINDS[i + 1..] { - assert_ne!( - LeafTypeAad::physical("ctx", *a).into_aad(), - LeafTypeAad::physical("ctx", *b).into_aad(), - "{a:?} and {b:?} bind the same" - ); - } - } - // One binding per column, cloned for each use. - let flag = LeafTypeAad::physical("flags", Kind::Bool); - let sealed = encrypt(true, &Mock, flag.clone()).expect("seals"); - assert!(decrypt::<bool, _, _>(&Mock, sealed, flag).expect("opens")); - } - - /// A known logical type binds over the one kind it is stored as, the - /// same binding as that kind with its id, so a column with a logical - /// type has a single binding. - #[test] - fn a_logical_type_binds_over_its_own_kind() { - assert_eq!(KnownLogical::Uuid.kind(), Kind::Bytes); - assert_eq!( - LeafTypeAad::logical("ctx", KnownLogical::Uuid).into_aad(), - parts(Kind::Bytes, id::UUID) - ); - assert_ne!( - LeafTypeAad::logical("ctx", KnownLogical::Uuid).into_aad(), - parts(Kind::Text, id::UUID) - ); - } - - /// The binding is associated data, so its `Debug` shows the parts. - #[test] - fn debug_shows_the_binding() { - let bound = LeafTypeAad::logical("ctx", KnownLogical::Date); - let shown = format!("{bound:?}"); - assert!(shown.contains("Int") && shown.contains("id: 2"), "{shown}"); - } - - fn date() -> LeafTypeAad<'static> { - LeafTypeAad::logical("schema", KnownLogical::Date) - } - - fn int() -> LeafTypeAad<'static> { - LeafTypeAad::physical("schema", Kind::Int) - } - - fn opens<T: crate::typed::Decrypt>( - sealed: Node<Leaf>, - aad: LeafTypeAad<'_>, - ) -> Result<T, DecryptError<crate::DecodeError, Refused>> { - decrypt(&Mock, sealed, aad) - } - - /// The binding is what the mock authenticates, so a value sealed under - /// one expected type cannot be opened under another, either way round, - /// and opens under its own. - #[test] - fn a_date_does_not_open_as_an_int_nor_an_int_as_a_date() { - let days = || Raw(Some(Logical::Date), Physical::Int(Int::I32(19_000))); - let sealed = encrypt(days(), &Mock, date()).expect("seals"); - assert!( - matches!( - opens::<i32>(sealed, int()), - Err(DecryptError::Cipher(Refused)) - ), - "a date opened under the int binding" - ); - - let sealed = encrypt(19_000i32, &Mock, int()).expect("seals"); - assert!( - matches!( - opens::<i32>(sealed, date()), - Err(DecryptError::Cipher(Refused)) - ), - "an int opened under the date binding" - ); - - let sealed = encrypt(19_000i32, &Mock, int()).expect("seals"); - assert_eq!(opens::<i32>(sealed, int()).expect("opens"), 19_000); - let sealed = encrypt(days(), &Mock, date()).expect("seals"); - let mut log = Vec::new(); - decrypt_into(&Mock, sealed, date(), Record(&mut log)).expect("opens"); - assert_eq!(log, record(days()).expect("records")); - } - - /// The int's width is not bound: an `i64` column and an `i32` column - /// are both int columns. - #[test] - fn the_width_is_not_bound() { - let sealed = encrypt(19_000i64, &Mock, int()).expect("seals"); - assert_eq!(opens::<i32>(sealed, int()).expect("opens"), 19_000); - } - - /// The scale is not bound, so one column holds decimals of any scale, - /// and each opens with the scale it was sealed with. - #[test] - fn decimals_of_different_scales_open_under_one_binding() { - let column = || LeafTypeAad::logical("price", KnownLogical::Decimal); - for (scale, mantissa) in [(2u8, 150i128), (1, 15), (0, 2)] { - let value = || { - Raw( - Some(Logical::Decimal { scale }), - Physical::Int(Int::I128(mantissa)), - ) - }; - let sealed = encrypt(value(), &Mock, column()).expect("seals"); - let mut log = Vec::new(); - decrypt_into(&Mock, sealed, column(), Record(&mut log)).expect("opens"); - assert_eq!( - log, - [Event::Scalar( - Some(Logical::Decimal { scale }), - Owned::Int(Int::I128(mantissa)) - )], - "scale {scale} did not round-trip" - ); - } - } - - /// The parameter is validated after opening, not by the binding: a leaf - /// whose scale is out of range is refused when it is read, whichever - /// binding it was sealed under. - #[test] - fn the_parameter_is_still_validated_after_opening() { - let column = || LeafTypeAad::logical("price", KnownLogical::Decimal); - // A leaf plaintext hand-built with a scale of 29, which the sink - // would never write. - let mut plaintext = vec![crate::tags::DECIMAL]; - plaintext.extend_from_slice(&(29u32 << 16).to_le_bytes()); - plaintext.extend_from_slice(&[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); - let leaf = crate::seal::Cipher::seal( - &Mock, - vitaminc_protected::Protected::new(plaintext), - &column().into_aad(), - ) - .expect("seals"); - let mut log = Vec::new(); - assert!( - matches!( - decrypt_into(&Mock, Node::Single(leaf), column(), Record(&mut log)), - Err(DecryptError::Malformed) - ), - "an out-of-range scale was read" - ); - } - - /// The old binding, `(old domain, base, tag)`, is a different context, - /// so nothing sealed under it opens under the new one. - #[test] - fn a_ciphertext_bound_under_the_old_label_does_not_open() { - let old = || { - ContextPiece::List(vec![ - ContextPiece::Bytes(Cow::Borrowed(b"vitaminc/aead-value/leaf-type/v1")), - "schema".into_context(), - ContextPiece::U8(crate::tags::INT32), - ]) - }; - let sealed = encrypt(19_000i32, &Mock, old()).expect("seals"); - assert!( - matches!( - opens::<i32>(sealed, int()), - Err(DecryptError::Cipher(Refused)) - ), - "a v1-bound ciphertext opened under v2" - ); - } -} diff --git a/packages/vitaminc-aead/src/aad/mod.rs b/packages/vitaminc-aead/src/aad/mod.rs index 20638c9ed..d4d4c338c 100644 --- a/packages/vitaminc-aead/src/aad/mod.rs +++ b/packages/vitaminc-aead/src/aad/mod.rs @@ -6,27 +6,8 @@ //! implements `IntoContext` once and gets `IntoAad` (and the PRF crate's //! `IntoPrfContext`) for free, with byte-identical results on both sides. -mod leaf_type; - -pub use leaf_type::LeafTypeAad; pub use vitaminc_context::{Context, ContextPiece, IntoContext}; -/// The associated data a context is authenticated as. Kept as a name for -/// the transition; it is [`Context`]. -#[deprecated( - since = "0.5.0", - note = "renamed to `Context`, re-exported here from `vitaminc_context`" -)] -pub type Aad<'a> = Context<'a>; - -/// The parts view of a context. Kept as a name for the transition; it is -/// [`ContextPiece`]. -#[deprecated( - since = "0.5.0", - note = "renamed to `ContextPiece`, re-exported here from `vitaminc_context`" -)] -pub type AadPiece<'a> = ContextPiece<'a>; - /// Types that can be used as the associated data of an AEAD call. /// /// This is the AEAD's view of a context. It is implemented for every type diff --git a/packages/vitaminc-aead/src/aes/backend.rs b/packages/vitaminc-aead/src/aes/backend.rs new file mode 100644 index 000000000..2f873d35f --- /dev/null +++ b/packages/vitaminc-aead/src/aes/backend.rs @@ -0,0 +1,207 @@ +//! Backend abstraction over AES-256-GCM implementations. +//! +//! Two implementations are selected via `cfg`: +//! +//! - **Native** (`cfg(not(target_arch = "wasm32"))`): `aws-lc-rs` — +//! FIPS-validated, hardware-accelerated. +//! - **Wasm32** (`cfg(target_arch = "wasm32")`): `aes-gcm` from RustCrypto — +//! pure Rust, builds without a C toolchain. +//! +//! Both implementations conform to RFC 5116 AES-256-GCM and produce +//! byte-identical ciphertext+tag output for the same inputs. +//! +//! The internal `_test-rust-crypto-backend` feature forces the RustCrypto +//! backend on native targets so CI can exercise it without wasm tooling. + +#[cfg(any(target_arch = "wasm32", feature = "_test-rust-crypto-backend"))] +mod rust_crypto; +#[cfg(any(target_arch = "wasm32", feature = "_test-rust-crypto-backend"))] +pub(crate) use rust_crypto::CipherKey; + +#[cfg(not(any(target_arch = "wasm32", feature = "_test-rust-crypto-backend")))] +mod aws_lc; +#[cfg(not(any(target_arch = "wasm32", feature = "_test-rust-crypto-backend")))] +pub(crate) use aws_lc::CipherKey; + +/// AES-256-GCM nonce length, in bytes. +pub(crate) const NONCE_LEN: usize = 12; + +#[cfg(test)] +mod tests { + use super::CipherKey; + + // wasm-pack invokes Node by default — no `wasm_bindgen_test_configure!` needed. + #[cfg(target_arch = "wasm32")] + use wasm_bindgen_test::wasm_bindgen_test; + + /// Cross-backend byte-parity check. + /// + /// The same test runs against the `aws-lc-rs` backend on native targets, + /// and against RustCrypto with the `_test-rust-crypto-backend` feature or + /// on wasm32. Both must produce the byte string in `EXPECTED`. + #[cfg_attr(not(target_arch = "wasm32"), test)] + #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)] + fn cross_backend_byte_parity() { + // Fixed inputs — chosen to exercise: non-empty plaintext, non-empty AAD, + // a plaintext length that's not a block boundary (so we cover GCM's + // partial-block handling). + let key: [u8; 32] = [ + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, + 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, + 0x1c, 0x1d, 0x1e, 0x1f, + ]; + let nonce: [u8; 12] = [ + 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, + ]; + let plaintext = b"vitaminc cross-backend parity vector"; + let aad = b"vitaminc-encrypt KAT v1"; + + // Ciphertext (36 bytes) || GCM tag (16 bytes), computed deterministically + // from the inputs above by an RFC 5116 AES-256-GCM implementation. + // Verified to be produced identically by both `aws-lc-rs` and RustCrypto + // `aes-gcm` when this test was introduced. + const EXPECTED: [u8; 52] = [ + 0x90, 0x71, 0x08, 0x4c, 0x28, 0xa2, 0x6c, 0xdc, 0x42, 0x06, 0xf5, 0xbc, 0x74, 0x09, + 0xed, 0xbc, 0x11, 0xcf, 0x32, 0x75, 0xfc, 0xd3, 0x62, 0x1c, 0xfd, 0x7c, 0x4f, 0xf2, + 0x06, 0x8b, 0x03, 0x64, 0xb1, 0x02, 0x28, 0x8d, 0xed, 0x9a, 0xa3, 0xcf, 0x46, 0x3d, + 0xa6, 0xb2, 0x0e, 0x7f, 0x86, 0x23, 0x76, 0x7a, 0xfb, 0x0a, + ]; + + let cipher = CipherKey::new(&key).expect("key construction failed"); + + let mut sealed = plaintext.to_vec(); + cipher.seal(&nonce, aad, &mut sealed).expect("seal failed"); + assert_eq!( + sealed, + EXPECTED.as_slice(), + "ciphertext+tag diverged from cross-backend KAT" + ); + + let mut to_open = sealed.clone(); + let pt_len = cipher.open(&nonce, aad, &mut to_open).expect("open failed"); + assert_eq!( + &to_open[..pt_len], + plaintext, + "round-trip plaintext mismatch" + ); + } + + // Deterministic counterparts to the quickcheck round-trip tests in + // `cipher::test`. Those property tests can't run under wasm-bindgen-test + // because quickcheck's runner uses `std::thread`, which isn't available on + // wasm32-unknown-unknown — so the cases below carry the same `#[cfg_attr]` + // attribute swap as the KAT and gate all three configurations (native + // aws-lc-rs, native RustCrypto, wasm32 RustCrypto in Node) on the same + // round-trip and failure-path behaviour. + + fn fixed_key() -> [u8; 32] { + [ + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, + 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, + 0x1c, 0x1d, 0x1e, 0x1f, + ] + } + + fn fixed_nonce() -> [u8; 12] { + [ + 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, + ] + } + + fn roundtrip(plaintext: &[u8], aad: &[u8]) { + let key = fixed_key(); + let nonce = fixed_nonce(); + let cipher = CipherKey::new(&key).expect("key"); + + let mut buf = plaintext.to_vec(); + cipher.seal(&nonce, aad, &mut buf).expect("seal"); + + let pt_len = cipher.open(&nonce, aad, &mut buf).expect("open"); + assert_eq!(&buf[..pt_len], plaintext); + } + + #[cfg_attr(not(target_arch = "wasm32"), test)] + #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)] + fn roundtrip_no_aad() { + roundtrip(b"hello world", b""); + } + + #[cfg_attr(not(target_arch = "wasm32"), test)] + #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)] + fn roundtrip_with_aad() { + roundtrip(b"hello world", b"associated data"); + } + + #[cfg_attr(not(target_arch = "wasm32"), test)] + #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)] + fn roundtrip_empty_plaintext() { + roundtrip(b"", b"some aad"); + } + + #[cfg_attr(not(target_arch = "wasm32"), test)] + #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)] + fn roundtrip_multi_block_plaintext() { + // 200 bytes — spans multiple AES blocks (16B each) plus a partial tail, + // catching any block-boundary handling regression. + let pt: Vec<u8> = (0..200u8).collect(); + roundtrip(&pt, b"multi-block aad"); + } + + #[cfg_attr(not(target_arch = "wasm32"), test)] + #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)] + fn open_fails_with_wrong_aad() { + let key = fixed_key(); + let nonce = fixed_nonce(); + let cipher = CipherKey::new(&key).expect("key"); + + let mut buf = b"payload".to_vec(); + cipher.seal(&nonce, b"correct-aad", &mut buf).expect("seal"); + + let mut tampered = buf.clone(); + assert!( + cipher.open(&nonce, b"wrong-aad", &mut tampered).is_err(), + "open must reject mismatched AAD" + ); + } + + #[cfg_attr(not(target_arch = "wasm32"), test)] + #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)] + fn open_fails_with_wrong_key() { + let nonce = fixed_nonce(); + + let key_a = fixed_key(); + let mut key_b = fixed_key(); + key_b[0] ^= 0xff; + + let cipher_a = CipherKey::new(&key_a).expect("key a"); + let cipher_b = CipherKey::new(&key_b).expect("key b"); + + let mut buf = b"payload".to_vec(); + cipher_a.seal(&nonce, b"", &mut buf).expect("seal"); + + assert!( + cipher_b.open(&nonce, b"", &mut buf).is_err(), + "open must reject ciphertext sealed under a different key" + ); + } + + #[cfg_attr(not(target_arch = "wasm32"), test)] + #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)] + fn open_fails_with_tampered_ciphertext() { + let key = fixed_key(); + let nonce = fixed_nonce(); + let cipher = CipherKey::new(&key).expect("key"); + + let mut buf = b"payload".to_vec(); + cipher.seal(&nonce, b"", &mut buf).expect("seal"); + + // Flip a bit in the ciphertext (not the tag) — GCM authentication + // must catch this. + buf[0] ^= 0x01; + + assert!( + cipher.open(&nonce, b"", &mut buf).is_err(), + "open must reject ciphertext whose bytes have been modified" + ); + } +} diff --git a/packages/vitaminc-aead/src/aes/backend/aws_lc.rs b/packages/vitaminc-aead/src/aes/backend/aws_lc.rs new file mode 100644 index 000000000..c154b69e1 --- /dev/null +++ b/packages/vitaminc-aead/src/aes/backend/aws_lc.rs @@ -0,0 +1,90 @@ +//! `aws-lc-rs` backend for AES-256-GCM. + +use crate::Unspecified; +use aws_lc_rs::aead::{Aad as LcAad, LessSafeKey, Nonce as LcNonce, UnboundKey, AES_256_GCM}; +use zeroize::Zeroize; + +/// The AES-GCM tag length. +const TAG_LEN: usize = 16; + +pub(crate) struct CipherKey(LessSafeKey); + +impl CipherKey { + pub(crate) fn new(key_bytes: &[u8; 32]) -> Result<Self, Unspecified> { + let unbound = UnboundKey::new(&AES_256_GCM, key_bytes.as_ref()).map_err(|_| Unspecified)?; + Ok(Self(LessSafeKey::new(unbound))) + } + + /// Encrypts `in_out` in place and appends the authentication tag. + pub(crate) fn seal( + &self, + nonce: &[u8], + aad: &[u8], + in_out: &mut Vec<u8>, + ) -> Result<(), Unspecified> { + reserve_tag(in_out); + let nonce = LcNonce::try_assume_unique_for_key(nonce).map_err(|_| Unspecified)?; + self.0 + .seal_in_place_append_tag(nonce, LcAad::from(aad), in_out) + .map_err(|_| Unspecified)?; + Ok(()) + } + + /// Decrypts `in_out` (ciphertext || tag) in place. Returns the plaintext + /// length — `in_out[..len]` is the plaintext after the call. + pub(crate) fn open( + &self, + nonce: &[u8], + aad: &[u8], + in_out: &mut [u8], + ) -> Result<usize, Unspecified> { + let nonce = LcNonce::try_assume_unique_for_key(nonce).map_err(|_| Unspecified)?; + self.0 + .open_in_place(nonce, LcAad::from(aad), in_out) + .map(|plaintext| plaintext.len()) + .map_err(|_| Unspecified) + } +} + +/// Make room in `buf` for the tag without leaving its plaintext behind. +/// +/// aws-lc-rs appends the tag's space to the buffer before it encrypts, while +/// the buffer still holds plaintext. If the buffer has no room, the `Vec` +/// moves, and the block it leaves is freed with the plaintext in it. So the +/// room is made here first, and the old block is wiped before it is freed. +fn reserve_tag(buf: &mut Vec<u8>) { + if buf.capacity() - buf.len() < TAG_LEN { + let mut grown = Vec::with_capacity(buf.len() + TAG_LEN); + grown.extend_from_slice(buf); + // Zeroes the whole allocation, spare capacity too, then clears it. + buf.zeroize(); + *buf = grown; + } +} + +#[cfg(test)] +mod tests { + use super::{reserve_tag, TAG_LEN}; + + #[test] + fn a_full_buffer_gains_room_for_the_tag_and_keeps_its_bytes() { + let mut buf = b"plaintext".to_vec(); + buf.shrink_to_fit(); + reserve_tag(&mut buf); + assert_eq!(buf, b"plaintext", "the bytes should be unchanged"); + assert!( + buf.capacity() - buf.len() >= TAG_LEN, + "there should be room for the tag, capacity {}", + buf.capacity() + ); + } + + #[test] + fn a_buffer_with_room_is_not_moved() { + let mut buf = Vec::with_capacity(9 + TAG_LEN); + buf.extend_from_slice(b"plaintext"); + let before = buf.as_ptr(); + reserve_tag(&mut buf); + assert_eq!(buf.as_ptr(), before, "a buffer with room should stay put"); + } +} diff --git a/packages/vitaminc-aead/src/aes/backend/rust_crypto.rs b/packages/vitaminc-aead/src/aes/backend/rust_crypto.rs new file mode 100644 index 000000000..6f856b2ad --- /dev/null +++ b/packages/vitaminc-aead/src/aes/backend/rust_crypto.rs @@ -0,0 +1,53 @@ +//! RustCrypto `aes-gcm` backend for AES-256-GCM. + +use crate::Unspecified; +use aes_gcm::aead::{AeadInPlace, KeyInit, Tag}; +use aes_gcm::{Aes256Gcm, Key, Nonce}; + +/// The AES-GCM tag length. This backend splits the tag off the buffer +/// itself; `aws-lc-rs` handles the tag internally, so only this backend +/// needs the constant. +const TAG_LEN: usize = 16; + +pub(crate) struct CipherKey(Aes256Gcm); + +impl CipherKey { + pub(crate) fn new(key_bytes: &[u8; 32]) -> Result<Self, Unspecified> { + let key = Key::<Aes256Gcm>::from_slice(key_bytes); + Ok(Self(Aes256Gcm::new(key))) + } + + /// Encrypts `in_out` in place and appends the authentication tag. + pub(crate) fn seal( + &self, + nonce: &[u8], + aad: &[u8], + in_out: &mut Vec<u8>, + ) -> Result<(), Unspecified> { + let nonce: &[u8; super::NONCE_LEN] = nonce.try_into().map_err(|_| Unspecified)?; + let nonce = Nonce::from_slice(nonce); + self.0 + .encrypt_in_place(nonce, aad, in_out) + .map_err(|_| Unspecified) + } + + /// Decrypts `in_out` (ciphertext || tag) in place. Returns the plaintext + /// length — `in_out[..len]` is the plaintext after the call. The tag bytes + /// at the tail are left untouched. + pub(crate) fn open( + &self, + nonce: &[u8], + aad: &[u8], + in_out: &mut [u8], + ) -> Result<usize, Unspecified> { + let plaintext_len = in_out.len().checked_sub(TAG_LEN).ok_or(Unspecified)?; + let nonce: &[u8; super::NONCE_LEN] = nonce.try_into().map_err(|_| Unspecified)?; + let nonce = Nonce::from_slice(nonce); + let (ciphertext, tag_bytes) = in_out.split_at_mut(plaintext_len); + let tag = Tag::<Aes256Gcm>::from_slice(tag_bytes); + self.0 + .decrypt_in_place_detached(nonce, aad, ciphertext, tag) + .map_err(|_| Unspecified)?; + Ok(plaintext_len) + } +} diff --git a/packages/vitaminc-aead/src/aes/cipher.rs b/packages/vitaminc-aead/src/aes/cipher.rs new file mode 100644 index 000000000..c8c00668d --- /dev/null +++ b/packages/vitaminc-aead/src/aes/cipher.rs @@ -0,0 +1,569 @@ +use super::backend::{CipherKey, NONCE_LEN}; +use super::Key; +use crate::seal::Cipher; +use crate::{ + CipherTextBuilder, Context, IntoAad, LocalCipherText, NonceGenerator, RandomNonceGenerator, + Unspecified, WIRE_VERSION, +}; +use vitaminc_protected::Protected; + +/// Implements AES-256-GCM. Backend is selected at compile time: +/// `aws-lc-rs` on native targets, `aes-gcm` (RustCrypto) on `wasm32`. +/// +/// This [`Cipher`] seals and opens one +/// tagged leaf under the AAD the walk derived for the leaf's place in the +/// tree, and nothing else. The container logic (element and entry AAD, +/// empty markers, the nothing-sealed refusal) lives once in +/// `crate::EncryptSink` and the opening walk, so a value encrypted +/// from static Rust seals the same tagged leaves a host value does and +/// every ciphertext is self-describing. Drive it with +/// [`crate::encrypt`] and [`crate::decrypt`]. +/// +/// The nonce generator is a `RefCell`, so the cipher is `!Sync`: it is +/// used from one thread at a time. +/// +/// ```compile_fail,E0277 +/// fn assert_sync<T: Sync>() {} +/// assert_sync::<vitaminc_aead::aes::Aes256Cipher>(); +/// ``` +pub struct Aes256Cipher { + pub(crate) nonce_generator: RandomNonceGenerator<NONCE_LEN>, + pub(crate) key: CipherKey, +} + +impl Aes256Cipher { + /// Construct a new AES-256-GCM cipher bound to the given [`Key`]. + /// + /// A fresh random nonce generator is initialised for each cipher instance. + /// Returns an error if the platform RNG cannot be seeded or the key cannot + /// be loaded into the backend. + pub fn new(key: &Key) -> Result<Self, Unspecified> { + Ok(Self { + nonce_generator: RandomNonceGenerator::init()?, + key: key.cipher_key()?, + }) + } +} + +/// Seal one leaf: `version(1) ‖ nonce ‖ ciphertext ‖ tag`, with the wire +/// version bound into the AAD via `Context::for_leaf`. +/// +pub(crate) fn seal_leaf<'a, A>( + cipher: &Aes256Cipher, + data: Protected<Vec<u8>>, + aad: A, +) -> Result<LocalCipherText, Unspecified> +where + A: IntoAad<'a>, +{ + let nonce = cipher.nonce_generator.generate()?; + let nonce_bytes: [u8; NONCE_LEN] = nonce.as_ref().try_into().map_err(|_| Unspecified)?; + // Outermost derivation: bind the wire version the builder prefixes to + // the stored leaf — see `Context::for_leaf`. + let aad = aad.into_aad().for_leaf(WIRE_VERSION); + + CipherTextBuilder::new() + .append_nonce(nonce) + .append_target_plaintext(data) + .accepts_ciphertext_and_tag_ok(|mut buf| { + cipher + .key + .seal(&nonce_bytes, aad.as_bytes(), &mut buf) + .map(|()| buf) + }) + .build() +} + +/// Open one leaf sealed by [`seal_leaf`]: checks the wire version before +/// parsing, then verifies with the same `Context::for_leaf` derivation. +/// Only the current wire version opens. +pub(crate) fn open_leaf<'a, A>( + cipher: &Aes256Cipher, + ct: LocalCipherText, + aad: A, +) -> Result<Protected<Vec<u8>>, Unspecified> +where + A: IntoAad<'a>, +{ + // `read_version` rejects any other wire version before parsing; the + // version is *also* bound under the tag (`for_leaf`, mirroring the seal + // side), so a relabeled byte that parses still fails. + let (nonce, reader) = ct.into_reader().read_version()?.read_nonce::<NONCE_LEN>()?; + let nonce_bytes = nonce.into_inner(); + let aad = aad.into_aad().for_leaf(WIRE_VERSION); + + reader + .accepts_plaintext_ok(|data| cipher.key.open(&nonce_bytes, aad.as_bytes(), data)) + .read() +} + +impl Cipher for Aes256Cipher { + type Leaf = LocalCipherText; + type Error = Unspecified; + + fn seal( + &self, + plaintext: Protected<Vec<u8>>, + aad: &Context<'_>, + ) -> Result<LocalCipherText, Unspecified> { + seal_leaf(self, plaintext, aad.clone()) + } + + fn open( + &self, + leaf: LocalCipherText, + aad: &Context<'_>, + ) -> Result<Protected<Vec<u8>>, Unspecified> { + open_leaf(self, leaf, aad.clone()) + } +} + +// Split cfgs (not `all(test, …)`) so cargo-mutants recognises the test +// module and skips it. The property tests draw random keys, which the +// wasm32 test harness cannot seed. +#[cfg(test)] +#[cfg(not(target_arch = "wasm32"))] +#[allow(clippy::unwrap_used)] +mod test { + use super::super::key::tests::DifferingKeyPair; + use super::*; + use crate::{decrypt, encrypt, CipherText, DecryptError, Node}; + use quickcheck_macros::quickcheck; + use std::collections::HashMap; + use vitaminc_protected::Controlled; + + fn cipher(key: &Key) -> Aes256Cipher { + Aes256Cipher::new(key).expect("cipher") + } + + fn leaf_of(node: Node<LocalCipherText>) -> LocalCipherText { + match node { + CipherText::Single(leaf) => leaf, + other => panic!("expected a single leaf, got {other:?}"), + } + } + + mod leaf_paths { + //! The sink-based `Cipher` seals the same leaf bytes as `seal_leaf`, + //! so a leaf from either path opens through the other. + use super::*; + + #[test] + fn a_leaf_sealed_by_the_cipher_opens_through_open_leaf() { + let cipher = cipher(&Key::from([3u8; 32])); + let aad = Context::from_encoded(b"ctx".as_slice()); + let leaf = cipher + .seal(Protected::new(b"\x04hi".to_vec()), &aad) + .unwrap(); + let opened = open_leaf(&cipher, leaf, aad).unwrap(); + assert_eq!(opened.risky_unwrap(), b"\x04hi"); + } + + #[test] + fn a_leaf_sealed_by_seal_leaf_opens_through_the_cipher() { + let cipher = cipher(&Key::from([3u8; 32])); + let aad = Context::from_encoded(b"ctx".as_slice()); + let leaf = seal_leaf(&cipher, Protected::new(b"\x04hi".to_vec()), aad.clone()).unwrap(); + let opened = Cipher::open(&cipher, leaf, &aad).unwrap(); + assert_eq!(opened.risky_unwrap(), b"\x04hi"); + } + + #[test] + fn the_cipher_refuses_a_leaf_under_another_aad() { + let cipher = cipher(&Key::from([3u8; 32])); + let leaf = cipher + .seal( + Protected::new(b"\x04hi".to_vec()), + &Context::from_encoded(b"right".as_slice()), + ) + .unwrap(); + assert!( + Cipher::open(&cipher, leaf, &Context::from_encoded(b"wrong".as_slice())).is_err() + ); + } + } + + // Round trips through the whole path, over random keys and values. + + #[quickcheck] + fn roundtrip_string(key: Key, plaintext: String) -> bool { + let cipher = cipher(&key); + let ct = encrypt(plaintext.clone(), &cipher, ()).unwrap(); + let back: String = decrypt(&cipher, ct, ()).unwrap(); + back == plaintext + } + + #[quickcheck] + fn roundtrip_u32(key: Key, plaintext: u32) -> bool { + let cipher = cipher(&key); + let ct = encrypt(plaintext, &cipher, ()).unwrap(); + let back: u32 = decrypt(&cipher, ct, ()).unwrap(); + back == plaintext + } + + #[quickcheck] + fn roundtrip_byte_array(key: Key, plaintext: [u8; 16]) -> bool { + let cipher = cipher(&key); + let ct = encrypt(plaintext, &cipher, ()).unwrap(); + let back: [u8; 16] = decrypt(&cipher, ct, ()).unwrap(); + back == plaintext + } + + #[quickcheck] + fn roundtrip_vec_of_strings_with_aad(key: Key, plaintext: Vec<String>) -> bool { + let cipher = cipher(&key); + let ct = encrypt(plaintext.clone(), &cipher, "rows").unwrap(); + let back: Vec<String> = decrypt(&cipher, ct, "rows").unwrap(); + back == plaintext + } + + #[quickcheck] + fn roundtrip_option(key: Key, plaintext: Option<String>) -> bool { + let cipher = cipher(&key); + let ct = encrypt(plaintext.clone(), &cipher, "opt").unwrap(); + let back: Option<String> = decrypt(&cipher, ct, "opt").unwrap(); + back == plaintext + } + + #[quickcheck] + fn roundtrip_protected_string(key: Key, plaintext: String) -> bool { + let cipher = cipher(&key); + let ct = encrypt(Protected::new(plaintext.clone()), &cipher, ()).unwrap(); + let back: Protected<String> = decrypt(&cipher, ct, ()).unwrap(); + back.risky_unwrap() == plaintext + } + + #[test] + fn roundtrip_hashmap_with_aad() { + let cipher = cipher(&Key::from([1u8; 32])); + let mut map = HashMap::new(); + map.insert("name".to_string(), "Ada".to_string()); + map.insert("role".to_string(), "founder".to_string()); + let ct = encrypt(map.clone(), &cipher, "user:42").unwrap(); + let back: HashMap<String, String> = decrypt(&cipher, ct, "user:42").unwrap(); + assert_eq!(back, map); + } + + #[test] + fn roundtrip_empty_composites_with_aad() { + let cipher = cipher(&Key::from([1u8; 32])); + let ct = encrypt(Vec::<String>::new(), &cipher, "ctx").unwrap(); + assert!(matches!(ct, CipherText::EmptySequence(_))); + let back: Vec<String> = decrypt(&cipher, ct, "ctx").unwrap(); + assert!(back.is_empty()); + let ct = encrypt(HashMap::<String, String>::new(), &cipher, "ctx").unwrap(); + assert!(matches!(ct, CipherText::EmptyMap(_))); + let back: HashMap<String, String> = decrypt(&cipher, ct, "ctx").unwrap(); + assert!(back.is_empty()); + } + + // The cipher refuses what it should. + + #[quickcheck] + fn decrypt_fails_with_wrong_aad(key: Key, plaintext: String) -> bool { + let cipher = cipher(&key); + let ct = encrypt(plaintext, &cipher, "right").unwrap(); + matches!( + decrypt::<String, _, _>(&cipher, ct, "wrong"), + Err(DecryptError::Cipher(Unspecified)) + ) + } + + #[quickcheck] + fn decrypt_fails_with_wrong_key(keys: DifferingKeyPair, plaintext: String) -> bool { + let DifferingKeyPair(a, b) = keys; + let ct = encrypt(plaintext, &cipher(&a), ()).unwrap(); + decrypt::<String, _, _>(&cipher(&b), ct, ()).is_err() + } + + #[test] + fn empty_composites_fail_with_wrong_aad() { + let cipher = cipher(&Key::from([2u8; 32])); + let ct = encrypt(Vec::<String>::new(), &cipher, "right").unwrap(); + assert!(decrypt::<Vec<String>, _, _>(&cipher, ct, "wrong").is_err()); + let ct = encrypt(HashMap::<String, String>::new(), &cipher, "right").unwrap(); + assert!(decrypt::<HashMap<String, String>, _, _>(&cipher, ct, "wrong").is_err()); + } + + #[test] + fn empty_composite_markers_are_domain_separated() { + // The two markers seal the same empty plaintext; the AAD derivation + // is what tells them apart, so one cannot stand in for the other. + let cipher = cipher(&Key::from([42u8; 32])); + let CipherText::EmptySequence(seq_marker) = + encrypt(Vec::<String>::new(), &cipher, "ctx").unwrap() + else { + panic!("expected an empty-sequence marker"); + }; + assert!(decrypt::<HashMap<String, String>, _, _>( + &cipher, + CipherText::EmptyMap(seq_marker), + "ctx" + ) + .is_err()); + let CipherText::EmptyMap(map_marker) = + encrypt(HashMap::<String, String>::new(), &cipher, "ctx").unwrap() + else { + panic!("expected an empty-map marker"); + }; + assert!(decrypt::<Vec<String>, _, _>( + &cipher, + CipherText::EmptySequence(map_marker), + "ctx" + ) + .is_err()); + } + + #[test] + fn single_rewrapped_as_sequence_fails_decryption() { + // The container shape is authenticated through the element AAD + // derivation: a top-level leaf is sealed against the bare AAD, a + // sequence element against `for_sequence_element` of it, so + // re-nesting `{Single}` as `Sequence([Single])` cannot get `["x"]` + // back where the app stored `"x"`. + let cipher = cipher(&Key::from([51u8; 32])); + let single = encrypt("x".to_string(), &cipher, ()).unwrap(); + let forged = CipherText::Sequence(vec![single]); + assert!(decrypt::<Vec<String>, _, _>(&cipher, forged, ()).is_err()); + } + + #[test] + fn sequence_element_rehomed_to_top_level_fails_decryption() { + let cipher = cipher(&Key::from([52u8; 32])); + let CipherText::Sequence(mut items) = encrypt(vec!["x".to_string()], &cipher, ()).unwrap() + else { + panic!("expected a sequence"); + }; + let element = items.pop().unwrap(); + assert!(decrypt::<String, _, _>(&cipher, element, ()).is_err()); + } + + #[test] + fn swapped_or_renamed_map_keys_fail_decryption() { + // Each map value is sealed against `Context::for_map_entry(aad, key)`, + // so key and value are inseparable. Leaves are not `Clone`, so each + // forgery starts from a fresh ciphertext. + let cipher = cipher(&Key::from([53u8; 32])); + let sealed = || { + let mut map = HashMap::new(); + map.insert("a".to_string(), "1".to_string()); + map.insert("b".to_string(), "2".to_string()); + match encrypt(map, &cipher, "ctx").unwrap() { + CipherText::Map(entries) => entries, + other => panic!("expected a map, got {other:?}"), + } + }; + let open = |entries| { + decrypt::<HashMap<String, String>, _, _>(&cipher, CipherText::Map(entries), "ctx") + }; + + let mut swapped = sealed(); + let (first, second) = (swapped[0].0.clone(), swapped[1].0.clone()); + swapped[0].0 = second; + swapped[1].0 = first; + assert!(open(swapped).is_err()); + + let mut renamed = sealed(); + for (key, _) in &mut renamed { + key.push('x'); + } + assert!(open(renamed).is_err()); + + // Order is not authenticated: the same entries reversed still open. + let mut reordered = sealed(); + reordered.reverse(); + let back = open(reordered).unwrap(); + assert_eq!(back["a"], "1"); + assert_eq!(back["b"], "2"); + } + + #[test] + fn every_leaf_carries_the_wire_version_prefix() { + // The version byte is the leaf format's first byte on every + // leaf-bearing node. `wire_version` is the keyless peek migration + // tooling relies on. + let cipher = cipher(&Key::from([54u8; 32])); + fn versions(node: &Node<LocalCipherText>) -> Vec<Option<u8>> { + match node { + CipherText::Single(l) | CipherText::EmptySequence(l) | CipherText::EmptyMap(l) => { + vec![l.wire_version()] + } + CipherText::Sequence(items) => items.iter().flat_map(versions).collect(), + CipherText::Map(entries) => entries.iter().flat_map(|(_, v)| versions(v)).collect(), + CipherText::Passthrough(_) => vec![], + } + } + let mut map = HashMap::new(); + map.insert("k".to_string(), "v".to_string()); + let nodes = [ + encrypt("single".to_string(), &cipher, ()).unwrap(), + encrypt(None::<String>, &cipher, ()).unwrap(), + encrypt(Vec::<String>::new(), &cipher, ()).unwrap(), + encrypt(HashMap::<String, String>::new(), &cipher, ()).unwrap(), + encrypt(vec!["a".to_string(), "b".to_string()], &cipher, ()).unwrap(), + encrypt(map, &cipher, ()).unwrap(), + ]; + for node in &nodes { + let found = versions(node); + assert!(!found.is_empty()); + assert!(found.iter().all(|v| *v == Some(WIRE_VERSION))); + } + } + + #[test] + fn relabeled_wire_version_fails_decryption() { + // Flipping the version byte must fail — first at the parse check + // (unknown version), and even a version a future parser accepted + // would fail the tag, because the byte is bound into the leaf AAD + // via `Context::for_leaf`. + let cipher = cipher(&Key::from([55u8; 32])); + let leaf = leaf_of(encrypt("x".to_string(), &cipher, ()).unwrap()); + let mut bytes = leaf.as_ref().to_vec(); + bytes[0] ^= 0x02; + let relabeled = CipherText::Single(LocalCipherText::from(bytes)); + assert!(decrypt::<String, _, _>(&cipher, relabeled, ()).is_err()); + } + + #[test] + fn tampering_any_byte_fails_decryption() { + let cipher = cipher(&Key::from([56u8; 32])); + let bytes = leaf_of(encrypt("hello".to_string(), &cipher, ()).unwrap()) + .as_ref() + .to_vec(); + for idx in 0..bytes.len() { + let mut tampered = bytes.clone(); + tampered[idx] ^= 1; + let node = CipherText::Single(LocalCipherText::from(tampered)); + assert!( + decrypt::<String, _, _>(&cipher, node, ()).is_err(), + "tamper at byte {idx}" + ); + } + } + + #[test] + fn a_truncated_or_extended_leaf_fails_decryption() { + // A short read or a tag cut off in storage, and a stray byte on the + // end: every prefix of a sealed leaf and the leaf plus one byte fail + // closed, on both backends. + let cipher = cipher(&Key::from([58u8; 32])); + let bytes = leaf_of(encrypt("hello".to_string(), &cipher, ()).unwrap()) + .as_ref() + .to_vec(); + for len in 0..bytes.len() { + let node = CipherText::Single(LocalCipherText::from(bytes[..len].to_vec())); + assert!( + decrypt::<String, _, _>(&cipher, node, ()).is_err(), + "truncated to {len} bytes" + ); + } + let mut extended = bytes.clone(); + extended.push(0); + let node = CipherText::Single(LocalCipherText::from(extended)); + assert!(decrypt::<String, _, _>(&cipher, node, ()).is_err()); + } + + mod wire_versions { + //! New leaves are wire version 2. Version 1 leaves come from two + //! released writers that cannot be told apart: the `Value` path + //! sealed tagged scalars, `vitaminc-encrypt` 0.5.1's `Encrypt` path + //! sealed raw bytes. The cipher, and so the typed path, refuses + //! every version 1 leaf. + use super::*; + use crate::tags; + + /// Seal a leaf as the 0.5.1 `seal_leaf` did: version 1 in front, + /// and version 1 bound into the AAD. + fn seal_version_1( + cipher: &Aes256Cipher, + plaintext: &[u8], + aad: Context, + ) -> LocalCipherText { + let nonce = cipher.nonce_generator.generate().unwrap(); + let nonce_bytes: [u8; NONCE_LEN] = nonce.as_ref().try_into().unwrap(); + let mut buf = plaintext.to_vec(); + cipher + .key + .seal(&nonce_bytes, aad.for_leaf(1).as_bytes(), &mut buf) + .unwrap(); + let mut leaf = vec![1]; + leaf.extend_from_slice(&nonce_bytes); + leaf.extend(buf); + LocalCipherText::from(leaf) + } + + #[test] + fn a_new_leaf_is_wire_version_2() { + let cipher = cipher(&Key::from([62u8; 32])); + let leaf = leaf_of(encrypt("x", &cipher, ()).unwrap()); + assert_eq!(WIRE_VERSION, 2); + assert_eq!(leaf.wire_version(), Some(2)); + } + + #[test] + fn a_0_5_1_raw_string_leaf_is_not_read_as_a_different_string() { + // What 0.5.1's `encrypt(&key, "\nhello")` stored: raw UTF-8, + // no tag. `\n` is `tags::STRING`, so read as tagged it would + // come back as "hello". + let key = Key::from([7u8; 32]); + let cipher = cipher(&key); + let leaf = || seal_version_1(&cipher, b"\nhello", Context::empty()); + let typed = decrypt::<String, _, _>(&cipher, CipherText::Single(leaf()), ()); + assert!(matches!(typed, Err(DecryptError::Cipher(_))), "{typed:?}"); + } + + #[test] + fn a_0_5_1_raw_bytes_leaf_is_not_read_as_different_bytes() { + let cipher = cipher(&Key::from([8u8; 32])); + let leaf = seal_version_1(&cipher, &[tags::BYTES, 1, 2, 3], Context::empty()); + let typed = decrypt::<Vec<u8>, _, _>(&cipher, CipherText::Single(leaf), ()); + assert!(matches!(typed, Err(DecryptError::Cipher(_))), "{typed:?}"); + } + + #[test] + fn the_cipher_refuses_a_tagged_version_1_leaf() { + let cipher = cipher(&Key::from([63u8; 32])); + let aad = Context::from_encoded(b"ctx".as_slice()); + let leaf = seal_version_1(&cipher, &[tags::STRING, b'h', b'i'], aad.clone()); + assert_eq!( + Cipher::open(&cipher, leaf, &aad).map(|_| ()), + Err(Unspecified) + ); + } + } + + #[quickcheck] + fn nonce_is_unique_across_encryptions(key: Key, plaintext: String) -> bool { + // Two encryptions of the same plaintext under the same cipher must + // produce different ciphertexts — each seal draws a fresh nonce. + // Running this as a property samples a fresh nonce pair per case. + let cipher = cipher(&key); + let a = leaf_of(encrypt(plaintext.clone(), &cipher, ()).unwrap()); + let b = leaf_of(encrypt(plaintext, &cipher, ()).unwrap()); + a.as_ref() != b.as_ref() && a.as_ref()[1..1 + NONCE_LEN] != b.as_ref()[1..1 + NONCE_LEN] + } + + #[test] + fn a_static_scalar_seals_the_same_leaf_plaintext_a_host_value_does() { + // A Rust `String` and a frame holding the same text open to the same + // tagged leaf plaintext, so there is one leaf format. + let cipher = cipher(&Key::from([57u8; 32])); + let aad = Context::from_encoded(b"ctx".as_slice()); + let frame = crate::to_frame("hi").unwrap(); + let from_frame = leaf_of( + encrypt( + crate::Frame::parse(frame.risky_ref()).unwrap(), + &cipher, + aad.clone(), + ) + .unwrap(), + ); + let from_rust = leaf_of(encrypt("hi".to_string(), &cipher, aad.clone()).unwrap()); + let opened_frame = Cipher::open(&cipher, from_frame, &aad).unwrap(); + let opened_rust = Cipher::open(&cipher, from_rust, &aad).unwrap(); + assert_eq!(opened_frame.risky_ref(), opened_rust.risky_ref()); + // The sealed leaf is the tagged text: `STRING` then the bytes, with + // no length prefix. + assert_eq!(opened_rust.risky_ref(), &[crate::tags::STRING, b'h', b'i']); + } +} diff --git a/packages/vitaminc-aead/src/aes/key.rs b/packages/vitaminc-aead/src/aes/key.rs new file mode 100644 index 000000000..eaa2568e8 --- /dev/null +++ b/packages/vitaminc-aead/src/aes/key.rs @@ -0,0 +1,74 @@ +use super::backend::CipherKey; +use crate::Unspecified; +use vitaminc_protected::{Controlled, Protected}; + +/// 256-bit key type for use with symmetric encryption algorithms like AES-256-GCM. +/// Vitaminc does not support smaller key sizes to ensure quantum security and compatibility with AWS-LC. +/// +/// A `Key` is deliberately not an [`Encrypt`](crate::Encrypt) +/// source or a [`Decrypt`](crate::typed::Decrypt) target. A +/// `Encrypt` walk hands each scalar to a [`Sink`](crate::Sink), +/// and any crate can write a sink, so it would be a way to copy the key +/// bytes out that a search for `risky_` does not find. +// SAFETY: Safe to implement Debug because the inner type is Protected, which does not leak sensitive data. +#[derive(Debug)] +#[cfg_attr(test, derive(Clone))] +pub struct Key(Protected<[u8; 32]>); + +impl Key { + pub(crate) fn cipher_key(&self) -> Result<CipherKey, Unspecified> { + // SAFETY: the borrowed `&[u8; 32]` is consumed by `CipherKey::new` only + // for the duration of the constructor; the backend cipher-key handle + // holds an opaque copy thereafter, so no bare key material outlives this + // call. `self.0` stays owned by `Protected` and is wiped on drop. + CipherKey::new(self.0.risky_ref()) + } +} + +impl From<[u8; 32]> for Key { + fn from(key: [u8; 32]) -> Self { + Self(Protected::new(key)) + } +} + +// Quickcheck `Arbitrary` impls for the property tests in `cipher::test` — +// gated to non-wasm32 alongside their consumers (see comment in `cipher.rs`). +// Split cfgs (not `all(test, …)`) so cargo-mutants recognises the test module. +#[cfg(test)] +#[cfg(not(target_arch = "wasm32"))] +pub(crate) mod tests { + use super::*; + use quickcheck::Arbitrary; + + fn gen_array(g: &mut quickcheck::Gen) -> [u8; 32] { + let mut array = [0u8; 32]; + for byte in array.iter_mut() { + *byte = u8::arbitrary(g); + } + array + } + + impl quickcheck::Arbitrary for Key { + fn arbitrary(g: &mut quickcheck::Gen) -> Self { + Key::from(gen_array(g)) + } + } + + /// A pair of keys guaranteed to be distinct at generation time. Property + /// tests that depend on the keys differing (e.g. wrong-key rejection) use + /// this so they cannot be flaky on the astronomically unlikely event that + /// two independently random keys collide. + #[derive(Clone, Debug)] + pub(crate) struct DifferingKeyPair(pub Key, pub Key); + + impl quickcheck::Arbitrary for DifferingKeyPair { + fn arbitrary(g: &mut quickcheck::Gen) -> Self { + let raw_a = gen_array(g); + let mut raw_b = gen_array(g); + while raw_a == raw_b { + raw_b = gen_array(g); + } + Self(Key::from(raw_a), Key::from(raw_b)) + } + } +} diff --git a/packages/vitaminc-aead/src/aes/mod.rs b/packages/vitaminc-aead/src/aes/mod.rs new file mode 100644 index 000000000..86d73243e --- /dev/null +++ b/packages/vitaminc-aead/src/aes/mod.rs @@ -0,0 +1,25 @@ +//! AES-256-GCM: the [`Cipher`](crate::Cipher) that seals and opens +//! [`LocalCipherText`](crate::LocalCipherText) leaves. +//! +//! Each leaf is `version ‖ nonce ‖ ciphertext ‖ tag`, under a fresh random +//! 96-bit nonce, with the wire version bound into the leaf's AAD. +//! +//! The backend is chosen when the crate is built: `aws-lc-rs` on native +//! targets, and RustCrypto's `aes-gcm` on `wasm32`. Both produce the same +//! bytes for the same inputs. +//! +//! ```rust +//! use vitaminc_aead::aes::{Aes256Cipher, Key}; +//! use vitaminc_aead::{decrypt, encrypt}; +//! +//! let cipher = Aes256Cipher::new(&Key::from([0u8; 32])).unwrap(); +//! let sealed = encrypt("message", &cipher, "users:email").unwrap(); +//! let opened: String = decrypt(&cipher, sealed, "users:email").unwrap(); +//! assert_eq!(opened, "message"); +//! ``` +mod backend; +mod cipher; +mod key; + +pub use cipher::Aes256Cipher; +pub use key::Key; diff --git a/packages/vitaminc-aead/src/ciphertext/mod.rs b/packages/vitaminc-aead/src/ciphertext/mod.rs index 1060781d8..8ee1e4573 100644 --- a/packages/vitaminc-aead/src/ciphertext/mod.rs +++ b/packages/vitaminc-aead/src/ciphertext/mod.rs @@ -1,9 +1,15 @@ +// The staged writer and reader of a leaf's layout. Only the `aes` cipher +// writes and reads leaves, so they are built only with it. +#[cfg(feature = "aes")] mod read_monads; +#[cfg(feature = "aes")] mod write_monads; use bytes::Bytes; +#[cfg(feature = "aes")] use read_monads::CipherTextReader; use serde::{Deserialize, Serialize}; -pub use write_monads::CipherTextBuilder; +#[cfg(feature = "aes")] +pub(crate) use write_monads::CipherTextBuilder; /// First byte of every [`LocalCipherText`] — the wire-format version. /// @@ -23,10 +29,8 @@ pub use write_monads::CipherTextBuilder; /// but what they hold depends on who sealed them: the legacy `Value` /// path (`vitaminc-aead-value` 0.5 and the Go binding) sealed tagged /// scalars, while `vitaminc-encrypt` 0.5's `Encrypt` path sealed raw, -/// untagged bytes. Nothing in a version 1 leaf tells the two apart, so a -/// reader that reads tags opens version 1 only where it knows the leaf came -/// from the `Value` path, by passing it to `read_version_in` on the reader -/// from [`LocalCipherText::into_reader`]. +/// untagged bytes. Nothing in a version 1 leaf tells the two apart, so +/// this crate's cipher opens version 2 only. pub const WIRE_VERSION: u8 = 2; /// A sealed leaf: `version(1) ‖ nonce ‖ ciphertext ‖ tag`. @@ -42,7 +46,8 @@ impl LocalCipherText { /// Consume the leaf and begin staged version/nonce parsing. /// Authentication remains the cipher implementation's responsibility. - pub fn into_reader(self) -> CipherTextReader { + #[cfg(feature = "aes")] + pub(crate) fn into_reader(self) -> CipherTextReader { CipherTextReader::new(self.0) } @@ -70,9 +75,10 @@ impl From<Vec<u8>> for LocalCipherText { } #[cfg(test)] +#[cfg(feature = "aes")] mod tests { use super::*; - use crate::Nonce; + use crate::nonce::Nonce; use vitaminc_protected::{Controlled, Protected}; #[test] @@ -85,7 +91,7 @@ mod tests { .accepts_ciphertext_and_tag_ok(|mut ciphertext| { ciphertext.copy_from_slice(&[2u8; 10]); ciphertext.extend([3u8; 16]); - Ok(ciphertext) + Ok::<_, ()>(ciphertext) }) .build()?; @@ -111,7 +117,7 @@ mod tests { .accepts_ciphertext_and_tag_ok(|mut ciphertext| { ciphertext.copy_from_slice(&[2u8; 10]); ciphertext.extend([3u8; 16]); - Ok(ciphertext) + Ok::<_, ()>(ciphertext) }) .build()?; @@ -129,7 +135,7 @@ mod tests { assert_eq!(&data[10..], [3u8; 16]); // Write in the same way as AWS-LC/Ring does data[..10].copy_from_slice(&[0u8; 10]); - Ok(10) + Ok::<_, ()>(10) }) .read()?; diff --git a/packages/vitaminc-aead/src/ciphertext/read_monads.rs b/packages/vitaminc-aead/src/ciphertext/read_monads.rs index 098c5ad72..21c56c714 100644 --- a/packages/vitaminc-aead/src/ciphertext/read_monads.rs +++ b/packages/vitaminc-aead/src/ciphertext/read_monads.rs @@ -1,4 +1,5 @@ -use crate::{Nonce, Unspecified}; +use crate::nonce::Nonce; +use crate::Unspecified; use bytes::{Buf, Bytes}; use std::array; use vitaminc_protected::{Controlled, Protected}; @@ -21,25 +22,11 @@ impl CipherTextReader { /// leaf AAD ([`Context::for_leaf`](crate::Context::for_leaf)), so a relabeled /// version that happens to parse still fails tag verification. pub fn read_version(self) -> Result<VersionedReader, Unspecified> { - self.read_version_in(&[super::WIRE_VERSION]) - .map(|(_, reader)| reader) - } - - /// Like [`read_version`](Self::read_version), but accepts any version in - /// `accepted` and returns the one it read, so the caller can bind that - /// version into the leaf AAD. Only a reader that knows where its older - /// leaves came from should pass a version other than - /// [`WIRE_VERSION`](super::WIRE_VERSION); see that constant for why. - pub fn read_version_in(self, accepted: &[u8]) -> Result<(u8, VersionedReader), Unspecified> { let mut buf = self.0; - if buf.is_empty() { + if buf.is_empty() || buf.get_u8() != super::WIRE_VERSION { return Err(Unspecified); } - let version = buf.get_u8(); - if !accepted.contains(&version) { - return Err(Unspecified); - } - Ok((version, VersionedReader(buf))) + Ok(VersionedReader(buf)) } } @@ -153,22 +140,6 @@ mod tests { } } - #[test] - fn read_version_in_accepts_only_the_listed_versions() { - for version in 0..=u8::MAX { - let read = CipherTextReader::new(Bytes::from(vec![version, 9])) - .read_version_in(&[1, WIRE_VERSION]) - .map(|(read, rest)| (read, rest.0)); - if version == 1 || version == WIRE_VERSION { - assert_eq!(read, Ok((version, Bytes::from_static(&[9])))); - } else { - assert!(read.is_err(), "version {version} must be rejected"); - } - } - let empty = CipherTextReader::new(Bytes::new()).read_version_in(&[1, WIRE_VERSION]); - assert!(empty.is_err()); - } - #[test] fn read_version_strips_exactly_one_byte() { let (nonce, rest) = versioned(&[1, 2, 3, 4, 5]) diff --git a/packages/vitaminc-aead/src/ciphertext/write_monads.rs b/packages/vitaminc-aead/src/ciphertext/write_monads.rs index 30df892c2..b99a722cc 100644 --- a/packages/vitaminc-aead/src/ciphertext/write_monads.rs +++ b/packages/vitaminc-aead/src/ciphertext/write_monads.rs @@ -1,5 +1,5 @@ use super::LocalCipherText; -use crate::Nonce; +use crate::nonce::Nonce; use bytes::BytesMut; use vitaminc_protected::{Controlled, Protected}; @@ -34,27 +34,6 @@ impl<const N: usize> NonceWritten<N> { ) -> PlaintextWritten<N> { PlaintextWritten::new(self.0, plaintext.into()) } - - /// Append a fixed-width array plaintext, reserving `reserve` extra bytes of - /// spare capacity in the backing buffer so an in-place AEAD seal can append - /// its tag without reallocating. Sizing the plaintext buffer is the - /// builder's job, so callers sealing fixed-width leaves route through here - /// rather than hand-rolling the `Vec` assembly at the call site. - /// - /// The array is copied out through `risky_ref` (a borrow) so `plaintext` - /// keeps ownership of the original and is wiped by `ZeroizeOnDrop` at end - /// of scope — a `risky_unwrap` would partially-move the bare `[u8; M]` out - /// and skip that wipe (see issue #170). - pub fn append_target_plaintext_array<const M: usize>( - self, - plaintext: Protected<[u8; M]>, - reserve: usize, - ) -> PlaintextWritten<N> { - let src = plaintext.risky_ref(); - let mut buf = Vec::with_capacity(M + reserve); - buf.extend_from_slice(src); - PlaintextWritten::new(self.0, Protected::new(buf)) - } } pub struct PlaintextWritten<const N: usize>(Nonce<N>, Protected<Vec<u8>>); diff --git a/packages/vitaminc-aead/src/container.rs b/packages/vitaminc-aead/src/container.rs index 7bafafbef..7a86cc411 100644 --- a/packages/vitaminc-aead/src/container.rs +++ b/packages/vitaminc-aead/src/container.rs @@ -1,13 +1,12 @@ -/// The ciphertext tree [`encrypt`](crate::encrypt) produces and -/// [`decrypt`](crate::decrypt) consumes. +/// A value as a tree. One shape for every stage of a value: staged for +/// encryption, sealed, and opened. The leaf type says which stage it is. /// -/// The shape mirrors the structure of the plaintext that was encrypted: a -/// scalar yields [`Single`](CipherText::Single), while non-empty sequences -/// and maps yield [`Sequence`](CipherText::Sequence) and -/// [`Map`](CipherText::Map). Empty composites use the authenticated marker -/// variants [`EmptySequence`](CipherText::EmptySequence) and -/// [`EmptyMap`](CipherText::EmptyMap), since they contain no element -/// ciphertexts to authenticate the supplied AAD. Nested structures are +/// The shape mirrors the structure of the value: a scalar is a +/// [`Single`](Node::Single), while non-empty sequences and maps are a +/// [`Sequence`](Node::Sequence) and a [`Map`](Node::Map). Empty composites +/// use the marker variants [`EmptySequence`](Node::EmptySequence) and +/// [`EmptyMap`](Node::EmptyMap), whose leaf authenticates the supplied AAD, +/// since they have no element to authenticate it. Nested structures are /// represented recursively. An absent value (`Option::None`, a host null) /// is a null leaf, a `Single` like any other scalar: the plain null, or a /// typed null padded to its type's length (see @@ -15,25 +14,25 @@ /// /// The two parameters: /// -/// - `Leaf` is the sealed leaf the cipher produces -/// ([`Cipher::Leaf`](crate::Cipher::Leaf)) — e.g. [`LocalCipherText`](crate::LocalCipherText) -/// for a local AES cipher, or an envelope leaf that additionally carries -/// a wrapped data key. -/// - `P` is the passthrough payload. For the sink-based path it is a -/// [`PassthroughFrame`](crate::PassthroughFrame): [`Node`](crate::Node) -/// is this tree with that payload. +/// - `Leaf` is what a leaf holds. For a sealed value it is the leaf the +/// cipher produces ([`Cipher::Leaf`](crate::Cipher::Leaf)): a +/// [`LocalCipherText`](crate::LocalCipherText) for a local AES cipher, or +/// an envelope leaf that also carries a wrapped data key. For a value +/// staged for encryption, or opened, it is plaintext. +/// - `P` is the passthrough payload: a +/// [`PassthroughFrame`](crate::PassthroughFrame) unless it is named. /// /// Only the `Leaf` type carries a byte-level format commitment (and should -/// implement `serde` where ciphertexts are persisted). The container itself +/// implement `serde` where ciphertexts are persisted). The tree itself /// has no canonical byte representation: hosts project it onto their native /// structures (a JS object tree, the Go binding's transport codec), with /// leaves as opaque byte strings. #[derive(Debug)] -pub enum CipherText<Leaf, P> { +pub enum Node<Leaf, P = crate::frame::PassthroughFrame> { /// A single sealed value. Single(Leaf), /// A sequence of ciphertexts produced from a sequence-shaped plaintext. - Sequence(Vec<CipherText<Leaf, P>>), + Sequence(Vec<Node<Leaf, P>>), /// An empty sequence, authenticated under domain-separated AAD /// ([`Context::for_empty_sequence`](crate::Context::for_empty_sequence)) /// by a marker leaf. @@ -43,7 +42,7 @@ pub enum CipherText<Leaf, P> { /// each value's AAD via [`Context::for_map_entry`](crate::Context::for_map_entry), /// so they cannot be swapped or renamed undetected (passthrough entries /// excepted). - Map(Vec<(String, CipherText<Leaf, P>)>), + Map(Vec<(String, Node<Leaf, P>)>), /// An empty map, authenticated under domain-separated AAD /// ([`Context::for_empty_map`](crate::Context::for_empty_map)) by a /// marker leaf. @@ -53,3 +52,8 @@ pub enum CipherText<Leaf, P> { /// [`Sink::passthrough`](crate::Sink::passthrough). Passthrough(P), } + +/// The tree's earlier name. A tree is a ciphertext only when its leaves are +/// sealed, so the name is [`Node`]. This alias stays for code that still +/// says `CipherText`. +pub type CipherText<Leaf, P> = Node<Leaf, P>; diff --git a/packages/vitaminc-aead/src/context.rs b/packages/vitaminc-aead/src/context.rs deleted file mode 100644 index a00b4635a..000000000 --- a/packages/vitaminc-aead/src/context.rs +++ /dev/null @@ -1,710 +0,0 @@ -//! Context-tagged encryption. -//! -//! This module provides [`ContextTag`], a wrapper that binds additional -//! authenticated data (AAD) to a plaintext value **at the type level**. The -//! AAD is an argument of [`encrypt`](crate::encrypt) and -//! [`decrypt`](crate::decrypt), and a tuple AAD such as `(extra, tag)` is -//! nothing more than [`IntoAad`] composition, but it is opt-in at every call -//! site and easy to forget. `ContextTag` moves the obligation into the type -//! system: a value wrapped in it is encrypted through -//! [`ContextTag::encrypt`] or [`ContextTag::encrypt_with_aad`], which fold the -//! embedded tag in themselves, so it *cannot* be encrypted without its -//! context. -//! -//! Decryption is symmetric. Rebuild the context with [`ContextTag::context`] -//! (and the same [`refine`](ContextTag::refine) chain used at encrypt time), -//! then recover the value with [`ContextTag::decrypt`] or -//! [`ContextTag::decrypt_with_aad`]. Because the tag (and any refinement) is -//! reconstructed by the same code path that bound it, it is never re-typed by -//! hand. For lower-level use against the bare entry points, [`ContextTag::aad`] -//! and [`ContextTag::aad_with`] build the raw AAD tuple the wrapper bound. -//! -//! # AAD encoding -//! -//! The final AAD is the extra AAD and the embedded tag as the tuple -//! `(extra_aad, tag)`, which [`IntoAad`] PAE-encodes: -//! -//! ```text -//! final_aad = PAE(extra_aad, tag) -//! ``` -//! -//! PAE (Pre-Authentication Encoding) prefixes each piece with its length, -//! preventing canonicalisation attacks where different inputs could otherwise -//! produce identical byte strings. -//! -//! With [`refine`](ContextTag::refine), the tag itself is a nested tuple that -//! is recursively PAE-encoded: -//! -//! ```text -//! ContextTag::new(data, "a").refine("b") -//! ──► tag = ("a", "b") -//! ──► final_aad = PAE(extra_aad, PAE("a", "b")) -//! ``` -//! -//! The context keeps its parts intact until it is encoded: `into_context()` -//! on the value the wrapper builds is `List([extra_aad, List(["a", "b"])])` -//! for the example, so a caller that names the parts (a key-management -//! service logging which field a key was issued for) reads them from the -//! tag or the AAD value before encrypting. The cipher itself sees only the -//! encoded bytes of each leaf's derived context ([`Context::for_map_entry`] -//! and the rest apply on top, as for any AAD), not the parts. - -use core::future::Future; - -use vitaminc_protected::OpaqueDebug; - -use crate::seal::{AsyncCipher, Cipher, Node}; -use crate::typed::{DecodeError, Decrypt}; -use crate::walk::DecryptError; -use crate::{Context, ContextPiece, Encrypt, EncryptError, IntoAad, IntoContext}; - -/// Folds a context `tag` and `extra_aad` into the context layout bound by -/// `ContextTag`: the pair `(extra_aad, tag)`. -/// -/// This is the layout shared by the type-driven paths: the encrypt methods -/// and the decrypt methods both go through it, so the two sides cannot drift -/// out of sync (a divergence would silently break authentication). The -/// low-level [`ContextTag::aad`] / [`ContextTag::aad_with`] builders reproduce -/// the same `(extra_aad, tag)` layout *by hand* (they must return the -/// unencoded tag for a caller to re-encode), so they are a parallel -/// construction kept in lockstep only by the `aad_helpers_match_the_encrypt_binding` -/// test — if you change the layout here, update those builders too. -/// -/// The tag becomes an owned/`'static` [`ContextPiece`] and is re-borrowed for -/// the call's `'a` lifetime (`ContextPiece` is covariant in its lifetime, so -/// `'static: 'a` permits the narrowing). The result is an ordinary pair, so it -/// is a context like any other: its parts are `List([extra_aad, tag])` and its -/// bytes are that list's encoding, written in one allocation. -fn fold_tag_aad<'a, Tag, A>(tag: Tag, extra_aad: A) -> (A, ContextPiece<'a>) -where - Tag: IntoContext<'static>, -{ - let tag: ContextPiece<'static> = tag.into_context(); - let tag: ContextPiece<'a> = tag; - (extra_aad, tag) -} - -/// A wrapper that pairs a plaintext value with a context tag used as -/// additional authenticated data (AAD). -/// -/// `ContextTag` guarantees, at the type level, that `tag` is folded into the -/// AAD whenever `inner` is encrypted. This is the recommended way to enforce -/// that a value is always sealed against a specific context (a user id, table -/// name, column name, …): because the tag is part of the type, the compiler -/// will not let you forget it. -/// -/// The tag can be any type that implements [`IntoAad<'static>`](IntoAad) — -/// `&'static str`, `String`, `u64`, `Vec<u8>`, and tuples of these. -/// (Non-`'static` borrowed tags such as a short-lived `&str` are intentionally -/// excluded; promote them to an owned `String` or a `&'static str`.) -/// -/// # Encrypting and decrypting -/// -/// Encrypt with [`ContextTag::new`]. To decrypt, mirror the encrypt side: -/// rebuild the context with [`ContextTag::context`] (and the same -/// [`refine`](ContextTag::refine) chain, if any), then recover the value with -/// [`decrypt`](ContextTag::decrypt) / -/// [`decrypt_with_aad`](ContextTag::decrypt_with_aad). The cipher below keeps -/// the plaintext in the clear so the example runs without a key; a real one -/// is `vitaminc_encrypt::Aes256Cipher`. -/// -/// ```rust -/// # use vitaminc_aead::{Cipher, Context, Unspecified}; -/// # use vitaminc_protected::Protected; -/// # struct Clear; -/// # impl Cipher for Clear { -/// # type Leaf = (Vec<u8>, Vec<u8>); -/// # type Error = Unspecified; -/// # fn seal(&self, plaintext: Protected<Vec<u8>>, aad: &Context<'_>) -> Result<Self::Leaf, Unspecified> { -/// # Ok((aad.as_bytes().to_vec(), vitaminc_protected::Controlled::risky_unwrap(plaintext))) -/// # } -/// # fn open(&self, leaf: Self::Leaf, aad: &Context<'_>) -> Result<Protected<Vec<u8>>, Unspecified> { -/// # if leaf.0 != aad.as_bytes() { return Err(Unspecified); } -/// # Ok(Protected::new(leaf.1)) -/// # } -/// # } -/// # let cipher = Clear; -/// use vitaminc_aead::ContextTag; -/// -/// let ciphertext = ContextTag::new("secret message", "user:42").encrypt(&cipher)?; -/// let plaintext: String = ContextTag::context("user:42").decrypt(&cipher, ciphertext)?; -/// assert_eq!(plaintext, "secret message"); -/// # Ok::<(), Box<dyn std::error::Error>>(()) -/// ``` -/// -/// # Debug output -/// -/// `Debug` shows the tag, which is authenticated but not secret, and masks -/// the value. There is no `PartialEq`: comparing plaintexts with `==` is not -/// constant-time. -/// -/// ```rust -/// use vitaminc_aead::ContextTag; -/// -/// let tagged = ContextTag::new("secret message", "user:42"); -/// let shown = format!("{tagged:?}"); -/// assert!(shown.ends_with(r#"{ inner: "***", tag: "user:42" }"#)); -/// ``` -/// -/// # Nesting versus refining -/// -/// Layer contexts with [`refine`](ContextTag::refine). Wrapping a -/// `ContextTag` *inside another* would fold the AAD twice, into -/// `((extra, "a"), "b")`, which is not the layout `context("a").refine("b")` -/// decrypts against; it does not compile, because a `ContextTag` is not an -/// [`Encrypt`]: -/// -/// ```rust,compile_fail,E0277 -/// use vitaminc_aead::{Cipher, ContextTag}; -/// -/// fn seal<C: Cipher>(cipher: &C) { -/// let _ = ContextTag::new(ContextTag::new("secret", "a"), "b").encrypt(cipher); -/// } -/// ``` -/// -/// # Async ciphers -/// -/// [`encrypt_async`](ContextTag::encrypt_async), -/// [`encrypt_with_aad_async`](ContextTag::encrypt_with_aad_async), -/// [`decrypt_async`](ContextTag::decrypt_async) and -/// [`decrypt_with_aad_async`](ContextTag::decrypt_with_aad_async) are the -/// same methods over an [`AsyncCipher`], binding the same AAD, for a key -/// service that has to be awaited. -#[derive(Clone, OpaqueDebug)] -pub struct ContextTag<Tag, T> { - inner: T, - #[non_sensitive] - tag: Tag, -} - -impl<Tag, T> ContextTag<Tag, T> { - /// Creates a new `ContextTag` pairing `inner` with the given `tag`. - /// - /// The tag is folded into the AAD whenever `inner` is encrypted. - /// - /// ```rust - /// use vitaminc_aead::ContextTag; - /// - /// let tagged = ContextTag::new("hello", "my-tag"); - /// # let _ = tagged; - /// ``` - pub fn new(inner: T, tag: Tag) -> Self { - ContextTag { inner, tag } - } - - /// Adds a second layer of context, producing a new `ContextTag` whose tag - /// is the tuple `(original_tag, tag)`. - /// - /// Useful for building hierarchical context such as - /// `("table:users", "column:email")`. The nested tag is PAE-encoded when - /// converted to AAD bytes, so distinct hierarchies never collide. `refine` - /// can be chained to build deeper hierarchies. - /// - /// ```rust - /// use vitaminc_aead::ContextTag; - /// - /// let tagged = ContextTag::new("secret", "table:users").refine("column:email"); - /// // The tag is now ("table:users", "column:email"). - /// # let _ = tagged; - /// ``` - pub fn refine<B>(self, tag: B) -> ContextTag<(Tag, B), T> { - ContextTag { - inner: self.inner, - tag: (self.tag, tag), - } - } - - /// Consumes the wrapper, returning the inner value and its tag. - pub fn into_parts(self) -> (T, Tag) { - (self.inner, self.tag) - } -} - -impl<Tag, T> ContextTag<Tag, T> -where - T: Encrypt, - // The tag is owned by the wrapper, and the AAD lifetime is chosen at the - // call site. Requiring `IntoAad<'static>` lets the tag become an owned (or - // `'static`-borrowed) `ContextPiece` that is then re-borrowed for the - // call's lifetime via covariance. Owned tags (`String`, `u64`, `Vec<u8>`, - // tuples thereof) and `&'static str` satisfy this; non-`'static` borrows - // do not — promote them to `String` or a `&'static str`. - Tag: IntoAad<'static>, -{ - /// Encrypts the inner value, folding the embedded tag into the AAD with - /// no extra AAD: the bound AAD is `((), tag)`. - pub fn encrypt<C: Cipher>(self, cipher: &C) -> Result<Node<C::Leaf>, EncryptError<C::Error>> { - self.encrypt_with_aad(cipher, Context::empty()) - } - - /// Encrypts the inner value, folding the embedded tag into the AAD. - /// - /// The final AAD is `(extra_aad, tag)`, PAE-encoded into an unambiguous - /// byte representation that binds both pieces. The walk derives each - /// leaf's AAD from it as from any other context. - pub fn encrypt_with_aad<'a, C, A>( - self, - cipher: &C, - extra_aad: A, - ) -> Result<Node<C::Leaf>, EncryptError<C::Error>> - where - C: Cipher, - A: IntoAad<'a>, - { - let ContextTag { inner, tag } = self; - crate::encrypt(inner, cipher, fold_tag_aad(tag, extra_aad)) - } - - /// [`encrypt`](ContextTag::encrypt) through an async cipher: the same - /// AAD, `((), tag)`. The value is walked before this returns, so the - /// future holds only the planned leaves and is `Send`. - pub fn encrypt_async<'c, C>( - self, - cipher: &'c C, - ) -> impl Future<Output = Result<Node<C::Leaf>, EncryptError<C::Error>>> - + Send - + 'c - + use<'c, Tag, T, C> - where - C: AsyncCipher, - { - self.encrypt_with_aad_async(cipher, Context::empty()) - } - - /// [`encrypt_with_aad`](ContextTag::encrypt_with_aad) through an async - /// cipher: the same AAD, `(extra_aad, tag)`. - pub fn encrypt_with_aad_async<'a, 'c, C, A>( - self, - cipher: &'c C, - extra_aad: A, - ) -> impl Future<Output = Result<Node<C::Leaf>, EncryptError<C::Error>>> - + Send - + 'c - + use<'a, 'c, Tag, T, C, A> - where - C: AsyncCipher, - A: IntoAad<'a>, - { - let ContextTag { inner, tag } = self; - crate::encrypt_async(inner, cipher, fold_tag_aad(tag, extra_aad)) - } -} - -impl<Tag> ContextTag<Tag, ()> { - /// Low-level: builds the raw AAD tuple for **decrypting** a value sealed - /// with `ContextTag::new(value, tag).encrypt(cipher)` (i.e. with no extra - /// AAD). - /// - /// Prefer [`ContextTag::context`] + [`decrypt`](ContextTag::decrypt) — it - /// folds the AAD for you and reconstructs nested - /// [`refine`](ContextTag::refine) tags via the same path used at encrypt - /// time. Reach for `aad` only to drive a bare entry point directly. - /// - /// This reproduces the `(empty, tag)` layout the encrypt methods bind, so - /// a bare entry point authenticates against exactly the same bytes. - /// - /// ```rust - /// use vitaminc_aead::{ContextTag, IntoAad}; - /// - /// // The AAD recovered for decryption matches what `encrypt` bound at seal time. - /// let decrypt_aad = ContextTag::aad("user:42"); - /// assert_eq!( - /// decrypt_aad.into_aad().as_bytes(), - /// ((), "user:42").into_aad().as_bytes(), - /// ); - /// ``` - pub fn aad(tag: Tag) -> (Context<'static>, Tag) { - (Context::empty(), tag) - } - - /// Low-level: builds the raw AAD tuple for **decrypting** a value sealed - /// with `ContextTag::new(value, tag).encrypt_with_aad(cipher, extra_aad)`. - /// - /// Prefer [`ContextTag::context`] + [`decrypt_with_aad`](ContextTag::decrypt_with_aad), - /// which puts the tag in the receiver so it can't be transposed with - /// `extra_aad`. This builder takes **both** as positional, same-typed args - /// (`extra_aad` first, then `tag`) — swapping them silently produces the - /// wrong AAD, so reach for it only to drive a bare entry point directly. - /// - /// Reproduces the `(extra_aad, tag)` layout bound at encrypt time. - /// - /// ```rust - /// use vitaminc_aead::{ContextTag, IntoAad}; - /// - /// let decrypt_aad = ContextTag::aad_with("row:99", "table:users"); - /// assert_eq!( - /// decrypt_aad.into_aad().as_bytes(), - /// ("row:99", "table:users").into_aad().as_bytes(), - /// ); - /// ``` - pub fn aad_with<A>(extra_aad: A, tag: Tag) -> (A, Tag) { - (extra_aad, tag) - } - - /// Begins a decrypt-side context carrying `tag` (and no value yet). - /// - /// This is the decrypt mirror of [`ContextTag::new`]: build (and - /// [`refine`](ContextTag::refine)) the tag exactly as you did at encrypt - /// time, then call [`decrypt`](ContextTag::decrypt) / - /// [`decrypt_with_aad`](ContextTag::decrypt_with_aad) to recover the value - /// — so the tag (and any nested refinement) is reconstructed by the same - /// code path that bound it, never re-typed by hand. - /// - /// ```rust - /// use vitaminc_aead::ContextTag; - /// - /// // mirrors `ContextTag::new(value, "table:users").refine("column:email")` - /// let ctx = ContextTag::context("table:users").refine("column:email"); - /// # let _ = ctx; - /// ``` - pub fn context(tag: Tag) -> Self { - ContextTag { inner: (), tag } - } -} - -impl<Tag> ContextTag<Tag, ()> -where - Tag: IntoAad<'static>, -{ - /// Decrypts a value sealed against this context, authenticating against - /// the embedded tag (no extra AAD). The decrypt mirror of - /// [`ContextTag::encrypt`]. - pub fn decrypt<T, C>( - self, - cipher: &C, - node: Node<C::Leaf>, - ) -> Result<T, DecryptError<DecodeError, C::Error>> - where - T: Decrypt, - C: Cipher, - { - self.decrypt_with_aad(cipher, node, Context::empty()) - } - - /// Decrypts a value sealed against this context plus `extra_aad`, - /// mirroring [`ContextTag::encrypt_with_aad`]. - /// - /// The tag lives in the receiver and `extra_aad` is the lone AAD argument, - /// so the two cannot be swapped; the bound AAD is `(extra_aad, tag)` — - /// byte-identical to what the encrypt side folds in at seal time. - pub fn decrypt_with_aad<'a, T, C, A>( - self, - cipher: &C, - node: Node<C::Leaf>, - extra_aad: A, - ) -> Result<T, DecryptError<DecodeError, C::Error>> - where - T: Decrypt, - C: Cipher, - A: IntoAad<'a>, - { - crate::decrypt(cipher, node, fold_tag_aad(self.tag, extra_aad)) - } - - /// [`decrypt`](ContextTag::decrypt) through an async cipher. - pub async fn decrypt_async<T, C>( - self, - cipher: &C, - node: Node<C::Leaf>, - ) -> Result<T, DecryptError<DecodeError, C::Error>> - where - T: Decrypt, - C: AsyncCipher, - { - self.decrypt_with_aad_async(cipher, node, Context::empty()) - .await - } - - /// [`decrypt_with_aad`](ContextTag::decrypt_with_aad) through an async - /// cipher: the bound AAD is `(extra_aad, tag)`, as on the sync path. - pub async fn decrypt_with_aad_async<'a, T, C, A>( - self, - cipher: &C, - node: Node<C::Leaf>, - extra_aad: A, - ) -> Result<T, DecryptError<DecodeError, C::Error>> - where - T: Decrypt, - C: AsyncCipher, - A: IntoAad<'a>, - { - crate::typed::decrypt_async(cipher, node, fold_tag_aad(self.tag, extra_aad)).await - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::seal::mock::{Leaf, Mock, Refused}; - use crate::{tags, CipherText}; - use std::borrow::Cow; - - /// The one leaf a tagged scalar seals: its AAD bytes and plaintext. - fn sealed<Tag: IntoAad<'static>>(tagged: ContextTag<Tag, &str>) -> Leaf { - match tagged.encrypt(&Mock).expect("the mock cannot fail") { - CipherText::Single(leaf) => leaf, - other => panic!("a scalar seals as one leaf, got {other:?}"), - } - } - - fn sealed_with<'a, Tag: IntoAad<'static>, A: IntoAad<'a>>( - tagged: ContextTag<Tag, &str>, - extra: A, - ) -> Leaf { - match tagged - .encrypt_with_aad(&Mock, extra) - .expect("the mock cannot fail") - { - CipherText::Single(leaf) => leaf, - other => panic!("a scalar seals as one leaf, got {other:?}"), - } - } - - /// The AAD the walk derives for a top-level scalar is the bare context, - /// so a sealed leaf's AAD bytes are the tuple's encoding. - fn bytes_of<'a>(aad: impl IntoAad<'a>) -> Vec<u8> { - aad.into_aad().as_bytes().to_vec() - } - - #[test] - fn the_context_keeps_its_parts() { - // The motivating consumer: a caller that names the parts (a key - // service logging which field a key was issued for) reads them from - // the folded value before encrypting. The cipher itself sees only the - // encoded bytes. The tag stays a nested list of its refinements, not - // pre-encoded bytes. - let folded = fold_tag_aad(("table:users", "column:email"), "row:99"); - let piece = folded.into_context(); - assert_eq!( - piece, - ContextPiece::List(vec![ - ContextPiece::Text(Cow::Borrowed("row:99")), - ContextPiece::List(vec![ - ContextPiece::Text(Cow::Borrowed("table:users")), - ContextPiece::Text(Cow::Borrowed("column:email")), - ]), - ]) - ); - let names: Vec<String> = piece.leaves().map(ToString::to_string).collect(); - assert_eq!(names, ["\"row:99\"", "\"table:users\"", "\"column:email\""]); - // Both views agree with the tuple: the parts tree re-encoded, and the - // bytes a byte-oriented cipher gets from the pair `(extra_aad, tag)`. - let expected = ("row:99", ("table:users", "column:email")).into_aad(); - assert_eq!(piece.into_aad().as_bytes(), expected.as_bytes()); - } - - #[test] - fn encrypts_inner_value_and_binds_tag() { - let leaf = sealed_with(ContextTag::new("hello world", "tag_aad"), "extra"); - // The inner value is sealed as its tagged leaf... - assert_eq!( - leaf.plaintext, - [&[tags::STRING][..], b"hello world"].concat() - ); - // ...and the bound AAD is the pair (extra, tag). - assert_eq!(leaf.aad, bytes_of(("extra", "tag_aad"))); - } - - #[test] - fn encrypt_with_no_extra_aad_still_binds_tag() { - let leaf = sealed(ContextTag::new("secret", "user:42")); - // `encrypt` supplies an empty extra AAD, so the bound AAD is PAE(empty, tag). - assert_eq!(leaf.aad, bytes_of(((), "user:42"))); - } - - #[test] - fn unit_tag_still_binds_nonempty_aad() { - let leaf = sealed(ContextTag::new("secret", ())); - // Pins the documented boundary: a `()` tag binds PAE(empty, empty), - // which is *not* empty AAD — so a bare `decrypt(ct, ())` must fail. A - // regression that folded a `()` tag to empty AAD would silently break - // it. - assert_eq!(leaf.aad, bytes_of(((), ()))); - assert_ne!(leaf.aad, Context::empty().as_bytes()); - } - - #[test] - fn refine_nests_the_tag() { - let leaf = sealed_with( - ContextTag::new("secret", "table:users").refine("column:email"), - "extra", - ); - // extra + (table, column) => the nested pair (extra, (table, column)). - assert_eq!( - leaf.aad, - bytes_of(("extra", ("table:users", "column:email"))) - ); - } - - #[test] - fn chained_refine_builds_left_nested_tuple() { - let leaf = sealed(ContextTag::new("data", "a").refine("b").refine("c")); - // tag = (("a", "b"), "c"); no extra AAD. - assert_eq!(leaf.aad, bytes_of(((), (("a", "b"), "c")))); - } - - #[test] - fn owned_and_byte_tags_are_accepted() { - let leaf = sealed(ContextTag::new("secret", String::from("owned-tag"))); - assert_eq!(leaf.aad, bytes_of(((), "owned-tag"))); - let leaf = sealed(ContextTag::new("secret", vec![0xde_u8, 0xad, 0xbe, 0xef])); - assert_eq!(leaf.aad, bytes_of(((), vec![0xde_u8, 0xad, 0xbe, 0xef]))); - } - - #[test] - fn aad_helpers_match_the_encrypt_binding() { - // The AAD the helpers produce for decryption must equal what the - // encrypt methods bind. - let leaf = sealed(ContextTag::new("secret", "user:42")); - assert_eq!(leaf.aad, bytes_of(ContextTag::aad("user:42"))); - let leaf = sealed_with(ContextTag::new("secret", "table:users"), "row:99"); - assert_eq!( - leaf.aad, - bytes_of(ContextTag::aad_with("row:99", "table:users")) - ); - } - - #[test] - fn different_tags_produce_different_aad() { - let a = sealed(ContextTag::new("secret", "user:42")); - let b = sealed(ContextTag::new("secret", "user:99")); - assert_ne!(a.aad, b.aad); - } - - #[test] - fn into_parts_round_trips() { - let tagged = ContextTag::new("secret", "ctx"); - let (inner, tag) = tagged.into_parts(); - assert_eq!(inner, "secret"); - assert_eq!(tag, "ctx"); - } - - #[test] - fn decrypt_mirrors_encrypt_through_the_same_fold() { - let node = ContextTag::new("secret".to_string(), "table:users") - .refine("column:email") - .encrypt_with_aad(&Mock, "row:99") - .expect("encrypts"); - let back: String = ContextTag::context("table:users") - .refine("column:email") - .decrypt_with_aad(&Mock, node, "row:99") - .expect("decrypts"); - assert_eq!(back, "secret"); - - let node = ContextTag::new(vec![1u32, 2], "user:42") - .encrypt(&Mock) - .expect("encrypts"); - let back: Vec<u32> = ContextTag::context("user:42") - .decrypt(&Mock, node) - .expect("decrypts"); - assert_eq!(back, [1, 2]); - } - - #[test] - fn a_different_tag_or_extra_aad_fails_at_the_cipher() { - let seal = || { - ContextTag::new("secret".to_string(), "table:users") - .encrypt_with_aad(&Mock, "row:99") - .expect("encrypts") - }; - for attempt in [ - ContextTag::context("table:orders").decrypt_with_aad::<String, _, _>( - &Mock, - seal(), - "row:99", - ), - ContextTag::context("table:users").decrypt_with_aad::<String, _, _>( - &Mock, - seal(), - "row:100", - ), - // The tag and the extra AAD are not interchangeable. - ContextTag::context("row:99").decrypt_with_aad::<String, _, _>( - &Mock, - seal(), - "table:users", - ), - // Nor is a bare decrypt under the tag alone. - crate::decrypt::<String, _, _>(&Mock, seal(), "table:users"), - ] { - assert!(matches!(attempt, Err(DecryptError::Cipher(Refused)))); - } - } - - #[test] - fn the_async_methods_bind_the_same_aad_as_the_sync_ones() { - use crate::seal::mock::Remote; - use futures_executor::block_on; - - let remote = Remote::new(false); - let sync_leaf = sealed_with(ContextTag::new("secret", "user:42"), "row:7"); - let async_node = - block_on(ContextTag::new("secret", "user:42").encrypt_with_aad_async(&remote, "row:7")) - .expect("the mock cannot fail"); - let CipherText::Single(async_leaf) = async_node else { - panic!("a scalar seals as one leaf"); - }; - assert_eq!(async_leaf.aad, sync_leaf.aad); - assert_eq!(async_leaf.plaintext, sync_leaf.plaintext); - - // And the async decrypt mirrors it, with and without extra AAD. - let back: String = block_on(ContextTag::context("user:42").decrypt_with_aad_async( - &remote, - CipherText::Single(async_leaf), - "row:7", - )) - .expect("decrypts"); - assert_eq!(back, "secret"); - let node = block_on(ContextTag::new("secret", "user:42").encrypt_async(&remote)) - .expect("the mock cannot fail"); - let back: String = block_on(ContextTag::context("user:42").decrypt_async(&remote, node)) - .expect("decrypts"); - assert_eq!(back, "secret"); - let node = block_on(ContextTag::new("secret", "user:42").encrypt_async(&remote)) - .expect("the mock cannot fail"); - assert!( - block_on(ContextTag::context("other").decrypt_async::<String, _>(&remote, node)) - .is_err(), - "a different tag is a different AAD" - ); - } - - #[test] - fn the_async_decrypt_futures_are_send() { - use crate::seal::mock::Remote; - use futures_executor::block_on; - - fn assert_send<F: Send>(future: F) -> F { - future - } - let remote = Remote::new(false); - let node = - block_on(ContextTag::new("secret", "user:42").encrypt_with_aad_async(&remote, "row:7")) - .expect("the mock cannot fail"); - let future = assert_send( - ContextTag::context("user:42") - .decrypt_with_aad_async::<String, _, _>(&remote, node, "row:7"), - ); - assert_eq!(block_on(future).expect("decrypts"), "secret"); - - let node = block_on(ContextTag::new("secret", "user:42").encrypt_async(&remote)) - .expect("the mock cannot fail"); - let future = - assert_send(ContextTag::context("user:42").decrypt_async::<String, _>(&remote, node)); - assert_eq!(block_on(future).expect("decrypts"), "secret"); - - let node = block_on(crate::encrypt_async("secret", &remote, "user:42")) - .expect("the mock cannot fail"); - let future = assert_send(crate::decrypt_async::<String, _, _>( - &remote, node, "user:42", - )); - assert_eq!(block_on(future).expect("decrypts"), "secret"); - } - - #[test] - fn debug_shows_the_tag_and_masks_the_value() { - let shown = format!("{:?}", ContextTag::new("secret message", "user:42")); - assert!(!shown.contains("secret message"), "got {shown}"); - assert!(shown.contains("user:42"), "got {shown}"); - } -} diff --git a/packages/vitaminc-aead/src/encrypt_sink.rs b/packages/vitaminc-aead/src/encrypt_sink.rs index b7ff6b99b..4ea64b466 100644 --- a/packages/vitaminc-aead/src/encrypt_sink.rs +++ b/packages/vitaminc-aead/src/encrypt_sink.rs @@ -1,13 +1,9 @@ //! Encryption as a sink. //! //! [`EncryptSink`] turns each scalar into tagged leaf plaintext and owns -//! every container rule in one place: +//! every rule about a value's shape in one place: //! -//! - a sequence element is sealed under -//! [`Context::for_sequence_element`], a map value under -//! [`Context::for_map_entry`] of its key; -//! - an empty sequence or map is an authenticated empty marker under -//! [`Context::for_empty_sequence`] or [`Context::for_empty_map`]; +//! - an empty sequence or map is a marker leaf with no plaintext; //! - a passthrough subtree is framed, in the clear; //! - the value keeps the [`shape`] rules: no duplicate keys, //! at least one leaf sealed in every container with children, no child @@ -22,13 +18,19 @@ //! sink holds only a borrow of its parent's place and its own index or //! key, so the path is built only when a value is refused. //! -//! The sink never calls a cipher. It plans a tree of [`Pending`] leaves, -//! each with its plaintext and the AAD its position derives, and -//! [`seal_all`] or [`seal_all_async`] seals them afterwards. So the walk -//! is synchronous whatever the cipher is, and terms collected by a sink -//! teed with this one are complete before the first await. +//! The sink never calls a cipher and holds no context. It walks a value +//! into a tree of [`Plaintext`] leaves: the value, staged for encryption. +//! [`Node::seal`] seals that tree afterwards, and derives each leaf's AAD +//! from its place: a sequence element under +//! [`for_sequence_element`](crate::Context::for_sequence_element), a map +//! value under [`for_map_entry`](crate::Context::for_map_entry) of its key, +//! an empty sequence or map under +//! [`for_empty_sequence`](crate::Context::for_empty_sequence) or +//! [`for_empty_map`](crate::Context::for_empty_map). Opening derives them +//! through the same function. So the walk is synchronous +//! whatever the cipher is, and terms collected by a sink teed with this +//! one are complete before any key is fetched. -use core::future::Future; use core::marker::PhantomData; use vitaminc_protected::{Controlled, Protected}; @@ -39,27 +41,22 @@ use crate::plaintext::{ Encrypt, EncryptRef, Error, FixedType, Logical, MapSink, Physical, SeqSink, Sink, SourceError, Step, }; -use crate::seal::{ - seal_all, seal_all_async, AsyncCipher, Cipher, LeafCount, Node, Pending, SealError, -}; +use crate::seal::{Cipher, Node, Plaintext}; use crate::shape::{ self, refuse, Locate, MapRules, Refusal, Root, SeqRules, Settle, Unencryptable, }; -use crate::{CipherText, Context, IntoAad}; +use crate::{CipherText, IntoAad}; /// Why encryption failed. /// /// A cipher's own error is printed in the message rather than chained as /// the `source()`, so a cipher error type need not implement `Error`. /// -/// Detected data-model and batch-count violations are errors, including -/// a value too long for the frame's `u32` length -/// prefixes ([`Unencryptable::Unwritable`], -/// [`Unencryptable::UnframablePassthrough`]) and a cipher that returns the -/// wrong number of leaves ([`EncryptError::Count`]). The value often comes -/// from a host (a JavaScript object, a Go frame) and the cipher may be a -/// remote key provider, so neither is under the caller's control. A panic -/// there would let hostile input or a bad response abort the process: in +/// A violation of the data model is an error, including a value too long +/// for the frame's `u32` length prefixes ([`Unencryptable::Unwritable`], +/// [`Unencryptable::UnframablePassthrough`]). The value often comes from a +/// host (a JavaScript object, a Go frame), so it is not under the caller's +/// control. A panic there would let hostile input abort the process: in /// the Node binding, a panic aborts Node. /// /// A type that derives `Encrypt` cannot hit most of these. The derive @@ -84,10 +81,6 @@ pub enum EncryptError<E> { /// value. See [`Refusal`]. #[error("cannot encrypt: {0}")] Shape(Refusal), - /// The cipher returned the wrong number of leaves: a cipher bug, not a - /// problem with the value. - #[error("cipher returned {0}")] - Count(LeafCount), } impl<E> Error for EncryptError<E> { @@ -96,23 +89,23 @@ impl<E> Error for EncryptError<E> { } } -impl<E> From<Refusal> for EncryptError<E> { - fn from(refusal: Refusal) -> Self { - Self::Shape(refusal) +/// A frame writer teed beside the encrypting sink reports through the +/// walk's one error type. +impl<E> From<crate::frame::FrameWriteError> for EncryptError<E> { + fn from(error: crate::frame::FrameWriteError) -> Self { + Self::Source(SourceError::new(error)) } } -impl<E> From<SealError<E>> for EncryptError<E> { - fn from(error: SealError<E>) -> Self { - match error { - SealError::Cipher(e) => Self::Cipher(e), - SealError::Count(count) => Self::Count(count), - } +impl<E> From<Refusal> for EncryptError<E> { + fn from(refusal: Refusal) -> Self { + Self::Shape(refusal) } } -/// Walk a source into a tree of pending leaves. No cipher is involved: -/// this is the whole of the data-model work, and it is synchronous. +/// Walk a source into a tree of plaintext leaves: the value, staged for +/// encryption. No cipher and no context is involved: this is the whole of +/// the data-model work, and it is synchronous. /// /// # Errors /// @@ -123,17 +116,13 @@ impl<E> From<SealError<E>> for EncryptError<E> { /// # Examples /// /// ``` -/// use vitaminc_aead::{plan, CipherText}; -/// let tree = plan::<_, std::convert::Infallible, _>(42u32, "account")?; -/// assert!(matches!(tree, CipherText::Single(_))); +/// use vitaminc_aead::{plan, Node}; +/// let staged = plan::<_, std::convert::Infallible>(42u32)?; +/// assert!(matches!(staged, Node::Single(_))); /// # Ok::<(), Box<dyn std::error::Error>>(()) /// ``` -pub fn plan<'a, P, E, A>(value: P, aad: A) -> Result<Node<Pending>, EncryptError<E>> -where - P: Encrypt, - A: IntoAad<'a>, -{ - value.visit(EncryptSink::root(aad)) +pub fn plan<P: Encrypt, E>(value: P) -> Result<Node<Plaintext>, EncryptError<E>> { + value.visit(EncryptSink::new()) } /// Encrypt any source. @@ -155,52 +144,29 @@ where C: Cipher, A: IntoAad<'a>, { - Ok(seal_all(cipher, plan(value, aad)?)?) -} - -/// Encrypt any source through an async cipher. A cipher with a batch API -/// seals the document in one round trip. -/// -/// The walk happens here, before this returns, and the future holds only -/// the planned leaves. So the future is `Send` even when the source is not -/// (a JavaScript object behind a host binding). -/// -/// # Errors and cancellation -/// -/// Planning failures are stored in the returned future and reported when it is -/// polled. Sealing errors and incorrect batch result counts return no tree. -/// Dropping the future drops its plan and protected buffers; any remote work -/// already submitted by the cipher may still finish. See [`AsyncCipher`]. -pub fn encrypt_async<'a, 'c, P, C, A>( - value: P, - cipher: &'c C, - aad: A, -) -> impl Future<Output = Result<Node<C::Leaf>, EncryptError<C::Error>>> + Send + 'c -where - P: Encrypt, - C: AsyncCipher, - A: IntoAad<'a>, -{ - let planned = plan(value, aad); - async move { Ok(seal_all_async(cipher, planned?).await?) } + plan(value)? + .seal(&aad.into_aad(), |plaintext, aad| { + cipher.seal(plaintext, aad) + }) + .map_err(EncryptError::Cipher) } /// Where a finished node goes: back to the caller, or into a parent. It /// also knows where the node sits, for a refusal. pub trait Slot: Locate { type Ok; - fn put(self, node: Node<Pending>) -> Self::Ok; + fn put(self, node: Node<Plaintext>) -> Self::Ok; } impl Slot for Root { - type Ok = Node<Pending>; - fn put(self, node: Node<Pending>) -> Node<Pending> { + type Ok = Node<Plaintext>; + fn put(self, node: Node<Plaintext>) -> Node<Plaintext> { node } } /// Tell a container's rules how its child ended. -fn settle(settle: Settle<'_>, node: &Node<Pending>) { +fn settle(settle: Settle<'_>, node: &Node<Plaintext>) { if matches!(node, CipherText::Passthrough(_)) { settle.passthrough(); } else { @@ -211,7 +177,7 @@ fn settle(settle: Settle<'_>, node: &Node<Pending>) { /// An element slot in a parent sequence: the parent's items, this /// element's hold on the parent's rules, and the parent's place. pub struct Push<'s> { - items: &'s mut Vec<Node<Pending>>, + items: &'s mut Vec<Node<Plaintext>>, settle: Settle<'s>, parent: &'s dyn Locate, } @@ -224,7 +190,7 @@ impl Locate for Push<'_> { impl Slot for Push<'_> { type Ok = (); - fn put(self, node: Node<Pending>) { + fn put(self, node: Node<Plaintext>) { settle(self.settle, &node); self.items.push(node); } @@ -234,7 +200,7 @@ impl Slot for Push<'_> { /// on the parent's rules, which also lends it the key, and the parent's /// place. pub struct Entry<'s> { - entries: &'s mut Vec<(String, Node<Pending>)>, + entries: &'s mut Vec<(String, Node<Plaintext>)>, settle: Settle<'s>, parent: &'s dyn Locate, } @@ -249,38 +215,78 @@ impl Slot for Entry<'_> { type Ok = (); /// The key stays in the parent's rules until the map ends, and the /// entry holds an empty string in its place, which does not allocate. - fn put(self, node: Node<Pending>) { + fn put(self, node: Node<Plaintext>) { settle(self.settle, &node); self.entries.push((String::new(), node)); } } -/// The encrypting sink. +/// The sink that walks a value into a `Node<Plaintext>`: a tree of +/// plaintext leaves, staged for encryption. +/// +/// It holds no context and calls no cipher. A leaf's AAD comes from its +/// place in the tree, and [`Node::seal`] derives it, as the function that +/// opens does. /// /// `E` is the cipher's error type, so this sink can be teed with others /// before any cipher is involved; the sink itself never produces /// `EncryptError::Cipher`. -pub struct EncryptSink<E, O = Root> { - aad: Context<'static>, +pub struct EncryptSink<O, E> { out: O, /// How far below the root this node sits. depth: usize, _error: PhantomData<E>, } -impl<E> EncryptSink<E, Root> { - /// A sink for a whole value under `aad`. Its `Ok` is the planned tree. - pub fn root<'a>(aad: impl IntoAad<'a>) -> Self { +impl<E> EncryptSink<Root, E> { + /// A sink for a whole value. Its `Ok` is the value staged for + /// encryption, with nothing sealed. + pub fn new() -> Self { + Self::at(Root) + } +} + +impl<E> Default for EncryptSink<Root, E> { + fn default() -> Self { + Self::new() + } +} + +impl<O: Slot, E> EncryptSink<O, E> { + /// A sink for a whole value, whose tree goes to `out` when the walk + /// ends. + fn at(out: O) -> Self { Self { - aad: aad.into_aad().into_owned(), - out: Root, + out, depth: 0, _error: PhantomData, } } } -impl<E, O: Slot> EncryptSink<E, O> { +/// A place a caller lends for one whole value's tree. A refusal's path +/// starts at that value. +impl Locate for &mut Option<Node<Plaintext>> { + fn locate(&self, _: &mut Vec<Step>) {} +} + +impl Slot for &mut Option<Node<Plaintext>> { + type Ok = (); + fn put(self, node: Node<Plaintext>) { + *self = Some(node); + } +} + +impl<'s, E> EncryptSink<&'s mut Option<Node<Plaintext>>, E> { + /// A sink for a whole value, which is written to `place`, staged for + /// encryption, when the walk ends. A caller that walks several values in one pass (the + /// fields of a record) lends a place for each. + pub fn into(place: &'s mut Option<Node<Plaintext>>) -> Self { + Self::at(place) + } +} + +impl<O: Slot, E> EncryptSink<O, E> { /// Plan one scalar as one leaf: its tag, then its payload. fn leaf(self, ty: Option<Logical>, v: Physical<'_>) -> Result<O::Ok, EncryptError<E>> { shape::scalar(self.depth, ty, &v, &self.out)?; @@ -295,10 +301,7 @@ impl<E, O: Slot> EncryptSink<E, O> { }, ) })?; - Ok(self.out.put(CipherText::Single(Pending { - plaintext, - aad: self.aad, - }))) + Ok(self.out.put(CipherText::Single(plaintext))) } /// Plan an absent value of a fixed-width type as one leaf: a typed @@ -310,25 +313,20 @@ impl<E, O: Slot> EncryptSink<E, O> { let ty = leaf::sealed_null_type(ty); let mut plaintext = Protected::new(Vec::with_capacity(leaf::typed_null_len(ty))); leaf::write_typed_null(ty, plaintext.risky_inner_mut()); - Ok(self.out.put(CipherText::Single(Pending { - plaintext, - aad: self.aad, - }))) + Ok(self.out.put(CipherText::Single(plaintext))) } } -fn marker(aad: Context<'static>) -> Pending { - Pending { - plaintext: Protected::new(Vec::new()), - aad, - } +/// The plaintext of an empty container's marker leaf: nothing. +fn marker() -> Protected<Vec<u8>> { + Protected::new(Vec::new()) } -impl<E, O: Slot> Sink for EncryptSink<E, O> { +impl<O: Slot, E> Sink for EncryptSink<O, E> { type Ok = O::Ok; type Error = EncryptError<E>; - type Seq = EncryptSeq<E, O>; - type Map = EncryptMap<E, O>; + type Seq = EncryptSeq<O, E>; + type Map = EncryptMap<O, E>; fn scalar(self, ty: Option<Logical>, v: Physical<'_>) -> Result<O::Ok, Self::Error> { self.leaf(ty, v) @@ -341,8 +339,6 @@ impl<E, O: Slot> Sink for EncryptSink<E, O> { fn seq(self, len: Option<usize>) -> Result<Self::Seq, Self::Error> { shape::container(self.depth, &self.out)?; Ok(EncryptSeq { - element_aad: self.aad.for_sequence_element(), - aad: self.aad, items: Vec::with_capacity(len.unwrap_or(0).min(1024)), rules: SeqRules::new(), out: self.out, @@ -354,7 +350,6 @@ impl<E, O: Slot> Sink for EncryptSink<E, O> { fn map(self, _len: Option<usize>) -> Result<Self::Map, Self::Error> { shape::container(self.depth, &self.out)?; Ok(EncryptMap { - aad: self.aad, entries: Vec::new(), rules: MapRules::new(), out: self.out, @@ -375,27 +370,24 @@ impl<E, O: Slot> Sink for EncryptSink<E, O> { } } -pub struct EncryptSeq<E, O> { - aad: Context<'static>, - element_aad: Context<'static>, - items: Vec<Node<Pending>>, +pub struct EncryptSeq<O, E> { + items: Vec<Node<Plaintext>>, rules: SeqRules, out: O, depth: usize, _error: PhantomData<E>, } -impl<E, O: Slot> SeqSink for EncryptSeq<E, O> { +impl<O: Slot, E> SeqSink for EncryptSeq<O, E> { type Ok = O::Ok; type Error = EncryptError<E>; type Element<'s> - = EncryptSink<E, Push<'s>> + = EncryptSink<Push<'s>, E> where Self: 's; fn element(&mut self) -> Result<Self::Element<'_>, Self::Error> { Ok(EncryptSink { - aad: self.element_aad.clone(), out: Push { settle: self.rules.element(&self.out)?, items: &mut self.items, @@ -409,7 +401,7 @@ impl<E, O: Slot> SeqSink for EncryptSeq<E, O> { fn end(self) -> Result<O::Ok, Self::Error> { self.rules.end(&self.out)?; let node = if self.items.is_empty() { - CipherText::EmptySequence(marker(self.aad.for_empty_sequence())) + CipherText::EmptySequence(marker()) } else { CipherText::Sequence(self.items) }; @@ -417,10 +409,9 @@ impl<E, O: Slot> SeqSink for EncryptSeq<E, O> { } } -pub struct EncryptMap<E, O> { - aad: Context<'static>, +pub struct EncryptMap<O, E> { /// Each entry's node, in order, with an empty key until the map ends. - entries: Vec<(String, Node<Pending>)>, + entries: Vec<(String, Node<Plaintext>)>, /// The only copy of each key, which `end` moves into `entries`. rules: MapRules, out: O, @@ -428,17 +419,16 @@ pub struct EncryptMap<E, O> { _error: PhantomData<E>, } -impl<E, O: Slot> MapSink for EncryptMap<E, O> { +impl<O: Slot, E> MapSink for EncryptMap<O, E> { type Ok = O::Ok; type Error = EncryptError<E>; type Entry<'s> - = EncryptSink<E, Entry<'s>> + = EncryptSink<Entry<'s>, E> where Self: 's; fn entry(&mut self, key: &str) -> Result<Self::Entry<'_>, Self::Error> { Ok(EncryptSink { - aad: self.aad.for_map_entry(key), out: Entry { settle: self.rules.entry(key, &self.out)?, entries: &mut self.entries, @@ -457,7 +447,7 @@ impl<E, O: Slot> MapSink for EncryptMap<E, O> { } } let node = if self.entries.is_empty() { - CipherText::EmptyMap(marker(self.aad.for_empty_map())) + CipherText::EmptyMap(marker()) } else { CipherText::Map(self.entries) }; @@ -496,14 +486,11 @@ mod tests { sink.passthrough(&Throws) } } - assert!(matches!( - plan::<_, (), _>(Doc, "ctx"), - Err(EncryptError::Source(_)) - )); + assert!(matches!(plan::<_, ()>(Doc), Err(EncryptError::Source(_)))); } - fn planned<P: Encrypt>(p: P) -> Result<Node<Pending>, EncryptError<Refused>> { - plan(p, "ctx") + fn planned<P: Encrypt>(p: P) -> Result<Node<Plaintext>, EncryptError<Refused>> { + plan(p) } /// Why a plan was refused and where, the path written out by @@ -524,7 +511,7 @@ mod tests { let node = planned(34u32).expect("plans"); let leaves = leaves_with_aad(node, &"ctx".into_aad()); assert_eq!(leaves.len(), 1); - assert_eq!(leaves[0].0.plaintext.risky_ref(), &[0x06, 34, 0, 0, 0]); + assert_eq!(leaves[0].0.risky_ref(), &[0x06, 34, 0, 0, 0]); assert_eq!(leaves[0].1, "ctx".into_aad()); } @@ -533,7 +520,7 @@ mod tests { let node = planned(None::<String>).expect("plans"); assert!(matches!(node, CipherText::Single(_))); let leaves = leaves_with_aad(node, &"ctx".into_aad()); - assert_eq!(leaves[0].0.plaintext.risky_ref(), &[0x00]); + assert_eq!(leaves[0].0.risky_ref(), &[0x00]); assert_eq!(leaves[0].1, "ctx".into_aad()); } @@ -542,10 +529,10 @@ mod tests { let node = planned(None::<u32>).expect("plans"); assert!(matches!(node, CipherText::Single(_))); let leaves = leaves_with_aad(node, &"ctx".into_aad()); - assert_eq!(leaves[0].0.plaintext.risky_ref(), &[0x15, 0x06, 0, 0, 0]); + assert_eq!(leaves[0].0.risky_ref(), &[0x15, 0x06, 0, 0, 0]); assert_eq!(leaves[0].1, "ctx".into_aad()); let some = leaves_with_aad(planned(Some(34u32)).expect("plans"), &"ctx".into_aad()); - assert_eq!(some[0].0.plaintext.risky_ref().len(), 5); + assert_eq!(some[0].0.risky_ref().len(), 5); } /// A timestamp and its typed null are sealed in nanoseconds, whatever @@ -565,7 +552,7 @@ mod tests { } let leaf = |p: Millis| { let leaves = leaves_with_aad(planned(p).expect("plans"), &"ctx".into_aad()); - leaves[0].0.plaintext.risky_ref().to_vec() + leaves[0].0.risky_ref().to_vec() }; let mut some = vec![0x13]; some.extend_from_slice(&0i64.to_le_bytes()); @@ -579,16 +566,14 @@ mod tests { #[test] fn a_typed_null_too_deep_is_refused_like_a_scalar() { use crate::plaintext::{FixedType, Width}; - let sink = EncryptSink::<Refused, Root> { - aad: "ctx".into_aad().into_owned(), + let sink = EncryptSink::<Root, Refused> { out: Root, depth: crate::frame::MAX_DEPTH + 1, _error: PhantomData, }; let err = sink .typed_null(FixedType::plain(Width::I8).expect("fixed")) - .err() - .expect("too deep"); + .expect_err("too deep"); assert!(matches!(err, EncryptError::Shape(_)), "{err:?}"); } @@ -737,7 +722,7 @@ mod tests { let mut scalars = 0; let (node, ()) = vec![1u32, 2] .visit(Tee( - EncryptSink::<Refused>::root("ctx"), + EncryptSink::<Root, Refused>::new(), Count(&mut scalars, PhantomData), )) .expect("walks"); @@ -1021,7 +1006,7 @@ mod tests { let mut scalars = 0; let invalid = Raw(Some(Logical::Uuid), Physical::Bytes(&[0; 3])); let teed = Users(invalid).visit(Tee( - EncryptSink::<Refused>::root("ctx"), + EncryptSink::<Root, Refused>::new(), Count(&mut scalars, PhantomData), )); assert_eq!( @@ -1032,9 +1017,7 @@ mod tests { #[test] fn a_refusal_shows_its_path_only_on_request() { - let err = plan::<_, &str, _>(Users(Dup), "ctx") - .err() - .expect("refused"); + let err = plan::<_, &str>(Users(Dup)).expect_err("refused"); // Neither the message nor `Debug` names a key; `Debug` keeps the // path's shape. assert_eq!(err.to_string(), "cannot encrypt: duplicate key"); @@ -1097,10 +1080,6 @@ mod tests { shape(Unencryptable::TooDeep), "cannot encrypt: value nests deeper than 128 levels" ); - assert_eq!( - EncryptError::<&str>::Count(LeafCount::TooFew).to_string(), - "cipher returned too few leaves" - ); assert_eq!( EncryptError::<&str>::Cipher("down").to_string(), "cipher failed: down" diff --git a/packages/vitaminc-aead/src/frame.rs b/packages/vitaminc-aead/src/frame.rs index 0396d9a8b..b92d740a7 100644 --- a/packages/vitaminc-aead/src/frame.rs +++ b/packages/vitaminc-aead/src/frame.rs @@ -595,8 +595,9 @@ impl<'o> FrameWriter<'o> { } impl<'o, E> FrameWriter<'o, E> { - /// A writer that reports `E`. - fn reporting(out: &'o mut Buffer, depth: usize) -> Self { + /// A writer that reports `E`: for a writer teed beside sinks that + /// report another error than [`FrameWriteError`]. + pub fn reporting(out: &'o mut Buffer, depth: usize) -> Self { Self { out, depth, @@ -751,8 +752,7 @@ impl<'o, E: Error + From<FrameWriteError>> Sink for FrameWriter<'o, E> { /// Written as the plain null. A frame is plaintext, never sealed, so /// padding hides nothing in it: what a frame writer produces goes to a - /// host (the frame [`decrypt_to_frame`](crate::decrypt_to_frame) - /// returns) or into the clear (a passthrough subtree), where the plain + /// host (a value decrypted into a [`FrameWriter`]) or into the clear (a passthrough subtree), where the plain /// null is what every reader already knows. A frame a host sends may /// still carry a typed null, which [`Frame`] reads, so the host's /// absent values are padded when sealed; [`OwnedFrame::typed_null`] @@ -908,7 +908,7 @@ mod tests { } } assert!(matches!( - crate::plan::<_, (), _>(Doc, "ctx"), + crate::plan::<_, ()>(Doc), Err(crate::EncryptError::Shape(_)) )); } diff --git a/packages/vitaminc-aead/src/hlist/cipher.rs b/packages/vitaminc-aead/src/hlist/cipher.rs deleted file mode 100644 index 5fd73fc53..000000000 --- a/packages/vitaminc-aead/src/hlist/cipher.rs +++ /dev/null @@ -1,182 +0,0 @@ -// The growing-HList builder return types are intentionally large — that's -// the whole design. Suppress the lint at module scope rather than smearing -// it across each method signature. -#![allow(clippy::type_complexity)] - -use vitaminc_protected::Protected; - -use crate::{Context, IntoAad}; - -use super::types::{Absent, Encrypted, Entry, Map, Passthrough}; -use super::{HCons, HList, HNil}; - -/// Statically-shaped counterpart to [`Cipher`](crate::Cipher). -/// -/// Each operation produces a leaf or builder whose Rust type fully -/// describes its content — no `Cipher::Ok` associated type, because the -/// output type changes per call. -/// -/// Implement for a reference type (e.g. `&MyCipher`) so the cipher can be -/// reused across the builder chain; the trait requires `Copy` for this -/// reason. -pub trait StaticCipher: Sized + Copy { - /// Opaque error type — typically `Unspecified`. - type Error; - - /// Seal `data` under the supplied AAD. - /// - /// The leaf holds the tagged bytes scalar, `[tags::BYTES] ++ data`, the - /// same leaf the sink path seals for a `Vec<u8>`, so an opener can tell - /// it from the null leaf [`encrypt_none`](Self::encrypt_none) seals. - /// - /// The plaintext is taken as `Protected<Vec<u8>>` so the chain of custody - /// survives the trait boundary, as [`Cipher::seal`](crate::Cipher::seal) - /// takes it. `Protected` wipes the buffer on drop. - fn encrypt_bytes<'a, A>( - self, - data: Protected<Vec<u8>>, - aad: A, - ) -> Result<Encrypted, Self::Error> - where - A: IntoAad<'a>; - - /// Produce an authenticated "no value" marker bound to `aad`: the null - /// leaf, `[tags::NULL]`, the same leaf the sink path seals for a `None` - /// of bytes. Bytes are variable width, so it is not padded. - fn encrypt_none<'a, A>(self, aad: A) -> Result<Absent, Self::Error> - where - A: IntoAad<'a>; - - /// Wrap `value` for passthrough — never fails, never encrypts. - fn passthrough<T>(self, value: T) -> Passthrough<T> { - Passthrough(value) - } - - /// Begin building a typed map. - fn encrypt_map(self) -> StaticMapBuilder<Self, HNil> { - StaticMapBuilder { - cipher: self, - list: HNil, - } - } -} - -/// HList-growing builder for typed maps. Each entry method consumes -/// `self` and returns a builder whose HList parameter is one cell longer. -pub struct StaticMapBuilder<C, L> { - cipher: C, - list: L, -} - -impl<C, L> StaticMapBuilder<C, L> -where - C: StaticCipher, - L: HList, -{ - /// Add an encrypted entry. - /// - /// The value is sealed against [`Context::for_map_entry`](crate::Context::for_map_entry) - /// of the caller's AAD and `key` — the same contract as the dynamic - /// encrypting walk ([`crate::encrypt`]) — so a stored entry's cleartext key - /// cannot be swapped or renamed undetected. Open with a counterpart that - /// derives the same binding (e.g. `Aes256Cipher::open_encrypted_entry`). - pub fn encrypt_entry<'a, A>( - self, - key: &'static str, - value: Protected<Vec<u8>>, - aad: A, - ) -> Result<StaticMapBuilder<C, HCons<Entry<Encrypted>, L>>, C::Error> - where - A: IntoAad<'a>, - { - let entry_aad = aad.into_aad().for_map_entry(key); - let encrypted = self.cipher.encrypt_bytes(value, entry_aad)?; - Ok(StaticMapBuilder { - cipher: self.cipher, - list: HCons( - Entry { - key, - value: encrypted, - }, - self.list, - ), - }) - } - - /// Add a passthrough entry whose value stays typed end-to-end. - pub fn passthrough_entry<T>( - self, - key: &'static str, - value: T, - ) -> StaticMapBuilder<C, HCons<Entry<Passthrough<T>>, L>> { - StaticMapBuilder { - cipher: self.cipher, - list: HCons( - Entry { - key, - value: Passthrough(value), - }, - self.list, - ), - } - } - - /// Add an authenticated absent entry, key-bound like - /// [`encrypt_entry`](StaticMapBuilder::encrypt_entry). - pub fn none_entry<'a, A>( - self, - key: &'static str, - aad: A, - ) -> Result<StaticMapBuilder<C, HCons<Entry<Absent>, L>>, C::Error> - where - A: IntoAad<'a>, - { - let entry_aad = aad.into_aad().for_map_entry(key); - let absent = self.cipher.encrypt_none(entry_aad)?; - Ok(StaticMapBuilder { - cipher: self.cipher, - list: HCons(Entry { key, value: absent }, self.list), - }) - } - - /// Add a nested map entry — the value is itself a [`Map<Inner>`], built - /// inside `build` against the AAD this method derives. - /// - /// A nested map has no leaf of its own to seal, so its outer cleartext - /// `key` can only be authenticated *through* its entries: `build` - /// receives [`Context::for_map_entry`](crate::Context::for_map_entry) of the - /// caller's AAD and `key`, and every inner entry must be sealed against - /// (a derivation of) it — the same chain the dynamic encrypting walk - /// ([`crate::encrypt`]) composes when it encrypts a nested - /// map inside an entry. Renaming the outer key, or splicing in a nested - /// map sealed under another record's AAD, then fails at every inner - /// open. Open with the counterpart derivation - /// ([`Entry::nested_aad`](super::Entry::nested_aad)). - /// - /// An attacher that accepted a pre-built `Map<Inner>` could not enforce - /// any of this — the closure shape is what puts the derived AAD in the - /// builder's hands at the only moment binding is possible. - pub fn nested_entry<'a, A, Inner, F>( - self, - key: &'static str, - aad: A, - build: F, - ) -> Result<StaticMapBuilder<C, HCons<Entry<Map<Inner>>, L>>, C::Error> - where - A: IntoAad<'a>, - Inner: HList, - F: FnOnce(StaticMapBuilder<C, HNil>, Context<'static>) -> Result<Map<Inner>, C::Error>, - { - let nested_aad = aad.into_aad().for_map_entry(key); - let value = build(self.cipher.encrypt_map(), nested_aad)?; - Ok(StaticMapBuilder { - cipher: self.cipher, - list: HCons(Entry { key, value }, self.list), - }) - } - - /// Finalise the builder into a [`Map<L>`] container. - pub fn end(self) -> Map<L> { - Map(self.list) - } -} diff --git a/packages/vitaminc-aead/src/hlist/mod.rs b/packages/vitaminc-aead/src/hlist/mod.rs deleted file mode 100644 index 40a0baa14..000000000 --- a/packages/vitaminc-aead/src/hlist/mod.rs +++ /dev/null @@ -1,86 +0,0 @@ -//! HList-based static ciphertext shape (opt-in via the `hlist` feature). -//! -//! # Why a second design? -//! -//! The default [`Cipher`](crate::Cipher) / `AesCipherText` path uses a -//! recursive enum, with a `Vec` per nested container and a -//! `Box<dyn Any + Send>` for passthrough values. This is the right trade-off -//! for wasm32 / JS bindings (dynamic shapes, smaller monomorphisation -//! footprint) and for code paths whose structure is only known at runtime. -//! -//! This module provides a parallel, **statically-shaped** encoding for -//! performance-sensitive native Rust code where: -//! -//! - the ciphertext schema is known at compile time (typically derive-macro -//! generated `Encrypt` / `Decrypt` impls for fixed structs), -//! - the cost of `Box<dyn Any>` allocation + downcast on every passthrough is -//! undesirable, or -//! - passthrough must remain typed end-to-end with no runtime fallibility. -//! -//! # Shape -//! -//! Each cipher operation produces a *different* output type. The builder -//! threads them into an [`HList`] so the final container type literally -//! describes the encrypted structure: -//! -//! ```text -//! Map<HCons<Entry<Passthrough<u8>>, HCons<Entry<Encrypted>, HNil>>> -//! // └── passthrough u8 field └── encrypted bytes field -//! ``` -//! -//! Decryption is destructuring — no shape check, no downcast, no allocation -//! for the structural nodes. The leaf ciphertexts (`Encrypted`, `Absent`) -//! still carry their `LocalCipherText` payload. -//! -//! # Trade-offs -//! -//! - **Single `Cipher::Ok` is impossible**: a separate trait, -//! [`StaticCipher`], replaces [`Cipher`](crate::Cipher) here. The two trait -//! hierarchies coexist behind the feature flag. -//! - **Homogeneous `Vec<_>` of varying length is not expressible** in HList -//! form — `Vec<Encrypted>` of uniform primitives still works, but the -//! dynamic path's `Vec<AesCipherText>` does not have a direct equivalent. -//! - **Type spellings are large**. A derive macro should generate the -//! `type FooCiphertext = Map<HCons<...>>` aliases; humans should rarely -//! write them by hand. - -mod cipher; -mod types; - -pub use cipher::{StaticCipher, StaticMapBuilder}; -pub use types::{Absent, Encrypted, Entry, Map, Passthrough, Seq}; - -/// The empty HList — terminates an [`HCons`] chain. -pub struct HNil; - -/// One cell of an HList: head element `H` plus tail HList `T`. -pub struct HCons<H, T>(pub H, pub T); - -/// Marker for types that form a well-formed (terminated) HList. -pub trait HList: sealed::Sealed {} -impl HList for HNil {} -impl<H, T: HList> HList for HCons<H, T> {} - -mod sealed { - pub trait Sealed {} - impl Sealed for super::HNil {} - impl<H, T: super::HList> Sealed for super::HCons<H, T> {} -} - -/// Construct an HList literal: `hlist![1, "two", 3.0]`. -#[macro_export] -macro_rules! hlist { - () => { $crate::hlist::HNil }; - ($head:expr $(, $tail:expr)* $(,)?) => { - $crate::hlist::HCons($head, $crate::hlist![$($tail),*]) - }; -} - -/// Destructure an HList: `let hlist_pat![a, b, c] = list;`. -#[macro_export] -macro_rules! hlist_pat { - () => { $crate::hlist::HNil }; - ($head:pat $(, $tail:pat)* $(,)?) => { - $crate::hlist::HCons($head, $crate::hlist_pat![$($tail),*]) - }; -} diff --git a/packages/vitaminc-aead/src/hlist/types.rs b/packages/vitaminc-aead/src/hlist/types.rs deleted file mode 100644 index 52888f551..000000000 --- a/packages/vitaminc-aead/src/hlist/types.rs +++ /dev/null @@ -1,93 +0,0 @@ -use crate::{Context, IntoAad, LocalCipherText}; - -use super::HList; - -/// A single sealed value (nonce + ciphertext + tag). -/// -/// The inner `LocalCipherText` is private: leaves are produced by a cipher -/// backend's `StaticCipher` impl (or, in future, a derive macro) via -/// [`Encrypted::from_local`] rather than constructed field-wise by arbitrary -/// callers. This is encapsulation, not unforgeability — `LocalCipherText: -/// From<Vec<u8>>` is public and the constructor must be reachable cross-crate, -/// so the cipher's tag verification on `open` remains the real authenticity -/// guard. -#[derive(Debug)] -pub struct Encrypted(LocalCipherText); - -impl Encrypted { - /// Wrap a sealed `LocalCipherText`. Plumbing for cipher backends and derive - /// macros — not part of the stable public surface. - #[doc(hidden)] - pub fn from_local(ct: LocalCipherText) -> Self { - Self(ct) - } - - /// Consume the leaf, yielding the inner `LocalCipherText` for decryption. - #[doc(hidden)] - pub fn into_local(self) -> LocalCipherText { - self.0 - } -} - -/// An authenticated "no value" marker: the null leaf (`[tags::NULL]`) -/// sealed under the slot's AAD, the same leaf the sink path seals for the -/// `None` of the bytes an [`Encrypted`] holds. (A `None` of a fixed-width -/// type seals there as a typed null instead, which is not an `Absent`.) -/// -/// Inner field is private for the same reason as [`Encrypted`]. -#[derive(Debug)] -pub struct Absent(LocalCipherText); - -impl Absent { - /// Wrap a sealed `LocalCipherText`. Plumbing for cipher backends and derive - /// macros — not part of the stable public surface. - #[doc(hidden)] - pub fn from_local(ct: LocalCipherText) -> Self { - Self(ct) - } - - /// Consume the marker, yielding the inner `LocalCipherText` for verification. - #[doc(hidden)] - pub fn into_local(self) -> LocalCipherText { - self.0 - } -} - -/// A typed value carried through the ciphertext container without -/// encryption. Holds `T` directly — no `Box`, no `Any`. -#[derive(Debug)] -pub struct Passthrough<T>(pub T); - -/// A map of typed `(key, value)` entries. The HList `L` encodes the -/// structural shape of the map at the type level. -#[derive(Debug)] -pub struct Map<L: HList>(pub L); - -/// A heterogeneous sequence — length and per-element type known at compile -/// time. For homogeneous, runtime-length sequences use a plain `Vec` of -/// leaf types (e.g. `Vec<Encrypted>`). -#[derive(Debug)] -pub struct Seq<L: HList>(pub L); - -/// One map entry. `key` is a `&'static str`; `value` is one of the leaf -/// or composite types above. -#[derive(Debug)] -pub struct Entry<V> { - /// Public map key used to derive the entry's context. - pub key: &'static str, - /// Sealed leaf, nested container, or explicit passthrough value at this key. - pub value: V, -} - -impl<Inner: HList> Entry<Map<Inner>> { - /// Derives the AAD this nested map's entries were built against — - /// [`Context::for_map_entry`](crate::Context::for_map_entry) of the enclosing - /// map's AAD and this entry's key. The open-side counterpart to - /// [`StaticMapBuilder::nested_entry`](super::StaticMapBuilder::nested_entry): - /// pass the result (or a further derivation of it) when opening each - /// inner entry, so a renamed outer key or a spliced-in foreign nested - /// map fails inner verification. - pub fn nested_aad<'a, A: IntoAad<'a>>(&self, aad: A) -> Context<'static> { - aad.into_aad().for_map_entry(self.key) - } -} diff --git a/packages/vitaminc-aead/src/lib.rs b/packages/vitaminc-aead/src/lib.rs index 64e044960..8fbe91c42 100644 --- a/packages/vitaminc-aead/src/lib.rs +++ b/packages/vitaminc-aead/src/lib.rs @@ -1,25 +1,20 @@ // These definitions precede the README so rustdoc links to the version being built. // The README supplies published-API URLs for GitHub. See docs/documentation.md. -//! [`AsyncCipher`]: crate::AsyncCipher //! [`CipherText`]: crate::CipherText //! [`Cipher`]: crate::Cipher -//! [`ContextTag`]: crate::ContextTag //! [`Decrypt`]: trait@crate::Decrypt //! [`Encrypt`]: trait@crate::Encrypt //! [`FrameWriter`]: crate::FrameWriter //! [`Frame`]: crate::Frame //! [`IntoAad`]: crate::IntoAad -//! [`LeafTypeAad`]: crate::LeafTypeAad //! [`PassthroughFrame`]: crate::PassthroughFrame //! [`Scalar`]: trait@crate::Scalar //! [`Sink::passthrough`]: crate::Sink::passthrough //! [`Sink`]: crate::Sink //! [`Tee`]: crate::Tee //! [`Unspecified`]: crate::Unspecified -//! [`decrypt_async`]: crate::decrypt_async //! [`decrypt_into`]: crate::decrypt_into //! [`decrypt`]: crate::decrypt -//! [`encrypt_async`]: crate::encrypt_async //! [`encrypt`]: crate::encrypt //! [`to_frame`]: crate::to_frame //! @@ -28,19 +23,19 @@ #![deny(clippy::unwrap_used, clippy::todo, unsafe_code, unused_imports)] #![doc = include_str!("../README.md")] mod aad; +#[cfg(feature = "aes")] +#[cfg_attr(docsrs, doc(cfg(feature = "aes")))] +pub mod aes; mod ciphertext; mod container; -mod context; #[cfg(feature = "jiff")] mod date_value; #[cfg(feature = "rust_decimal")] mod decimal_value; mod encrypt_sink; pub mod frame; -#[cfg(feature = "hlist")] -#[cfg_attr(docsrs, doc(cfg(feature = "hlist")))] -pub mod hlist; pub mod leaf; +#[cfg(feature = "aes")] mod nonce; pub mod plaintext; pub mod seal; @@ -70,19 +65,18 @@ pub use plaintext::{ pub use vitaminc_aead_derive::Encrypt; // Encryption: the sink, the ciphers and the entry points. #[doc(inline)] -pub use encrypt_sink::{encrypt, encrypt_async, plan, EncryptError, EncryptSink}; +pub use encrypt_sink::{encrypt, plan, EncryptError, EncryptSink}; #[doc(inline)] -pub use seal::{AsyncCipher, Cipher, Node, Opened, Pending}; +pub use seal::{Cipher, Node, Plaintext}; #[doc(inline)] 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, ScalarTarget, - TakesScalar, + decrypt, DecodeError, Decrypt, DecryptProtected, FromScalar, ScalarTarget, TakesScalar, }; #[doc(inline)] -pub use walk::{decrypt_into, decrypt_into_async, decrypt_to_frame, walk, DecryptError}; +pub use walk::{decrypt_into, walk, DecryptError}; // The frame: a value as transport bytes, and back. #[doc(inline)] pub use frame::{to_frame, Frame, FrameWriter, OwnedFrame, PassthroughFrame}; @@ -99,17 +93,14 @@ pub use timestamp::{OutOfRange, Timestamp}; #[cfg(feature = "uuid")] pub use uuid_value::Uuid; +pub use aad::{Context, ContextPiece, IntoAad, IntoContext}; +#[cfg(feature = "aes")] +pub(crate) use ciphertext::CipherTextBuilder; #[doc(inline)] -#[allow(deprecated)] -pub use aad::{Aad, AadPiece}; -pub use aad::{Context, ContextPiece, IntoAad, IntoContext, LeafTypeAad}; -#[doc(inline)] -pub use ciphertext::{CipherTextBuilder, LocalCipherText, WIRE_VERSION}; +pub use ciphertext::{LocalCipherText, WIRE_VERSION}; #[doc(inline)] pub use container::CipherText; -#[doc(inline)] -pub use context::ContextTag; -#[doc(inline)] -pub use nonce::{Nonce, NonceGenerator, RandomNonceGenerator}; +#[cfg(feature = "aes")] +pub(crate) use nonce::{NonceGenerator, RandomNonceGenerator}; #[doc(inline)] pub use unspecified::Unspecified; diff --git a/packages/vitaminc-aead/src/plaintext/depth.rs b/packages/vitaminc-aead/src/plaintext/depth.rs index c8933c6c1..35caeb6cd 100644 --- a/packages/vitaminc-aead/src/plaintext/depth.rs +++ b/packages/vitaminc-aead/src/plaintext/depth.rs @@ -30,7 +30,7 @@ //! value: T, //! } //! -//! let _ = plan::<_, (), _>(Holder { value: V128::<u32>::new() }, "aad"); +//! let _ = plan::<_, ()>(Holder { value: V128::<u32>::new() }); //! ``` //! //! One level shallower, at exactly `MAX_DEPTH`, it builds: @@ -52,7 +52,7 @@ //! value: T, //! } //! -//! assert!(plan::<_, (), _>(Holder { value: V127::<u32>::new() }, "aad").is_ok()); +//! assert!(plan::<_, ()>(Holder { value: V127::<u32>::new() }).is_ok()); //! ``` //! //! A type with only lifetime parameters is checked where it is defined, as diff --git a/packages/vitaminc-aead/src/plaintext/kinds.rs b/packages/vitaminc-aead/src/plaintext/kinds.rs index f2eea56a8..dd14f7126 100644 --- a/packages/vitaminc-aead/src/plaintext/kinds.rs +++ b/packages/vitaminc-aead/src/plaintext/kinds.rs @@ -38,9 +38,8 @@ //! 3. **Name it without its parameter**: add the matching variant to //! [`KnownLogical`], with its id and the one kind it is stored as in //! [`KnownLogical::id`], [`KnownLogical::kind`] and -//! [`KnownLogical::from_id`]. This is what a schema binds for a column -//! (see [`LeafTypeAad`](crate::LeafTypeAad)), so the kind is part of the -//! cross-language commitment too. +//! [`KnownLogical::from_id`]. The kind is part of the cross-language +//! commitment too. //! 4. **Map it on the wire** in [`Logical::to_wire`] and //! [`Logical::from_wire`]. `from_wire` must return `None` for a //! parameter the type cannot take, so a malformed envelope is refused @@ -111,8 +110,7 @@ pub enum Physical<'a> { /// A physical kind, named without a value: what a schema expects a column /// to hold. Closed, like [`Physical`], and with a wire byte of its own for -/// the places a kind is bound rather than carried, such as -/// [`LeafTypeAad`](crate::LeafTypeAad). +/// the places a kind is bound rather than carried. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Kind { /// An absent value with no payload. @@ -675,9 +673,7 @@ pub mod id { /// values may each have a scale of their own. /// /// Each one is stored as exactly one [`Kind`], named by -/// [`kind`](KnownLogical::kind), so -/// [`LeafTypeAad::logical`](crate::LeafTypeAad::logical) derives the kind -/// from it and a column with a logical type has one binding. A logical +/// [`kind`](KnownLogical::kind). A logical /// type this build does not know is an [`UnknownLogicalId`] instead. #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[non_exhaustive] @@ -734,7 +730,7 @@ impl KnownLogical { /// A logical id above [`id::LAST_KNOWN`]: a logical type from a newer /// build, which this one has no meaning for and so cannot say what kind it -/// is stored as. See [`LeafTypeAad::unknown`](crate::LeafTypeAad::unknown). +/// is stored as. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct UnknownLogicalId(u8); diff --git a/packages/vitaminc-aead/src/plaintext/sources.rs b/packages/vitaminc-aead/src/plaintext/sources.rs index 6b5245012..a439aa39e 100644 --- a/packages/vitaminc-aead/src/plaintext/sources.rs +++ b/packages/vitaminc-aead/src/plaintext/sources.rs @@ -273,9 +273,8 @@ impl<'b, T: ?Sized + EncryptRef> Scalar for &&'b T where &'b T: Scalar {} /// /// /// The shape of the one leaf `value` plans. /// fn leaf<P: Encrypt>(value: P) -> Result<Shape, EncryptError<Infallible>> { -/// match plan::<_, Infallible, _>(value, "aad")? { +/// match plan::<_, Infallible>(value)? { /// CipherText::Single(leaf) => Ok(leaf -/// .plaintext /// .map(|bytes| [bytes[0], u8::try_from(bytes.len()).expect("short")]) /// .into()), /// _ => panic!("not one leaf"), @@ -301,7 +300,7 @@ impl<'b, T: ?Sized + EncryptRef> Scalar for &&'b T where &'b T: Scalar {} /// /// // `Option<Vec<i32>>`: a `Some` is a sequence with one int leaf per /// // element, two here, and a `None` is still the one plain null leaf. -/// let some = plan::<_, Infallible, _>(Some(vec![1i32, 2]), "aad")?; +/// let some = plan::<_, Infallible>(Some(vec![1i32, 2]))?; /// let CipherText::Sequence(elements) = some else { panic!("not a sequence") }; /// assert_eq!(elements.len(), 2); /// assert!(elements.iter().all(|element| matches!(element, CipherText::Single(_)))); diff --git a/packages/vitaminc-aead/src/plaintext/tee.rs b/packages/vitaminc-aead/src/plaintext/tee.rs index 76800821e..4806e6363 100644 --- a/packages/vitaminc-aead/src/plaintext/tee.rs +++ b/packages/vitaminc-aead/src/plaintext/tee.rs @@ -104,6 +104,74 @@ impl<A: MapSink, B: MapSink<Error = A::Error>> MapSink for Tee<A, B> { } } +/// A sink that may be absent. `Some` hands every value to the sink inside. +/// `None` takes the value and keeps nothing, and checks nothing about it. +/// +/// Beside [`Tee`], it sends a value to the sinks that want it and to no +/// others: a record's field to the sink that seals it, the sink that +/// indexes it and the sink that keeps it in the clear, each present or +/// not as the field's declaration says. +impl<S: Sink> Sink for Option<S> { + type Ok = Option<S::Ok>; + type Error = S::Error; + type Seq = Option<S::Seq>; + type Map = Option<S::Map>; + + fn scalar(self, ty: Option<Logical>, value: Physical<'_>) -> Result<Self::Ok, S::Error> { + self.map(|sink| sink.scalar(ty, value)).transpose() + } + + fn typed_null(self, ty: FixedType) -> Result<Self::Ok, S::Error> { + self.map(|sink| sink.typed_null(ty)).transpose() + } + + fn seq(self, len: Option<usize>) -> Result<Self::Seq, S::Error> { + self.map(|sink| sink.seq(len)).transpose() + } + + fn map(self, len: Option<usize>) -> Result<Self::Map, S::Error> { + self.map(|sink| Sink::map(sink, len)).transpose() + } + + fn passthrough<P: ?Sized + EncryptRef>(self, value: &P) -> Result<Self::Ok, S::Error> { + self.map(|sink| sink.passthrough(value)).transpose() + } +} + +impl<S: SeqSink> SeqSink for Option<S> { + type Ok = Option<S::Ok>; + type Error = S::Error; + type Element<'s> + = Option<S::Element<'s>> + where + Self: 's; + + fn element(&mut self) -> Result<Self::Element<'_>, S::Error> { + self.as_mut().map(SeqSink::element).transpose() + } + + fn end(self) -> Result<Self::Ok, S::Error> { + self.map(SeqSink::end).transpose() + } +} + +impl<S: MapSink> MapSink for Option<S> { + type Ok = Option<S::Ok>; + type Error = S::Error; + type Entry<'s> + = Option<S::Entry<'s>> + where + Self: 's; + + fn entry(&mut self, key: &str) -> Result<Self::Entry<'_>, S::Error> { + self.as_mut().map(|sink| sink.entry(key)).transpose() + } + + fn end(self) -> Result<Self::Ok, S::Error> { + self.map(MapSink::end).transpose() + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/packages/vitaminc-aead/src/seal.rs b/packages/vitaminc-aead/src/seal.rs index a8b7eaca8..f17772432 100644 --- a/packages/vitaminc-aead/src/seal.rs +++ b/packages/vitaminc-aead/src/seal.rs @@ -7,39 +7,30 @@ //! [`EncryptSink`](crate::EncryptSink) and [`walk`](crate::walk()), so a //! second cipher cannot diverge on it. //! -//! [`Cipher`] is synchronous. [`AsyncCipher`] is for anything that has to -//! be awaited: a remote key provider, a KMS, a cloud HSM. Its `seal_many` -//! and `open_many` take every leaf of one document at once, so a provider -//! with a batch API makes one round trip per document. The walk itself is -//! never awaited: encryption plans a tree of [`Pending`] leaves first, and +//! [`Cipher`] is synchronous, and it is the only cipher trait. A caller +//! whose keys come from something that has to be awaited (a remote key +//! provider, a KMS) fetches the keys first and then seals or opens here, +//! with the keys in hand. The walk itself is never awaited: encryption +//! walks the value into a tree of [`Plaintext`] leaves first, and //! decryption opens every leaf before the sink sees anything. //! -//! Both traits are re-exported from the crate root. +//! The trait is re-exported from the crate root. -use core::future::Future; use std::collections::HashSet; -use futures_util::stream::{self, StreamExt, TryStreamExt}; use vitaminc_protected::Protected; -use crate::frame::PassthroughFrame; use crate::{CipherText, Context}; -/// A ciphertext tree whose passthrough subtrees are frames. -pub type Node<L> = CipherText<L, PassthroughFrame>; +pub use crate::container::Node; -/// A leaf the walk has planned but nobody has sealed: its tagged plaintext -/// and the AAD derived for its place in the tree. -pub struct Pending { - /// Owned tagged scalar bytes, or an empty buffer for an empty-container marker. - /// Dropping this wrapper wipes its buffer. - pub plaintext: Protected<Vec<u8>>, - /// Owned tree context before the cipher adds its leaf wire version. - pub aad: Context<'static>, -} - -/// A leaf after opening: its tagged plaintext. -pub type Opened = Protected<Vec<u8>>; +/// A leaf that is not sealed: its tagged plaintext, or an empty buffer for +/// an empty-container marker. Dropping it wipes its buffer. +/// +/// A `Node<Plaintext>` is a value staged for encryption: +/// [`EncryptSink`](crate::EncryptSink) builds one, and [`Node::seal`] seals +/// it. Opening a sealed value gives one too. +pub type Plaintext = Protected<Vec<u8>>; /// Seal and open one leaf, synchronously. /// @@ -90,187 +81,36 @@ pub trait Cipher { fn open(&self, leaf: Self::Leaf, aad: &Context<'_>) -> Result<Protected<Vec<u8>>, Self::Error>; } -/// Seal and open leaves through something that has to be awaited. -/// -/// `seal_many` and `open_many` take every leaf of one document in walk -/// order. The defaults seal each leaf concurrently, at most -/// [`DEFAULT_CONCURRENCY`] at a time; a provider with a batch API -/// overrides them to make one round trip per document. Either way the -/// cipher must return exactly one leaf per leaf it was given, in the same -/// order, or the document is refused. -/// -/// `Sync`, because an async cipher is shared across tasks. -/// The authentication and plaintext-handling obligations are those of [`Cipher`]. -/// -/// # Failure and cancellation -/// -/// The default batch methods return the first error observed in input order -/// and drop pending futures and collected outputs. They expose no partial -/// result. Dropping the batch future also drops its owned state, including -/// protected plaintext buffers. Work already submitted to a remote service -/// may still complete; there is no rollback or exactly-once guarantee. -/// Overrides must document any additional side effects or retry requirements. -pub trait AsyncCipher: Sync { - /// Owned sealed leaf, transferable between tasks. - type Leaf: Send; - /// Authentication, format, randomness, or backend failure. - type Error: Send; - - /// Seal one owned plaintext with owned AAD; see [`Cipher::seal`] for the - /// authentication, nonce, ownership, and error contract. - /// Dropping the future abandons the result, not necessarily remote work. - fn seal( - &self, - plaintext: Protected<Vec<u8>>, - aad: Context<'static>, - ) -> impl Future<Output = Result<Self::Leaf, Self::Error>> + Send; - - /// Open one owned leaf with owned AAD; see [`Cipher::open`] for the - /// authentication and error contract. Only authenticated plaintext may - /// be returned. Dropping the future need not cancel remote work. - fn open( - &self, - leaf: Self::Leaf, - aad: Context<'static>, - ) -> impl Future<Output = Result<Protected<Vec<u8>>, Self::Error>> + Send; - - /// Every pending leaf of one document, in walk order. - /// - /// Return exactly one sealed leaf per input in the same order. The default - /// handles an empty batch without calling [`seal`](Self::seal). On error, - /// return no partial vector; see the trait's cancellation contract. - fn seal_many( - &self, - leaves: Vec<Pending>, - ) -> impl Future<Output = Result<Vec<Self::Leaf>, Self::Error>> + Send { - stream::iter(leaves) - .map(|p| self.seal(p.plaintext, p.aad)) - .buffered(DEFAULT_CONCURRENCY) - .try_collect() +impl<L> Node<L> { + /// How many leaves the tree has: every scalar and every + /// empty-container marker. A passthrough is not a leaf. + pub fn leaf_count(&self) -> usize { + leaves(self).len() } +} - /// Every sealed leaf of one document with the AAD its position derives, - /// in walk order. +impl Node<Plaintext> { + /// Seal every leaf with `seal`, which is given the leaf's plaintext and + /// the context its place derives under `context`. Leaves are sealed in + /// walk order, the order [`leaves`] lists the sealed tree in. /// - /// Return exactly one authenticated plaintext per input in the same order. - /// The default handles an empty batch without calling [`open`](Self::open). - /// On error, return no partial vector; see the trait's cancellation contract. - fn open_many( - &self, - leaves: Vec<(Self::Leaf, Context<'static>)>, - ) -> impl Future<Output = Result<Vec<Protected<Vec<u8>>>, Self::Error>> + Send { - stream::iter(leaves) - .map(|(leaf, aad)| self.open(leaf, aad)) - .buffered(DEFAULT_CONCURRENCY) - .try_collect() + /// With one cipher for the whole value, `seal` is + /// `|plaintext, context| cipher.seal(plaintext, context)`. A caller + /// with a key for each leaf builds that leaf's cipher in `seal`. + /// + /// # Errors + /// + /// The first error `seal` returns. No partial tree is returned, and the + /// leaves not yet sealed are wiped. + pub fn seal<L, E>( + self, + context: &Context<'_>, + mut seal: impl FnMut(Plaintext, &Context<'_>) -> Result<L, E>, + ) -> Result<Node<L>, E> { + map_under(self, context, &mut seal) } } -/// How many leaves the default `seal_many` and `open_many` have in flight -/// at once, so a large document does not send every leaf to a remote -/// provider at the same moment. -pub const DEFAULT_CONCURRENCY: usize = 32; - -/// A cipher returned a different number of leaves than it was given. -#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)] -pub enum LeafCount { - /// Fewer results than the planned tree requires. - #[error("too few leaves")] - TooFew, - /// Results remain after every planned position has been filled. - #[error("too many leaves")] - TooMany, -} - -/// Seal every pending leaf, one at a time. -pub fn seal_all<C: Cipher>( - cipher: &C, - node: Node<Pending>, -) -> Result<Node<C::Leaf>, SealError<C::Error>> { - let mut pending = Vec::new(); - let shape = split(node, &mut pending); - let leaves = pending - .into_iter() - .map(|p| cipher.seal(p.plaintext, &p.aad)) - .collect::<Result<Vec<_>, _>>() - .map_err(SealError::Cipher)?; - fill(shape, leaves).map_err(SealError::Count) -} - -/// Seal every pending leaf in one `seal_many` call. -/// -/// A tree with no leaves (a top-level passthrough) makes no call at all, -/// as the sync path and the per-leaf defaults would not, so a batching -/// provider is never asked for an empty batch. -pub async fn seal_all_async<C: AsyncCipher>( - cipher: &C, - node: Node<Pending>, -) -> Result<Node<C::Leaf>, SealError<C::Error>> { - let mut pending = Vec::new(); - let shape = split(node, &mut pending); - let leaves = if pending.is_empty() { - Vec::new() - } else { - cipher.seal_many(pending).await.map_err(SealError::Cipher)? - }; - fill(shape, leaves).map_err(SealError::Count) -} - -/// Why sealing failed. -/// -/// A cipher's own error is printed in the message rather than chained as -/// the `source()`, so a cipher error type need not implement `Error`. -#[derive(Debug, thiserror::Error)] -pub enum SealError<E> { - /// A leaf operation or batch failed; no completed tree is returned. - #[error("cipher failed: {0}")] - Cipher(E), - /// A batch violated the one-result-per-input contract. - #[error("cipher returned {0}")] - Count(LeafCount), -} - -/// Open every leaf, one at a time. -/// -/// The tree's structure is checked before any leaf is opened, so a -/// malformed tree costs no cipher calls. A cipher's failure is returned as -/// it is: for an AEAD that is wrong key, wrong AAD or tampering, for a -/// remote provider it may also be an outage, and the cipher's error type -/// says which. A leaf count mismatch is a cipher bug. -pub fn open_all<'a, C: Cipher>( - cipher: &C, - node: Node<C::Leaf>, - aad: &Context<'a>, -) -> Result<Node<Opened>, OpenError<C::Error>> { - check_shape(&node)?; - let mut sealed = Vec::new(); - let shape = split_with_aad(node, aad, &mut sealed); - let opened = sealed - .into_iter() - .map(|(leaf, aad)| cipher.open(leaf, &aad)) - .collect::<Result<Vec<_>, _>>() - .map_err(OpenError::Cipher)?; - fill(shape, opened).map_err(OpenError::Count) -} - -/// Open every leaf in one `open_many` call, after the same structural -/// check as [`open_all`]. A tree with no leaves makes no call. -pub async fn open_all_async<'a, C: AsyncCipher>( - cipher: &C, - node: Node<C::Leaf>, - aad: &Context<'a>, -) -> Result<Node<Opened>, OpenError<C::Error>> { - check_shape(&node)?; - let mut sealed = Vec::new(); - let shape = split_with_aad(node, aad, &mut sealed); - let opened = if sealed.is_empty() { - Vec::new() - } else { - cipher.open_many(sealed).await.map_err(OpenError::Cipher)? - }; - fill(shape, opened).map_err(OpenError::Count) -} - /// Why opening failed. #[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)] pub enum OpenError<E> { @@ -281,9 +121,6 @@ pub enum OpenError<E> { /// in it, a repeated map key, or a passthrough that is not a frame. #[error("malformed ciphertext")] Malformed, - /// The cipher returned the wrong number of leaves. - #[error("cipher returned {0}")] - Count(LeafCount), } /// The container rules `EncryptSink` enforced, checked on the sealed tree @@ -318,113 +155,93 @@ fn check_shape<L, E>(node: &Node<L>) -> Result<(), OpenError<E>> { } } -/// A tree's shape with its leaves taken out, in walk order. -fn split<L>(node: Node<L>, leaves: &mut Vec<L>) -> Node<()> { - match node { - CipherText::Single(leaf) => { - leaves.push(leaf); - CipherText::Single(()) - } - CipherText::Sequence(items) => { - CipherText::Sequence(items.into_iter().map(|n| split(n, leaves)).collect()) - } - CipherText::EmptySequence(leaf) => { - leaves.push(leaf); - CipherText::EmptySequence(()) - } - CipherText::Map(entries) => CipherText::Map( - entries - .into_iter() - .map(|(k, n)| (k, split(n, leaves))) - .collect(), - ), - CipherText::EmptyMap(leaf) => { - leaves.push(leaf); - CipherText::EmptyMap(()) - } - CipherText::Passthrough(p) => CipherText::Passthrough(p), - } -} - -/// A tree's shape with its leaves taken out, each paired with the AAD its -/// position derives. The derivations are the ones `EncryptSink` used. -fn split_with_aad<L>( +/// Every leaf of a tree mapped through `leaf`, which is given the AAD the +/// leaf's place derives under `aad`. Leaves are visited in walk order. +/// +/// This is the one place a leaf's AAD is derived from its place. Sealing +/// and opening both come here. +pub(crate) fn map_under<L, M, E>( node: Node<L>, aad: &Context<'_>, - leaves: &mut Vec<(L, Context<'static>)>, -) -> Node<()> { - match node { - CipherText::Single(leaf) => { - leaves.push((leaf, aad.clone().into_owned())); - CipherText::Single(()) - } + leaf: &mut impl FnMut(L, &Context<'_>) -> Result<M, E>, +) -> Result<Node<M>, E> { + Ok(match node { + CipherText::Single(l) => CipherText::Single(leaf(l, aad)?), CipherText::Sequence(items) => { let element_aad = aad.for_sequence_element(); CipherText::Sequence( items .into_iter() - .map(|n| split_with_aad(n, &element_aad, leaves)) - .collect(), + .map(|n| map_under(n, &element_aad, leaf)) + .collect::<Result<_, _>>()?, ) } - CipherText::EmptySequence(leaf) => { - leaves.push((leaf, aad.for_empty_sequence())); - CipherText::EmptySequence(()) + CipherText::EmptySequence(l) => { + CipherText::EmptySequence(leaf(l, &aad.for_empty_sequence())?) } CipherText::Map(entries) => CipherText::Map( entries .into_iter() .map(|(k, n)| { - let shape = split_with_aad(n, &aad.for_map_entry(&k), leaves); - (k, shape) + let node = map_under(n, &aad.for_map_entry(&k), leaf)?; + Ok((k, node)) }) - .collect(), + .collect::<Result<_, _>>()?, ), - CipherText::EmptyMap(leaf) => { - leaves.push((leaf, aad.for_empty_map())); - CipherText::EmptyMap(()) - } + CipherText::EmptyMap(l) => CipherText::EmptyMap(leaf(l, &aad.for_empty_map())?), CipherText::Passthrough(p) => CipherText::Passthrough(p), - } + }) } -/// Put leaves back into a shape, in walk order. -fn fill<L>(shape: Node<()>, leaves: Vec<L>) -> Result<Node<L>, LeafCount> { - let mut leaves = leaves.into_iter(); - let node = fill_from(shape, &mut leaves).ok_or(LeafCount::TooFew)?; - if leaves.next().is_some() { - return Err(LeafCount::TooMany); - } - Ok(node) +/// Open every leaf of a sealed value with `open`, which is given the leaf +/// and the AAD its place derives under `aad`. The tree's structure is +/// checked before any leaf is opened. Leaves are opened in walk order, the +/// order [`leaves`] lists them in. +/// +/// # Errors +/// +/// [`OpenError::Malformed`] for a tree that breaks a container rule, or the +/// first error `open` returns, as [`OpenError::Cipher`]. +pub fn open_with<L, E>( + node: Node<L>, + aad: &Context<'_>, + mut open: impl FnMut(L, &Context<'_>) -> Result<Plaintext, E>, +) -> Result<Node<Plaintext>, OpenError<E>> { + check_shape(&node)?; + map_under(node, aad, &mut open).map_err(OpenError::Cipher) } -fn fill_from<L>(shape: Node<()>, leaves: &mut impl Iterator<Item = L>) -> Option<Node<L>> { - Some(match shape { - CipherText::Single(()) => CipherText::Single(leaves.next()?), - CipherText::Sequence(items) => CipherText::Sequence( - items - .into_iter() - .map(|n| fill_from(n, leaves)) - .collect::<Option<_>>()?, - ), - CipherText::EmptySequence(()) => CipherText::EmptySequence(leaves.next()?), - CipherText::Map(entries) => CipherText::Map( - entries - .into_iter() - .map(|(k, n)| fill_from(n, leaves).map(|n| (k, n))) - .collect::<Option<_>>()?, - ), - CipherText::EmptyMap(()) => CipherText::EmptyMap(leaves.next()?), - CipherText::Passthrough(p) => CipherText::Passthrough(p), - }) +/// Every leaf of a tree, in walk order: the order [`Node::seal`] and +/// [`open_with`] visit them in. A passthrough is not a leaf. +pub fn leaves<L>(node: &Node<L>) -> Vec<&L> { + fn collect<'n, L>(node: &'n Node<L>, out: &mut Vec<&'n L>) { + match node { + CipherText::Single(leaf) + | CipherText::EmptySequence(leaf) + | CipherText::EmptyMap(leaf) => out.push(leaf), + CipherText::Sequence(items) => items.iter().for_each(|n| collect(n, out)), + CipherText::Map(entries) => entries.iter().for_each(|(_, n)| collect(n, out)), + CipherText::Passthrough(_) => {} + } + } + let mut out = Vec::new(); + collect(node, &mut out); + out } -/// Every leaf of a tree, in walk order, with the AAD its position derives. -/// For tests and for ciphers that inspect a plan. -pub fn leaves_with_aad<L>(node: Node<L>, aad: &Context<'_>) -> Vec<(L, Context<'static>)> { +/// Every leaf of a tree, in walk order, with the AAD its place derives. +/// For this crate's tests. +#[cfg(test)] +pub(crate) fn leaves_with_aad<L>(node: Node<L>, aad: &Context<'_>) -> Vec<(L, Context<'static>)> { let mut out = Vec::new(); - split_with_aad(node, aad, &mut out); - out + let walked = map_under(node, aad, &mut |leaf, aad| { + out.push((leaf, aad.clone().into_owned())); + Ok::<_, core::convert::Infallible>(()) + }); + match walked { + Ok(_) => out, + Err(never) => match never {}, + } } /// A cipher that stores the plaintext and AAD in the clear, for tests of @@ -432,8 +249,6 @@ pub fn leaves_with_aad<L>(node: Node<L>, aad: &Context<'_>) -> Vec<(L, Context<' #[cfg(test)] pub(crate) mod mock { use super::*; - use core::sync::atomic::{AtomicUsize, Ordering}; - use futures_util::future::try_join_all; #[derive(Debug, Clone, PartialEq, Eq)] pub struct Leaf { @@ -465,86 +280,15 @@ pub(crate) mod mock { Ok(Protected::new(leaf.plaintext)) } } - - /// The mock behind an await, counting calls. `batch` decides whether - /// `seal_many`/`open_many` are one call or the per-leaf defaults. - pub struct Remote { - pub calls: AtomicUsize, - pub batch: bool, - } - - impl Remote { - pub fn new(batch: bool) -> Self { - Self { - calls: AtomicUsize::new(0), - batch, - } - } - - pub fn calls(&self) -> usize { - self.calls.load(Ordering::SeqCst) - } - } - - impl AsyncCipher for Remote { - type Leaf = Leaf; - type Error = Refused; - - async fn seal( - &self, - plaintext: Protected<Vec<u8>>, - aad: Context<'static>, - ) -> Result<Leaf, Refused> { - self.calls.fetch_add(1, Ordering::SeqCst); - Cipher::seal(&Mock, plaintext, &aad) - } - - async fn open( - &self, - leaf: Leaf, - aad: Context<'static>, - ) -> Result<Protected<Vec<u8>>, Refused> { - self.calls.fetch_add(1, Ordering::SeqCst); - Cipher::open(&Mock, leaf, &aad) - } - - async fn seal_many(&self, leaves: Vec<Pending>) -> Result<Vec<Leaf>, Refused> { - if !self.batch { - return try_join_all(leaves.into_iter().map(|p| self.seal(p.plaintext, p.aad))) - .await; - } - self.calls.fetch_add(1, Ordering::SeqCst); - leaves - .into_iter() - .map(|p| Cipher::seal(&Mock, p.plaintext, &p.aad)) - .collect() - } - - async fn open_many( - &self, - leaves: Vec<(Leaf, Context<'static>)>, - ) -> Result<Vec<Protected<Vec<u8>>>, Refused> { - if !self.batch { - return try_join_all(leaves.into_iter().map(|(l, aad)| self.open(l, aad))).await; - } - self.calls.fetch_add(1, Ordering::SeqCst); - leaves - .into_iter() - .map(|(l, aad)| Cipher::open(&Mock, l, &aad)) - .collect() - } - } } #[cfg(test)] mod tests { - use super::mock::{Leaf, Mock, Refused, Remote}; + use super::mock::{Leaf, Mock, Refused}; use super::*; use crate::frame::PassthroughFrame; - use crate::plaintext::record::{record, Event, Owned}; - use crate::{decrypt_into, encrypt, encrypt_async, plan, walk, EncryptError, Int, IntoAad}; - use core::sync::atomic::{AtomicUsize, Ordering}; - use futures_executor::block_on; + use crate::plaintext::record::record; + use crate::{decrypt_into, encrypt, plan, walk, EncryptError, IntoAad}; use std::collections::BTreeMap; use vitaminc_protected::Controlled; @@ -558,7 +302,7 @@ mod tests { #[test] fn leaves_come_out_in_walk_order_with_their_own_aad() { - let planned = plan::<_, Refused, _>(sample(), "ctx").expect("plans"); + let planned = plan::<_, Refused>(sample()).expect("plans"); let leaves = leaves_with_aad(planned, &"ctx".into_aad()); // a: three elements, b: one empty marker, c: one element. assert_eq!(leaves.len(), 5); @@ -576,9 +320,9 @@ mod tests { ); // The marker is empty; the absent `u32` is a typed null, as long // as the `u32` leaves beside it. - assert!(leaves[3].0.plaintext.risky_ref().is_empty()); - assert_eq!(leaves[1].0.plaintext.risky_ref(), &[0x15, 0x06, 0, 0, 0]); - assert_eq!(leaves[0].0.plaintext.risky_ref().len(), 5); + assert!(leaves[3].0.risky_ref().is_empty()); + assert_eq!(leaves[1].0.risky_ref(), &[0x15, 0x06, 0, 0, 0]); + assert_eq!(leaves[0].0.risky_ref().len(), 5); // And the plan's AAD is what the sealed leaf is bound under. let sealed = encrypt(sample(), &Mock, "ctx").expect("encrypts"); let sealed = leaves_with_aad(sealed, &"ctx".into_aad()); @@ -588,7 +332,8 @@ mod tests { #[test] fn open_then_walk_is_the_original() { let sealed = encrypt(sample(), &Mock, "ctx").expect("encrypts"); - let opened = open_all(&Mock, sealed, &"ctx".into_aad()).expect("opens"); + let opened = + open_with(sealed, &"ctx".into_aad(), |leaf, aad| Mock.open(leaf, aad)).expect("opens"); let mut log = Vec::new(); walk(opened, crate::plaintext::record::Record(&mut log)).expect("walks"); assert_eq!(log, record(sample()).expect("records")); @@ -598,7 +343,9 @@ mod tests { fn a_wrong_aad_fails_to_open() { let sealed = encrypt(sample(), &Mock, "ctx").expect("encrypts"); assert_eq!( - open_all(&Mock, sealed, &"other".into_aad()).err(), + open_with(sealed, &"other".into_aad(), |leaf, aad| Mock + .open(leaf, aad)) + .err(), Some(OpenError::Cipher(Refused)) ); } @@ -645,7 +392,7 @@ mod tests { for node in malformed { let cipher = Counting(core::cell::Cell::new(0)); assert_eq!( - open_all(&cipher, node, &"ctx".into_aad()).err(), + open_with(node, &"ctx".into_aad(), |leaf, aad| cipher.open(leaf, aad)).err(), Some(OpenError::Malformed) ); assert_eq!(cipher.0.get(), 0); @@ -653,179 +400,7 @@ mod tests { } #[test] - fn a_provider_error_on_open_is_not_reported_as_tampering() { - struct Down; - impl AsyncCipher for Down { - type Leaf = Leaf; - type Error = &'static str; - async fn seal( - &self, - p: Protected<Vec<u8>>, - aad: Context<'static>, - ) -> Result<Leaf, &'static str> { - Mock.seal(p, &aad).map_err(|_| "refused") - } - async fn open( - &self, - _: Leaf, - _: Context<'static>, - ) -> Result<Protected<Vec<u8>>, &'static str> { - Err("kms unavailable") - } - } - let sealed = encrypt(34u32, &Mock, ()).expect("encrypts"); - let mut log = Vec::new(); - assert!(matches!( - block_on(crate::decrypt_into_async( - &Down, - sealed, - (), - crate::plaintext::record::Record(&mut log) - )), - Err(crate::DecryptError::Cipher("kms unavailable")) - )); - } - - /// Tracks how many leaves are in flight at once through the default - /// `seal_many`/`open_many`. Each call yields once, so the stream has to - /// hold several open to make progress. - #[derive(Default)] - struct Concurrency { - now: AtomicUsize, - max: AtomicUsize, - } - - struct YieldOnce(bool); - - impl Future for YieldOnce { - type Output = (); - fn poll( - mut self: core::pin::Pin<&mut Self>, - cx: &mut core::task::Context<'_>, - ) -> core::task::Poll<()> { - if self.0 { - return core::task::Poll::Ready(()); - } - self.0 = true; - cx.waker().wake_by_ref(); - core::task::Poll::Pending - } - } - - impl Concurrency { - async fn one<T>(&self, f: impl FnOnce() -> T) -> T { - let now = self.now.fetch_add(1, Ordering::SeqCst) + 1; - self.max.fetch_max(now, Ordering::SeqCst); - YieldOnce(false).await; - self.now.fetch_sub(1, Ordering::SeqCst); - f() - } - } - - impl AsyncCipher for Concurrency { - type Leaf = Leaf; - type Error = Refused; - async fn seal( - &self, - p: Protected<Vec<u8>>, - aad: Context<'static>, - ) -> Result<Leaf, Refused> { - self.one(|| Mock.seal(p, &aad)).await - } - async fn open( - &self, - l: Leaf, - aad: Context<'static>, - ) -> Result<Protected<Vec<u8>>, Refused> { - self.one(|| Mock.open(l, &aad)).await - } - } - - /// Each call waits longer than the one after it, so leaves finish in - /// the reverse of the order they started. - struct LastFirst(AtomicUsize); - - impl LastFirst { - async fn one<T>(&self, f: impl FnOnce() -> T) -> T { - let wait = 64usize.saturating_sub(self.0.fetch_add(1, Ordering::SeqCst)); - for _ in 0..wait { - YieldOnce(false).await; - } - f() - } - } - - impl AsyncCipher for LastFirst { - type Leaf = Leaf; - type Error = Refused; - async fn seal( - &self, - p: Protected<Vec<u8>>, - aad: Context<'static>, - ) -> Result<Leaf, Refused> { - self.one(|| Mock.seal(p, &aad)).await - } - async fn open( - &self, - l: Leaf, - aad: Context<'static>, - ) -> Result<Protected<Vec<u8>>, Refused> { - self.one(|| Mock.open(l, &aad)).await - } - } - - #[test] - fn the_default_batch_keeps_walk_order_when_leaves_finish_out_of_order() { - let values = vec![1u32, 2, 3, 4]; - let cipher = LastFirst(AtomicUsize::new(0)); - let sealed = block_on(encrypt_async(values.clone(), &cipher, "ctx")).expect("encrypts"); - let opened = open_all(&Mock, sealed, &"ctx".into_aad()).expect("opens"); - let mut log = Vec::new(); - walk(opened, crate::plaintext::record::Record(&mut log)).expect("walks"); - assert_eq!(log, record(values.clone()).expect("records")); - - let sealed = encrypt(values.clone(), &Mock, "ctx").expect("encrypts"); - let mut log = Vec::new(); - block_on(crate::decrypt_into_async( - &cipher, - sealed, - "ctx", - crate::plaintext::record::Record(&mut log), - )) - .expect("decrypts"); - assert_eq!(log, record(values).expect("records")); - } - - #[test] - fn a_malformed_tree_costs_an_async_cipher_no_round_trip() { - let leaf = || match encrypt(1u16, &Mock, "ctx").expect("encrypts") { - CipherText::Single(leaf) => leaf, - _ => unreachable!(), - }; - let duplicate_keys: Node<Leaf> = CipherText::Map(vec![ - ("k".into(), CipherText::Single(leaf())), - ("k".into(), CipherText::Single(leaf())), - ]); - let remote = Remote::new(true); - assert_eq!( - block_on(open_all_async(&remote, duplicate_keys, &"ctx".into_aad())).err(), - Some(OpenError::Malformed) - ); - assert_eq!(remote.calls(), 0); - } - - #[test] - fn seal_and_open_errors_say_what_failed() { - assert_eq!(LeafCount::TooFew.to_string(), "too few leaves"); - assert_eq!(LeafCount::TooMany.to_string(), "too many leaves"); - assert_eq!( - SealError::<&str>::Cipher("down").to_string(), - "cipher failed: down" - ); - assert_eq!( - SealError::<&str>::Count(LeafCount::TooMany).to_string(), - "cipher returned too many leaves" - ); + fn open_errors_say_what_failed() { assert_eq!( OpenError::<&str>::Cipher("down").to_string(), "cipher failed: down" @@ -834,211 +409,104 @@ mod tests { OpenError::<&str>::Malformed.to_string(), "malformed ciphertext" ); - assert_eq!( - OpenError::<&str>::Count(LeafCount::TooFew).to_string(), - "cipher returned too few leaves" - ); fn is_error<E: core::error::Error>(_: &E) {} - is_error(&SealError::<&str>::Cipher("down")); is_error(&OpenError::<&str>::Malformed); } - #[test] - fn the_default_batch_bounds_how_many_leaves_are_in_flight() { - let cipher = Concurrency::default(); - let many: Vec<u32> = (0..200).collect(); - let sealed = block_on(encrypt_async(many.clone(), &cipher, "ctx")).expect("encrypts"); - let max = cipher.max.load(Ordering::SeqCst); - assert!(max > 1 && max <= DEFAULT_CONCURRENCY, "{max}"); - let mut log = Vec::new(); - block_on(crate::decrypt_into_async( - &cipher, - sealed, - "ctx", - crate::plaintext::record::Record(&mut log), - )) - .expect("decrypts"); - assert!(cipher.max.load(Ordering::SeqCst) <= DEFAULT_CONCURRENCY); - assert_eq!(log, record(many).expect("records")); - } + /// A cipher whose key provider is down. + struct Down; - #[test] - fn encrypt_async_walks_before_returning_a_send_future() { - // A source a JavaScript binding might hand over: not `Send`. - #[derive(Clone)] - struct Local(std::rc::Rc<u32>); - impl crate::Encrypt for Local { - fn visit<S: crate::Sink>(self, sink: S) -> Result<S::Ok, S::Error> { - (*self.0).visit(sink) - } + impl Cipher for Down { + type Leaf = Leaf; + type Error = &'static str; + + fn seal(&self, _: Protected<Vec<u8>>, _: &Context<'_>) -> Result<Leaf, &'static str> { + Err("key provider unavailable") } - fn assert_send<T: Send>(t: T) -> T { - t + + fn open(&self, _: Leaf, _: &Context<'_>) -> Result<Protected<Vec<u8>>, &'static str> { + Err("kms unavailable") } - let remote = Remote::new(true); - let future = assert_send(encrypt_async(Local(std::rc::Rc::new(34)), &remote, "ctx")); - assert_eq!(remote.calls(), 0); - block_on(future).expect("encrypts"); - assert_eq!(remote.calls(), 1); } #[test] - fn a_cipher_that_miscounts_is_refused() { - struct DropsOne; - impl Cipher for DropsOne { - type Leaf = Leaf; - type Error = Refused; - fn seal( - &self, - plaintext: Protected<Vec<u8>>, - aad: &Context<'_>, - ) -> Result<Leaf, Refused> { - Mock.seal(plaintext, aad) - } - fn open(&self, leaf: Leaf, aad: &Context<'_>) -> Result<Protected<Vec<u8>>, Refused> { - Mock.open(leaf, aad) - } - } - struct Extra(Remote); - impl AsyncCipher for Extra { - type Leaf = Leaf; - type Error = Refused; - async fn seal( - &self, - plaintext: Protected<Vec<u8>>, - aad: Context<'static>, - ) -> Result<Leaf, Refused> { - self.0.seal(plaintext, aad).await - } - async fn open( - &self, - leaf: Leaf, - aad: Context<'static>, - ) -> Result<Protected<Vec<u8>>, Refused> { - self.0.open(leaf, aad).await - } - async fn seal_many(&self, leaves: Vec<Pending>) -> Result<Vec<Leaf>, Refused> { - let mut out = self.0.seal_many(leaves).await?; - out.push(out[0].clone()); - Ok(out) - } - async fn open_many( - &self, - mut leaves: Vec<(Leaf, Context<'static>)>, - ) -> Result<Vec<Protected<Vec<u8>>>, Refused> { - leaves.pop(); - self.0.open_many(leaves).await - } - } - let extra = Extra(Remote::new(true)); + fn a_provider_error_on_open_is_not_reported_as_tampering() { + let sealed = encrypt(34u32, &Mock, ()).expect("encrypts"); + let mut log = Vec::new(); assert!(matches!( - block_on(encrypt_async(sample(), &extra, "ctx")), - Err(EncryptError::Count(LeafCount::TooMany)) + decrypt_into( + &Down, + sealed, + (), + crate::plaintext::record::Record(&mut log) + ), + Err(crate::DecryptError::Cipher("kms unavailable")) )); - let sealed = encrypt(sample(), &DropsOne, "ctx").expect("encrypts"); - assert_eq!( - block_on(open_all_async(&extra, sealed, &"ctx".into_aad())).err(), - Some(OpenError::<Refused>::Count(LeafCount::TooFew)) - ); } #[test] - fn a_batching_cipher_makes_one_round_trip_each_way() { - let remote = Remote::new(true); - let sealed = block_on(encrypt_async(sample(), &remote, "ctx")).expect("encrypts"); - assert_eq!(remote.calls(), 1); - let mut log = Vec::new(); - block_on(crate::decrypt_into_async( - &remote, - sealed, - "ctx", - crate::plaintext::record::Record(&mut log), - )) - .expect("decrypts"); - assert_eq!(remote.calls(), 2); - assert_eq!(log, record(sample()).expect("records")); + fn a_cipher_failure_fails_the_document() { + assert!(matches!( + encrypt(34u32, &Down, ()), + Err(EncryptError::Cipher("key provider unavailable")) + )); } - #[test] - fn a_document_with_no_leaves_makes_no_cipher_call() { - // A top-level passthrough seals nothing, so a batching provider is - // not asked for an empty batch either way. - struct Pass; - impl crate::Encrypt for Pass { - fn visit<S: crate::Sink>(self, sink: S) -> Result<S::Ok, S::Error> { - sink.passthrough(&"public") - } + mod given_a_value_staged_for_encryption { + use super::*; + + fn staged() -> Node<Plaintext> { + plan::<_, Refused>(sample()).expect("walks") } - let remote = Remote::new(true); - let sealed = block_on(encrypt_async(Pass, &remote, "ctx")).expect("encrypts"); - assert!(matches!(sealed, CipherText::Passthrough(_))); - let mut log = Vec::new(); - block_on(crate::decrypt_into_async( - &remote, - sealed, - "ctx", - crate::plaintext::record::Record(&mut log), - )) - .expect("decrypts"); - assert_eq!(remote.calls(), 0); - assert_eq!(log, record(Pass).expect("records")); - } - #[test] - fn without_a_batch_api_each_leaf_is_its_own_call() { - let remote = Remote::new(false); - let sealed = block_on(encrypt_async(sample(), &remote, "ctx")).expect("encrypts"); - assert_eq!(remote.calls(), 5); - let mut log = Vec::new(); - block_on(crate::decrypt_into_async( - &remote, - sealed, - "ctx", - crate::plaintext::record::Record(&mut log), - )) - .expect("decrypts"); - assert_eq!(remote.calls(), 10); - } + #[test] + fn the_leaf_count_is_the_number_of_leaves_sealed() { + let staged = staged(); - #[test] - fn sync_and_async_ciphers_read_each_others_leaves() { - let remote = Remote::new(true); - let sealed = block_on(encrypt_async(34u32, &remote, ())).expect("encrypts"); - let mut log = Vec::new(); - decrypt_into( - &Mock, - sealed, - (), - crate::plaintext::record::Record(&mut log), - ) - .expect("decrypts"); - assert_eq!(log, [Event::Scalar(None, Owned::Int(Int::U32(34)))]); - } + let count = staged.leaf_count(); + let sealed = staged + .seal(&"ctx".into_aad(), |plaintext, aad| { + Mock.seal(plaintext, aad) + }) + .expect("seals"); - #[test] - fn a_cipher_failure_fails_the_document() { - struct Down; - impl AsyncCipher for Down { - type Leaf = Leaf; - type Error = &'static str; - async fn seal( - &self, - _: Protected<Vec<u8>>, - _: Context<'static>, - ) -> Result<Leaf, &'static str> { - Err("key provider unavailable") - } - async fn open( - &self, - _: Leaf, - _: Context<'static>, - ) -> Result<Protected<Vec<u8>>, &'static str> { - Err("key provider unavailable") - } + assert_eq!(count, 5, "four elements, and the marker of `b`"); + assert_eq!( + sealed.leaf_count(), + count, + "the sealed tree has a leaf for each one counted" + ); + } + + #[test] + fn seal_is_called_once_for_each_leaf_in_walk_order() { + let mut numbers = vec![5u8, 4, 3, 2, 1]; + + let sealed = staged().seal(&"ctx".into_aad(), |_, _| { + numbers.pop().ok_or("no number left") + }); + + let sealed: Vec<u8> = leaves(&sealed.expect("five numbers seal five leaves")) + .into_iter() + .copied() + .collect(); + assert_eq!(sealed, [1, 2, 3, 4, 5], "each leaf has the next number"); + assert!(numbers.is_empty(), "every number was used"); + } + + #[test] + fn a_seal_that_fails_fails_the_whole_value() { + let mut numbers = vec![1u8]; + + let sealed = staged().seal(&"ctx".into_aad(), |_, _| { + numbers.pop().ok_or("no number left") + }); + + assert_eq!( + sealed.err(), + Some("no number left"), + "no partial tree is returned" + ); } - assert!(matches!( - block_on(encrypt_async(34u32, &Down, ())), - Err(EncryptError::Cipher("key provider unavailable")) - )); } } diff --git a/packages/vitaminc-aead/src/typed.rs b/packages/vitaminc-aead/src/typed.rs index 4ac8ae934..25d613384 100644 --- a/packages/vitaminc-aead/src/typed.rs +++ b/packages/vitaminc-aead/src/typed.rs @@ -54,8 +54,8 @@ use zeroize::Zeroize; use crate::plaintext::{ EncryptRef, Error, FixedType, Float, Logical, MapSink, Physical, SeqSink, Sink, SourceError, }; -use crate::seal::{AsyncCipher, Cipher, Node}; -use crate::walk::{decrypt_into, decrypt_into_async, DecryptError}; +use crate::seal::{Cipher, Node}; +use crate::walk::{decrypt_into, DecryptError}; use crate::IntoAad; /// Derive [`Decrypt`] for a struct or a fieldless enum: the sink that builds @@ -149,25 +149,6 @@ where decrypt_into(cipher, node, aad, T::sink()) } -/// Decrypt into `T` through an async cipher. Gives the same result as -/// [`decrypt`] for the same ciphertext. -/// -/// Reports the same categories of errors as [`decrypt`]. All opening awaits -/// finish before the target receives plaintext. Dropping the future drops its -/// owned state but does not guarantee cancellation of remote cipher work. -pub async fn decrypt_async<'a, T, C, A>( - cipher: &C, - node: Node<C::Leaf>, - aad: A, -) -> Result<T, DecryptError<DecodeError, C::Error>> -where - T: Decrypt, - C: AsyncCipher, - A: IntoAad<'a>, -{ - decrypt_into_async(cipher, node, aad, T::sink()).await -} - /// A type that decodes from one scalar. /// /// # Examples @@ -1667,11 +1648,10 @@ where #[cfg(test)] mod tests { use super::*; + use crate::encrypt; use crate::plaintext::Encrypt; use crate::plaintext::{Int, Raw, Width}; - use crate::seal::mock::{Mock, Remote}; - use crate::{encrypt, encrypt_async}; - use futures_executor::block_on; + use crate::seal::mock::Mock; fn round_trip<T: Decrypt>( p: impl Encrypt, @@ -1915,31 +1895,6 @@ mod tests { assert_eq!(expected(round_trip::<Option<u32>>("x")), "u32"); } - #[test] - fn a_typed_target_works_through_an_async_cipher() { - let remote = Remote::new(true); - let sealed = block_on(encrypt_async(vec![1u32, 2], &remote, ())).expect("encrypts"); - let out: Vec<u32> = block_on(decrypt_async(&remote, sealed, ())).expect("decrypts"); - assert_eq!(out, [1, 2]); - assert_eq!(remote.calls(), 2); - } - - #[test] - fn sync_and_async_decrypt_agree() { - let mut value = BTreeMap::new(); - value.insert(String::from("a"), vec![Some(1u32), None]); - value.insert(String::from("b"), vec![]); - // The mock is deterministic, so both are the same ciphertext. - let sealed = || encrypt(value.clone(), &Mock, "ctx").expect("encrypts"); - let sync: BTreeMap<String, Vec<Option<u32>>> = - decrypt(&Mock, sealed(), "ctx").expect("sync"); - let remote = Remote::new(true); - let async_: BTreeMap<String, Vec<Option<u32>>> = - block_on(decrypt_async(&remote, sealed(), "ctx")).expect("async"); - assert_eq!(sync, async_); - assert_eq!(sync, value); - } - #[test] fn maps_round_trip() { let mut hash = HashMap::new(); @@ -2276,17 +2231,12 @@ mod tests { decrypt::<Vec<u32>, _, _>(&Mock, sealed(), "other"), Err(DecryptError::Cipher(_)) )); - let remote = Remote::new(true); - // With the right AAD the async path decrypts, so the next - // assertion is about the AAD and nothing else. + // With the right AAD the value decrypts, so the assertions above + // are about the AAD and nothing else. assert_eq!( - block_on(decrypt_async::<u32, _, _>(&remote, sealed(), "ctx")).expect("decrypts"), + decrypt::<u32, _, _>(&Mock, sealed(), "ctx").expect("decrypts"), 34 ); - assert!(matches!( - block_on(decrypt_async::<String, _, _>(&remote, sealed(), "other")), - Err(DecryptError::Cipher(_)) - )); } #[test] diff --git a/packages/vitaminc-aead/src/walk.rs b/packages/vitaminc-aead/src/walk.rs index b1910d4b5..0e360d845 100644 --- a/packages/vitaminc-aead/src/walk.rs +++ b/packages/vitaminc-aead/src/walk.rs @@ -2,8 +2,8 @@ //! //! Two steps, mirroring encryption: //! -//! 1. [`open_all`] or [`open_all_async`]: derive each leaf's AAD from its -//! position, open every leaf (one `open_many` call for an async cipher), +//! 1. [`open_with`]: derive each leaf's AAD from its position, open every +//! leaf, //! and put the plaintexts back into the tree. //! 2. [`walk`]: feed the opened tree to the sink, scalar by scalar, //! physical plus logical. A Go guest passes a @@ -17,11 +17,11 @@ use core::convert::Infallible; use std::collections::HashSet; -use vitaminc_protected::{Buffer, Controlled}; +use vitaminc_protected::Controlled; use crate::leaf::{self, Item}; use crate::plaintext::{Error, MapSink, SeqSink, Sink, SourceError}; -use crate::seal::{open_all, open_all_async, AsyncCipher, Cipher, Node, OpenError, Opened}; +use crate::seal::{open_with, Cipher, Node, OpenError, Plaintext}; use crate::{CipherText, IntoAad}; /// Why decryption failed. @@ -74,7 +74,7 @@ impl<E> DecryptError<E> { fn opening<E, C>(e: OpenError<C>) -> DecryptError<E, C> { match e { OpenError::Cipher(c) => DecryptError::Cipher(c), - OpenError::Malformed | OpenError::Count(_) => DecryptError::Malformed, + OpenError::Malformed => DecryptError::Malformed, } } @@ -108,41 +108,12 @@ where A: IntoAad<'a>, { walk( - open_all(cipher, node, &aad.into_aad()).map_err(opening)?, + open_with(node, &aad.into_aad(), |leaf, aad| cipher.open(leaf, aad)).map_err(opening)?, sink, ) .map_err(DecryptError::with_cipher) } -/// Decrypt through an async cipher. Every leaf is opened before the sink -/// sees anything, so the sink itself is never awaited. -/// -/// The sink is held across the await, so the future is `Send` only if the -/// sink is. A caller with a sink that is not (a builder of JavaScript -/// values) awaits [`open_all_async`] and then calls [`walk`] itself. -/// -/// # Errors and cancellation -/// -/// Has the same partial-output behavior as [`decrypt_into`] once walking starts. -/// While opening is suspended the sink has not been visited. Dropping the future -/// drops owned state but cannot guarantee cancellation of a remote request. -pub async fn decrypt_into_async<'a, C, S, A>( - cipher: &C, - node: Node<C::Leaf>, - aad: A, - sink: S, -) -> Result<S::Ok, DecryptError<S::Error, C::Error>> -where - C: AsyncCipher, - S: Sink, - A: IntoAad<'a>, -{ - let opened = open_all_async(cipher, node, &aad.into_aad()) - .await - .map_err(opening)?; - walk(opened, sink).map_err(DecryptError::with_cipher) -} - fn sealed_any<'n, L: 'n>(mut nodes: impl Iterator<Item = &'n Node<L>>) -> bool { nodes.any(|n| !matches!(n, CipherText::Passthrough(_))) } @@ -159,8 +130,8 @@ fn sealed_any<'n, L: 'n>(mut nodes: impl Iterator<Item = &'n Node<L>>) -> bool { /// [`DecryptError::Auth`] for a nonempty empty-container marker, or /// [`DecryptError::Sink`] for a refused value. Earlier sink writes are not /// rolled back when a later node fails. -pub fn walk<S: Sink>(node: Node<Opened>, sink: S) -> Result<S::Ok, DecryptError<S::Error>> { - let empty_marker = |plaintext: Opened| match plaintext.risky_ref().is_empty() { +pub fn walk<S: Sink>(node: Node<Plaintext>, sink: S) -> Result<S::Ok, DecryptError<S::Error>> { + let empty_marker = |plaintext: Plaintext| match plaintext.risky_ref().is_empty() { true => Ok(()), false => Err(DecryptError::Auth), }; @@ -191,7 +162,10 @@ pub fn walk<S: Sink>(node: Node<Opened>, sink: S) -> Result<S::Ok, DecryptError< } } -fn walk_seq<S: Sink>(items: Vec<Node<Opened>>, sink: S) -> Result<S::Ok, DecryptError<S::Error>> { +fn walk_seq<S: Sink>( + items: Vec<Node<Plaintext>>, + sink: S, +) -> Result<S::Ok, DecryptError<S::Error>> { if !sealed_any(items.iter()) { return Err(DecryptError::Malformed); } @@ -203,7 +177,7 @@ fn walk_seq<S: Sink>(items: Vec<Node<Opened>>, sink: S) -> Result<S::Ok, Decrypt } fn walk_map<S: Sink>( - entries: Vec<(String, Node<Opened>)>, + entries: Vec<(String, Node<Plaintext>)>, sink: S, ) -> Result<S::Ok, DecryptError<S::Error>> { let mut seen = HashSet::with_capacity(entries.len()); @@ -219,24 +193,6 @@ fn walk_map<S: Sink>( Ok(map.end()?) } -/// Decrypt into a frame: the Go guest's whole `decrypt`. -/// -/// The frame is plaintext, so it is built in a [`Buffer`] -/// and wiped on every error path. -pub fn decrypt_to_frame<'a, C, A>( - cipher: &C, - node: Node<C::Leaf>, - aad: A, -) -> Result<Buffer, DecryptError<crate::frame::FrameWriteError, C::Error>> -where - C: Cipher, - A: IntoAad<'a>, -{ - let mut out = Buffer::new(); - decrypt_into(cipher, node, aad, crate::frame::FrameWriter::new(&mut out))?; - Ok(out) -} - #[cfg(test)] mod tests { use super::*; @@ -324,7 +280,7 @@ mod tests { #[test] fn every_marker_that_is_not_empty_is_an_auth_failure() { let tampered = || Protected::new(vec![1]); - let nodes: [Node<Opened>; 2] = [ + let nodes: [Node<Plaintext>; 2] = [ CipherText::EmptySequence(tampered()), CipherText::EmptyMap(tampered()), ]; @@ -362,7 +318,7 @@ mod tests { Err(DecryptError::Malformed) )); // Duplicate keys. - let node: Node<Opened> = CipherText::Map(vec![ + let node: Node<Plaintext> = CipherText::Map(vec![ ("k".into(), leaf(&[0x00])), ("k".into(), leaf(&[0x00])), ]); @@ -371,14 +327,14 @@ mod tests { Err(DecryptError::Malformed) )); // Nothing sealed. - let node: Node<Opened> = + let node: Node<Plaintext> = CipherText::Sequence(vec![CipherText::Passthrough(PassthroughFrame(vec![0x00]))]); assert!(matches!( walk(node, Record(&mut Vec::new())), Err(DecryptError::Malformed) )); // A passthrough that is not a frame. - let node: Node<Opened> = CipherText::Passthrough(PassthroughFrame(vec![0xF0])); + let node: Node<Plaintext> = CipherText::Passthrough(PassthroughFrame(vec![0xF0])); assert!(matches!( walk(node, Record(&mut Vec::new())), Err(DecryptError::Malformed) @@ -397,18 +353,5 @@ mod tests { )); } - #[test] - fn decrypt_to_frame_is_the_frame_of_the_source() { - let sealed = encrypt(sample(), &Mock, "ctx").expect("encrypts"); - let frame = decrypt_to_frame(&Mock, sealed, "ctx").expect("decrypts"); - assert_eq!( - frame.risky_ref().as_slice(), - crate::to_frame(sample()) - .expect("frames") - .risky_ref() - .as_slice() - ); - } - use crate::frame::PassthroughFrame; } diff --git a/packages/vitaminc-aead/tasks.toml b/packages/vitaminc-aead/tasks.toml index 18c7eb06e..00b81d08a 100644 --- a/packages/vitaminc-aead/tasks.toml +++ b/packages/vitaminc-aead/tasks.toml @@ -26,7 +26,7 @@ run = [ # test, so the step also checks that both ran. On a failure it prints the # test output before it exits. ["test:vitaminc-aead:features"] -description = "Test vitaminc-aead with each optional feature alone (jiff, rust_decimal, uuid, hlist), its release-only jiff tests, and recipher-frame with and without serde" +description = "Test vitaminc-aead with each optional feature alone (jiff, rust_decimal, uuid), its release-only jiff tests, and recipher-frame with and without serde" run = [ "cargo test --locked -p vitaminc-aead", "cargo test --locked -p vitaminc-aead --features jiff", @@ -42,7 +42,6 @@ run = [ ''', "cargo test --locked -p vitaminc-aead --features rust_decimal", "cargo test --locked -p vitaminc-aead --features uuid", - "cargo test --locked -p vitaminc-aead --features hlist", "cargo test --locked -p recipher-frame", "cargo test --locked -p recipher-frame --features serde", "cargo test --locked -p recipher-frame --features serde --bench storage", diff --git a/packages/vitaminc-aead/tests/aes_cipher.rs b/packages/vitaminc-aead/tests/aes_cipher.rs new file mode 100644 index 000000000..0c11f81ee --- /dev/null +++ b/packages/vitaminc-aead/tests/aes_cipher.rs @@ -0,0 +1,201 @@ +//! `Aes256Cipher` as the sink-based `Cipher`, driven through +//! `vitaminc_aead::encrypt` and `decrypt`: scalars, nested containers, +//! empty containers and passthrough round-trip through real AES-256-GCM, +//! and a wrong AAD or key fails at the cipher. + +use std::collections::BTreeMap; + +use vitaminc_aead::aes::{Aes256Cipher, Key}; +use vitaminc_aead::{ + decrypt, encrypt, CipherText, Decrypt, DecryptError, Encrypt, EncryptError, MapSink, Sink, + Unencryptable, +}; +use vitaminc_protected::{Controlled, Protected}; + +fn cipher() -> Aes256Cipher { + Aes256Cipher::new(&Key::from([42u8; 32])).expect("cipher") +} + +#[derive(Debug, Clone, PartialEq, Encrypt, Decrypt)] +struct Record { + #[aead(passthrough)] + id: u64, + name: String, + scores: Vec<u32>, + labels: BTreeMap<String, String>, + nickname: Option<String>, +} + +fn record() -> Record { + Record { + id: 7, + name: "Ada".into(), + scores: vec![1, 2, 3], + labels: BTreeMap::from([("role".to_string(), "founder".to_string())]), + nickname: None, + } +} + +mod given_a_scalar { + use super::*; + + #[test] + fn round_trips_through_aes() { + let cipher = cipher(); + let node = encrypt("hello".to_string(), &cipher, "ctx").expect("encrypt"); + assert!( + matches!(node, CipherText::Single(_)), + "a scalar seals as one leaf" + ); + let got: String = decrypt(&cipher, node, "ctx").expect("decrypt"); + assert_eq!(got, "hello"); + } + + #[test] + fn returns_a_cipher_error_under_the_wrong_aad() { + let cipher = cipher(); + let node = encrypt(42u32, &cipher, "right").expect("encrypt"); + let err = decrypt::<u32, _, _>(&cipher, node, "wrong").expect_err("wrong AAD"); + assert!(matches!(err, DecryptError::Cipher(_)), "got {err:?}"); + } + + #[test] + fn returns_a_cipher_error_under_the_wrong_key() { + let node = encrypt(42u32, &cipher(), "ctx").expect("encrypt"); + let other = Aes256Cipher::new(&Key::from([1u8; 32])).expect("cipher"); + let err = decrypt::<u32, _, _>(&other, node, "ctx").expect_err("wrong key"); + assert!(matches!(err, DecryptError::Cipher(_)), "got {err:?}"); + } +} + +mod given_a_nested_record { + use super::*; + + #[test] + fn round_trips_with_its_passthrough_in_the_clear() { + let cipher = cipher(); + let node = encrypt(record(), &cipher, "users").expect("encrypt"); + let CipherText::Map(entries) = &node else { + panic!("a struct seals as a map"); + }; + assert!( + entries + .iter() + .any(|(key, node)| key == "id" && matches!(node, CipherText::Passthrough(_))), + "the passthrough field is a cleartext entry" + ); + let got: Record = decrypt(&cipher, node, "users").expect("decrypt"); + assert_eq!(got, record()); + } + + #[test] + fn seals_empty_containers_as_authenticated_markers() { + let cipher = cipher(); + let empty = Record { + scores: Vec::new(), + labels: BTreeMap::new(), + ..record() + }; + let node = encrypt(empty.clone(), &cipher, "users").expect("encrypt"); + let CipherText::Map(entries) = &node else { + panic!("a struct seals as a map"); + }; + let shapes: BTreeMap<&str, &str> = entries + .iter() + .map(|(key, node)| { + let shape = match node { + CipherText::EmptySequence(_) => "empty-seq", + CipherText::EmptyMap(_) => "empty-map", + _ => "other", + }; + (key.as_str(), shape) + }) + .collect(); + assert_eq!(shapes["scores"], "empty-seq"); + assert_eq!(shapes["labels"], "empty-map"); + let got: Record = decrypt(&cipher, node, "users").expect("decrypt"); + assert_eq!(got, empty); + } + + #[test] + fn refuses_a_map_with_nothing_sealed() { + // The derive refuses this shape at compile time, so the source is + // written by hand: a map whose only entry is a passthrough. + struct OnlyPlain; + impl Encrypt for OnlyPlain { + fn visit<S: Sink>(self, sink: S) -> Result<S::Ok, S::Error> { + let mut map = sink.map(Some(1))?; + map.entry("id")?.passthrough(&7u64)?; + map.end() + } + } + let err = encrypt(OnlyPlain, &cipher(), "ctx").expect_err("nothing sealed"); + assert!( + matches!( + err, + EncryptError::Shape(ref refusal) + if refusal.reason() == Unencryptable::MapHasNothingSealed + ), + "got {err:?}" + ); + } +} + +mod given_protected_bytes { + use super::*; + + #[test] + fn round_trips_without_leaving_the_wrapper() { + let cipher = cipher(); + let secret = Protected::new(vec![0xDEu8, 0xAD, 0xBE, 0xEF]); + let node = encrypt(secret, &cipher, "blob").expect("encrypt"); + let got: Protected<Vec<u8>> = decrypt(&cipher, node, "blob").expect("decrypt"); + assert_eq!(got.risky_unwrap(), vec![0xDE, 0xAD, 0xBE, 0xEF]); + } +} + +mod given_an_absent_fixed_width_value { + use super::*; + + /// The ciphertext length of the one leaf `value` seals as. + fn sealed_len<P: Encrypt>(value: P) -> usize { + match encrypt(value, &cipher(), "ctx").expect("encrypt") { + CipherText::Single(leaf) => leaf.as_ref().len(), + other => panic!("not one leaf: {other:?}"), + } + } + + fn same_length<T: Encrypt>(value: T) { + assert_eq!( + sealed_len(None::<T>), + sealed_len(Some(value)), + "{}", + core::any::type_name::<T>() + ); + } + + #[test] + fn seals_to_the_length_of_a_present_one() { + same_length(-1i8); + same_length(-1i16); + same_length(-1i32); + same_length(-1i64); + same_length(-1i128); + same_length(1u16); + same_length(1u32); + same_length(1u64); + same_length(1u128); + same_length(1.5f32); + same_length(1.5f64); + // A bool's plain null is already as long as a bool. + same_length(true); + } + + #[test] + fn round_trips_through_aes_as_none() { + let cipher = cipher(); + let node = encrypt(None::<u64>, &cipher, "ctx").expect("encrypt"); + let got: Option<u64> = decrypt(&cipher, node, "ctx").expect("decrypt"); + assert_eq!(got, None); + } +} diff --git a/packages/vitaminc-aead/tests/derive_depth.rs b/packages/vitaminc-aead/tests/derive_depth.rs index 61e0cde67..eeb5f4ab7 100644 --- a/packages/vitaminc-aead/tests/derive_depth.rs +++ b/packages/vitaminc-aead/tests/derive_depth.rs @@ -55,7 +55,7 @@ impl<T: Full> Full for HashMap<String, T> { /// Whether the encrypting sink accepts `value`, or refuses it as too deep. fn accepted<P: Encrypt>(value: P) -> bool { - match plan::<_, (), _>(value, "aad") { + match plan::<_, ()>(value) { Ok(_) => true, Err(EncryptError::Shape(refusal)) if refusal.reason() == Unencryptable::TooDeep => false, Err(other) => panic!("refused for another reason: {other:?}"), diff --git a/packages/vitaminc-aead/tests/derive_sink.rs b/packages/vitaminc-aead/tests/derive_sink.rs index 126fbcf00..a8c39114a 100644 --- a/packages/vitaminc-aead/tests/derive_sink.rs +++ b/packages/vitaminc-aead/tests/derive_sink.rs @@ -7,7 +7,7 @@ use std::collections::BTreeMap; use vitaminc_aead::{ decrypt, encrypt, Bytes, Context, DecodeError, Decrypt, DecryptError, Encrypt, EncryptRef, - FixedType, Int, IntoAad, Logical, MapSink, Physical, Raw, SeqSink, Sink, SourceError, + FixedType, Int, Logical, MapSink, Physical, Raw, SeqSink, Sink, SourceError, }; use vitaminc_protected::{Controlled, Protected}; use zeroize::ZeroizeOnDrop; @@ -417,8 +417,7 @@ fn passthrough_fields_travel_in_the_clear_and_come_back() { // Only the sealed fields are leaves; the passthrough ones are frames. let sealed = encrypt(row.clone(), &Mock, "ctx").expect("encrypts"); - let leaves = vitaminc_aead::seal::leaves_with_aad(sealed, &"ctx".into_aad()); - assert_eq!(leaves.len(), 2); + assert_eq!(sealed.leaf_count(), 2); let sealed = encrypt(row.clone(), &Mock, "ctx").expect("encrypts"); let back: Row = decrypt(&Mock, sealed, "ctx").expect("decodes"); @@ -816,9 +815,8 @@ fn a_struct_with_borrowed_fields_walks_the_same_by_reference() { assert_eq!(by_value[0], Event::Map(Some(7))); assert_eq!(record(&user), by_value); let sealed = encrypt(&user, &Mock, "ctx").expect("encrypts"); - let leaves = vitaminc_aead::seal::leaves_with_aad(sealed, &"ctx".into_aad()); // Every scalar but the passthrough tenant is a leaf. - assert_eq!(leaves.len(), 7); + assert_eq!(sealed.leaf_count(), 7); } // Custody: a walk that fails part way wipes the fields it did not reach, diff --git a/packages/vitaminc-aead/tests/scalar.rs b/packages/vitaminc-aead/tests/scalar.rs index e7c1e2e22..d69e07094 100644 --- a/packages/vitaminc-aead/tests/scalar.rs +++ b/packages/vitaminc-aead/tests/scalar.rs @@ -23,7 +23,7 @@ use vitaminc_protected::{AsProtectedRef, Protected, ProtectedRef}; /// the type says it is a scalar, and the walk agrees. fn one_leaf<S: Scalar>(value: S) { assert_eq!(S::DEPTH, depth::SCALAR); - let tree = plan::<_, Infallible, _>(value, "aad").expect("a scalar always plans"); + let tree = plan::<_, Infallible>(value).expect("a scalar always plans"); assert!(matches!(tree, CipherText::Single(_)), "not one leaf"); } diff --git a/packages/vitaminc-aead/tests/typed_null.rs b/packages/vitaminc-aead/tests/typed_null.rs index 8adc3348a..8a31bb667 100644 --- a/packages/vitaminc-aead/tests/typed_null.rs +++ b/packages/vitaminc-aead/tests/typed_null.rs @@ -6,8 +6,8 @@ //! to every leaf. use vitaminc_aead::{ - decrypt, decrypt_to_frame, encrypt, tags, to_frame, CipherText, Context, DecodeError, Decrypt, - DecryptError, Encrypt, FixedType, Frame, IntoAad, Node, Width, + decrypt, decrypt_into, encrypt, tags, to_frame, CipherText, Context, DecodeError, Decrypt, + DecryptError, Encrypt, FixedType, Frame, FrameWriter, IntoAad, Node, Width, }; use vitaminc_protected::{Controlled, Protected}; @@ -221,7 +221,8 @@ fn a_frame_reads_a_typed_null_and_writes_the_plain_null() { &[tags::NULL] ); let node = encrypt(None::<u32>, &Mock, "ctx").expect("encrypts"); - let back = decrypt_to_frame(&Mock, node, "ctx").expect("decrypts"); + let mut back = vitaminc_protected::Buffer::new(); + decrypt_into(&Mock, node, "ctx", FrameWriter::new(&mut back)).expect("decrypts"); assert_eq!(back.risky_ref().as_slice(), &[tags::NULL]); } diff --git a/packages/vitaminc-normalize/CHANGELOG.md b/packages/vitaminc-normalize/CHANGELOG.md new file mode 100644 index 000000000..65c6bf184 --- /dev/null +++ b/packages/vitaminc-normalize/CHANGELOG.md @@ -0,0 +1,72 @@ + +## [0.10.0] - 2026-11-19 + +### Index terms + +- Index terms for every value in the supported range are the same as in 0.9.1. + +### Breaking + +- **Breaking:** a date or timestamp outside years -9999 to 9999 no longer has an index term. + In 0.9.1, the range was years -262143 to 262142. + The 0.10.0 changelog for `vitaminc-aead` gives the exact limits. + +## [0.9.1] - 2026-11-06 + +## [0.9.0] - 2026-11-04 + +### Breaking + +- **Breaking:** the crate now needs Rust 1.89 or later. + Version 0.8.1 needed Rust 1.88. + +### Fixes + +- Normalizing an integer or a timestamp no longer passes the value through a stack slot that is not wiped. + The `vitaminc-aead` helpers that this crate calls are now inlined into this crate's code. + +## [0.8.1] - 2026-10-26 + +### Dependencies + +- `orderable-bytes` 0.2.1. It changes no encoding, so every term is the same as 0.8.0's, and terms you stored still compare. + +## [0.8.0] - 2026-10-21 + +Existing equality terms do not change: every domain label and encoding of 0.7 stays as it is, and the null term is a new label beside them. An index built by 0.7 holds a SQL `NULL` where a value was absent; 0.8 writes a term there instead. Both read correctly, but the rows 0.7 wrote still show their absences until they are re-indexed. + +### Breaking + +- **Breaking:** Every null, typed or plain, now has an equality term, under the new frozen domain `vitaminc/prf/value/null/v1` with the one byte `0x00`. A sealed `None` is now as long as a `Some` (`vitaminc-aead` 0.8.0), but the term column still held a SQL `NULL` exactly where a value was absent. So `normalize(None, Physical::Null)` succeeds where it returned `NoDomain`, and a walk over a value with a null returns one more term, at the null's path. A layer that must keep a SQL `NULL` for some column drops the term whose domain is `domain::NULL`; producing it is the default because dropping a term should be an explicit act. A boolean and an `undefined` still have no term. `domain::ALL` now lists nine labels. + +### Features + +- `NormalizeError::Reserved`, which an order space that places nulls returns for the one value it keeps for them (`vitaminc-ore` 0.8.0). `NormalizeError` is `#[non_exhaustive]`, so a match on it still compiles. + +### Not guaranteed + +- In an equality index the nulls are one more group of equal terms, as any repeated value is. That is never more than the SQL `NULL` it replaces, which needed no inference to read. + +## [0.7.0] - 2026-10-20 + +### Fixes + +- Each fixed-width and decimal encoder writes straight into the wiped buffer it returns, so no unwiped intermediate copy of an encoded value is made. The encoded bytes, and so stored terms, do not change. + +### Not guaranteed + +- `vitaminc_normalize::text` runs text through the `unicode-normalization` iterators, whose small internal buffers move to the heap as soon as a character's combining marks pass four code points (four marks followed by any character is enough), and are then freed without being wiped. This is outside this crate's control (#488). + +## [0.6.1] - 2026-10-18 + +## [0.6.0] - 2026-10-17 + +### Features + +- First release. `vitaminc-normalize` decides the equality terms for `vitaminc-aead`'s plaintext data model: for each scalar kind that can be indexed, a frozen domain label (the `domain` module) and an encoding to bytes. `normalize(logical, physical)` returns a `Normalized` (domain and protected bytes) that a PRF such as `vitaminc-prf` derives a term from. It has no cryptography. +- Equal values give equal terms whatever width or scale wrote them: every integer width shares one domain, `f32` widens exactly to `f64`, decimals normalize scale and signed zero, and timestamps in any unit truncate to microseconds. Values that only look alike do not match: a date, timestamp, decimal and uuid each have their own domain, separate from the physical value they are stored as. Text is Unicode 16 NFC with no case or accent folding. A code point unassigned in Unicode 16 is refused. A null, boolean or `undefined`, and any logical type the crate does not know, has no term (`NormalizeError::NoDomain`). The encodings are documented in the README and on `decimal`; changing one means a new domain label. +- `Terms` is a sink that collects one `Term` (path and normalized value) per indexable scalar. Run it beside encryption with `encrypt_with_terms` or `encrypt_with_terms_async`, which have every term before the first cipher call (and before the first await), with `plan_with_terms`, or alone with `terms`. `terms` refuses exactly what encryption refuses, at the same path: read a shape refusal with `TermsError::refusal`. +- A refused scalar is reported as a `TermError` holding the `NormalizeError`, the `Path` to the field and the index it was for. The error message names neither the field nor the value, because map keys can be user data; read the path with `TermError::path`. `Debug` masks the value of a `Normalized` or `Term`, and the map keys in a path. +- In a walk, a null, boolean or `undefined` produces no term and does not stop the walk. A logical type with no domain does stop it, so an index is never left silently incomplete. +- `Terms::by` and `terms_by` run the same walk under a normalizer of your own (the `Normalize` trait, which must be `Copy`). `vitaminc-ore`'s order index is the first. +- Text normalization is variable-time. The integer and float paths use no floating-point arithmetic. diff --git a/packages/vitaminc-normalize/Cargo.toml b/packages/vitaminc-normalize/Cargo.toml new file mode 100644 index 000000000..8fe8bdb60 --- /dev/null +++ b/packages/vitaminc-normalize/Cargo.toml @@ -0,0 +1,104 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies. +# +# If you are reading this file be aware that the original Cargo.toml +# will likely look very different (and much more reasonable). +# See Cargo.toml.orig for the original contents. + +[package] +edition = "2021" +rust-version = "1.89.0" +name = "vitaminc-normalize" +version = "0.10.0" +authors = ["Dan Draper <dan@cipherstash.com>"] +build = false +autolib = false +autobins = false +autoexamples = false +autotests = false +autobenches = false +description = "Normalized equality terms for the plaintext data model. Part of the Vitamin-C cryptographic suite." +homepage = "https://cipherstash.com" +documentation = "https://docs.rs/vitaminc-normalize" +readme = "README.md" +keywords = [ + "cryptography", + "security", +] +categories = ["cryptography"] +license = "MIT" +repository = "https://github.com/cipherstash/vitaminc" + +[lib] +name = "vitaminc_normalize" +path = "src/lib.rs" + +[[test]] +name = "agreement" +path = "tests/agreement.rs" + +[[test]] +name = "allocations" +path = "tests/allocations.rs" + +[[test]] +name = "known_answers" +path = "tests/known_answers.rs" + +[[test]] +name = "normalizer" +path = "tests/normalizer.rs" + +[dependencies.thiserror] +version = "2.0.18" + +[dependencies.unicode-general-category] +version = "=1.1.0" + +[dependencies.unicode-normalization] +version = "0.1.24" + +[dependencies.vitaminc-aead] +version = "0.10.0" + +[dependencies.vitaminc-protected] +version = "0.10.0" + +[dev-dependencies.jiff] +version = "1.0.0" +default-features = false + +[dev-dependencies.orderable-bytes] +version = "=0.2.1" +features = ["decimal"] + +[dev-dependencies.quickcheck] +version = "1.1.0" + +[dev-dependencies.quickcheck_macros] +version = "1.2.0" + +[dev-dependencies.rust_decimal] +version = "1.41" +features = ["std"] +default-features = false + +[dev-dependencies.uuid] +version = "1" +default-features = false + +# The crate's own manifest in cipherstash/vitaminc has this test dependency, +# by path. Publishing removes a dependency that has only a path, so the +# published manifest lacks it. `test-support` is for `plaintext::render`. +[dev-dependencies.vitaminc-aead] +version = "0.10.0" +features = [ + "jiff", + "rust_decimal", + "uuid", + "test-support", +] diff --git a/packages/vitaminc-normalize/README.md b/packages/vitaminc-normalize/README.md new file mode 100644 index 000000000..f32fa7074 --- /dev/null +++ b/packages/vitaminc-normalize/README.md @@ -0,0 +1,180 @@ +# Vitamin C Normalize + +[![Crates.io](https://img.shields.io/crates/v/vitaminc-normalize.svg)](https://crates.io/crates/vitaminc-normalize) +[![Workflow Status](https://github.com/cipherstash/vitaminc/actions/workflows/test.yml/badge.svg)](https://github.com/cipherstash/vitaminc/actions/workflows/test.yml) + +Normalized equality terms for the plaintext data model of +[`vitaminc-aead`](https://docs.rs/vitaminc-aead). Part of the +[Vitamin C](https://github.com/cipherstash/vitaminc) framework. + +An equality index derives a key from a value. Two values that are equal +must derive the same key whichever width, scale or spelling wrote them, +and two values that merely look alike (a date and the integer it is stored +as, a uuid and the same sixteen bytes) must not. This crate decides both: +each scalar kind that can be indexed has a frozen **domain label** and a +**normalization** to bytes, and everything else has no term. + +There is no cryptography here and no PAE: the crate's own dependencies +are the Unicode tables. (It builds on `vitaminc-aead` for the data model, +which brings that crate's dependencies with it.) The encodings are its +own, including the decimal one, which is ported from the frozen +`orderable-bytes` release and checked against it byte for byte. A PRF crate such as +[`vitaminc-prf`](https://docs.rs/vitaminc-prf) takes a [`Normalized`] +and derives under its domain. + +## Installation + +```sh +cargo add vitaminc-normalize +``` + +## One scalar + +```rust +use vitaminc_normalize::{domain, normalize}; +use vitaminc_aead::{Int, Logical, Physical}; +use vitaminc_protected::Controlled; + +// Every integer width is one term. +let a = normalize(None, Physical::Int(Int::I8(34)))?; +let b = normalize(None, Physical::Int(Int::U64(34)))?; +assert_eq!(a.domain, domain::INTEGER); +assert_eq!(a.bytes.risky_ref(), b.bytes.risky_ref()); + +// A date is not the integer it is stored as. +let day = normalize(Some(Logical::Date), Physical::Int(Int::I32(34)))?; +assert_eq!(day.domain, domain::DATE); +assert_ne!(day.bytes.risky_ref(), a.bytes.risky_ref()); +# Ok::<(), vitaminc_normalize::NormalizeError>(()) +``` + +Logical types opt in: a date, a timestamp, a decimal and a uuid have +domains of their own. A boolean, an `undefined` and a logical type this +crate does not know have no term, and `normalize` refuses them with +[`NormalizeError::NoDomain`]. + +Every null has a term, typed or plain, under a domain of its own. It is +the same term in every column, as SQL says `NULL IS NULL` whatever the +column; spaces that must not tie already differ in context. So the term +column of an index holds a term where the value was absent, as it does +where the value was there, and the nulls show only as one more group of +equal terms, which is what any repeated value shows. + +```rust +use vitaminc_normalize::{domain, normalize}; +use vitaminc_aead::Physical; +use vitaminc_protected::Controlled; + +let null = normalize(None, Physical::Null)?; +assert_eq!(null.domain, domain::NULL); +assert_eq!(null.bytes.risky_ref(), &[0x00]); +# Ok::<(), vitaminc_normalize::NormalizeError>(()) +``` + +A layer that must keep a SQL `NULL` in the term column for some column +drops the term it was handed. It knows the term is a null's because its +domain is [`domain::NULL`]. Producing the term is the default, because the +secure path should be the easy one, and dropping it is an explicit act. + +## A whole value, beside encryption + +[`Terms`] is a sink that collects one [`Term`] per indexable scalar, with +the path to it. Teed with the encrypting sink it sees the same walk, so +the terms are complete before any cipher call: + +```rust +use std::collections::BTreeMap; +use vitaminc_normalize::{domain, encrypt_with_terms, Step}; +# use vitaminc_aead::{seal::Cipher, Context}; +# use vitaminc_protected::{Controlled, Protected}; +# /// Keeps the plaintext in the clear, for the example. Any `Cipher` will do. +# struct Clear; +# impl Cipher for Clear { +# type Leaf = Vec<u8>; +# type Error = core::convert::Infallible; +# fn seal(&self, plaintext: Protected<Vec<u8>>, _: &Context<'_>) -> Result<Vec<u8>, Self::Error> { +# Ok(plaintext.risky_unwrap()) +# } +# fn open(&self, leaf: Vec<u8>, _: &Context<'_>) -> Result<Protected<Vec<u8>>, Self::Error> { +# Ok(Protected::new(leaf)) +# } +# } +# let cipher = Clear; + +let mut user = BTreeMap::new(); +user.insert("email", "ada@example.com"); +user.insert("name", "Ada"); + +let (ciphertext, terms) = encrypt_with_terms(user, &cipher, "users/v1")?; +assert_eq!(terms.len(), 2); +assert_eq!(terms[0].path.steps(), [Step::Key("email".into())]); +assert_eq!(terms[0].normalized.domain, domain::TEXT); +# Ok::<(), vitaminc_aead::EncryptError<core::convert::Infallible>>(()) +``` + +`encrypt_with_terms_async` does the same through an async cipher and has +every term before its first await. `plan_with_terms` walks without +sealing at all, and `terms` collects the terms with no encryption in the +walk. + +`terms` refuses every value encryption refuses, for the same reason and +at the same path, so an index never holds terms for a value that cannot +be stored. It keeps the same shape rules, through the same code: no +duplicate key, no value nested too deep, every scalar valid for its +logical type, every passthrough framable, and something sealed in every +container with children, even though it seals nothing itself. Read such a +refusal with `TermsError::refusal`; encryption reports the same one as +`EncryptError::Shape`. + +A null, typed or plain, has its term at its own path. A scalar whose kind +has no domain (a boolean, an `undefined`) produces no term and does not +stop the walk; passthrough subtrees get none either. A scalar whose +*logical type* has no domain, one from a newer client, stops the walk: +encrypting it with no term and no error would leave an index silently +incomplete. That refusal and an unassigned code point +arrive as `EncryptError::Source` carrying a `TermError` (from `terms`, as +`TermsError::term`), which holds the `NormalizeError` and the path to the +refused field. Downcast to `TermError`; the `NormalizeError` is also its +`source()`, so a reporter that walks the error chain reaches it. The +message names neither the field nor the value, because map keys can be +user data; read the path with `TermError::path`. + +## Encodings + +These are protocol data. Changing any of them, or a domain label, means a +new label. + +| Kind | Domain | Bytes | +| --- | --- | --- | +| integer, any width | `vitaminc/prf/value/integer-orderable/v1` | sign byte (`0x00` negative, `0x01` otherwise), then the big-endian 128-bit two's-complement word | +| float, either width | `vitaminc/prf/value/float-orderable/v1` | the `f64` value's orderable bytes; `f32` widened exactly, zero signs and NaN payloads folded | +| date | `vitaminc/prf/value/date-orderable/v1` | orderable days from 0001-01-01 | +| timestamp, any unit | `vitaminc/prf/value/timestamp-micros-orderable/v1` | orderable seconds, then nanoseconds truncated to microseconds | +| decimal | `vitaminc/prf/value/decimal-orderable/v1` | the 14-byte orderable encoding of the value (see [`decimal`]), scale and signed zero normalized | +| text | `vitaminc/prf/value/text-nfc/unicode-16/v1` | Unicode 16 NFC; a code point unassigned in Unicode 16 is refused | +| bytes | `vitaminc/prf/value/bytes/v1` | as they are | +| uuid | `vitaminc/prf/value/uuid/v1` | the sixteen raw bytes | +| null, typed or plain | `vitaminc/prf/value/null/v1` | one byte, `0x00` | + +Text normalization is variable-time. The integer and float paths use no +floating-point arithmetic. + +## Cargo features + +This crate defines no Cargo feature flags. + +## Compatibility + +Requires Rust <!-- msrv:vitaminc-normalize -->**1.89.0**<!-- /msrv --> and the Rust standard library (`std`). +MSRV increases require a minor release; patch releases retain the existing +floor. See the [workspace compatibility policy](https://github.com/cipherstash/vitaminc#compatibility). + +License: MIT. + +<!-- GitHub API links target the latest release; src/lib.rs resolves these for rustdoc. --> +[`NormalizeError::NoDomain`]: https://docs.rs/vitaminc-normalize/latest/vitaminc_normalize/enum.NormalizeError.html#variant.NoDomain +[`Normalized`]: https://docs.rs/vitaminc-normalize/latest/vitaminc_normalize/struct.Normalized.html +[`Term`]: https://docs.rs/vitaminc-normalize/latest/vitaminc_normalize/struct.Term.html +[`Terms`]: https://docs.rs/vitaminc-normalize/latest/vitaminc_normalize/struct.Terms.html +[`decimal`]: https://docs.rs/vitaminc-normalize/latest/vitaminc_normalize/fn.decimal.html +[`domain::NULL`]: https://docs.rs/vitaminc-normalize/latest/vitaminc_normalize/domain/constant.NULL.html diff --git a/packages/vitaminc-normalize/src/decimal.rs b/packages/vitaminc-normalize/src/decimal.rs new file mode 100644 index 000000000..ec9654c26 --- /dev/null +++ b/packages/vitaminc-normalize/src/decimal.rs @@ -0,0 +1,385 @@ +//! The canonical, order-preserving 14-byte encoding of a decimal. +//! +//! Ported from `orderable-bytes` 0.2.0, whose encoding is frozen: an +//! equality index stores terms under [`domain::DECIMAL`](crate::domain::DECIMAL) +//! made from these bytes, so they can never change, and this crate owns +//! them rather than reaching into a crate that is kept only for +//! cipherstash-client's stored terms. The tests check every value against +//! that release byte for byte. +//! +//! The input is the mantissa and scale a [`Logical::Decimal`](vitaminc_aead::Logical::Decimal) +//! leaf carries: `value = mantissa × 10^(-scale)`, with the mantissa in +//! `(-2^96, 2^96)` and the scale at most 28, which is `rust_decimal`'s +//! range. The encoder refuses anything outside it: a larger mantissa would +//! lose its top bits and take the bytes of another value. +//! +//! The layout is documented on [`decimal`](crate::decimal()), the public +//! function that wraps this encoder, so it is in the published docs. +//! +//! ## Constant time +//! +//! Past the range check, [`orderable`] is straight-line code with +//! fixed-iteration loops and branchless mask arithmetic: no branch on the +//! sign, the zero-ness, the digit count, the trailing-zero count or the +//! scale, and no hardware division, whose latency is data-dependent on +//! some targets. + +use vitaminc_aead::plaintext::kinds::{strip_trailing_zeros, MAX_DECIMAL_SCALE}; +use vitaminc_protected::Protected; + +use crate::scalar::fixed; + +/// Width of the padded-significand field in bytes (104 bits). +const MANTISSA_BYTES: usize = 13; + +/// Bias applied to `leading_exp` so it fits unsigned in the 7-bit field. +const EXP_BIAS: i32 = 64; + +/// The digit count the significand is padded to: the most a 96-bit +/// mantissa has. +const PADDED_DIGITS: u32 = 29; + +/// Top bit of byte 0: set for positives and zero, clear for negatives. +const SIGN_BIT: u8 = 0x80; + +/// The 7-bit exponent field of byte 0. +const EXP_MASK: u8 = 0x7F; + +/// One past the largest mantissa magnitude: a mantissa fits 96 bits. +const MANTISSA_LIMIT: u128 = 1 << 96; + +/// The length of the encoding. +pub(crate) const ENCODED_LEN: usize = 14; + +/// The encoding of `mantissa × 10^(-scale)`. Two equal values give the +/// same bytes, and the bytes sort as the values do. `None` if the mantissa +/// does not fit 96 bits or the scale is above 28. +/// +/// The encoder makes the protected vector it returns and writes every +/// byte of the encoding straight into it, so no caller has to supply a +/// buffer and remember to wipe it. The working values below are plain +/// integers, which the compiler keeps in registers or short-lived stack +/// slots that Rust cannot promise to wipe. +pub(crate) fn orderable(mantissa: i128, scale: u8) -> Option<Protected<Vec<u8>>> { + if scale > MAX_DECIMAL_SCALE || mantissa.unsigned_abs() >= MANTISSA_LIMIT { + return None; + } + let scale = u32::from(scale); + + // The pipeline runs unconditionally: zero goes through the same steps + // as every other value (the helpers give it significand 0, digits 0, + // trailing 0) and its byte 0 is fixed up by a mask at the end, rather + // than a short-circuit that would tell zero apart by timing. + // + // Branchless absolute value: `(x ^ s) - s` where `s` is the sign bit + // arithmetically shifted across the word. + let sign_extension = mantissa >> 127; + let abs_mantissa = ((mantissa ^ sign_extension).wrapping_sub(sign_extension)) as u128; + let (significand, trailing) = strip_trailing_zeros(abs_mantissa); + let digits = digit_count(significand); + + // value = ±significand × 10^trailing × 10^(-scale); the leading digit's + // exponent is in [-28, 28] for a non-zero value. For zero the formula + // gives -1 - scale, in [-29, -1]: a valid-looking positive byte that is + // overwritten below. + let leading_exp = digits as i32 - 1 + trailing - scale as i32; + debug_assert!( + (-29..=28).contains(&leading_exp), + "leading_exp {leading_exp} out of bounds: mantissa or scale out of range" + ); + let biased_exp = (leading_exp + EXP_BIAS) as u8; + debug_assert!(biased_exp <= EXP_MASK, "biased_exp overflowed 7 bits"); + + // Pad the significand to 29 digits. Not `pow`, whose work depends on + // its exponent: a fixed loop that multiplies by ten under a mask that + // is set while padding remains. The product is computed every + // iteration and never overflows: while the mask is set the value is + // below 10^28, and once clear the unstored product is below 10^30. + let mut padded_mantissa = significand; + for i in 0..PADDED_DIGITS { + let do_step = ((digits + i) < PADDED_DIGITS) as u128; + let mask = 0u128.wrapping_sub(do_step); + let stepped = padded_mantissa.wrapping_mul(10); + padded_mantissa = (padded_mantissa & !mask) | (stepped & mask); + } + debug_assert!( + padded_mantissa >> (8 * MANTISSA_BYTES) == 0, + "padded mantissa overflowed 104 bits" + ); + + // One mask handles the sign: 0xFF for a negative, 0x00 otherwise. Byte + // 0 keeps the sign bit only when positive and XORs the exponent bits + // with the mask; each significand byte is XORed with it too. + let neg_mask = (mantissa >> 127) as u8; + + // The zero plaintext, applied branchlessly: the tail is already all + // zero, so only byte 0 is replaced, by the bare sign bit, when the + // mantissa is zero. + let mant_nonzero_bit = ((abs_mantissa | abs_mantissa.wrapping_neg()) >> 127) as u8; + let zero_mask = 0u8.wrapping_sub(mant_nonzero_bit ^ 1); + + // Every byte is written. The significand bytes are taken from the + // integer by shifting, most significant first, rather than through a + // plain array of its bytes. + Some(fixed::<ENCODED_LEN>(|out| { + let head = (SIGN_BIT & !neg_mask) | (biased_exp ^ (neg_mask & EXP_MASK)); + out[0] = (head & !zero_mask) | (SIGN_BIT & zero_mask); + for i in 0..MANTISSA_BYTES { + let shift = 8 * (MANTISSA_BYTES - 1 - i); + out[1 + i] = (padded_mantissa >> shift) as u8 ^ neg_mask; + } + })) +} + +/// The number of decimal digits in `m`, `0` for zero: how many powers of +/// ten below `10^PADDED_DIGITS` it is at least, each test a borrow. +fn digit_count(m: u128) -> u32 { + let mut n: u32 = 0; + let mut pow: u128 = 1; + for _ in 0..PADDED_DIGITS { + let (_, borrow) = m.overflowing_sub(pow); + n = n.wrapping_add((borrow as u32) ^ 1); + pow = pow.wrapping_mul(10); + } + n +} + +#[cfg(test)] +mod tests { + use super::*; + use orderable_bytes::OrderableBytes; + use quickcheck_macros::quickcheck; + use rust_decimal::Decimal; + use vitaminc_protected::Controlled; + + const U96_MAX: u128 = (1u128 << 96) - 1; + + /// The encoding of an in-range value, copied out of its protected + /// vector into a plain array. The tests below index, sort and compare + /// the bytes against another crate's plain arrays, so this is the one + /// place they leave the wrapper. The inputs are test values, not real + /// plaintext, so a plain array of them is fine here. + /// + /// The bytes are copied through a read-only borrow, so the vector + /// itself is never taken out of its `Protected`, and it is wiped when it + /// drops at the end of this function. The returned array is the one + /// plain copy, and it is deliberate. + fn encode(mantissa: i128, scale: u32) -> [u8; ENCODED_LEN] { + let scale = u8::try_from(scale).expect("scale fits u8"); + let encoded = orderable(mantissa, scale).expect("in range"); + <[u8; ENCODED_LEN]>::try_from(encoded.risky_ref().as_slice()) + .expect("the encoding is ENCODED_LEN bytes") + } + + /// Whether the encoder accepts `mantissa` and `scale`. + fn accepts(mantissa: i128, scale: u8) -> bool { + orderable(mantissa, scale).is_some() + } + + /// The frozen encoding this one was ported from. + fn oracle(mantissa: i128, scale: u32) -> [u8; ENCODED_LEN] { + Decimal::try_from_i128_with_scale(mantissa, scale) + .expect("in range") + .to_orderable_bytes() + } + + #[test] + fn zero_in_any_scale_or_sign_is_the_bare_sign_bit() { + let mut expected = [0u8; ENCODED_LEN]; + expected[0] = SIGN_BIT; + for scale in [0, 1, 3, 28] { + assert_eq!(encode(0, scale), expected, "scale {scale}"); + } + assert_eq!(encode(-0, 0), expected); + } + + #[test] + fn equivalent_forms_encode_identically() { + let one = encode(1, 0); + assert_eq!(encode(10, 1), one); + assert_eq!(encode(100, 2), one); + assert_eq!(encode(1_000, 3), one); + // 100 strips to significand 1 at exponent 2: the same significand + // bytes as 1, and an exponent two higher. + let hundred = encode(100, 0); + assert_eq!(&one[1..], &hundred[1..]); + assert_eq!(one[0], SIGN_BIT | EXP_BIAS as u8); + assert_eq!(hundred[0], SIGN_BIT | (2 + EXP_BIAS) as u8); + } + + #[test] + fn worked_examples() { + assert_eq!(encode(5, 1)[0], SIGN_BIT | (-1 + EXP_BIAS) as u8); + assert_eq!(encode(10, 0)[0], SIGN_BIT | (1 + EXP_BIAS) as u8); + let (neg_one, pos_one) = (encode(-1, 0), encode(1, 0)); + assert_eq!(neg_one[0] & SIGN_BIT, 0); + assert_eq!(neg_one[0] & EXP_MASK, !(EXP_BIAS as u8) & EXP_MASK); + for i in 1..ENCODED_LEN { + assert_eq!(neg_one[i], !pos_one[i]); + } + } + + #[test] + fn byte_order_is_value_order() { + let values: [(i128, u32); 13] = [ + (-(U96_MAX as i128), 0), + (-1_000_000_000, 0), + (-15, 1), + (-105, 2), + (-1, 0), + (-1, 3), + (0, 0), + (1, 3), + (1, 0), + (105, 2), + (15, 1), + (1_000_000_000, 0), + (U96_MAX as i128, 0), + ]; + for pair in values.windows(2) { + let (a, b) = (pair[0], pair[1]); + assert!(encode(a.0, a.1) < encode(b.0, b.1), "{a:?} < {b:?} failed"); + } + } + + #[test] + fn digit_count_counts_digits() { + assert_eq!(digit_count(0), 0); + assert_eq!(digit_count(1), 1); + assert_eq!(digit_count(9), 1); + assert_eq!(digit_count(10), 2); + assert_eq!(digit_count(U96_MAX), 29); + } + + fn u96(m: u128) -> u128 { + m & U96_MAX + } + + #[quickcheck] + fn strip_reconstructs_and_is_canonical(m: u128) -> bool { + let m = u96(m); + let (s, c) = strip_trailing_zeros(m); + (0..=28).contains(&c) + && s.wrapping_mul(10u128.pow(c as u32)) == m + && (s == 0 || s % 10 != 0) + && (m == 0) == (s == 0) + && strip_trailing_zeros(s) == (s, 0) + } + + #[quickcheck] + fn strip_distributes_over_powers_of_ten(m: u128, k: u8) -> bool { + let (s, _) = strip_trailing_zeros(u96(m)); + let k = u32::from(k) % 29; + match s.checked_mul(10u128.pow(k)) { + Some(extended) if s != 0 && extended <= U96_MAX => { + strip_trailing_zeros(extended) == (s, k as i32) + } + _ => true, + } + } + + /// Every value encodes exactly as the frozen `orderable-bytes` release + /// encodes it. + #[quickcheck] + fn matches_orderable_bytes_byte_for_byte(m: u128, negative: bool, scale: u8) -> bool { + let magnitude = u96(m) as i128; + let mantissa = if negative { -magnitude } else { magnitude }; + let scale = u32::from(scale) % 29; + encode(mantissa, scale) == oracle(mantissa, scale) + } + + #[test] + fn the_extremes_match_orderable_bytes() { + for (mantissa, scale) in [ + (U96_MAX as i128, 0), + (-(U96_MAX as i128), 0), + (U96_MAX as i128, 28), + (-(U96_MAX as i128), 28), + (1, 28), + (-1, 28), + (0, 28), + ] { + assert_eq!(encode(mantissa, scale), oracle(mantissa, scale)); + } + } + + #[quickcheck] + fn byte_order_matches_decimal_order(a: u64, b: u64, sa: u8, sb: u8, neg: (bool, bool)) -> bool { + let (sa, sb) = (u32::from(sa) % 29, u32::from(sb) % 29); + let (a, b) = ( + if neg.0 { -(a as i128) } else { a as i128 }, + if neg.1 { -(b as i128) } else { b as i128 }, + ); + let (x, y) = ( + Decimal::try_from_i128_with_scale(a, sa).expect("in range"), + Decimal::try_from_i128_with_scale(b, sb).expect("in range"), + ); + encode(a, sa).cmp(&encode(b, sb)) == x.cmp(&y) + } + + /// The encoder checks its own range, so no caller can hand it a + /// mantissa whose top bits it would drop. + mod given_a_mantissa_or_scale_at_the_edge_of_the_range { + use super::*; + + #[test] + fn returns_an_encoding() { + let limit = 1i128 << 96; + assert!(accepts(limit - 1, 0), "the largest mantissa is accepted"); + assert!(accepts(1 - limit, 0), "the smallest mantissa is accepted"); + assert!(accepts(1, 28), "the largest scale is accepted"); + } + } + + mod given_a_mantissa_or_scale_one_past_the_range { + use super::*; + + #[test] + fn returns_none() { + let limit = 1i128 << 96; + assert!( + !accepts(limit, 0), + "one past the largest mantissa is refused" + ); + assert!( + !accepts(-limit, 0), + "one past the smallest mantissa is refused" + ); + assert!(!accepts(1, 29), "one past the largest scale is refused"); + } + } + + /// Every digit count, with and without trailing zeros, at every scale + /// and both signs. Random 96-bit mantissas almost all have 28 or 29 + /// digits, so the quickcheck oracle above rarely reaches short ones. + #[test] + fn every_digit_count_scale_and_sign_matches_orderable_bytes() { + for k in 0..=28u32 { + let p = 10i128.pow(k); + for magnitude in [p, p - 1, 7 * p, 123_456_789 * p] { + if magnitude as u128 > U96_MAX { + continue; + } + for scale in 0..=28u32 { + for mantissa in [magnitude, -magnitude] { + assert_eq!( + encode(mantissa, scale), + oracle(mantissa, scale), + "{mantissa} at scale {scale}" + ); + } + } + } + } + } + + /// Built from a short significand, so `s * 10^k` stays in range and + /// every case reaches the comparison. + #[quickcheck] + fn strip_distributes_over_powers_of_ten_for_short_significands(base: u32, k: u8) -> bool { + let (s, _) = strip_trailing_zeros(u128::from(base)); + // `s` has at most 10 digits, so `s * 10^k` stays below 10^28. + let k = u32::from(k) % (29 - digit_count(s)); + s == 0 || strip_trailing_zeros(s * 10u128.pow(k)) == (s, k as i32) + } +} diff --git a/packages/vitaminc-normalize/src/lib.rs b/packages/vitaminc-normalize/src/lib.rs new file mode 100644 index 000000000..0a443bd08 --- /dev/null +++ b/packages/vitaminc-normalize/src/lib.rs @@ -0,0 +1,26 @@ +// These definitions precede the README so rustdoc links to the version being built. +// The README supplies published-API URLs for GitHub. See docs/documentation.md. +//! [`NormalizeError::NoDomain`]: crate::NormalizeError::NoDomain +//! [`Normalized`]: crate::Normalized +//! [`Term`]: crate::Term +//! [`Terms`]: crate::Terms +//! [`decimal`]: crate::decimal() +//! [`domain::NULL`]: crate::domain::NULL +//! +#![deny(missing_docs)] +#![deny(clippy::unwrap_used, clippy::todo, unsafe_code, unused_imports)] +#![doc = include_str!("../README.md")] + +mod decimal; +mod scalar; +mod terms; + +pub use scalar::{ + bytes, date, decimal, domain, domain_of, float, integer, normalize, null, text, timestamp, + uuid, NormalizeError, Normalized, +}; +pub use terms::{ + encrypt_with_terms, plan_with_terms, terms, terms_by, Equality, Normalize, Term, TermError, + Terms, TermsError, TermsMap, TermsSeq, WithTerms, +}; +pub use vitaminc_aead::plaintext::{Path, Step}; diff --git a/packages/vitaminc-normalize/src/scalar.rs b/packages/vitaminc-normalize/src/scalar.rs new file mode 100644 index 000000000..84330dde3 --- /dev/null +++ b/packages/vitaminc-normalize/src/scalar.rs @@ -0,0 +1,420 @@ +//! One normalized equality term per scalar. +//! +//! [`normalize`] turns a physical value and its optional logical type into +//! the bytes an equality index derives under, and the frozen domain label +//! those bytes belong to. The encoders are public, one per kind, so an index +//! layer that already knows a value's kind can call them directly. +//! +//! Every integer width shares one 17-byte encoding and domain, and both +//! float widths share one 8-byte encoding and domain, so equal numbers +//! match whichever width wrote them. Text is Unicode 16 NFC. These bytes +//! and their [`domain`] labels are protocol data: changing either requires +//! a new domain. Text processing is variable-time; this module makes no +//! constant-time claim for Unicode normalization. +//! +//! Logical types opt in. A date, a timestamp, a decimal and a uuid each +//! have a domain of their own, separate from the physical value they are +//! stored as, so a date's day count never matches the integer it equals and +//! a uuid never matches the same sixteen bytes written as bytes. Every other +//! logical type, [`Logical::Unknown`] included, has no term and is refused +//! with [`NormalizeError::NoDomain`]. +//! +//! A null has a term too, under [`domain::NULL`]: one byte, the same in +//! every column, so an absent value is indexed like any other value and +//! the nulls show only as one more tied group. A boolean and an +//! `undefined` have none. + +use unicode_general_category::{get_general_category, GeneralCategory}; +use unicode_normalization::UnicodeNormalization; +use vitaminc_aead::plaintext::kinds::{timestamp_nanos, MAX_DATE_DAYS, MIN_DATE_DAYS}; +use vitaminc_aead::{Float, Int, Logical, Physical, TimeUnit}; +use vitaminc_protected::{Controlled, OpaqueDebug, Protected}; + +/// Frozen domain labels for equality terms, one per kind that has one. +pub mod domain { + /// Every integer width, `i8` through `u128`. + pub const INTEGER: &str = "vitaminc/prf/value/integer-orderable/v1"; + /// `f32` and `f64`, as `f64`. + pub const FLOAT: &str = "vitaminc/prf/value/float-orderable/v1"; + /// A date, over its day count. + pub const DATE: &str = "vitaminc/prf/value/date-orderable/v1"; + /// A timestamp, truncated to microseconds. + pub const TIMESTAMP: &str = "vitaminc/prf/value/timestamp-micros-orderable/v1"; + /// A decimal, with scale and signed zero normalized. + pub const DECIMAL: &str = "vitaminc/prf/value/decimal-orderable/v1"; + /// Text, as Unicode 16 NFC. + pub const TEXT: &str = "vitaminc/prf/value/text-nfc/unicode-16/v1"; + /// Bytes. + pub const BYTES: &str = "vitaminc/prf/value/bytes/v1"; + /// A uuid, over its sixteen raw bytes. + pub const UUID: &str = "vitaminc/prf/value/uuid/v1"; + /// A null, typed or plain, whatever column it sits in: the one byte + /// `0x00`. + pub const NULL: &str = "vitaminc/prf/value/null/v1"; + /// Every domain, for a test or an index layer that enumerates them. A + /// slice, so a domain added later does not change its type. + pub const ALL: &[&str] = &[ + INTEGER, FLOAT, DATE, TIMESTAMP, DECIMAL, TEXT, BYTES, UUID, NULL, + ]; +} + +/// The normalized bytes for one equality term and the domain they belong +/// to. +/// +/// The fields are public so an index layer can build a term of its own, +/// and whatever consumes a `Normalized` trusts them: a PRF derives under +/// the `domain` it is handed. The only way to get the frozen encodings is +/// through [`normalize`] or the per-kind encoders here. +/// +/// `Debug` shows the domain and masks the bytes. +#[derive(OpaqueDebug)] +pub struct Normalized { + /// The frozen domain label, one of the [`domain`] constants. + #[non_sensitive] + pub domain: &'static str, + /// The normalized plaintext, protected. + pub bytes: Protected<Vec<u8>>, +} + +/// Why a scalar has no term. Never includes plaintext. +#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)] +#[non_exhaustive] +pub enum NormalizeError { + /// The scalar has no domain under the normalizer: an `undefined`, a + /// boolean, a logical type outside its opt-in table, or a null under + /// an index that gives nulls no term (an order index whose space does + /// not place them). The message does not name an index, because the + /// equality and order normalizers both report it; whatever wraps it + /// says which. + #[error("no domain for this kind of value")] + NoDomain, + /// The value is not valid for its logical type. + #[error("the value is not valid for its logical type")] + Invalid, + /// Text contains a code point unassigned in Unicode 16. + #[error("text contains a code point unassigned in Unicode 16")] + UnassignedCodePoint, + /// The value is of another kind than the type the index declares: text + /// for an integer column, say. Not reported by the equality + /// normalizer, which declares no type. + #[error("the value is not of the kind the index declares")] + Mismatch, + /// The value is of the kind the index declares but does not fit it: an + /// integer outside the declared width. Not reported by the equality + /// normalizer, which declares no type. + #[error("the value does not fit the type the index declares")] + OutOfRange, + /// The value is of the kind the index declares, and fits it, but its + /// code is the one the index keeps for nulls: the maximum of an + /// integer or uuid target in an order space that places nulls first + /// or last. Not reported by the equality normalizer, which gives a + /// null a domain of its own. + #[error("the value's code is the one this space keeps for the null")] + Reserved, +} + +/// The opt-in table: the domain for a scalar, or `None` for one that has +/// no term. A logical type decides on its own; a value without one goes by +/// its kind. Neither looks at the value: [`normalize`] checks that. +pub fn domain_of(ty: Option<Logical>, v: &Physical<'_>) -> Option<&'static str> { + match (ty, v) { + (None, Physical::Int(_)) => Some(domain::INTEGER), + (None, Physical::Float(_)) => Some(domain::FLOAT), + (None, Physical::Text(_)) => Some(domain::TEXT), + (None, Physical::Bytes(_)) => Some(domain::BYTES), + (None, Physical::Null) => Some(domain::NULL), + (None, Physical::Bool(_)) => None, + (Some(Logical::Date), _) => Some(domain::DATE), + (Some(Logical::Timestamp(_)), _) => Some(domain::TIMESTAMP), + (Some(Logical::Decimal { .. }), _) => Some(domain::DECIMAL), + (Some(Logical::Uuid), _) => Some(domain::UUID), + // `Logical` is non-exhaustive: a type this build does not know, and + // any added later, has no term until it is given a domain here. + (Some(_), _) => None, + } +} + +/// Encode one scalar for equality, with the domain its term belongs to. +/// +/// Integers of every width share [`domain::INTEGER`]: a sign byte (`0x00` +/// negative, `0x01` otherwise) then the value as a big-endian 128-bit +/// two's-complement word, which orders correctly across `i128::MIN` to +/// `u128::MAX`. Both float widths share [`domain::FLOAT`]: an `f32` widens +/// exactly to `f64`, so it matches an `f64` only when the numbers are equal +/// (`f32` 1.5 matches, `f32` 0.1 does not match `f64` 0.1). Float zero +/// signs and NaN payloads are folded. A timestamp in any unit is truncated +/// to microseconds. A decimal's scale is normalized, so `1.50` and `1.5` +/// are one term, as are `-0.00` and `0`. A null is [`domain::NULL`] and +/// the one byte `0x00`; a typed null is walked as a plain one, so it is +/// the same term. +/// +/// # Examples +/// +/// ``` +/// use vitaminc_aead::Physical; +/// use vitaminc_normalize::{domain, normalize}; +/// use vitaminc_protected::Controlled; +/// +/// let null = normalize(None, Physical::Null)?; +/// assert_eq!(null.domain, domain::NULL); +/// assert_eq!(null.bytes.risky_ref(), &[0x00]); +/// # Ok::<(), vitaminc_normalize::NormalizeError>(()) +/// ``` +pub fn normalize(ty: Option<Logical>, v: Physical<'_>) -> Result<Normalized, NormalizeError> { + // A value that does not fit its logical type is refused as invalid + // before the type is looked up, so `undefined` over an int is `Invalid` + // rather than "nothing to index". + if ty.is_some_and(|ty| !ty.admits(&v)) { + return Err(NormalizeError::Invalid); + } + let domain = domain_of(ty, &v).ok_or(NormalizeError::NoDomain)?; + let bytes = match (ty, v) { + (None, Physical::Int(i)) => Some(integer(i)), + (None, Physical::Float(f)) => Some(float(f)), + (None, Physical::Text(s)) => Some(text(s)?), + (None, Physical::Bytes(b)) => Some(bytes(b)), + (None, Physical::Null) => Some(null()), + (Some(Logical::Date), Physical::Int(days)) => date(days), + (Some(Logical::Timestamp(unit)), Physical::Int(count)) => timestamp(unit, count), + (Some(Logical::Decimal { scale }), Physical::Int(mantissa)) => decimal(scale, mantissa), + (Some(Logical::Uuid), Physical::Bytes(b)) => uuid(b), + // `admits` has already refused a logical type over the wrong kind, + // and `domain_of` everything without a term. Each encoder checks + // its own range as well, for a caller that goes to it directly. + _ => None, + } + .ok_or(NormalizeError::Invalid)?; + Ok(Normalized { domain, bytes }) +} + +/// An integer of any width: a sign byte, then the big-endian 128-bit word. +pub fn integer(value: Int) -> Protected<Vec<u8>> { + // `sign_and_word` is `#[inline]`, so it is compiled into this function + // and the sign and word stay in registers until they are written to the + // buffer, rather than coming back through an unwiped stack slot + // (checked in the compiled code for AArch64; Rust does not promise it). + let (negative, word) = value.sign_and_word(); + fixed::<17>(|b| { + b[0] = u8::from(!negative); + b[1..].copy_from_slice(&word.to_be_bytes()); + }) +} + +/// A float of either width, as the orderable bytes of its `f64` value with +/// zero signs and NaN payloads folded. +pub fn float(value: Float) -> Protected<Vec<u8>> { + let value = match value { + Float::F32(f) => widen_f32(f), + Float::F64(f) => f, + }; + orderable_f64(canonical_f64(value)) +} + +/// A date's day count since 1970-01-01, as the orderable bytes of its +/// count of days from 0001-01-01, so the bytes order as the dates do. +/// `None` outside the date range. +pub fn date(days: Int) -> Option<Protected<Vec<u8>>> { + let days = i32::try_from(days.to_i128()?).ok()?; + if !(MIN_DATE_DAYS..=MAX_DATE_DAYS).contains(&days) { + return None; + } + let from_ce = days.checked_add(EPOCH_DAYS_FROM_CE)?; + Some(fixed(|b| { + *b = ((from_ce as u32) ^ (1u32 << 31)).to_be_bytes() + })) +} + +/// A count of `unit`s since the Unix epoch, as orderable seconds then +/// big-endian nanoseconds truncated to microseconds, so the bytes order as +/// the instants do, to the microsecond. `None` outside the timestamp +/// range. +pub fn timestamp(unit: TimeUnit, count: Int) -> Option<Protected<Vec<u8>>> { + // `timestamp_nanos` is `#[inline]` for the same reason as + // `sign_and_word` in `integer`: so the count is not returned through + // an unwiped stack slot. + let nanos = timestamp_nanos(unit, count)?; + let seconds = i64::try_from(nanos.div_euclid(NANOS_PER_SECOND)).ok()?; + let sub = (nanos.rem_euclid(NANOS_PER_SECOND) as u32) / 1_000 * 1_000; + Some(fixed::<12>(|b| { + b[..8].copy_from_slice(&((seconds as u64) ^ (1u64 << 63)).to_be_bytes()); + b[8..].copy_from_slice(&sub.to_be_bytes()); + })) +} + +/// A decimal's mantissa and scale, as the 14-byte orderable encoding of +/// its value, ported from the frozen `orderable-bytes` release and checked +/// against it, which normalizes the scale and a signed zero. `None` +/// if the mantissa does not fit 96 bits or the scale is above 28, the +/// range `rust_decimal` represents. +/// +/// # Encoding (scientific form, base 10) +/// +/// Each non-zero value is re-expressed in signed scientific form: +/// +/// ```text +/// value = ±significand × 10^(leading_exp − digits(significand) + 1) +/// ``` +/// +/// where `significand` is the mantissa with trailing zeros stripped and +/// `leading_exp` is the decimal exponent of the leading significant digit, +/// in `[-28, 28]`. The 14 bytes are: +/// +/// ```text +/// byte 0 : [sign:1][biased_exp:7] +/// bytes 1..=13 : padded_significand (104 bits, big-endian) +/// ``` +/// +/// - The sign bit is `1` for positive and zero, `0` for negative, so every +/// negative sorts below zero and zero below every positive. +/// - The biased exponent is `leading_exp + 64`, in `[36, 92]` for a +/// non-zero value. Zero uses `0`, which no non-zero value reaches. +/// - The padded significand is the significand left-justified to 29 +/// digits by appending zeros, so values at one exponent compare +/// byte-wise however many digits they have. A 96-bit mantissa has at +/// most 29 digits, so the padded value fits 104 bits. +/// +/// For a negative, the exponent bits and the significand are inverted, so +/// a larger magnitude sorts lower. `1`, `1.0` and `1.00` reduce to the +/// same significand and exponent, and `+0` and `-0` to the same zero, so +/// equal values are equal bytes, as `rust_decimal` compares them. +pub fn decimal(scale: u8, mantissa: Int) -> Option<Protected<Vec<u8>>> { + crate::decimal::orderable(mantissa.to_i128()?, scale) +} + +/// NFC in the pinned Unicode version, without case or accent folding. +/// +/// The result is written into one protected buffer sized exactly up front, +/// so it never reallocates and frees an unwiped partial copy. +/// +/// The `unicode-normalization` iterators keep pending code points in small +/// buffers of their own, with room for four code points inside the +/// iterator. Decomposition holds the combining marks that follow a +/// character in the same buffer as the decomposed form of the next +/// character, so the buffer moves to the heap as soon as those together +/// pass four code points: four marks followed by any character is enough. +/// Composition moves its buffer to the heap when five marks after one +/// character do not combine with it. Once a buffer is on the heap it stays +/// there for the rest of the string, so every later character passes +/// through it, and it is freed without being wiped. That is out of this +/// crate's control (see #488). +pub fn text(text: &str) -> Result<Protected<Vec<u8>>, NormalizeError> { + if text + .chars() + .any(|c| get_general_category(c) == GeneralCategory::Unassigned) + { + return Err(NormalizeError::UnassignedCodePoint); + } + // NFC can grow UTF-8 (U+0344 is two bytes, its NFC form four), so measure + // the output first rather than sizing from the input. + let len = text.nfc().map(char::len_utf8).sum(); + let mut result = Protected::new(Vec::with_capacity(len)); + for c in text.nfc() { + let mut encoded = Protected::new([0u8; 4]); + result + .risky_inner_mut() + .extend_from_slice(c.encode_utf8(encoded.risky_inner_mut()).as_bytes()); + } + Ok(result) +} + +/// Bytes, as they are. +pub fn bytes(value: &[u8]) -> Protected<Vec<u8>> { + Protected::new(value.to_vec()) +} + +/// A null, typed or plain: the one byte `0x00`, under [`domain::NULL`]. +/// Every null is this one term, whatever column it sits in, as SQL says +/// `NULL IS NULL` whatever the column. Spaces that must not tie already +/// differ in context. +pub fn null() -> Protected<Vec<u8>> { + fixed::<1>(|b| *b = [0x00]) +} + +/// A uuid's sixteen raw bytes. `None` for any other length. +pub fn uuid(value: &[u8]) -> Option<Protected<Vec<u8>>> { + (value.len() == 16).then(|| Protected::new(value.to_vec())) +} + +/// A fixed-width encoding, written by `write` straight into the protected +/// vector that is returned. +/// +/// The vector is allocated once at its final size, so it never +/// reallocates, and `write` fills it in place. No separate array of the +/// encoding is made and copied, so there is no extra copy to wipe. The +/// compiler can still make short-lived temporaries while `write` runs, for +/// example the array that `to_be_bytes` returns, and Rust cannot promise +/// to wipe those. +/// +/// `vitaminc-ore` has its own private copy of this function rather than +/// sharing this one, so it stays out of this crate's public API. +pub(crate) fn fixed<const N: usize>(mut write: impl FnMut(&mut [u8; N])) -> Protected<Vec<u8>> { + let mut bytes = Protected::new(vec![0u8; N]); + bytes.update(|bytes| { + let array = <&mut [u8; N]>::try_from(bytes.as_mut_slice()) + .expect("the vector was made with exactly N bytes"); + write(array); + }); + bytes +} + +/// Days from 0001-01-01 (counted as day 1, the "days from CE" of the +/// proleptic Gregorian calendar) to 1970-01-01. +const EPOCH_DAYS_FROM_CE: i32 = 719_163; +const NANOS_PER_SECOND: i128 = 1_000_000_000; + +/// The orderable bytes of an `f64`: negatives flip every bit, positives +/// the sign bit, so the bytes sort as the numbers do. Expects a value +/// [`canonical_f64`] has already folded. +/// +/// The bytes are written straight into the protected vector that is +/// returned (see [`fixed`]). +fn orderable_f64(value: f64) -> Protected<Vec<u8>> { + let bits = value.to_bits(); + let sign_extension = ((bits as i64) >> 63) as u64; + fixed(|b| *b = (bits ^ (sign_extension | (1u64 << 63))).to_be_bytes()) +} + +/// `f64::from(f32)` in integer operations only. A hardware conversion can +/// take a slow path on subnormal inputs, which would leak timing; this keeps +/// the float path free of floating-point arithmetic. +fn widen_f32(value: f32) -> f64 { + let bits = value.to_bits(); + let sign = u64::from(bits >> 31) << 63; + let exponent = (bits >> 23) & 0xff; + let mantissa = u64::from(bits & 0x7f_ffff); + let zero_exponent = 0u64.wrapping_sub((exponent == 0) as u64); + let max_exponent = 0u64.wrapping_sub((exponent == 0xff) as u64); + let nonzero = 0u64.wrapping_sub((mantissa != 0) as u64); + // Normal, infinite and NaN: rebias the exponent (127 to 1023, or all + // ones stays all ones) and left-align the mantissa. + let rebiased = ((u64::from(exponent) + 896) & !max_exponent) | (0x7ff & max_exponent); + let normal = (rebiased << 52) | (mantissa << 29); + // Subnormal: the highest set bit becomes the implicit leading one. + let top = highest_set_bit(mantissa); + let subnormal = ((top + 874) << 52) | ((mantissa << (52 - top)) & ((1 << 52) - 1)); + f64::from_bits(sign | (normal & !zero_exponent) | (subnormal & zero_exponent & nonzero)) +} + +/// Index of the highest set bit of a subnormal f32 mantissa. `| 1` keeps the +/// result in range for a zero mantissa, which `widen_f32` masks out. +/// +/// Kept out of `widen_f32` so the `.cargo/mutants.toml` exclusion of that +/// function's equivalent `|`-to-`^` mutants cannot reach this `|`, whose +/// operands overlap and whose mutant a test does catch. +fn highest_set_bit(mantissa: u64) -> u64 { + u64::from(63 - (mantissa | 1).leading_zeros()) +} + +/// Folds every NaN to one quiet NaN and `-0.0` to `0.0`, in integer +/// operations only. +fn canonical_f64(value: f64) -> f64 { + let bits = value.to_bits(); + let magnitude = bits & 0x7fff_ffff_ffff_ffff; + let nan = 0u64.wrapping_sub((magnitude > 0x7ff0_0000_0000_0000) as u64); + let nonzero = 0u64.wrapping_sub((magnitude != 0) as u64); + f64::from_bits((bits & !nan).wrapping_add(0x7ff8_0000_0000_0000 & nan) & nonzero) +} + +#[cfg(test)] +#[path = "scalar_tests.rs"] +mod tests; diff --git a/packages/vitaminc-normalize/src/scalar_tests.rs b/packages/vitaminc-normalize/src/scalar_tests.rs new file mode 100644 index 000000000..07b156c6f --- /dev/null +++ b/packages/vitaminc-normalize/src/scalar_tests.rs @@ -0,0 +1,607 @@ +use super::*; +use orderable_bytes::OrderableBytes; +use quickcheck_macros::quickcheck; +use vitaminc_aead::UnknownLogical; + +fn term(ty: Option<Logical>, v: Physical<'_>) -> Vec<u8> { + normalize(ty, v) + .expect("valid test value") + .bytes + .risky_ref() + .clone() +} + +fn int(ty: Option<Logical>, i: Int) -> Vec<u8> { + term(ty, Physical::Int(i)) +} + +fn integer_bytes(sign: u8, word: u128) -> Vec<u8> { + let mut expected = vec![sign]; + expected.extend_from_slice(&word.to_be_bytes()); + expected +} + +#[test] +fn integers_share_one_domain_whatever_their_width() { + let five = [ + Int::I8(5), + Int::U8(5), + Int::I16(5), + Int::U16(5), + Int::I32(5), + Int::U32(5), + Int::I64(5), + Int::U64(5), + Int::I128(5), + Int::U128(5), + ]; + for value in five { + let n = normalize(None, Physical::Int(value)).expect("int"); + assert_eq!(n.domain, domain::INTEGER); + assert_eq!(n.bytes.risky_ref(), &integer_bytes(1, 5)); + } + for value in [ + Int::I8(-7), + Int::I16(-7), + Int::I32(-7), + Int::I64(-7), + Int::I128(-7), + ] { + assert_eq!(int(None, value), integer_bytes(0, -7i128 as u128)); + } + assert_eq!(int(None, Int::I128(i128::MIN)), integer_bytes(0, 1 << 127)); + assert_eq!(int(None, Int::I128(-1)), integer_bytes(0, u128::MAX)); + assert_eq!(int(None, Int::I128(0)), integer_bytes(1, 0)); + assert_eq!(int(None, Int::U128(u128::MAX)), integer_bytes(1, u128::MAX)); + let ascending = [ + Int::I128(i128::MIN), + Int::I64(i64::MIN), + Int::I8(-1), + Int::U8(0), + Int::I8(i8::MAX), + Int::U64(u64::MAX), + Int::I128(i128::MAX), + Int::U128(u128::MAX), + ]; + for pair in ascending.windows(2) { + assert!(int(None, pair[0]) < int(None, pair[1])); + } +} + +#[quickcheck] +fn signed_and_unsigned_integers_agree_when_equal(value: u64) -> bool { + int(None, Int::U64(value)) == int(None, Int::I128(value.into())) + && int(None, Int::U128(value.into())) == int(None, Int::I128(value.into())) +} + +#[quickcheck] +fn integer_order_agrees_with_numeric_order(a: i64, b: u64) -> bool { + let (wide_a, wide_b) = (i128::from(a), i128::from(b)); + int(None, Int::I64(a)).cmp(&int(None, Int::U64(b))) == wide_a.cmp(&wide_b) + && int(None, Int::I128(wide_a * wide_b)).cmp(&int(None, Int::I64(a))) + == (wide_a * wide_b).cmp(&wide_a) +} + +#[test] +fn the_opt_in_table_names_every_domain_and_nothing_else() { + let one = Physical::Int(Int::I32(1)); + assert_eq!(domain_of(None, &one), Some(domain::INTEGER)); + assert_eq!( + domain_of(None, &Physical::Float(Float::F32(1.0))), + Some(domain::FLOAT) + ); + assert_eq!(domain_of(None, &Physical::Text("a")), Some(domain::TEXT)); + assert_eq!(domain_of(None, &Physical::Bytes(&[1])), Some(domain::BYTES)); + assert_eq!(domain_of(Some(Logical::Date), &one), Some(domain::DATE)); + assert_eq!( + domain_of(Some(Logical::Timestamp(TimeUnit::Millis)), &one), + Some(domain::TIMESTAMP) + ); + assert_eq!( + domain_of(Some(Logical::Decimal { scale: 2 }), &one), + Some(domain::DECIMAL) + ); + assert_eq!( + domain_of(Some(Logical::Uuid), &Physical::Bytes(&[0; 16])), + Some(domain::UUID) + ); + assert_eq!(domain_of(None, &Physical::Null), Some(domain::NULL)); + assert_eq!(domain_of(None, &Physical::Bool(true)), None); + assert_eq!(domain_of(Some(Logical::Undefined), &Physical::Null), None); + let unknown = Logical::from_wire(200, 1).expect("unknown"); + assert!(matches!(unknown, Logical::Unknown(UnknownLogical { .. }))); + assert_eq!(domain_of(Some(unknown), &one), None); + assert_eq!(domain::ALL.len(), 9); + for label in domain::ALL { + assert!(label.starts_with("vitaminc/prf/value/"), "{label}"); + } +} + +#[test] +fn a_scalar_with_no_domain_is_refused_with_no_domain() { + let unknown = Logical::from_wire(200, 1).expect("unknown"); + for (ty, v) in [ + (None, Physical::Bool(false)), + (Some(Logical::Undefined), Physical::Null), + (Some(unknown), Physical::Int(Int::I32(1))), + (Some(unknown), Physical::Text("x")), + ] { + assert_eq!( + normalize(ty, v).expect_err("no term"), + NormalizeError::NoDomain + ); + } + for error in [ + NormalizeError::NoDomain, + NormalizeError::Invalid, + NormalizeError::UnassignedCodePoint, + NormalizeError::Reserved, + ] { + assert!(!error.to_string().is_empty()); + } +} + +#[test] +fn a_value_that_does_not_fit_its_logical_type_is_invalid() { + for (ty, v) in [ + (Logical::Date, Physical::Text("2024-01-01")), + (Logical::Date, Physical::Int(Int::I64(i64::MAX))), + ( + Logical::Timestamp(TimeUnit::Nanos), + Physical::Int(Int::I128(i128::MAX)), + ), + (Logical::Decimal { scale: 29 }, Physical::Int(Int::I32(1))), + ( + Logical::Decimal { scale: 1 }, + Physical::Int(Int::I128(1 << 100)), + ), + (Logical::Uuid, Physical::Bytes(&[0; 15])), + (Logical::Uuid, Physical::Int(Int::I32(1))), + ] { + assert_eq!( + normalize(Some(ty), v).expect_err("invalid"), + NormalizeError::Invalid + ); + } + // `undefined` over anything but a null is a value that does not fit + // its type, not one with nothing to index. + assert_eq!( + normalize(Some(Logical::Undefined), Physical::Int(Int::I32(1))).expect_err("invalid"), + NormalizeError::Invalid + ); + // The encoders say the same without going through `admits`, one day + // past the wire's range on either side included. + assert!(date(Int::I64(i64::MAX)).is_none()); + assert!(date(Int::I32(MAX_DATE_DAYS + 1)).is_none()); + assert!(date(Int::I32(MIN_DATE_DAYS - 1)).is_none()); + assert!(date(Int::I32(MAX_DATE_DAYS)).is_some()); + assert!(date(Int::I32(MIN_DATE_DAYS)).is_some()); + for days in [MAX_DATE_DAYS + 1, MIN_DATE_DAYS - 1] { + assert_eq!( + normalize(Some(Logical::Date), Physical::Int(Int::I32(days))).expect_err("invalid"), + NormalizeError::Invalid + ); + } + assert!(timestamp(TimeUnit::Nanos, Int::I128(i128::MAX)).is_none()); + assert!(decimal(29, Int::I32(1)).is_none()); + assert!(decimal(1, Int::U128(u128::MAX)).is_none()); + assert!(uuid(&[0; 15]).is_none()); +} + +#[test] +fn a_logical_value_never_shares_a_term_with_its_physical_value() { + let days = Int::I32(19_000); + assert_ne!(int(Some(Logical::Date), days), int(None, days)); + let count = Int::I64(1_700_000_000_000); + assert_ne!( + int(Some(Logical::Timestamp(TimeUnit::Millis)), count), + int(None, count) + ); + let mantissa = Int::I128(150); + assert_ne!( + int(Some(Logical::Decimal { scale: 2 }), mantissa), + int(None, mantissa) + ); + // A uuid is its sixteen bytes, so the domain alone keeps it apart from + // the same bytes written as bytes. + let id = [5u8; 16]; + assert_eq!(uuid(&id).expect("uuid").risky_ref(), bytes(&id).risky_ref()); + assert_ne!( + normalize(Some(Logical::Uuid), Physical::Bytes(&id)) + .expect("uuid") + .domain, + normalize(None, Physical::Bytes(&id)).expect("bytes").domain + ); +} + +#[test] +fn dates_are_orderable_days_from_the_common_era() { + // 0001-01-01 is day 1 from CE; 1970-01-01 is day 719163. + assert_eq!( + int(Some(Logical::Date), Int::I32(1 - EPOCH_DAYS_FROM_CE)), + [0x80, 0x00, 0x00, 0x01] + ); + assert_eq!( + int(Some(Logical::Date), Int::I32(0)), + ((EPOCH_DAYS_FROM_CE as u32) ^ (1 << 31)).to_be_bytes() + ); + assert!(int(Some(Logical::Date), Int::I32(-1)) < int(Some(Logical::Date), Int::I32(0))); + assert!(int(Some(Logical::Date), Int::I32(0)) < int(Some(Logical::Date), Int::I32(1))); +} + +#[test] +fn timestamps_in_any_unit_truncate_to_microseconds() { + let nanos = Int::I128(1_700_000_000_123_456_789); + let micros = Int::I64(1_700_000_000_123_456); + let millis = Int::I64(1_700_000_000_123); + let seconds = Int::I64(1_700_000_000); + let by = |unit, count| int(Some(Logical::Timestamp(unit)), count); + assert_eq!(by(TimeUnit::Nanos, nanos), by(TimeUnit::Micros, micros)); + assert_eq!( + by(TimeUnit::Millis, millis), + by(TimeUnit::Micros, Int::I64(1_700_000_000_123_000)) + ); + assert_eq!( + by(TimeUnit::Seconds, seconds), + by(TimeUnit::Nanos, Int::I128(1_700_000_000_000_000_000)) + ); + let mut expected = ((1_700_000_000u64) ^ (1 << 63)).to_be_bytes().to_vec(); + expected.extend_from_slice(&123_456_000u32.to_be_bytes()); + assert_eq!(by(TimeUnit::Nanos, nanos), expected); + // Before the epoch the seconds floor and the fraction stays positive. + let before = by(TimeUnit::Nanos, Int::I128(-1_000_000_000 + 123_456_789)); + let mut expected = ((-1i64 as u64) ^ (1 << 63)).to_be_bytes().to_vec(); + expected.extend_from_slice(&123_456_000u32.to_be_bytes()); + assert_eq!(before, expected); + assert!(before < by(TimeUnit::Seconds, Int::I64(0))); +} + +#[test] +fn decimals_normalize_scale_and_signed_zero() { + let by = |scale, mantissa| int(Some(Logical::Decimal { scale }), Int::I128(mantissa)); + assert_eq!(by(0, 1), by(1, 10)); + assert_eq!(by(0, 1), by(2, 100)); + assert_eq!(by(2, 150), by(1, 15)); + assert_eq!(by(2, 0), by(0, 0)); + assert_eq!(by(0, -0), by(0, 0)); + assert!(by(0, -1) < by(0, 0)); + assert!(by(0, 0) < by(0, 1)); + assert!(by(2, 150) < by(0, 2)); +} + +#[test] +fn nfc_expansion_fills_an_exactly_sized_buffer() { + // U+0344 is two UTF-8 bytes; its NFC form U+0308 U+0301 is four. + let normalized = text("\u{344}").expect("valid test value"); + assert_eq!(normalized.risky_ref(), "\u{308}\u{301}".as_bytes()); + assert_eq!(normalized.risky_ref().capacity(), 4); +} + +#[test] +fn unicode_version_and_equivalence_are_frozen() { + // Normalization stability makes newer NFC tables safe for text that is + // assigned in Unicode 16; the assignment table is the exact pin. + assert!(unicode_normalization::UNICODE_VERSION >= (16, 0, 0)); + assert_eq!(unicode_general_category::UNICODE_VERSION, (16, 0, 0)); + assert_eq!(term(None, Physical::Text("e\u{301}")), "é".as_bytes()); + assert_ne!( + term(None, Physical::Text("É")), + term(None, Physical::Text("é")) + ); + assert_ne!( + term(None, Physical::Text("e")), + term(None, Physical::Text("é")) + ); + for s in ["\u{378}", "\u{10ffff}", "\u{1faea}"] { + assert_eq!( + normalize(None, Physical::Text(s)).expect_err("unsupported input"), + NormalizeError::UnassignedCodePoint + ); + } + assert_eq!(text("a\0").expect("valid test value").risky_ref(), b"a\0"); +} + +#[quickcheck] +fn nfc_is_idempotent(s: String) -> bool { + match text(&s) { + Ok(first) => { + let first = String::from_utf8(first.risky_ref().clone()).expect("utf-8"); + text(&first).expect("valid test value").risky_ref() == first.as_bytes() + } + Err(_) => s + .chars() + .any(|c| get_general_category(c) == GeneralCategory::Unassigned), + } +} + +fn f32_term(v: f32) -> Vec<u8> { + term(None, Physical::Float(Float::F32(v))) +} + +fn f64_term(v: f64) -> Vec<u8> { + term(None, Physical::Float(Float::F64(v))) +} + +#[test] +fn floats_have_postgres_zero_and_nan_ordering() { + assert_eq!(f64_term(-0.0), f64_term(0.0)); + assert_eq!(f32_term(-0.0), f64_term(0.0)); + for bits in [0x7fc0_0000, 0xff80_0001, 0xffff_ffff, 0x7f80_0001] { + assert_eq!( + f32_term(f32::from_bits(bits)), + [0xff, 0xf8, 0, 0, 0, 0, 0, 0] + ); + } + for bits in [0x7ff8_0000_0000_0000, 0xfff0_0000_0000_0001, u64::MAX] { + assert_eq!( + f64_term(f64::from_bits(bits)), + [0xff, 0xf8, 0, 0, 0, 0, 0, 0] + ); + } + assert_eq!(f32_term(1.5), [0xbf, 0xf8, 0, 0, 0, 0, 0, 0]); + assert_eq!( + f32_term(-1.5), + [0x40, 0x07, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff] + ); + assert_eq!(f32_term(f32::INFINITY), [0xff, 0xf0, 0, 0, 0, 0, 0, 0]); + assert_eq!( + f32_term(f32::NEG_INFINITY), + [0, 0x0f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff] + ); + let ascending = [f64::NEG_INFINITY, -1.0, 0.0, 1.0, f64::INFINITY, f64::NAN]; + for pair in ascending.windows(2) { + assert!(f64_term(pair[0]) < f64_term(pair[1])); + } +} + +#[quickcheck] +fn f64_order_agrees_with_numeric_order(a: f64, b: f64) -> bool { + a.is_nan() + || b.is_nan() + || f64_term(a).cmp(&f64_term(b)) == a.partial_cmp(&b).expect("valid test value") +} + +#[test] +fn float_widths_share_one_domain_for_equal_numbers() { + for value in [ + 0.0f32, + 1.5, + -0.25, + 16_777_216.0, + f32::MAX, + f32::MIN_POSITIVE, + ] { + assert_eq!(f32_term(value), f64_term(value.into())); + } + // 0.1 is a different number in each width, so the terms differ. + assert_ne!(f32_term(0.1), f64_term(0.1)); +} + +fn widen_matches_hardware(bits: u32) -> bool { + let value = f32::from_bits(bits); + let (ours, hardware) = (widen_f32(value), f64::from(value)); + // NaN payload bits are folded later; only NaN-ness must agree for them. + if value.is_nan() { + ours.is_nan() && ours.is_sign_negative() == hardware.is_sign_negative() + } else { + ours.to_bits() == hardware.to_bits() + } +} + +#[test] +fn widening_matches_hardware_at_every_exponent_and_subnormal_bit() { + for sign in [0, 1u32 << 31] { + for exponent in 0..=0xffu32 { + for mantissa in [0, 1, 0x40_0000, 0x7f_ffff, 0x2a_aaaa] { + let bits = sign | (exponent << 23) | mantissa; + assert!(widen_matches_hardware(bits), "{bits:#010x}"); + } + } + for shift in 0..23 { + let bits = sign | 1 << shift; + assert!(widen_matches_hardware(bits), "{bits:#010x}"); + assert!( + widen_matches_hardware(bits | ((1 << shift) - 1)), + "{bits:#010x}" + ); + } + } +} + +#[quickcheck] +fn widening_matches_hardware_conversion(bits: u32) -> bool { + widen_matches_hardware(bits) +} + +/// Every f32 bit pattern; slow in debug builds, so run on demand with +/// `cargo test --release -p vitaminc-normalize -- --ignored`. +#[test] +#[ignore] +fn widening_matches_hardware_for_every_f32() { + assert!((0..=u32::MAX).all(widen_matches_hardware)); +} + +#[quickcheck] +fn f64_canonicalisation_is_idempotent(bits: u64) -> bool { + let value = canonical_f64(f64::from_bits(bits)); + canonical_f64(value).to_bits() == value.to_bits() +} + +/// Whether `bytes` holds exactly `expected`. The encoding is compared +/// through a borrow, so no copy of it is made outside its `Protected`, and +/// there is nothing left unwiped. Only the answer, which is not secret, +/// is taken out. +fn holds(bytes: &Protected<Vec<u8>>, expected: &[u8]) -> bool { + bytes.risky_ref().as_slice() == expected +} + +mod given_any_canonical_f64 { + use super::*; + + #[quickcheck] + fn returns_the_bytes_orderable_bytes_gives(bits: u64) -> bool { + let value = canonical_f64(f64::from_bits(bits)); + holds(&orderable_f64(value), &value.to_orderable_bytes()) + } +} + +#[test] +fn timestamps_one_past_the_wire_range_are_invalid() { + use vitaminc_aead::plaintext::kinds::{MAX_TIMESTAMP_NANOS, MIN_TIMESTAMP_NANOS}; + let ns = Logical::Timestamp(TimeUnit::Nanos); + assert!(timestamp(TimeUnit::Nanos, Int::I128(MAX_TIMESTAMP_NANOS)).is_some()); + assert!(timestamp(TimeUnit::Nanos, Int::I128(MIN_TIMESTAMP_NANOS)).is_some()); + for nanos in [MAX_TIMESTAMP_NANOS + 1, MIN_TIMESTAMP_NANOS - 1] { + assert!(timestamp(TimeUnit::Nanos, Int::I128(nanos)).is_none()); + assert_eq!( + normalize(Some(ns), Physical::Int(Int::I128(nanos))).expect_err("invalid"), + NormalizeError::Invalid + ); + } +} + +/// Whether `bytes` holds exactly `len` bytes in a buffer with room for +/// exactly `len`, checked inside the protected value with `zip_ref` so +/// the encoding never leaves its wrapper. Only the answer, which is not +/// secret, is taken out. +fn fills_exactly(bytes: &Protected<Vec<u8>>, len: usize) -> bool { + Protected::new(len) + .zip_ref(bytes, |len, bytes: &Vec<u8>| { + bytes.len() == len && bytes.capacity() == len + }) + .risky_unwrap() +} + +/// A `Vec` that grows frees its old buffer without wiping it, and spare +/// capacity is a sign the buffer was not made at its final size. So every +/// fixed-width encoder must return a buffer whose length is its capacity. +mod given_a_fixed_width_encoder { + use super::*; + + #[test] + fn returns_a_buffer_with_no_spare_capacity() { + for value in [Int::I8(-1), Int::U128(u128::MAX), Int::I128(i128::MIN)] { + assert!(fills_exactly(&integer(value), 17), "integer {value:?}"); + } + for value in [Float::F32(-1.5), Float::F64(f64::MAX), Float::F64(f64::NAN)] { + assert!(fills_exactly(&float(value), 8), "float {value:?}"); + } + for days in [Int::I32(-1), Int::I32(0), Int::I32(20_000)] { + let bytes = date(days).expect("in range"); + assert!(fills_exactly(&bytes, 4), "date {days:?}"); + } + for count in [Int::I64(-1), Int::I64(1_700_000_000_123)] { + let bytes = timestamp(TimeUnit::Millis, count).expect("in range"); + assert!(fills_exactly(&bytes, 12), "timestamp {count:?}"); + } + for (scale, mantissa) in [(0, Int::I64(0)), (2, Int::I64(-12_345)), (28, Int::I128(1))] { + let bytes = decimal(scale, mantissa).expect("in range"); + assert!( + fills_exactly(&bytes, 14), + "decimal {mantissa:?} at scale {scale}" + ); + } + } +} + +#[test] +fn debug_output_does_not_show_the_normalized_bytes() { + let n = normalize(None, Physical::Text("secret")).expect("text"); + let v = format!("{n:?}"); + assert!(v.contains(domain::TEXT), "{v}"); + assert!(v.contains("***"), "{v}"); + // "secret" as a `Vec<u8>` would print as [115, 101, 99, ...]. + assert!(!v.contains("secret") && !v.contains("115, 101, 99"), "{v}"); +} + +/// The widths an `i16` fits, each holding `n`. +fn every_width(n: i16) -> Vec<Int> { + let mut widths = vec![ + Int::I16(n), + Int::I32(n.into()), + Int::I64(n.into()), + Int::I128(n.into()), + ]; + if let Ok(v) = i8::try_from(n) { + widths.push(Int::I8(v)); + } + if let Ok(v) = u16::try_from(n) { + widths.extend([ + Int::U16(v), + Int::U32(v.into()), + Int::U64(v.into()), + Int::U128(v.into()), + ]); + } + if let Ok(v) = u8::try_from(n) { + widths.push(Int::U8(v)); + } + widths +} + +/// A logical term is over the number, not the width that carried it, as +/// the plain integer term is. +#[quickcheck] +fn a_logical_term_is_the_same_at_every_integer_width(n: i16) -> bool { + [ + Logical::Date, + Logical::Timestamp(TimeUnit::Seconds), + Logical::Decimal { scale: 2 }, + ] + .into_iter() + .all(|ty| { + let widths = every_width(n); + let first = int(Some(ty), widths[0]); + widths.iter().all(|&w| int(Some(ty), w) == first) + }) +} + +/// The 96-bit check is the only one between a direct caller and the +/// encoder, which would otherwise drop a mantissa's top bits and give it +/// the term of another value. +#[test] +fn decimal_refuses_a_mantissa_outside_96_bits_by_itself() { + let limit = 1i128 << 96; + assert!( + decimal(0, Int::I128(limit - 1)).is_some(), + "the largest mantissa" + ); + assert!( + decimal(0, Int::I128(1 - limit)).is_some(), + "the smallest mantissa" + ); + assert!( + decimal(0, Int::I128(limit)).is_none(), + "one past the largest" + ); + assert!( + decimal(0, Int::I128(-limit)).is_none(), + "one past the smallest" + ); + assert!( + decimal(5, Int::I128((1i128 << 104) + 10i128.pow(28))).is_none(), + "above 104 bits this would take the term of 10^23" + ); + assert!(decimal(0, Int::I128(i128::MAX)).is_none()); + assert!(decimal(0, Int::I128(i128::MIN)).is_none()); +} + +/// A null is one byte under a domain of its own, so every null in a space +/// ties with every other and with nothing else. +#[test] +fn a_null_is_one_zero_byte_under_the_null_domain() { + let null = normalize(None, Physical::Null).expect("a null has a term"); + assert_eq!(null.domain, domain::NULL, "a null has its own domain"); + assert_eq!( + null.domain, "vitaminc/prf/value/null/v1", + "the null label is frozen" + ); + assert_eq!(null.bytes.risky_ref(), &[0x00], "a null is the byte 0x00"); + assert_eq!(super::null().risky_ref(), &[0x00], "the encoder agrees"); + // No other domain's encoding is one zero byte under the null label. + let zero = normalize(None, Physical::Bytes(&[0x00])).expect("bytes"); + assert_ne!( + zero.domain, null.domain, + "the byte 0x00 as bytes is not a null" + ); +} diff --git a/packages/vitaminc-normalize/src/terms.rs b/packages/vitaminc-normalize/src/terms.rs new file mode 100644 index 000000000..4fd89de50 --- /dev/null +++ b/packages/vitaminc-normalize/src/terms.rs @@ -0,0 +1,788 @@ +//! Equality terms as a sink, and encryption that produces them in the +//! same walk. +//! +//! [`Terms`] is a [`Sink`] that produces one [`Term`] per scalar that has +//! an equality domain. It runs beside encryption as `Tee(EncryptSink, +//! Terms)`, so a caller holds every term before any cipher is called and, +//! with an async cipher, before the first await. [`terms`] runs it alone, +//! and then it refuses what encryption would refuse. +//! +//! The sink does the walking and the [`Normalize`] it is given does the +//! encoding, so an index of another kind (an order index, whose bytes +//! differ from an equality term's) collects its terms through the same +//! sink with a normalizer of its own, through [`Terms::by`] and +//! [`terms_by`]. + +use core::marker::PhantomData; + +use vitaminc_aead::plaintext::{Error, Path, Step}; +use vitaminc_aead::seal::Cipher; +use vitaminc_aead::shape::{self, Locate, MapRules, SeqRules, Settle}; +use vitaminc_aead::{ + Encrypt, EncryptError, EncryptRef, EncryptSink, FixedType, IntoAad, Logical, MapSink, Node, + Physical, Plaintext, Refusal, SeqSink, Sink, SourceError, Tee, +}; + +use vitaminc_protected::OpaqueDebug; + +use crate::scalar::{normalize, NormalizeError, Normalized}; + +/// How [`Terms`] turns one scalar into a term. +/// +/// [`Equality`] is the normalizer this crate is about. An index of another +/// kind supplies its own, with a term type of its own (an order index +/// seals its term so only a scheme can read it) and the same outcome +/// contract: a scalar whose kind has no term under this index (a boolean, +/// or a null where the index gives nulls none) returns +/// [`NormalizeError::NoDomain`], and [`Terms`] skips it +/// when it has no logical type; a scalar whose logical type has no term +/// returns the same error and stops the walk; any other error stops the +/// walk too. +/// +/// A normalizer is copied into every child sink of a walk, so it is +/// `Copy`: it carries settings, such as the type an index declares, but +/// no state that a walk changes. +pub trait Normalize: Copy { + /// What one scalar becomes. + type Term; + + /// The kind of index the terms are for, as a refusal names it: + /// `"equality"` for [`Equality`], so a scalar it cannot normalize is + /// reported as having no equality term. + const INDEX: &'static str; + + /// The term for one scalar, or why it has none. + fn normalize( + &self, + ty: Option<Logical>, + value: Physical<'_>, + ) -> Result<Self::Term, NormalizeError>; +} + +/// The equality normalizer: [`normalize`]. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct Equality; + +impl Normalize for Equality { + type Term = Normalized; + + const INDEX: &'static str = "equality"; + + fn normalize( + &self, + ty: Option<Logical>, + value: Physical<'_>, + ) -> Result<Normalized, NormalizeError> { + normalize(ty, value) + } +} + +/// One term: where the scalar sits in the value, and what the normalizer +/// made of it. An equality term, a [`Normalized`], unless [`Terms::by`] +/// was given another normalizer. +/// +/// `Debug` shows the path's shape, with its map keys masked as [`Step`] +/// masks them, and masks the term. +#[derive(OpaqueDebug)] +pub struct Term<T = Normalized> { + /// The path from the root, empty for a scalar at the root. + #[non_sensitive] + pub path: Path, + /// The term itself: for equality, the frozen domain label and the + /// normalized bytes. + pub normalized: T, +} + +/// A scalar [`Terms`] refused: why, and where in the value. +/// +/// This is the type to downcast a refusal to. Its +/// [`source`](core::error::Error::source) is the [`NormalizeError`], so a +/// reporter that walks the error chain reaches the reason too. +/// +/// `Display` shows only the reason, because the path can hold map keys and +/// map keys can be user data. `Debug` shows the reason and the path's +/// shape, with every key masked. Read the path with +/// [`path`](TermError::path). +#[derive(Clone, OpaqueDebug, thiserror::Error)] +#[error("no {index} term: {error}")] +pub struct TermError { + #[non_sensitive] + index: &'static str, + #[non_sensitive] + path: Path, + #[non_sensitive] + #[source] + error: NormalizeError, +} + +impl TermError { + /// The kind of index the scalar has no term for: the normalizer's + /// [`Normalize::INDEX`]. + pub fn index(&self) -> &'static str { + self.index + } + + /// Where the refused scalar sits, from the root. + pub fn path(&self) -> &Path { + &self.path + } + + /// Why the scalar has no term. + pub fn error(&self) -> NormalizeError { + self.error + } +} + +/// What [`terms`] fails with: what [`Terms`] refuses, or the source's own +/// failure. +/// +/// A source reports through [`Error::source`] whichever sink it feeds, so +/// every failure arrives as a [`SourceError`]. [`term`](TermsError::term) +/// recovers a [`TermError`] from it, the same downcast a caller makes on +/// [`EncryptError::Source`] when `Terms` runs beside encryption, and +/// [`refusal`](TermsError::refusal) a value refused for its shape, which +/// encryption reports as [`EncryptError::Shape`]. +/// [`source_error`](TermsError::source_error) is the error as it arrived. +#[derive(Debug, thiserror::Error)] +#[error(transparent)] +pub struct TermsError(SourceError); + +impl TermsError { + /// The scalar [`Terms`] refused, or `None` if the source failed on its + /// own or the value was refused for its shape. + pub fn term(&self) -> Option<&TermError> { + self.0.inner().downcast_ref() + } + + /// The value refused for its shape, as encryption would refuse it, or + /// `None` if it was refused for another reason. + pub fn refusal(&self) -> Option<&Refusal> { + self.0.inner().downcast_ref() + } + + /// The failure as the walk reported it: what [`Terms`] refused, or the + /// source's own error. + pub fn source_error(&self) -> &SourceError { + &self.0 + } +} + +impl Error for TermsError { + fn source(error: SourceError) -> Self { + Self(error) + } +} + +/// A sink that collects one [`Term`] per scalar with an equality domain, +/// in walk order. +/// +/// Generic over its error type so it adopts its [`Tee`] partner's. To +/// collect terms without encrypting, call [`terms`], whose error type is +/// [`TermsError`]. Generic too over the [`Normalize`] that encodes each +/// scalar, [`Equality`] unless [`by`](Terms::by) is given another, so an +/// index of another kind collects its terms through this same walk. +/// +/// Under [`Equality`] every null has a term, typed or plain, at the +/// null's path and under [`domain::NULL`](crate::domain::NULL), so an +/// absent value is indexed like any other. A layer that must keep a SQL +/// `NULL` for some column drops that term; its domain says it is a null. +/// +/// A scalar whose *kind* has no domain (a boolean, an `undefined`, or a +/// null under a normalizer that gives nulls none) produces no term and +/// does not stop the walk: an unindexable value is an ordinary thing to +/// find in a document, and the caller has the paths to see which fields +/// were indexed. A scalar whose *logical +/// type* has no domain ([`Logical::Unknown`], or a type this crate does +/// not know) stops the walk instead: it came from a newer client and +/// means something, and encrypting it with no term and no error would +/// leave an index silently incomplete. +/// +/// Passthrough subtrees travel in the clear and get no terms. +/// +/// # Only what can be encrypted +/// +/// A `Terms` refuses every value [`EncryptSink`] refuses, for the same +/// [`Unencryptable`](vitaminc_aead::Unencryptable) reason and at the same path, so an index never holds +/// terms for a value that cannot be stored. It keeps the +/// [`shape`] rules through the code `EncryptSink` +/// keeps them with: nothing deeper than the transport's depth limit, every +/// scalar valid for its logical type, every passthrough subtree framable, +/// no map key given twice, no child sink dropped without a value, and +/// something sealed in every container with children. The last rule is +/// about sealing, and this walk seals nothing, but a value that breaks it +/// cannot be encrypted, so it is refused here too. A passthrough is framed +/// as encryption frames it, to check that it can be, and the frame is +/// dropped. +/// +/// So [`terms`] accepts a value exactly when [`encrypt_with_terms`] does +/// with a cipher that does not fail, and refuses it for the same reason at +/// the same path. [`plan_with_terms`], and the encrypting functions built +/// on it, pair `EncryptSink` with a `Terms` that leaves the shape rules to +/// it, so they are kept once. +/// +/// # Errors +/// +/// The walk stops with `E::source(SourceError::new(error))`, where `error` +/// is one of: +/// +/// - a [`Refusal`]: the value breaks a shape rule, as above. A scalar not +/// valid for its logical type is refused this way, as +/// [`Unencryptable::InvalidValue`](vitaminc_aead::Unencryptable::InvalidValue), before it is normalized. Through +/// [`terms`] it is [`TermsError::refusal`]. Beside `EncryptSink`, which +/// refuses it first, it is [`EncryptError::Shape`]. +/// - a [`TermError`] holding the scalar's path and the +/// [`NormalizeError`]: the scalar's logical type has no domain +/// (`NoDomain`), or its text holds a code point unassigned in Unicode 16 +/// (`UnassignedCodePoint`). Beside [`EncryptSink`] that arrives as +/// [`EncryptError::Source`], and +/// `source.inner().downcast_ref::<TermError>()` recovers it. Alone, +/// through [`terms`], it is [`TermsError::term`]. Either way the +/// [`NormalizeError`] is on the `source()` chain. +/// +/// # Cost +/// +/// A path costs nothing until a term is pushed or a refusal is built. Each +/// child sink holds a link to its container's place and its own index, or +/// the position of its key in one buffer of the keys on the path being +/// walked, which the whole walk shares and reuses. So the walk allocates +/// that buffer, as long as the keys on the longest path, and otherwise +/// only what each pushed term needs. +/// +/// The shape rules cost what they cost encryption: a map keeps one copy +/// of each of its keys until it ends, which is what checking for a repeat +/// exactly takes, and a passthrough is framed. Beside `EncryptSink`, +/// through [`plan_with_terms`], none of that is paid twice. A caller that +/// tees `Terms::new` beside `EncryptSink` itself has both keep the rules. +pub struct Terms<'t, E, N: Normalize = Equality> { + out: &'t mut Vec<Term<N::Term>>, + keys: Keys<'t>, + at: Place<'t>, + /// `None` beside an [`EncryptSink`] that keeps the rules itself. + rules: Option<NodeRules<'t>>, + by: N, + _error: PhantomData<E>, +} + +/// The shape rules one node keeps: how deep it sits, and its hold on its +/// container's rules, which it settles when it ends. The root has no +/// container. +struct NodeRules<'t> { + depth: usize, + settle: Option<Settle<'t>>, +} + +impl NodeRules<'_> { + /// The node put a sealed node: a scalar, or a container. + fn sealed(self) { + if let Some(settle) = self.settle { + settle.sealed(); + } + } +} + +/// A container's shape rules, `R`, with the rules of the node it is. +struct Held<'t, R> { + node: NodeRules<'t>, + rules: R, +} + +/// The map keys on the path being walked, end to end. The root owns the +/// buffer and every sink below it borrows it. A container truncates it +/// back to where its own keys begin before each child, so it holds only +/// the keys of the current path. +enum Keys<'t> { + Own(String), + Lent(&'t mut String), +} + +impl Keys<'_> { + fn get(&mut self) -> &mut String { + match self { + Keys::Own(keys) => keys, + Keys::Lent(keys) => keys, + } + } + + fn as_str(&self) -> &str { + match self { + Keys::Own(keys) => keys, + Keys::Lent(keys) => keys, + } + } +} + +/// Where a node sits: a link to its container's place and its own step. +/// A key is named by its position in [`Keys`]. +#[derive(Clone, Copy)] +enum Place<'t> { + Root, + Element { + parent: &'t Place<'t>, + index: usize, + }, + Entry { + parent: &'t Place<'t>, + key: (usize, usize), + }, +} + +impl Place<'_> { + /// Append the steps from the root to this node, reading keys from + /// `keys`. + fn locate(&self, keys: &str, steps: &mut Vec<Step>) { + match *self { + Place::Root => {} + Place::Element { parent, index } => { + parent.locate(keys, steps); + steps.push(Step::Index(index)); + } + Place::Entry { + parent, + key: (start, end), + } => { + parent.locate(keys, steps); + steps.extend(keys.get(start..end).map(|key| Step::Key(key.to_owned()))); + } + } + } + + /// The path from the root to this node. + fn path(&self, keys: &str) -> Path { + let mut steps = Vec::new(); + self.locate(keys, &mut steps); + Path::new(steps) + } +} + +/// A place with the keys it names: what the shape rules locate a refusal +/// with. +struct At<'a> { + place: &'a Place<'a>, + keys: &'a str, +} + +impl Locate for At<'_> { + fn locate(&self, steps: &mut Vec<Step>) { + self.place.locate(self.keys, steps); + } +} + +/// A shape refusal, reported the only way a sink generic over its error +/// can report anything. +fn refused<E: Error>(refusal: Refusal) -> E { + E::source(SourceError::new(refusal)) +} + +impl<'t, E> Terms<'t, E> { + /// A sink that appends equality terms to `out` and keeps the shape + /// rules itself. + pub fn new(out: &'t mut Vec<Term>) -> Self { + Self::by(Equality, out) + } + + /// A sink that appends to `out` and leaves the shape rules to the + /// [`EncryptSink`] it is teed beside, which refuses first. + fn beside_encryption(out: &'t mut Vec<Term>) -> Self { + Self { + rules: None, + ..Self::new(out) + } + } +} + +impl<'t, E, N: Normalize> Terms<'t, E, N> { + /// A sink that appends the terms `by` makes to `out` and keeps the + /// shape rules itself. + /// + /// The normalizer is copied into every child sink, which is why + /// [`Normalize`] requires `Copy`. + pub fn by(by: N, out: &'t mut Vec<Term<N::Term>>) -> Self { + Self { + out, + keys: Keys::Own(String::new()), + at: Place::Root, + rules: Some(NodeRules { + depth: 0, + settle: None, + }), + by, + _error: PhantomData, + } + } + + fn at(&self) -> At<'_> { + At { + place: &self.at, + keys: self.keys.as_str(), + } + } +} + +impl<'t, E: Error, N: Normalize> Sink for Terms<'t, E, N> { + type Ok = (); + type Error = E; + type Seq = TermsSeq<'t, E, N>; + type Map = TermsMap<'t, E, N>; + + fn scalar(self, ty: Option<Logical>, value: Physical<'_>) -> Result<(), E> { + if let Some(rules) = &self.rules { + shape::scalar(rules.depth, ty, &value, &self.at()).map_err(refused)?; + } + match self.by.normalize(ty, value) { + Ok(normalized) => { + let path = self.at.path(self.keys.as_str()); + self.out.push(Term { path, normalized }); + } + // No domain for the kind: nothing to index, carry on. No domain + // for a logical type: refuse, see the type's docs. + Err(NormalizeError::NoDomain) if matches!(ty, None | Some(Logical::Undefined)) => {} + Err(error) => { + return Err(E::source(SourceError::new(TermError { + index: N::INDEX, + path: self.at.path(self.keys.as_str()), + error, + }))) + } + } + if let Some(rules) = self.rules { + rules.sealed(); + } + Ok(()) + } + + /// Indexed as a plain null. Equality has no width, so the type adds + /// nothing: under [`Equality`] a typed null is the same term as a + /// plain one. + fn typed_null(self, _: FixedType) -> Result<(), E> { + self.scalar(None, Physical::Null) + } + + fn seq(self, _: Option<usize>) -> Result<Self::Seq, E> { + let rules = match self.rules { + Some(node) => { + shape::container( + node.depth, + &At { + place: &self.at, + keys: self.keys.as_str(), + }, + ) + .map_err(refused)?; + Some(Held { + node, + rules: SeqRules::new(), + }) + } + None => None, + }; + Ok(TermsSeq { + mark: self.keys.as_str().len(), + out: self.out, + keys: self.keys, + at: self.at, + next: 0, + rules, + by: self.by, + _error: PhantomData, + }) + } + + fn map(self, _: Option<usize>) -> Result<Self::Map, E> { + let rules = match self.rules { + Some(node) => { + shape::container( + node.depth, + &At { + place: &self.at, + keys: self.keys.as_str(), + }, + ) + .map_err(refused)?; + Some(Held { + node, + rules: MapRules::new(), + }) + } + None => None, + }; + Ok(TermsMap { + mark: self.keys.as_str().len(), + out: self.out, + keys: self.keys, + at: self.at, + rules, + by: self.by, + _error: PhantomData, + }) + } + + /// No terms. Keeping the shape rules, the subtree is framed, as + /// encryption frames it, and the frame dropped. + fn passthrough<P: ?Sized + EncryptRef>(self, value: &P) -> Result<(), E> { + if let Some(rules) = self.rules { + let at = At { + place: &self.at, + keys: self.keys.as_str(), + }; + shape::frame_passthrough(value.lend(), rules.depth, &at, refused)?; + if let Some(settle) = rules.settle { + settle.passthrough(); + } + } + Ok(()) + } +} + +/// The sequence side of [`Terms`]: each element's path is the sequence's +/// plus its index. +pub struct TermsSeq<'t, E, N: Normalize = Equality> { + out: &'t mut Vec<Term<N::Term>>, + keys: Keys<'t>, + /// Where this sequence's own keys would begin: the length of `keys` + /// at its start. + mark: usize, + at: Place<'t>, + next: usize, + rules: Option<Held<'t, SeqRules>>, + by: N, + _error: PhantomData<E>, +} + +impl<E: Error, N: Normalize> SeqSink for TermsSeq<'_, E, N> { + type Ok = (); + type Error = E; + type Element<'s> + = Terms<'s, E, N> + where + Self: 's; + + fn element(&mut self) -> Result<Terms<'_, E, N>, E> { + let TermsSeq { + out, + keys, + mark, + at, + next, + rules, + by, + .. + } = self; + let keys = keys.get(); + let rules = match rules { + Some(held) => Some(NodeRules { + depth: held.node.depth + 1, + settle: Some( + held.rules + .element(&At { place: at, keys }) + .map_err(refused)?, + ), + }), + None => None, + }; + keys.truncate(*mark); + let index = *next; + *next += 1; + Ok(Terms { + out, + keys: Keys::Lent(keys), + at: Place::Element { parent: at, index }, + rules, + by: *by, + _error: PhantomData, + }) + } + + fn end(self) -> Result<(), E> { + if let Some(held) = self.rules { + let at = At { + place: &self.at, + keys: self.keys.as_str(), + }; + held.rules.end(&at).map_err(refused)?; + held.node.sealed(); + } + Ok(()) + } +} + +/// The map side of [`Terms`]: each entry's path is the map's plus its +/// key. +pub struct TermsMap<'t, E, N: Normalize = Equality> { + out: &'t mut Vec<Term<N::Term>>, + keys: Keys<'t>, + /// Where this map's keys begin in `keys`: its length at the map's + /// start. Each entry's key replaces the last one there. + mark: usize, + at: Place<'t>, + rules: Option<Held<'t, MapRules>>, + by: N, + _error: PhantomData<E>, +} + +impl<E: Error, N: Normalize> MapSink for TermsMap<'_, E, N> { + type Ok = (); + type Error = E; + type Entry<'s> + = Terms<'s, E, N> + where + Self: 's; + + fn entry(&mut self, key: &str) -> Result<Terms<'_, E, N>, E> { + let TermsMap { + out, + keys, + mark, + at, + rules, + by, + .. + } = self; + let keys = keys.get(); + let rules = match rules { + Some(held) => Some(NodeRules { + depth: held.node.depth + 1, + settle: Some( + held.rules + .entry(key, &At { place: at, keys }) + .map_err(refused)?, + ), + }), + None => None, + }; + keys.truncate(*mark); + keys.push_str(key); + let key = (*mark, keys.len()); + Ok(Terms { + out, + keys: Keys::Lent(keys), + at: Place::Entry { parent: at, key }, + rules, + by: *by, + _error: PhantomData, + }) + } + + fn end(self) -> Result<(), E> { + if let Some(held) = self.rules { + let at = At { + place: &self.at, + keys: self.keys.as_str(), + }; + held.rules.end(&at).map_err(refused)?; + held.node.sealed(); + } + Ok(()) + } +} + +/// Every equality term of `value`, in walk order, without encrypting it. +/// +/// It refuses every value encryption refuses, for the same reason at the +/// same path (see [`Terms`]), so it never returns terms for a value that +/// cannot be stored. +/// +/// # Examples +/// +/// ``` +/// use std::collections::BTreeMap; +/// use vitaminc_normalize::{domain, terms, NormalizeError, Step}; +/// +/// let mut user = BTreeMap::new(); +/// user.insert("name", "Ada"); +/// let found = terms(&user)?; +/// assert_eq!(found[0].path.steps(), [Step::Key("name".into())]); +/// assert_eq!(found[0].normalized.domain, domain::TEXT); +/// +/// // U+0378 is unassigned in Unicode 16, so the name has no term. +/// user.insert("name", "\u{378}"); +/// let refused = terms(&user).unwrap_err(); +/// let term = refused.term().expect("refused by Terms"); +/// assert_eq!(term.error(), NormalizeError::UnassignedCodePoint); +/// assert_eq!(term.path().steps(), [Step::Key("name".into())]); +/// // The message names neither the field nor its value. +/// assert_eq!( +/// refused.to_string(), +/// "no equality term: text contains a code point unassigned in Unicode 16" +/// ); +/// +/// // A uuid of three bytes cannot be encrypted, so it has no term either: +/// // `terms` refuses it as encryption does. +/// use vitaminc_aead::{Logical, Physical, Raw, Unencryptable}; +/// let id = Raw(Some(Logical::Uuid), Physical::Bytes(&[0; 3])); +/// let refused = terms(id).unwrap_err(); +/// let refusal = refused.refusal().expect("refused for its shape"); +/// assert_eq!(refusal.reason(), Unencryptable::InvalidValue); +/// # Ok::<(), vitaminc_normalize::TermsError>(()) +/// ``` +/// +/// # Errors +/// +/// [`TermsError`]: what [`Terms`] refuses, a value encryption would refuse +/// included, or the source's own failure. +pub fn terms<P: Encrypt>(value: P) -> Result<Vec<Term>, TermsError> { + terms_by(Equality, value) +} + +/// Every term of `value` under the normalizer `by`, in walk order, without +/// encrypting it: [`terms`] for an index of another kind. +/// +/// It refuses what [`terms`] refuses for the value's shape, and what `by` +/// refuses for a scalar, the way [`Terms`] describes. +/// +/// # Errors +/// +/// [`TermsError`]: what [`Terms`] refuses, a value encryption would refuse +/// included, or the source's own failure. +pub fn terms_by<N, P>(by: N, value: P) -> Result<Vec<Term<N::Term>>, TermsError> +where + N: Normalize, + P: Encrypt, +{ + let mut out = Vec::new(); + value.visit(Terms::by(by, &mut out))?; + Ok(out) +} + +/// A value's tree and the terms of the value, in walk order. +pub type WithTerms<L> = (Node<L>, Vec<Term>); + +/// Walk `value` into the encrypting sink and the terms sink at once, +/// without sealing: the value staged for encryption, and every term. +/// +/// # Errors +/// +/// Everything [`EncryptSink`] refuses, plus what [`Terms`] refuses, which +/// arrives as [`EncryptError::Source`] carrying a [`TermError`]. +pub fn plan_with_terms<P: Encrypt, E>(value: P) -> Result<WithTerms<Plaintext>, EncryptError<E>> { + let mut terms = Vec::new(); + let (planned, ()) = value.visit(Tee( + EncryptSink::new(), + Terms::beside_encryption(&mut terms), + ))?; + Ok((planned, terms)) +} + +/// Encrypt `value` and produce its equality terms in the same walk. +/// +/// # Errors +/// +/// As [`plan_with_terms`], then [`EncryptError::Cipher`] if the cipher +/// refuses a leaf. +pub fn encrypt_with_terms<'a, P, C, A>( + value: P, + cipher: &C, + aad: A, +) -> Result<WithTerms<C::Leaf>, EncryptError<C::Error>> +where + P: Encrypt, + C: Cipher, + A: IntoAad<'a>, +{ + let (planned, terms) = plan_with_terms(value)?; + let sealed = planned + .seal(&aad.into_aad(), |plaintext, aad| { + cipher.seal(plaintext, aad) + }) + .map_err(EncryptError::Cipher)?; + Ok((sealed, terms)) +} diff --git a/packages/vitaminc-normalize/tests/agreement.rs b/packages/vitaminc-normalize/tests/agreement.rs new file mode 100644 index 000000000..d3ac4ea28 --- /dev/null +++ b/packages/vitaminc-normalize/tests/agreement.rs @@ -0,0 +1,393 @@ +//! `terms` and `encrypt_with_terms` agree on every value: each accepts +//! what the other accepts, with the same terms, and refuses what the other +//! refuses, for the same reason at the same path. One case per rule +//! encryption keeps, and per refusal of `Terms`'s own. + +use std::collections::BTreeMap; + +use vitaminc_aead::frame::MAX_DEPTH; +use vitaminc_aead::plaintext::render; +use vitaminc_aead::seal::Cipher; +use vitaminc_aead::{ + Context, Encrypt, EncryptError, EncryptRef, Logical, MapSink, Physical, Raw, SeqSink, Sink, + SourceError, Unencryptable, +}; +use vitaminc_normalize::{encrypt_with_terms, terms, NormalizeError, Term, TermError}; +use vitaminc_protected::{Controlled, Protected}; + +/// Seals in the clear: these tests are about the walk, not the cipher. +struct Clear; + +impl Cipher for Clear { + type Leaf = Vec<u8>; + type Error = &'static str; + + fn seal( + &self, + plaintext: Protected<Vec<u8>>, + _: &Context<'_>, + ) -> Result<Vec<u8>, &'static str> { + Ok(plaintext.risky_unwrap()) + } + + fn open(&self, leaf: Vec<u8>, _: &Context<'_>) -> Result<Protected<Vec<u8>>, &'static str> { + Ok(Protected::new(leaf)) + } +} + +/// How a walk ended, with every path written out. +#[derive(Debug, PartialEq)] +enum Outcome { + Terms(Vec<String>), + Shape(Unencryptable, String), + Term(NormalizeError, String), + Source(String), +} + +use Outcome::{Shape, Source, Term as NoTerm, Terms}; + +fn paths(found: &[Term]) -> Outcome { + Terms(found.iter().map(|t| render(&t.path)).collect()) +} + +fn sourced(source: &SourceError) -> Outcome { + match source.inner().downcast_ref::<TermError>() { + Some(term) => NoTerm(term.error(), render(term.path())), + None => Source(source.to_string()), + } +} + +fn alone<P: Encrypt>(value: P) -> Outcome { + match terms(value) { + Ok(found) => paths(&found), + Err(err) => match err.refusal() { + Some(refusal) => Shape(refusal.reason(), render(refusal.path())), + None => sourced(err.source_error()), + }, + } +} + +fn encrypting<P: Encrypt>(value: P) -> Outcome { + match encrypt_with_terms(value, &Clear, "ctx") { + Ok((_, found)) => paths(&found), + Err(EncryptError::Shape(refusal)) => Shape(refusal.reason(), render(refusal.path())), + Err(EncryptError::Source(source)) => sourced(&source), + Err(other) => panic!("{other:?}"), + } +} + +/// `value()` ends the same way both walks, and that way is `expected`. +#[track_caller] +fn agree<P: Encrypt>(value: impl Fn() -> P, expected: Outcome) { + assert_eq!(encrypting(value()), expected, "encrypt_with_terms"); + assert_eq!(alone(value()), expected, "terms"); +} + +fn shape(reason: Unencryptable, at: &str) -> Outcome { + Shape(reason, at.to_owned()) +} + +/// A document whose `users` entry is a sequence of two values, the second +/// of them `bad`, beside a well-formed `id`, so every refusal below the +/// root has a path with a key and an index in it. +#[derive(Clone)] +struct Users<P>(P); + +impl<P: Encrypt> Encrypt for Users<P> { + fn visit<S: Sink>(self, sink: S) -> Result<S::Ok, S::Error> { + let mut map = sink.map(Some(2))?; + 1u32.visit(map.entry("id")?)?; + let mut users = map.entry("users")?.seq(Some(2))?; + "ada".visit(users.element()?)?; + self.0.visit(users.element()?)?; + users.end()?; + map.end() + } +} + +/// A map that gives `k` twice. +#[derive(Clone)] +struct Dup; + +impl Encrypt for Dup { + fn visit<S: Sink>(self, sink: S) -> Result<S::Ok, S::Error> { + let mut map = sink.map(None)?; + "one".visit(map.entry("k")?)?; + "two".visit(map.entry("k")?)?; + map.end() + } +} + +/// A container with one passthrough in it and nothing sealed. +#[derive(Clone)] +struct OnlyPass { + map: bool, +} + +impl Encrypt for OnlyPass { + fn visit<S: Sink>(self, sink: S) -> Result<S::Ok, S::Error> { + if self.map { + let mut map = sink.map(Some(1))?; + map.entry("note")?.passthrough(&"public")?; + map.end() + } else { + let mut seq = sink.seq(Some(1))?; + seq.element()?.passthrough(&"public")?; + seq.end() + } + } +} + +/// A container whose source takes a child sink and drops it unused. +#[derive(Clone)] +struct DropsAChild { + map: bool, +} + +impl Encrypt for DropsAChild { + fn visit<S: Sink>(self, sink: S) -> Result<S::Ok, S::Error> { + if self.map { + let mut map = sink.map(None)?; + let _ = map.entry("a")?; + "b".visit(map.entry("b")?)?; + map.end() + } else { + let mut seq = sink.seq(None)?; + "a".visit(seq.element()?)?; + let _ = seq.element()?; + seq.end() + } + } +} + +/// A passthrough that opens a container and never ends it. +#[derive(Clone)] +struct Unclosed; + +impl Encrypt for Unclosed { + fn visit<S: Sink>(self, sink: S) -> Result<S::Ok, S::Error> { + let mut outer = sink.seq(None)?; + let mut inner = outer.element()?.seq(None)?; + 1u32.visit(inner.element()?)?; + drop(inner); + outer.end() + } +} + +/// `inner` as a passthrough, beside a sealed sibling. +struct Passes<P>(P); + +impl<P: EncryptRef> Encrypt for Passes<P> { + fn visit<S: Sink>(self, sink: S) -> Result<S::Ok, S::Error> { + let mut seq = sink.seq(Some(2))?; + "sealed".visit(seq.element()?)?; + seq.element()?.passthrough(&self.0)?; + seq.end() + } +} + +/// A source whose getter throws. +#[derive(Clone)] +struct Throws; + +impl Encrypt for Throws { + fn visit<S: Sink>(self, _: S) -> Result<S::Ok, S::Error> { + Err(<S::Error as vitaminc_aead::plaintext::Error>::source( + SourceError::msg("getter threw"), + )) + } +} + +#[derive(Clone, Copy)] +enum Kind { + Seq, + Map, + Pass, + Scalar, +} + +/// `n` levels of one kind of nesting around an innermost value at depth +/// `n`: an empty sequence, or for `Scalar`, a string inside sequences. +#[derive(Clone, Copy)] +struct Nest(Kind, usize); + +impl Encrypt for Nest { + fn visit<S: Sink>(self, sink: S) -> Result<S::Ok, S::Error> { + let Nest(kind, n) = self; + if n == 0 { + return match kind { + Kind::Scalar => "deep".visit(sink), + _ => sink.seq(Some(0))?.end(), + }; + } + let inner = Nest(kind, n - 1); + match kind { + Kind::Seq | Kind::Scalar => { + let mut seq = sink.seq(Some(1))?; + inner.visit(seq.element()?)?; + seq.end() + } + Kind::Map => { + let mut map = sink.map(Some(1))?; + inner.visit(map.entry("k")?)?; + map.end() + } + Kind::Pass => sink.passthrough(&inner), + } + } +} + +/// A passthrough is lent, so a source a test passes through walks by +/// reference too, as the value it is. +macro_rules! lent_as_owned { + ($($ty:ident => $value:expr),+ $(,)?) => {$( + impl Encrypt for &$ty { + fn visit<S: Sink>(self, sink: S) -> Result<S::Ok, S::Error> { + let owned: $ty = $value(self); + owned.visit(sink) + } + } + )+}; +} +lent_as_owned!( + Dup => |_| Dup, + Unclosed => |_| Unclosed, + Throws => |_| Throws, + Nest => |nest: &Nest| *nest, +); + +#[test] +fn both_accept_a_well_formed_value_with_the_same_terms() { + let doc = || { + let mut doc = BTreeMap::new(); + doc.insert("ages", vec![Some(36u32), None]); + doc.insert("empty", vec![]); + doc + }; + // The absent age has a term as the present one does. + agree(doc, Terms(vec![".ages[0]".into(), ".ages[1]".into()])); + // A passthrough beside a sealed sibling, and nesting right up to the + // limit, are fine. + agree(|| Passes("public"), Terms(vec!["[0]".into()])); + agree( + || Nest(Kind::Scalar, MAX_DEPTH), + Terms(vec!["[0]".repeat(MAX_DEPTH)]), + ); + agree(|| Nest(Kind::Map, MAX_DEPTH), Terms(Vec::new())); +} + +#[test] +fn both_refuse_a_duplicate_key_at_the_repeated_entry() { + agree( + || Users(Dup), + shape(Unencryptable::DuplicateKey, ".users[1].k"), + ); + agree(|| Dup, shape(Unencryptable::DuplicateKey, ".k")); +} + +#[test] +fn both_refuse_a_container_with_nothing_sealed() { + agree( + || Users(OnlyPass { map: false }), + shape(Unencryptable::SequenceHasNothingSealed, ".users[1]"), + ); + agree( + || Users(OnlyPass { map: true }), + shape(Unencryptable::MapHasNothingSealed, ".users[1]"), + ); + agree( + || OnlyPass { map: false }, + shape(Unencryptable::SequenceHasNothingSealed, ""), + ); +} + +#[test] +fn both_refuse_a_dropped_child_sink() { + for map in [false, true] { + agree( + || Users(DropsAChild { map }), + shape(Unencryptable::DroppedChild, ".users[1]"), + ); + } +} + +#[test] +fn both_refuse_a_value_invalid_for_its_logical_type() { + let invalid = || Raw(Some(Logical::Uuid), Physical::Bytes(&[0; 3])); + agree( + || Users(invalid()), + shape(Unencryptable::InvalidValue, ".users[1]"), + ); + // `undefined` over an int has no term either, but is refused all the + // same: it cannot be encrypted. + agree( + || { + Raw( + Some(Logical::Undefined), + Physical::Int(vitaminc_aead::Int::I8(1)), + ) + }, + shape(Unencryptable::InvalidValue, ""), + ); +} + +#[test] +fn both_refuse_a_passthrough_that_does_not_frame_at_the_passthrough() { + agree( + || Passes(Unclosed), + shape(Unencryptable::UnframablePassthrough, "[1]"), + ); + agree( + || Passes(Dup), + shape(Unencryptable::UnframablePassthrough, "[1]"), + ); + // A source error inside the passthrough is the source's, both ways. + agree(|| Passes(Throws), Source("getter threw".into())); +} + +#[test] +fn both_refuse_a_value_nested_too_deep_at_the_same_node() { + for (kind, step) in [(Kind::Seq, "[0]"), (Kind::Map, ".k"), (Kind::Scalar, "[0]")] { + agree( + || Nest(kind, MAX_DEPTH + 1), + shape(Unencryptable::TooDeep, &step.repeat(MAX_DEPTH + 1)), + ); + } + // A passthrough too deep, or with too much inside it, is refused as a + // whole at its own place. + agree( + || Nest(Kind::Pass, MAX_DEPTH + 1), + shape(Unencryptable::TooDeep, ""), + ); + agree( + || Passes(Nest(Kind::Seq, MAX_DEPTH - 1)), + shape(Unencryptable::TooDeep, "[1]"), + ); + agree( + || Users(Nest(Kind::Seq, MAX_DEPTH - 1)), + shape( + Unencryptable::TooDeep, + &format!(".users[1]{}", "[0]".repeat(MAX_DEPTH - 1)), + ), + ); +} + +#[test] +fn both_refuse_what_terms_refuses_with_the_same_term_error() { + agree( + || Users("\u{378}"), + NoTerm(NormalizeError::UnassignedCodePoint, ".users[1]".into()), + ); + let newer = || { + Users(Raw( + Some(Logical::from_wire(200, 0).expect("unknown")), + Physical::Bytes(b"x"), + )) + }; + agree(newer, NoTerm(NormalizeError::NoDomain, ".users[1]".into())); +} + +#[test] +fn both_pass_a_source_failure_through() { + agree(|| Users(Throws), Source("getter threw".into())); +} diff --git a/packages/vitaminc-normalize/tests/allocations.rs b/packages/vitaminc-normalize/tests/allocations.rs new file mode 100644 index 000000000..a5bf99d48 --- /dev/null +++ b/packages/vitaminc-normalize/tests/allocations.rs @@ -0,0 +1,68 @@ +//! What collecting terms beside encryption allocates, counted by a global +//! allocator. In its own test binary, so no other test allocates while one +//! is counting. + +use std::alloc::{GlobalAlloc, Layout, System}; +use std::collections::BTreeMap; +use std::sync::atomic::{AtomicUsize, Ordering}; + +use vitaminc_aead::plan; +use vitaminc_normalize::plan_with_terms; + +struct Counting; + +static ALLOCATIONS: AtomicUsize = AtomicUsize::new(0); + +// SAFETY: every call forwards to `System` unchanged; the counter is the +// only addition. +unsafe impl GlobalAlloc for Counting { + unsafe fn alloc(&self, layout: Layout) -> *mut u8 { + ALLOCATIONS.fetch_add(1, Ordering::SeqCst); + // SAFETY: the caller's contract is `System`'s. + unsafe { System.alloc(layout) } + } + + unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { + // SAFETY: the caller's contract is `System`'s. + unsafe { System.dealloc(ptr, layout) } + } + + unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 { + ALLOCATIONS.fetch_add(1, Ordering::SeqCst); + // SAFETY: the caller's contract is `System`'s. + unsafe { System.realloc(ptr, layout, new_size) } + } +} + +#[global_allocator] +static GLOBAL: Counting = Counting; + +fn allocations(f: impl FnOnce()) -> usize { + let before = ALLOCATIONS.load(Ordering::SeqCst); + f(); + ALLOCATIONS.load(Ordering::SeqCst) - before +} + +/// Beside encryption, a walk that pushes no term allocates one buffer for +/// the keys on its path and nothing for any container or entry, however +/// many there are. +#[test] +fn a_walk_with_no_terms_allocates_only_the_key_buffer() { + let mut inner = BTreeMap::new(); + for key in ["a", "b", "c", "d"] { + // Booleans, because they have no equality term. A null has one. + inner.insert(key, vec![true, false]); + } + let mut doc = BTreeMap::new(); + for key in ["p", "q", "r"] { + doc.insert(key, vec![inner.clone(), inner.clone()]); + } + let encrypting = allocations(|| { + plan::<_, ()>(doc.clone()).expect("plans"); + }); + let with_terms = allocations(|| { + let (_, terms) = plan_with_terms::<_, ()>(doc.clone()).expect("plans"); + assert!(terms.is_empty()); + }); + assert_eq!(with_terms, encrypting + 1); +} diff --git a/packages/vitaminc-normalize/tests/known_answers.rs b/packages/vitaminc-normalize/tests/known_answers.rs new file mode 100644 index 000000000..85bbdacd6 --- /dev/null +++ b/packages/vitaminc-normalize/tests/known_answers.rs @@ -0,0 +1,1445 @@ +//! Known answers for every term: the bytes and the domain label each scalar +//! normalizes to, pinned as literals. These are the terms the `canonical` +//! encoders of `vitaminc-aead-value` produced before ADR 0001, captured +//! from them when that crate held them, so an index written then still +//! matches one written now. A change here is a change to a frozen domain. +//! +//! The second half is the terms sink beside encryption. + +use core::sync::atomic::{AtomicUsize, Ordering}; +use std::collections::BTreeMap; + +use vitaminc_aead::plaintext::kinds::jiff as conv; +use vitaminc_aead::plaintext::render; +use vitaminc_aead::seal::Cipher; +use vitaminc_aead::{ + Context, Encrypt, EncryptError, Float, Int, Logical, Physical, Refusal, SeqSink, Sink, + SourceError, TimeUnit, Unencryptable, +}; +use vitaminc_normalize::{ + domain, encrypt_with_terms, normalize, plan_with_terms, terms, NormalizeError, Path, Term, + TermError, +}; +use vitaminc_protected::{Controlled, Protected}; + +fn hex(bytes: &[u8]) -> String { + bytes.iter().map(|b| format!("{b:02x}")).collect() +} + +#[track_caller] +fn pin(ty: Option<Logical>, v: Physical<'_>, domain: &str, bytes: &str) { + let term = normalize(ty, v).expect("normalizes"); + assert_eq!(term.domain, domain, "{ty:?} {v:?}"); + assert_eq!(hex(term.bytes.risky_ref()), bytes, "{ty:?} {v:?}"); +} + +#[test] +fn every_integer_width_normalizes_to_its_pinned_term() { + pin( + None, + Physical::Int(Int::I8(0)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000000000000000000000", + ); + pin( + None, + Physical::Int(Int::U8(0)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000000000000000000000", + ); + pin( + None, + Physical::Int(Int::I16(0)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000000000000000000000", + ); + pin( + None, + Physical::Int(Int::U16(0)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000000000000000000000", + ); + pin( + None, + Physical::Int(Int::I32(0)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000000000000000000000", + ); + pin( + None, + Physical::Int(Int::U32(0)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000000000000000000000", + ); + pin( + None, + Physical::Int(Int::I64(0)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000000000000000000000", + ); + pin( + None, + Physical::Int(Int::U64(0)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000000000000000000000", + ); + pin( + None, + Physical::Int(Int::I128(0)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000000000000000000000", + ); + pin( + None, + Physical::Int(Int::U128(0)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000000000000000000000", + ); + pin( + None, + Physical::Int(Int::I8(1)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000000000000000000001", + ); + pin( + None, + Physical::Int(Int::U8(1)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000000000000000000001", + ); + pin( + None, + Physical::Int(Int::I16(1)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000000000000000000001", + ); + pin( + None, + Physical::Int(Int::U16(1)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000000000000000000001", + ); + pin( + None, + Physical::Int(Int::I32(1)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000000000000000000001", + ); + pin( + None, + Physical::Int(Int::U32(1)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000000000000000000001", + ); + pin( + None, + Physical::Int(Int::I64(1)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000000000000000000001", + ); + pin( + None, + Physical::Int(Int::U64(1)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000000000000000000001", + ); + pin( + None, + Physical::Int(Int::I128(1)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000000000000000000001", + ); + pin( + None, + Physical::Int(Int::U128(1)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000000000000000000001", + ); + pin( + None, + Physical::Int(Int::I8(5)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000000000000000000005", + ); + pin( + None, + Physical::Int(Int::U8(5)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000000000000000000005", + ); + pin( + None, + Physical::Int(Int::I16(5)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000000000000000000005", + ); + pin( + None, + Physical::Int(Int::U16(5)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000000000000000000005", + ); + pin( + None, + Physical::Int(Int::I32(5)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000000000000000000005", + ); + pin( + None, + Physical::Int(Int::U32(5)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000000000000000000005", + ); + pin( + None, + Physical::Int(Int::I64(5)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000000000000000000005", + ); + pin( + None, + Physical::Int(Int::U64(5)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000000000000000000005", + ); + pin( + None, + Physical::Int(Int::I128(5)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000000000000000000005", + ); + pin( + None, + Physical::Int(Int::U128(5)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000000000000000000005", + ); + pin( + None, + Physical::Int(Int::I8(-7)), + "vitaminc/prf/value/integer-orderable/v1", + "00fffffffffffffffffffffffffffffff9", + ); + pin( + None, + Physical::Int(Int::I16(-7)), + "vitaminc/prf/value/integer-orderable/v1", + "00fffffffffffffffffffffffffffffff9", + ); + pin( + None, + Physical::Int(Int::I32(-7)), + "vitaminc/prf/value/integer-orderable/v1", + "00fffffffffffffffffffffffffffffff9", + ); + pin( + None, + Physical::Int(Int::I64(-7)), + "vitaminc/prf/value/integer-orderable/v1", + "00fffffffffffffffffffffffffffffff9", + ); + pin( + None, + Physical::Int(Int::I128(-7)), + "vitaminc/prf/value/integer-orderable/v1", + "00fffffffffffffffffffffffffffffff9", + ); + pin( + None, + Physical::Int(Int::I8(127)), + "vitaminc/prf/value/integer-orderable/v1", + "010000000000000000000000000000007f", + ); + pin( + None, + Physical::Int(Int::U8(127)), + "vitaminc/prf/value/integer-orderable/v1", + "010000000000000000000000000000007f", + ); + pin( + None, + Physical::Int(Int::I16(127)), + "vitaminc/prf/value/integer-orderable/v1", + "010000000000000000000000000000007f", + ); + pin( + None, + Physical::Int(Int::U16(127)), + "vitaminc/prf/value/integer-orderable/v1", + "010000000000000000000000000000007f", + ); + pin( + None, + Physical::Int(Int::I32(127)), + "vitaminc/prf/value/integer-orderable/v1", + "010000000000000000000000000000007f", + ); + pin( + None, + Physical::Int(Int::U32(127)), + "vitaminc/prf/value/integer-orderable/v1", + "010000000000000000000000000000007f", + ); + pin( + None, + Physical::Int(Int::I64(127)), + "vitaminc/prf/value/integer-orderable/v1", + "010000000000000000000000000000007f", + ); + pin( + None, + Physical::Int(Int::U64(127)), + "vitaminc/prf/value/integer-orderable/v1", + "010000000000000000000000000000007f", + ); + pin( + None, + Physical::Int(Int::I128(127)), + "vitaminc/prf/value/integer-orderable/v1", + "010000000000000000000000000000007f", + ); + pin( + None, + Physical::Int(Int::U128(127)), + "vitaminc/prf/value/integer-orderable/v1", + "010000000000000000000000000000007f", + ); + pin( + None, + Physical::Int(Int::I8(-128)), + "vitaminc/prf/value/integer-orderable/v1", + "00ffffffffffffffffffffffffffffff80", + ); + pin( + None, + Physical::Int(Int::I16(-128)), + "vitaminc/prf/value/integer-orderable/v1", + "00ffffffffffffffffffffffffffffff80", + ); + pin( + None, + Physical::Int(Int::I32(-128)), + "vitaminc/prf/value/integer-orderable/v1", + "00ffffffffffffffffffffffffffffff80", + ); + pin( + None, + Physical::Int(Int::I64(-128)), + "vitaminc/prf/value/integer-orderable/v1", + "00ffffffffffffffffffffffffffffff80", + ); + pin( + None, + Physical::Int(Int::I128(-128)), + "vitaminc/prf/value/integer-orderable/v1", + "00ffffffffffffffffffffffffffffff80", + ); + pin( + None, + Physical::Int(Int::U8(255)), + "vitaminc/prf/value/integer-orderable/v1", + "01000000000000000000000000000000ff", + ); + pin( + None, + Physical::Int(Int::I16(255)), + "vitaminc/prf/value/integer-orderable/v1", + "01000000000000000000000000000000ff", + ); + pin( + None, + Physical::Int(Int::U16(255)), + "vitaminc/prf/value/integer-orderable/v1", + "01000000000000000000000000000000ff", + ); + pin( + None, + Physical::Int(Int::I32(255)), + "vitaminc/prf/value/integer-orderable/v1", + "01000000000000000000000000000000ff", + ); + pin( + None, + Physical::Int(Int::U32(255)), + "vitaminc/prf/value/integer-orderable/v1", + "01000000000000000000000000000000ff", + ); + pin( + None, + Physical::Int(Int::I64(255)), + "vitaminc/prf/value/integer-orderable/v1", + "01000000000000000000000000000000ff", + ); + pin( + None, + Physical::Int(Int::U64(255)), + "vitaminc/prf/value/integer-orderable/v1", + "01000000000000000000000000000000ff", + ); + pin( + None, + Physical::Int(Int::I128(255)), + "vitaminc/prf/value/integer-orderable/v1", + "01000000000000000000000000000000ff", + ); + pin( + None, + Physical::Int(Int::U128(255)), + "vitaminc/prf/value/integer-orderable/v1", + "01000000000000000000000000000000ff", + ); + pin( + None, + Physical::Int(Int::U16(65535)), + "vitaminc/prf/value/integer-orderable/v1", + "010000000000000000000000000000ffff", + ); + pin( + None, + Physical::Int(Int::I32(65535)), + "vitaminc/prf/value/integer-orderable/v1", + "010000000000000000000000000000ffff", + ); + pin( + None, + Physical::Int(Int::U32(65535)), + "vitaminc/prf/value/integer-orderable/v1", + "010000000000000000000000000000ffff", + ); + pin( + None, + Physical::Int(Int::I64(65535)), + "vitaminc/prf/value/integer-orderable/v1", + "010000000000000000000000000000ffff", + ); + pin( + None, + Physical::Int(Int::U64(65535)), + "vitaminc/prf/value/integer-orderable/v1", + "010000000000000000000000000000ffff", + ); + pin( + None, + Physical::Int(Int::I128(65535)), + "vitaminc/prf/value/integer-orderable/v1", + "010000000000000000000000000000ffff", + ); + pin( + None, + Physical::Int(Int::U128(65535)), + "vitaminc/prf/value/integer-orderable/v1", + "010000000000000000000000000000ffff", + ); + pin( + None, + Physical::Int(Int::I16(-32768)), + "vitaminc/prf/value/integer-orderable/v1", + "00ffffffffffffffffffffffffffff8000", + ); + pin( + None, + Physical::Int(Int::I32(-32768)), + "vitaminc/prf/value/integer-orderable/v1", + "00ffffffffffffffffffffffffffff8000", + ); + pin( + None, + Physical::Int(Int::I64(-32768)), + "vitaminc/prf/value/integer-orderable/v1", + "00ffffffffffffffffffffffffffff8000", + ); + pin( + None, + Physical::Int(Int::I128(-32768)), + "vitaminc/prf/value/integer-orderable/v1", + "00ffffffffffffffffffffffffffff8000", + ); + pin( + None, + Physical::Int(Int::I128(-170141183460469231731687303715884105728)), + "vitaminc/prf/value/integer-orderable/v1", + "0080000000000000000000000000000000", + ); + pin( + None, + Physical::Int(Int::I128(170141183460469231731687303715884105727)), + "vitaminc/prf/value/integer-orderable/v1", + "017fffffffffffffffffffffffffffffff", + ); + pin( + None, + Physical::Int(Int::I16(32767)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000000000000000007fff", + ); + pin( + None, + Physical::Int(Int::I32(-2147483648)), + "vitaminc/prf/value/integer-orderable/v1", + "00ffffffffffffffffffffffff80000000", + ); + pin( + None, + Physical::Int(Int::I32(2147483647)), + "vitaminc/prf/value/integer-orderable/v1", + "010000000000000000000000007fffffff", + ); + pin( + None, + Physical::Int(Int::I64(-9223372036854775808)), + "vitaminc/prf/value/integer-orderable/v1", + "00ffffffffffffffff8000000000000000", + ); + pin( + None, + Physical::Int(Int::I64(9223372036854775807)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000007fffffffffffffff", + ); + pin( + None, + Physical::Int(Int::U32(4294967295)), + "vitaminc/prf/value/integer-orderable/v1", + "01000000000000000000000000ffffffff", + ); + pin( + None, + Physical::Int(Int::U64(18446744073709551615)), + "vitaminc/prf/value/integer-orderable/v1", + "010000000000000000ffffffffffffffff", + ); + pin( + None, + Physical::Int(Int::U128(340282366920938463463374607431768211455)), + "vitaminc/prf/value/integer-orderable/v1", + "01ffffffffffffffffffffffffffffffff", + ); +} + +#[test] +fn both_float_widths_normalize_to_their_pinned_terms() { + pin( + None, + Physical::Float(Float::F32(f32::from_bits(0x0))), + "vitaminc/prf/value/float-orderable/v1", + "8000000000000000", + ); + pin( + None, + Physical::Float(Float::F32(f32::from_bits(0x80000000))), + "vitaminc/prf/value/float-orderable/v1", + "8000000000000000", + ); + pin( + None, + Physical::Float(Float::F32(f32::from_bits(0x3fc00000))), + "vitaminc/prf/value/float-orderable/v1", + "bff8000000000000", + ); + pin( + None, + Physical::Float(Float::F32(f32::from_bits(0xbfc00000))), + "vitaminc/prf/value/float-orderable/v1", + "4007ffffffffffff", + ); + pin( + None, + Physical::Float(Float::F32(f32::from_bits(0x3dcccccd))), + "vitaminc/prf/value/float-orderable/v1", + "bfb99999a0000000", + ); + pin( + None, + Physical::Float(Float::F32(f32::from_bits(0x7f7fffff))), + "vitaminc/prf/value/float-orderable/v1", + "c7efffffe0000000", + ); + pin( + None, + Physical::Float(Float::F32(f32::from_bits(0x800000))), + "vitaminc/prf/value/float-orderable/v1", + "b810000000000000", + ); + pin( + None, + Physical::Float(Float::F32(f32::from_bits(0x7f800000))), + "vitaminc/prf/value/float-orderable/v1", + "fff0000000000000", + ); + pin( + None, + Physical::Float(Float::F32(f32::from_bits(0xff800000))), + "vitaminc/prf/value/float-orderable/v1", + "000fffffffffffff", + ); + pin( + None, + Physical::Float(Float::F32(f32::from_bits(0x7fc00000))), + "vitaminc/prf/value/float-orderable/v1", + "fff8000000000000", + ); + pin( + None, + Physical::Float(Float::F32(f32::from_bits(0xff800001))), + "vitaminc/prf/value/float-orderable/v1", + "fff8000000000000", + ); + pin( + None, + Physical::Float(Float::F32(f32::from_bits(0x1))), + "vitaminc/prf/value/float-orderable/v1", + "b6a0000000000000", + ); + pin( + None, + Physical::Float(Float::F64(f64::from_bits(0x0))), + "vitaminc/prf/value/float-orderable/v1", + "8000000000000000", + ); + pin( + None, + Physical::Float(Float::F64(f64::from_bits(0x8000000000000000))), + "vitaminc/prf/value/float-orderable/v1", + "8000000000000000", + ); + pin( + None, + Physical::Float(Float::F64(f64::from_bits(0x3ff8000000000000))), + "vitaminc/prf/value/float-orderable/v1", + "bff8000000000000", + ); + pin( + None, + Physical::Float(Float::F64(f64::from_bits(0x3fb999999999999a))), + "vitaminc/prf/value/float-orderable/v1", + "bfb999999999999a", + ); + pin( + None, + Physical::Float(Float::F64(f64::from_bits(0x7fefffffffffffff))), + "vitaminc/prf/value/float-orderable/v1", + "ffefffffffffffff", + ); + pin( + None, + Physical::Float(Float::F64(f64::from_bits(0x10000000000000))), + "vitaminc/prf/value/float-orderable/v1", + "8010000000000000", + ); + pin( + None, + Physical::Float(Float::F64(f64::from_bits(0x7ff0000000000000))), + "vitaminc/prf/value/float-orderable/v1", + "fff0000000000000", + ); + pin( + None, + Physical::Float(Float::F64(f64::from_bits(0xfff0000000000000))), + "vitaminc/prf/value/float-orderable/v1", + "000fffffffffffff", + ); + pin( + None, + Physical::Float(Float::F64(f64::from_bits(0x7ff8000000000000))), + "vitaminc/prf/value/float-orderable/v1", + "fff8000000000000", + ); + pin( + None, + Physical::Float(Float::F64(f64::from_bits(0xfff0000000000001))), + "vitaminc/prf/value/float-orderable/v1", + "fff8000000000000", + ); +} + +#[test] +fn text_and_bytes_normalize_to_their_pinned_terms() { + pin( + None, + Physical::Text(""), + "vitaminc/prf/value/text-nfc/unicode-16/v1", + "", + ); + pin( + None, + Physical::Text("Ada"), + "vitaminc/prf/value/text-nfc/unicode-16/v1", + "416461", + ); + pin( + None, + Physical::Text("e\u{301}"), + "vitaminc/prf/value/text-nfc/unicode-16/v1", + "c3a9", + ); + pin( + None, + Physical::Text("\u{344}"), + "vitaminc/prf/value/text-nfc/unicode-16/v1", + "cc88cc81", + ); + pin( + None, + Physical::Text("a\0b"), + "vitaminc/prf/value/text-nfc/unicode-16/v1", + "610062", + ); + pin( + None, + Physical::Text("日本語"), + "vitaminc/prf/value/text-nfc/unicode-16/v1", + "e697a5e69cace8aa9e", + ); + pin( + None, + Physical::Bytes(&[]), + "vitaminc/prf/value/bytes/v1", + "", + ); + pin( + None, + Physical::Bytes(&[0x00]), + "vitaminc/prf/value/bytes/v1", + "00", + ); + pin( + None, + Physical::Bytes(&[0x01, 0x02, 0x03]), + "vitaminc/prf/value/bytes/v1", + "010203", + ); + pin( + None, + Physical::Bytes(&[ + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + ]), + "vitaminc/prf/value/bytes/v1", + "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", + ); + assert_eq!( + normalize(None, Physical::Text("\u{378}")).expect_err("unassigned"), + NormalizeError::UnassignedCodePoint + ); +} + +#[test] +fn dates_normalize_to_their_pinned_terms() { + // The wire's minimum (jiff's Date::MIN, -9999-01-01), 0001-01-01, + // 1969-12-31, 1970-01-01, 2024-02-29, the wire's maximum (jiff's + // Date::MAX, 9999-12-31). + pin( + Some(Logical::Date), + Physical::Int(Int::I32(-4371587)), + "vitaminc/prf/value/date-orderable/v1", + "7fc844b8", + ); + pin( + Some(Logical::Date), + Physical::Int(Int::I32(-719162)), + "vitaminc/prf/value/date-orderable/v1", + "80000001", + ); + pin( + Some(Logical::Date), + Physical::Int(Int::I32(-1)), + "vitaminc/prf/value/date-orderable/v1", + "800af93a", + ); + pin( + Some(Logical::Date), + Physical::Int(Int::I32(0)), + "vitaminc/prf/value/date-orderable/v1", + "800af93b", + ); + pin( + Some(Logical::Date), + Physical::Int(Int::I32(19782)), + "vitaminc/prf/value/date-orderable/v1", + "800b4681", + ); + pin( + Some(Logical::Date), + Physical::Int(Int::I32(2932896)), + "vitaminc/prf/value/date-orderable/v1", + "8037b9db", + ); +} + +#[test] +fn timestamps_in_every_unit_normalize_to_their_pinned_terms() { + // Five instants as nanoseconds, each then truncated to micros, millis + // and seconds (a coarser unit matches the term of the instant at that + // precision), then the wire's minimum and maximum (jiff's + // Timestamp::MIN and Timestamp::MAX). + pin( + Some(Logical::Timestamp(TimeUnit::Nanos)), + Physical::Int(Int::I128(0)), + "vitaminc/prf/value/timestamp-micros-orderable/v1", + "800000000000000000000000", + ); + pin( + Some(Logical::Timestamp(TimeUnit::Micros)), + Physical::Int(Int::I64(0)), + "vitaminc/prf/value/timestamp-micros-orderable/v1", + "800000000000000000000000", + ); + pin( + Some(Logical::Timestamp(TimeUnit::Millis)), + Physical::Int(Int::I64(0)), + "vitaminc/prf/value/timestamp-micros-orderable/v1", + "800000000000000000000000", + ); + pin( + Some(Logical::Timestamp(TimeUnit::Seconds)), + Physical::Int(Int::I64(0)), + "vitaminc/prf/value/timestamp-micros-orderable/v1", + "800000000000000000000000", + ); + pin( + Some(Logical::Timestamp(TimeUnit::Nanos)), + Physical::Int(Int::I128(-876543211)), + "vitaminc/prf/value/timestamp-micros-orderable/v1", + "7fffffffffffffff075bca00", + ); + pin( + Some(Logical::Timestamp(TimeUnit::Micros)), + Physical::Int(Int::I64(-876544)), + "vitaminc/prf/value/timestamp-micros-orderable/v1", + "7fffffffffffffff075bca00", + ); + pin( + Some(Logical::Timestamp(TimeUnit::Millis)), + Physical::Int(Int::I64(-877)), + "vitaminc/prf/value/timestamp-micros-orderable/v1", + "7fffffffffffffff0754d4c0", + ); + pin( + Some(Logical::Timestamp(TimeUnit::Seconds)), + Physical::Int(Int::I64(-1)), + "vitaminc/prf/value/timestamp-micros-orderable/v1", + "7fffffffffffffff00000000", + ); + pin( + Some(Logical::Timestamp(TimeUnit::Nanos)), + Physical::Int(Int::I128(59999999999)), + "vitaminc/prf/value/timestamp-micros-orderable/v1", + "800000000000003b3b9ac618", + ); + pin( + Some(Logical::Timestamp(TimeUnit::Micros)), + Physical::Int(Int::I64(59999999)), + "vitaminc/prf/value/timestamp-micros-orderable/v1", + "800000000000003b3b9ac618", + ); + pin( + Some(Logical::Timestamp(TimeUnit::Millis)), + Physical::Int(Int::I64(59999)), + "vitaminc/prf/value/timestamp-micros-orderable/v1", + "800000000000003b3b8b87c0", + ); + pin( + Some(Logical::Timestamp(TimeUnit::Seconds)), + Physical::Int(Int::I64(59)), + "vitaminc/prf/value/timestamp-micros-orderable/v1", + "800000000000003b00000000", + ); + pin( + Some(Logical::Timestamp(TimeUnit::Nanos)), + Physical::Int(Int::I128(1700000000123456789)), + "vitaminc/prf/value/timestamp-micros-orderable/v1", + "800000006553f100075bca00", + ); + pin( + Some(Logical::Timestamp(TimeUnit::Micros)), + Physical::Int(Int::I64(1700000000123456)), + "vitaminc/prf/value/timestamp-micros-orderable/v1", + "800000006553f100075bca00", + ); + pin( + Some(Logical::Timestamp(TimeUnit::Millis)), + Physical::Int(Int::I64(1700000000123)), + "vitaminc/prf/value/timestamp-micros-orderable/v1", + "800000006553f1000754d4c0", + ); + pin( + Some(Logical::Timestamp(TimeUnit::Seconds)), + Physical::Int(Int::I64(1700000000)), + "vitaminc/prf/value/timestamp-micros-orderable/v1", + "800000006553f10000000000", + ); + pin( + Some(Logical::Timestamp(TimeUnit::Nanos)), + Physical::Int(Int::I128(-61999999999999995000)), + "vitaminc/prf/value/timestamp-micros-orderable/v1", + "7ffffff19083140000001388", + ); + pin( + Some(Logical::Timestamp(TimeUnit::Micros)), + Physical::Int(Int::I64(-61999999999999995)), + "vitaminc/prf/value/timestamp-micros-orderable/v1", + "7ffffff19083140000001388", + ); + pin( + Some(Logical::Timestamp(TimeUnit::Millis)), + Physical::Int(Int::I64(-62000000000000)), + "vitaminc/prf/value/timestamp-micros-orderable/v1", + "7ffffff19083140000000000", + ); + pin( + Some(Logical::Timestamp(TimeUnit::Seconds)), + Physical::Int(Int::I64(-62000000000)), + "vitaminc/prf/value/timestamp-micros-orderable/v1", + "7ffffff19083140000000000", + ); + pin( + Some(Logical::Timestamp(TimeUnit::Nanos)), + Physical::Int(Int::I128(-377705023201000000000)), + "vitaminc/prf/value/timestamp-micros-orderable/v1", + "7fffffa80f06b91f00000000", + ); + pin( + Some(Logical::Timestamp(TimeUnit::Nanos)), + Physical::Int(Int::I128(253402207200999999999)), + "vitaminc/prf/value/timestamp-micros-orderable/v1", + "8000003afff2d3e03b9ac618", + ); +} + +#[test] +fn decimals_normalize_to_their_pinned_terms() { + // 0 + pin( + Some(Logical::Decimal { scale: 0 }), + Physical::Int(Int::I128(0)), + "vitaminc/prf/value/decimal-orderable/v1", + "8000000000000000000000000000", + ); + // 0.0 + pin( + Some(Logical::Decimal { scale: 1 }), + Physical::Int(Int::I128(0)), + "vitaminc/prf/value/decimal-orderable/v1", + "8000000000000000000000000000", + ); + // -0.00 + pin( + Some(Logical::Decimal { scale: 2 }), + Physical::Int(Int::I128(0)), + "vitaminc/prf/value/decimal-orderable/v1", + "8000000000000000000000000000", + ); + // 1 + pin( + Some(Logical::Decimal { scale: 0 }), + Physical::Int(Int::I128(1)), + "vitaminc/prf/value/decimal-orderable/v1", + "c000204fce5e3e25026110000000", + ); + // 1.0 + pin( + Some(Logical::Decimal { scale: 1 }), + Physical::Int(Int::I128(10)), + "vitaminc/prf/value/decimal-orderable/v1", + "c000204fce5e3e25026110000000", + ); + // 1.50 + pin( + Some(Logical::Decimal { scale: 2 }), + Physical::Int(Int::I128(150)), + "vitaminc/prf/value/decimal-orderable/v1", + "c0003077b58d5d37839198000000", + ); + // 1.5 + pin( + Some(Logical::Decimal { scale: 1 }), + Physical::Int(Int::I128(15)), + "vitaminc/prf/value/decimal-orderable/v1", + "c0003077b58d5d37839198000000", + ); + // -1.5 + pin( + Some(Logical::Decimal { scale: 1 }), + Physical::Int(Int::I128(-15)), + "vitaminc/prf/value/decimal-orderable/v1", + "3fffcf884a72a2c87c6e67ffffff", + ); + // 0.001 + pin( + Some(Logical::Decimal { scale: 3 }), + Physical::Int(Int::I128(1)), + "vitaminc/prf/value/decimal-orderable/v1", + "bd00204fce5e3e25026110000000", + ); + // 123456789.987654321 + pin( + Some(Logical::Decimal { scale: 9 }), + Physical::Int(Int::I128(123456789987654321)), + "vitaminc/prf/value/decimal-orderable/v1", + "c80027e41b37904205f388c66800", + ); + // 79228162514264337593543950335 + pin( + Some(Logical::Decimal { scale: 0 }), + Physical::Int(Int::I128(79228162514264337593543950335)), + "vitaminc/prf/value/decimal-orderable/v1", + "dc00ffffffffffffffffffffffff", + ); + // -79228162514264337593543950335 + pin( + Some(Logical::Decimal { scale: 0 }), + Physical::Int(Int::I128(-79228162514264337593543950335)), + "vitaminc/prf/value/decimal-orderable/v1", + "23ff000000000000000000000000", + ); + // 0.0000000000000000000000000001 + pin( + Some(Logical::Decimal { scale: 28 }), + Physical::Int(Int::I128(1)), + "vitaminc/prf/value/decimal-orderable/v1", + "a400204fce5e3e25026110000000", + ); +} + +/// Every null is one term, typed or plain, under a domain of its own: +/// the walk sends a typed null as a plain one, so a `None` of any fixed +/// width is the same pinned byte. +#[test] +fn a_null_is_one_pinned_byte_under_the_null_domain_whatever_its_type() { + pin(None, Physical::Null, "vitaminc/prf/value/null/v1", "00"); + let typed = |found: Vec<Term>| { + assert_eq!(found.len(), 1, "a typed null has one term"); + assert_eq!(found[0].normalized.domain, domain::NULL); + hex(found[0].normalized.bytes.risky_ref()) + }; + assert_eq!(typed(terms(None::<u32>).expect("walks")), "00"); + assert_eq!(typed(terms(None::<i128>).expect("walks")), "00"); + assert_eq!(typed(terms(None::<f64>).expect("walks")), "00"); + assert_eq!(typed(terms(None::<uuid::Uuid>).expect("walks")), "00"); +} + +#[test] +fn a_uuid_has_a_domain_of_its_own() { + let id = uuid::Uuid::from_bytes([ + 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, + 0xf0, + ]); + let n = normalize(Some(Logical::Uuid), Physical::Bytes(id.as_bytes())).expect("uuid"); + assert_eq!(n.domain, "vitaminc/prf/value/uuid/v1"); + assert_eq!(hex(n.bytes.risky_ref()), "123456789abcdef0123456789abcdef0"); + let plain = normalize(None, Physical::Bytes(id.as_bytes())).expect("bytes"); + assert_eq!(hex(plain.bytes.risky_ref()), hex(n.bytes.risky_ref())); + assert_ne!(plain.domain, n.domain); + // The uuid source carries its logical type, so the two never meet. + let mut terms = Vec::new(); + let (_, ()) = id + .visit(vitaminc_aead::Tee( + vitaminc_aead::EncryptSink::<vitaminc_aead::shape::Root, ()>::new(), + vitaminc_normalize::Terms::new(&mut terms), + )) + .expect("walks"); + assert_eq!(terms[0].normalized.domain, domain::UUID); +} + +#[test] +fn a_date_never_matches_its_day_count_and_widths_agree() { + let date = jiff::civil::Date::constant(2024, 2, 29); + let days = conv::date_days(date); + let as_date = normalize(Some(Logical::Date), Physical::Int(Int::I32(days))).expect("date"); + let as_int = normalize(None, Physical::Int(Int::I32(days))).expect("int"); + assert_ne!(as_date.domain, as_int.domain); + assert_ne!(as_date.bytes.risky_ref(), as_int.bytes.risky_ref()); + let narrow = normalize(None, Physical::Int(Int::I8(34))).expect("i8"); + let wide = normalize(None, Physical::Int(Int::U64(34))).expect("u64"); + assert_eq!(narrow.domain, wide.domain); + assert_eq!(narrow.bytes.risky_ref(), wide.bytes.risky_ref()); +} + +// The terms sink beside encryption. + +#[derive(Debug, Clone, PartialEq, Eq)] +struct Leaf { + aad: Vec<u8>, + plaintext: Vec<u8>, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +struct Refused; + +/// Seals in the clear and counts calls, so a test can see when the cipher +/// first runs. +#[derive(Default)] +struct Counting { + calls: AtomicUsize, +} + +impl Cipher for Counting { + type Leaf = Leaf; + type Error = Refused; + + fn seal(&self, plaintext: Protected<Vec<u8>>, aad: &Context<'_>) -> Result<Leaf, Refused> { + self.calls.fetch_add(1, Ordering::SeqCst); + Ok(Leaf { + aad: aad.as_bytes().to_vec(), + plaintext: plaintext.risky_unwrap(), + }) + } + + fn open(&self, leaf: Leaf, aad: &Context<'_>) -> Result<Protected<Vec<u8>>, Refused> { + if leaf.aad != aad.as_bytes() { + return Err(Refused); + } + Ok(Protected::new(leaf.plaintext)) + } +} + +fn user() -> BTreeMap<&'static str, Vec<Option<u32>>> { + let mut m = BTreeMap::new(); + m.insert("ages", vec![Some(36), None, Some(41)]); + m.insert("empty", vec![]); + m +} + +fn paths(terms: &[Term]) -> Vec<String> { + terms.iter().map(|t| render(&t.path)).collect() +} + +/// What `Terms` refused inside an encryption error, and where. +fn term_error(err: &EncryptError<Refused>) -> Option<(NormalizeError, String)> { + match err { + EncryptError::Source(source) => source + .inner() + .downcast_ref::<TermError>() + .map(|t| (t.error(), render(t.path()))), + _ => None, + } +} + +fn refused(error: NormalizeError, at: &str) -> Option<(NormalizeError, String)> { + Some((error, at.to_owned())) +} + +#[test] +fn plan_with_terms_has_every_term_without_a_cipher() { + let (planned, terms) = plan_with_terms::<_, Refused>(user()).expect("plans"); + assert_eq!(paths(&terms), [".ages[0]", ".ages[1]", ".ages[2]"]); + assert_eq!(terms[0].normalized.domain, domain::INTEGER); + assert_eq!( + terms[1].normalized.domain, + domain::NULL, + "the absent age has the null term" + ); + assert_eq!( + terms[2].normalized.bytes.risky_ref(), + normalize(None, Physical::Int(Int::U32(41))) + .expect("int") + .bytes + .risky_ref() + ); + // The plan is the same one `encrypt` would seal. + let cipher = Counting::default(); + let sealed = planned + .seal( + &vitaminc_aead::IntoAad::into_aad("ctx"), + |plaintext, aad| cipher.seal(plaintext, aad), + ) + .expect("seals"); + assert!(matches!(sealed, vitaminc_aead::CipherText::Map(_))); +} + +#[test] +fn encrypt_with_terms_seals_the_same_leaves_and_returns_the_terms() { + let cipher = Counting::default(); + let (sealed, terms) = encrypt_with_terms(user(), &cipher, "ctx").expect("encrypts"); + assert_eq!(terms.len(), 3, "the absent age has a term too"); + // Three elements, one empty marker. + assert_eq!(cipher.calls.load(Ordering::SeqCst), 4); + let back: BTreeMap<String, Vec<Option<u32>>> = + vitaminc_aead::decrypt(&cipher, sealed, "ctx").expect("decrypts"); + assert_eq!(back["ages"], [Some(36), None, Some(41)]); +} + +#[test] +fn scalars_without_a_domain_and_passthroughs_get_no_term_and_a_null_gets_one() { + struct Doc; + impl Encrypt for Doc { + fn visit<S: Sink>(self, sink: S) -> Result<S::Ok, S::Error> { + use vitaminc_aead::MapSink; + let mut map = sink.map(Some(5))?; + true.visit(map.entry("active")?)?; + None::<u32>.visit(map.entry("missing")?)?; + map.entry("tenant")?.passthrough(&"acme")?; + vitaminc_aead::Raw(Some(Logical::Undefined), Physical::Null) + .visit(map.entry("undefined")?)?; + "Ada".visit(map.entry("name")?)?; + map.end() + } + } + let (_, terms) = plan_with_terms::<_, Refused>(Doc).expect("plans"); + assert_eq!( + paths(&terms), + [".missing", ".name"], + "a boolean, a passthrough and an undefined get no term; a null does" + ); + assert_eq!(terms[0].normalized.domain, domain::NULL); + assert_eq!(terms[1].normalized.domain, domain::TEXT); +} + +/// A logical type this build does not know means something to the client +/// that sent it, so it is refused rather than encrypted with no term. +#[test] +fn an_unknown_logical_type_stops_the_walk() { + let newer = vitaminc_aead::Raw( + Some(Logical::from_wire(200, 0).expect("unknown")), + Physical::Int(Int::I32(1)), + ); + let err = plan_with_terms::<_, Refused>(vec![newer]).expect_err("refused"); + assert_eq!(term_error(&err), refused(NormalizeError::NoDomain, "[0]")); +} + +/// Nested paths are the container's path plus the step, at every depth. +#[test] +fn paths_follow_the_nesting() { + let mut inner = BTreeMap::new(); + inner.insert("k", vec![vec![1u8, 2]]); + let mut outer = BTreeMap::new(); + outer.insert("m", vec![inner]); + let (_, terms) = plan_with_terms::<_, Refused>(outer).expect("plans"); + assert_eq!(paths(&terms), [".m[0].k[0]"]); + assert_eq!(terms[0].normalized.domain, domain::BYTES); +} + +/// Every container on a path shares one buffer of keys, and each starts +/// over where its own keys begin, so a path names only its own keys +/// however many siblings went before it. +#[test] +fn sibling_paths_name_only_their_own_keys() { + let mut first = BTreeMap::new(); + first.insert("x", vec!["1", "2"]); + first.insert("yy", vec!["3"]); + let mut second = BTreeMap::new(); + second.insert("zzz", vec!["4"]); + let mut doc = BTreeMap::new(); + doc.insert("a", vec![first.clone(), second]); + doc.insert("bb", vec![first]); + for found in [ + plan_with_terms::<_, Refused>(doc.clone()).expect("plans").1, + terms(doc).expect("walks"), + ] { + assert_eq!( + paths(&found), + [ + ".a[0].x[0]", + ".a[0].x[1]", + ".a[0].yy[0]", + ".a[1].zzz[0]", + ".bb[0].x[0]", + ".bb[0].x[1]", + ".bb[0].yy[0]", + ] + ); + } +} + +#[test] +fn an_unassigned_code_point_stops_the_walk_with_the_normalize_error() { + let err = plan_with_terms::<_, Refused>("\u{378}").expect_err("refused"); + assert_eq!( + term_error(&err), + refused(NormalizeError::UnassignedCodePoint, "") + ); +} + +/// The refusal names the field, nested at any depth, through an accessor +/// only: neither the message nor `Debug` shows a key. +#[test] +fn a_refusal_names_the_field_only_on_request() { + let mut inner = BTreeMap::new(); + inner.insert("ada@example.com", vec!["ok", "\u{378}"]); + let mut outer = BTreeMap::new(); + outer.insert("emails", vec![inner]); + let err = plan_with_terms::<_, Refused>(outer).expect_err("refused"); + assert_eq!( + term_error(&err), + refused( + NormalizeError::UnassignedCodePoint, + ".emails[0].ada@example.com[1]" + ) + ); + let EncryptError::Source(source) = &err else { + panic!("{err:?}") + }; + let term = source + .inner() + .downcast_ref::<TermError>() + .expect("a term error"); + assert_eq!( + term.to_string(), + "no equality term: text contains a code point unassigned in Unicode 16" + ); + for shown in [format!("{term:?}"), format!("{err:?}")] { + assert!(!shown.contains("ada"), "{shown}"); + assert!(!shown.contains("emails"), "{shown}"); + } + // The walk's error shows a placeholder for the error inside it, so the + // reason and the place are read from the term error itself. + let shown = format!("{term:?}"); + assert!(shown.contains("UnassignedCodePoint"), "{shown}"); + assert!(shown.contains("Index(1)"), "{shown}"); +} + +/// Every error in a chain, from `err` down through each `source()`. +fn chain<'e>( + err: &'e (dyn core::error::Error + 'static), +) -> Vec<&'e (dyn core::error::Error + 'static)> { + core::iter::successors(Some(err), |e| e.source()).collect() +} + +/// A reporter that walks `source()` reaches the `NormalizeError` behind a +/// refusal, whether it arrived through encryption or through `terms`. +#[test] +fn the_normalize_error_is_on_the_source_chain() { + let reason = |err: &(dyn core::error::Error + 'static)| { + chain(err) + .into_iter() + .find_map(|e| e.downcast_ref::<NormalizeError>().copied()) + }; + let encrypting = plan_with_terms::<_, &str>(vec!["\u{378}"]).expect_err("refused"); + assert_eq!( + reason(&encrypting), + Some(NormalizeError::UnassignedCodePoint) + ); + let alone = terms(vec!["\u{378}"]).expect_err("refused"); + assert_eq!(reason(&alone), Some(NormalizeError::UnassignedCodePoint)); + // The chain ends at the reason, which says why and nothing more. + let last = chain(&alone).pop().expect("a chain"); + assert!(last.source().is_none()); + assert_eq!( + last.to_string(), + "text contains a code point unassigned in Unicode 16" + ); + // `TermError` itself names its reason as its source. + let term = alone.term().expect("refused by Terms"); + let source = core::error::Error::source(term).expect("a source"); + assert_eq!( + source.downcast_ref::<NormalizeError>(), + Some(&NormalizeError::UnassignedCodePoint) + ); +} + +#[test] +fn terms_collects_every_term_without_encrypting() { + let found = terms(user()).expect("walks"); + assert_eq!(paths(&found), [".ages[0]", ".ages[1]", ".ages[2]"]); + assert_eq!(found[1].normalized.domain, domain::NULL); + assert_eq!(found[2].normalized.domain, domain::INTEGER); + // A borrowed value walks too, and a scalar at the root has no steps. + let name = String::from("Ada"); + let found = terms(&name).expect("walks"); + assert_eq!(paths(&found), [""]); + assert!(terms(Vec::<u32>::new()).expect("walks").is_empty()); +} + +#[test] +fn terms_says_which_field_it_refused() { + let mut doc = BTreeMap::new(); + doc.insert("x", "\u{378}"); + let err = terms(doc).expect_err("refused"); + let term = err.term().expect("refused by Terms"); + assert!(err.refusal().is_none()); + assert_eq!(term.error(), NormalizeError::UnassignedCodePoint); + assert_eq!(render(term.path()), ".x"); + assert_eq!( + err.to_string(), + "no equality term: text contains a code point unassigned in Unicode 16" + ); + + // A value invalid for its logical type cannot be encrypted, so it is + // refused for its shape, as encryption refuses it, before it is + // normalized. + let invalid = vitaminc_aead::Raw(Some(Logical::Undefined), Physical::Int(Int::I32(1))); + let mut doc = BTreeMap::new(); + doc.insert("x", invalid); + let err = terms(doc).expect_err("refused"); + assert!(err.term().is_none()); + let refusal = err.refusal().expect("refused for its shape"); + assert_eq!(refusal.reason(), Unencryptable::InvalidValue); + assert_eq!(render(refusal.path()), ".x"); + assert_eq!(err.to_string(), "value is not valid for its logical type"); +} + +#[test] +fn terms_passes_a_source_failure_through() { + struct Throws; + impl Encrypt for Throws { + fn visit<S: Sink>(self, sink: S) -> Result<S::Ok, S::Error> { + let mut seq = sink.seq(None)?; + 1u32.visit(seq.element()?)?; + Err(<S::Error as vitaminc_aead::plaintext::Error>::source( + SourceError::msg("getter threw"), + )) + } + } + let err = terms(Throws).expect_err("refused"); + assert!(err.term().is_none()); + assert_eq!(err.to_string(), "getter threw"); + assert_eq!(err.source_error().to_string(), "getter threw"); +} + +fn is_unassigned(err: &EncryptError<Refused>) -> bool { + term_error(err) == refused(NormalizeError::UnassignedCodePoint, "[1]") +} + +/// The walk ends before any leaf is sealed, so a value `Terms` refuses +/// reaches no cipher, even when its first element was fine. +#[test] +fn a_refused_walk_never_reaches_the_cipher() { + let doc = || vec!["ok", "\u{378}"]; + let cipher = Counting::default(); + let err = encrypt_with_terms(doc(), &cipher, "ctx").expect_err("refused"); + assert!(is_unassigned(&err), "{err:?}"); + assert_eq!(cipher.calls.load(Ordering::SeqCst), 0); +} + +/// `Terms` is public and works without `EncryptSink` in front of it, and +/// then refuses a value invalid for its logical type itself, as +/// encryption would. The refusal arrives through its partner's error type +/// as a source error. +#[test] +fn terms_alone_refuses_a_value_invalid_for_its_logical_type() { + use vitaminc_aead::Raw; + use vitaminc_normalize::Terms; + + // A scalar at the root has an empty path. + let mut out = Vec::new(); + let sink: Terms<'_, EncryptError<Refused>> = Terms::new(&mut out); + "Ada".visit(sink).expect("walks"); + assert_eq!(paths(&out), [""]); + + let mut out = Vec::new(); + let sink: Terms<'_, EncryptError<Refused>> = Terms::new(&mut out); + let err = Raw(Some(Logical::Undefined), Physical::Int(Int::I32(1))) + .visit(sink) + .expect_err("refused"); + let EncryptError::Source(source) = &err else { + panic!("{err:?}") + }; + let refusal = source + .inner() + .downcast_ref::<Refusal>() + .expect("refused for its shape"); + assert_eq!(refusal.reason(), Unencryptable::InvalidValue); + assert_eq!(refusal.path(), &Path::default()); + assert!(out.is_empty()); +} + +/// `EncryptSink` runs first in the `Tee`, so a value invalid for its +/// logical type is a shape error from encryption, not a normalize error. +#[test] +fn an_invalid_logical_value_is_refused_by_the_encrypt_sink_first() { + let invalid = vitaminc_aead::Raw(Some(Logical::Date), Physical::Text("2024-01-01")); + let err = plan_with_terms::<_, Refused>(invalid).expect_err("refused"); + assert!(matches!(err, EncryptError::Shape(_)), "{err:?}"); +} diff --git a/packages/vitaminc-normalize/tests/normalizer.rs b/packages/vitaminc-normalize/tests/normalizer.rs new file mode 100644 index 000000000..f76583f29 --- /dev/null +++ b/packages/vitaminc-normalize/tests/normalizer.rs @@ -0,0 +1,134 @@ +//! `Terms` under a normalizer of the caller's own: the walk is the same, +//! the terms are the normalizer's, and the skip-or-stop rule for a scalar +//! with no term is applied to what the normalizer returns. + +use std::collections::BTreeMap; + +use vitaminc_aead::plaintext::render; +use vitaminc_aead::{Encrypt, Int, Logical, Physical, Raw, Tee}; +use vitaminc_normalize::{ + domain, terms, terms_by, Equality, Normalize, NormalizeError, Normalized, Terms, TermsError, +}; +use vitaminc_protected::{Controlled, Protected}; + +/// Every int is one byte under a domain of its own; nothing else has a +/// term. +#[derive(Clone, Copy)] +struct LowByte; + +impl Normalize for LowByte { + type Term = Normalized; + + const INDEX: &'static str = "low byte"; + + fn normalize( + &self, + ty: Option<Logical>, + value: Physical<'_>, + ) -> Result<Normalized, NormalizeError> { + match (ty, value) { + (None, Physical::Int(i)) => Ok(Normalized { + domain: "test/low-byte/v1", + bytes: Protected::new(vec![i.to_i128().unwrap_or(0) as u8]), + }), + _ => Err(NormalizeError::NoDomain), + } + } +} + +fn doc() -> BTreeMap<&'static str, Raw<'static>> { + let mut doc = BTreeMap::new(); + doc.insert("a", Raw(None, Physical::Int(Int::I32(0x1_02)))); + doc.insert("b", Raw(None, Physical::Text("text"))); + doc.insert("c", Raw(None, Physical::Null)); + doc +} + +#[test] +fn the_terms_are_the_normalizers_and_the_walk_is_the_same() { + let found = terms_by(LowByte, doc()).expect("terms"); + assert_eq!(found.len(), 1, "text and null have no term under LowByte"); + assert_eq!(render(&found[0].path), ".a"); + assert_eq!(found[0].normalized.domain, "test/low-byte/v1"); + assert_eq!(found[0].normalized.bytes.risky_ref(), &[0x02]); + // `terms` is `terms_by(Equality, ..)`. + let equality = terms(doc()).expect("terms"); + let by_name = terms_by(Equality, doc()).expect("terms"); + assert_eq!(equality.len(), 3, "under equality the null has a term too"); + assert_eq!(equality.len(), by_name.len()); + assert_eq!( + equality[1].normalized.bytes.risky_ref(), + by_name[1].normalized.bytes.risky_ref() + ); +} + +#[test] +fn a_logical_type_the_normalizer_refuses_stops_the_walk() { + let mut doc = BTreeMap::new(); + doc.insert("d", Raw(Some(Logical::Date), Physical::Int(Int::I32(1)))); + let err = terms_by(LowByte, doc).expect_err("refused"); + let term = err.term().expect("refused by the normalizer"); + assert_eq!(term.error(), NormalizeError::NoDomain); + assert_eq!(render(term.path()), ".d"); + // The refusal names the normalizer's index, not equality. + assert_eq!(term.index(), "low byte"); + assert_eq!( + err.to_string(), + "no low byte term: no domain for this kind of value" + ); +} + +#[test] +fn two_normalizers_share_one_walk() { + let (mut equality, mut low) = (Vec::new(), Vec::new()); + doc() + .visit(Tee( + Terms::<TermsError>::new(&mut equality), + Terms::by(LowByte, &mut low), + )) + .expect("walk"); + assert_eq!( + equality.iter().map(|t| render(&t.path)).collect::<Vec<_>>(), + [".a", ".b", ".c"] + ); + assert_eq!( + low.iter().map(|t| render(&t.path)).collect::<Vec<_>>(), + [".a"] + ); +} + +/// A fixed-width `None` reaches the sink as a typed null. Under equality +/// it is indexed as a plain null, so the absent field has a term at its +/// own path under the null domain, and the walk carries on. A normalizer +/// that gives nulls no term still skips it. +#[test] +fn a_fixed_width_none_has_the_null_term_at_its_path_and_does_not_stop_the_walk() { + let mut doc = BTreeMap::new(); + doc.insert("gone", None::<i32>); + doc.insert("here", Some(5i32)); + let found = terms(doc).expect("a typed null does not stop the walk"); + assert_eq!( + found.iter().map(|t| render(&t.path)).collect::<Vec<_>>(), + [".gone", ".here"], + "the absent field has a term as the present one does" + ); + assert_eq!( + found[0].normalized.domain, + domain::NULL, + "the absent field's term is under the null domain" + ); + assert_eq!( + found[0].normalized.bytes.risky_ref(), + &[0x00], + "the absent field's term is the null's one byte" + ); + let plain = terms(BTreeMap::from([("gone", Raw(None, Physical::Null))])).expect("terms"); + assert_eq!( + plain[0].normalized.bytes.risky_ref(), + found[0].normalized.bytes.risky_ref(), + "a typed null and a plain null are one term" + ); + let by_name = terms_by(LowByte, BTreeMap::from([("gone", None::<i32>)])) + .expect("a typed null does not stop a normalizer of the caller's own"); + assert!(by_name.is_empty(), "a typed null has no term under LowByte"); +}