diff --git a/.changeset/eql-bindings-plaintext-by-reference.md b/.changeset/eql-bindings-plaintext-by-reference.md new file mode 100644 index 0000000000..674b2634ce --- /dev/null +++ b/.changeset/eql-bindings-plaintext-by-reference.md @@ -0,0 +1,10 @@ +--- +'@cipherstash/eql': minor +--- + +**eql-bindings reads every plaintext in place** (`stack-encrypt` feature). The EQL v4 types seal and index a plaintext without copying it, so a plaintext no longer needs `Clone`. + +- The `Ciphertext` and `Hmac256` targets, and the query twins, are bounded by `Encrypt + EncryptRef`, where they were bounded by `Encrypt + Clone`. A plaintext with only a by-value `Encrypt` impl adds `impl Encrypt for &T`. +- A query twin's plaintext is `Zeroize`, because a query hands its value to the index by value and wipes it. +- `v4::plaintext::Date`, `Timestamp`, and `Decimal` are Vitamin C's types, built from jiff's and rust_decimal's values. They are not `Clone`. +- The crate's `jiff` and `rust_decimal` features now only turn on `stack-encrypt`. That feature turns on both. diff --git a/.changeset/eql-v4-date-timestamp-numeric.md b/.changeset/eql-v4-date-timestamp-numeric.md index e47be979f5..c7899b0953 100644 --- a/.changeset/eql-v4-date-timestamp-numeric.md +++ b/.changeset/eql-v4-date-timestamp-numeric.md @@ -2,4 +2,4 @@ '@cipherstash/eql': minor --- -**Stack Encrypt produces the EQL v4 date, timestamp and numeric types `Date`, `DateEq`, `Timestamp`, `TimestampEq`, `Numeric` and `NumericEq`** (`eql-bindings`, `stack-encrypt` feature). Their Rust plaintexts are Stack Encrypt's `stack_encrypt::value::Date`, `Timestamp` and `Decimal`, re-exported as `v4::plaintext::Date`, `Timestamp` and `Decimal`. They hold the integers the engine stores (days since 1970-01-01; Unix seconds and nanoseconds; a mantissa and a scale), are range checked when built and are wiped when dropped. eql-bindings' `jiff` and `rust_decimal` features turn on Stack Encrypt's features of the same names, which convert to and from those crates' types. Dates are from `-009999-01-01` to `9999-12-31`, and instants from `-009999-01-02T01:59:59Z` to `9999-12-30T22:00:00.999999999Z`. `=` on `NumericEq` normalises the scale (`1.5 = 1.50`) and on `TimestampEq` compares to the microsecond, truncating (never rounding) the nanoseconds below it; each value decrypts as it was stored. The Go SDK's `encrypt/eql` table marks the six producible, from `encrypt.Date`, `time.Time` and `encrypt.Decimal`. +**Stack Encrypt produces the EQL v4 date, timestamp and numeric types `Date`, `DateEq`, `Timestamp`, `TimestampEq`, `Numeric` and `NumericEq`** (`eql-bindings`, `stack-encrypt` feature). Their Rust plaintexts are Vitamin C's `Date`, `Timestamp` and `Decimal`, which `stack_encrypt::value` re-exports, re-exported again as `v4::plaintext::Date`, `Timestamp` and `Decimal`. A `Date` is built from a jiff `civil::Date`, a `Timestamp` from a jiff `Timestamp`, and a `Decimal` from a rust_decimal `Decimal`, and each is read back as that type. None is `Clone`, and each is wiped when it is dropped. The `stack-encrypt` feature turns on jiff and rust_decimal, so the three types exist whenever it is on. Dates are from `-009999-01-01` to `9999-12-31`, and instants from `-009999-01-02T01:59:59Z` to `9999-12-30T22:00:00.999999999Z`. `=` on `NumericEq` normalises the scale (`1.5 = 1.50`) and on `TimestampEq` compares to the microsecond, truncating (never rounding) the nanoseconds below it; each value decrypts as it was stored. The Go SDK's `encrypt/eql` table marks the six producible, from `encrypt.Date`, `time.Time` and `encrypt.Decimal`. diff --git a/.changeset/eql-v4-ordered-date-timestamp-numeric.md b/.changeset/eql-v4-ordered-date-timestamp-numeric.md index d36ef0e085..9c7dd99294 100644 --- a/.changeset/eql-v4-ordered-date-timestamp-numeric.md +++ b/.changeset/eql-v4-ordered-date-timestamp-numeric.md @@ -2,4 +2,4 @@ '@cipherstash/eql': minor --- -**Stack Encrypt produces the EQL v4 ordered date, timestamp and numeric types** (`eql-bindings`, `stack-encrypt` feature): `DateOrd`, `DateOrdOpe`, `DateOrdOre`, `TimestampOrd`, `TimestampOrdOpe`, `TimestampOrdOre`, `NumericOrd`, `NumericOrdOpe` and `NumericOrdOre`. A date orders by its day, a timestamp by the microsecond (truncated, as `TimestampEq`'s `=` is) and a decimal by value, so `1.5` and `1.50` order as equal. `v4::plaintext::Date`, `Timestamp`, `Decimal` and `RangeError` are now Stack Encrypt's own types, re-exported at the same path. The Go SDK's `encrypt/eql` table marks the nine producible. +**Stack Encrypt produces the EQL v4 ordered date, timestamp and numeric types** (`eql-bindings`, `stack-encrypt` feature): `DateOrd`, `DateOrdOpe`, `DateOrdOre`, `TimestampOrd`, `TimestampOrdOpe`, `TimestampOrdOre`, `NumericOrd`, `NumericOrdOpe` and `NumericOrdOre`. A date orders by its day, a timestamp by the microsecond (truncated, as `TimestampEq`'s `=` is) and a decimal by value, so `1.5` and `1.50` order as equal. `v4::plaintext::Date`, `Timestamp` and `Decimal` are Vitamin C's types, re-exported through Stack Encrypt at the same path, with `OutOfRange` for a jiff `Timestamp` outside the range. The Go SDK's `encrypt/eql` table marks the nine producible. diff --git a/Cargo.lock b/Cargo.lock index 0ed8dfd1fd..3f84e775bb 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4483,12 +4483,15 @@ version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9a1d92d394e577ee424b4f35479a101896aecbce98f00c37bca5af1aa0d3b2c0" dependencies = [ + "jiff", + "rust_decimal", "thiserror 2.0.18", "unicode-general-category", "unicode-normalization", "vitaminc-aead 0.10.0", "vitaminc-context 0.10.0", "vitaminc-normalize", + "vitaminc-prf", "vitaminc-protected 0.10.0", "zeroize", ] diff --git a/Cargo.toml b/Cargo.toml index 21eca1577d..750f783762 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -152,6 +152,6 @@ vitaminc-hmac = "0.10.0" vitaminc-normalize = "0.10.0" # The text order key: the system ADR-0002's fold, pinned to Unicode 16, # which text ORE and OPE terms are derived over (ADR-0009). -vitaminc-ore = "0.10.0" +vitaminc-ore = { version = "0.10.0", features = ["prf"] } vitaminc-prf = { version = "0.10.0", features = ["normalize"] } vitaminc-protected = "0.10.0" diff --git a/conformance/stack-encrypt/values-contract.md b/conformance/stack-encrypt/values-contract.md index 90eb01bd31..2948a13c16 100644 --- a/conformance/stack-encrypt/values-contract.md +++ b/conformance/stack-encrypt/values-contract.md @@ -101,11 +101,11 @@ it and the engine stores an order term, but no dynamic operator reads it. This is a leak, not only a gap. Anyone who holds the stored rows can compare the order terms without a key. No query uses them. -The typed Rust path has the same fault. An order index needs only -`Orderable`, but its operators need `Ordered`, and `Vec` is not -`Ordered`. The fix is to refuse an order index on `bytes` when it is -declared, at compile time on the typed path. Data that Go rc.3 stored must -stay readable. Until then, this entry keeps the behaviour visible. +The typed Rust path refuses it. An order index is bounded by vitaminc-ore's +`Orderable`, which does not cover `Vec`, so an order index on bytes +does not compile. The fix for the declaration is to refuse an order index +on `bytes` there too. Data that Go rc.3 stored must stay readable. Until +then, this entry keeps the behaviour visible. `expected_error` cases are refused before any pending operation, with the structured diagnostic `code`, `reason` and `field`, and no key call. They diff --git a/docs/target-directed-encryption.md b/docs/target-directed-encryption.md index a96a5aed0e..387b076c97 100644 --- a/docs/target-directed-encryption.md +++ b/docs/target-directed-encryption.md @@ -1,7 +1,7 @@ # Target-directed encryption **Status:** design record, reconciled with the shipped API on 2026-08-28 and again on 2026-09-04 (contexts are vitaminc's `NonEmpty`; a caller's context *extends* a field's own; `row = ..` became `struct = ..`, and `from` exists only there). The snippets below are the API as it ships in `stack-encrypt` (cipherstash-suite #2146, #2147); the async shape is specified by [RFC 0002](rfcs/0002-async-shape-for-target-directed-encryption.md). -**Superseded in part:** the snippets record the design as it first shipped. Since then `EncryptFrom`, `DecryptInto`, `encrypt_as`, `decrypt_as`, the plan builder and the call chain were removed. The API that ships now is `EncryptTarget` and `DecryptSource` with `encrypt_into` and `decrypt_from`, field markers for queries, and `dynamic::Planned` for a declaration that is data. See the crate docs and `packages/stack-encrypt/CHANGELOG.md`. +**Superseded in part:** the snippets record the design as it first shipped. Since then `EncryptFrom`, `DecryptInto`, `encrypt_as`, `decrypt_as`, the plan builder and the call chain were removed. The API that ships now is `EncryptTarget` and `DecryptSource` with `encrypt_into` and `decrypt_from`, field markers for queries, and `dynamic::Planned` for a declaration that is data. See the crate docs and `packages/stack-encrypt/CHANGELOG.md`. Implementation note 1 below resolved to option 1, a `Clone` bound and one copy for each term. ADR 0014 (`packages/stack-encrypt/docs/adr/0014-operations-read-the-plaintext-and-at-most-one-takes-it.md`) replaced it with option 2: every operation reads the plaintext through a reference (`EncryptRef`), and nothing is copied. Note 2's term clones are gone with it. **Date:** 2026-08-21 **Scope:** vitaminc (primitives), stack-encrypt (the new trait + batching), eql-bindings (one class of targets) @@ -303,9 +303,9 @@ An earlier iteration had two traits, `EncryptInto` on the source and `Deri 2. Blanket `impl Encrypt for &T where T: Encrypt`. vitaminc already has `impl Encrypt for &str`, so the shape exists but is not systematic. 3. Derive hands ownership to the ciphertext field and borrows to the term fields. Cheapest; puts field-ordering knowledge into the macro. -**Resolved:** (1). `S: Encrypt + Clone` on the bridge; (2) later if the copies show up in a profile. +**Resolved:** (1). `S: Encrypt + Clone` on the bridge; (2) later if the copies show up in a profile. **Superseded by ADR 0014:** (2), through vitaminc's `EncryptRef`. No plaintext is copied. -**2. Fan-out and zeroize.** **Resolved, and narrower than proposed.** The source reaches k consumers, but only the ciphertext's copy lives in `Protected` — it is held inside the pending and wiped as it seals. Term clones are ordinary values consumed during the synchronous build and dropped before any I/O; they are not wrapped. So the custody widening is bounded to the build phase for terms and to the pending's lifetime for the ciphertext. Stated in the `stack_encrypt::target` rustdoc ("Plaintext fan-out"), as this section asked. +**2. Fan-out and zeroize.** **Resolved, and narrower than proposed. Superseded by ADR 0014: no term takes a clone.** The source reaches k consumers, but only the ciphertext's copy lives in `Protected` — it is held inside the pending and wiped as it seals. Term clones are ordinary values consumed during the synchronous build and dropped before any I/O; they are not wrapped. So the custody widening is bounded to the build phase for terms and to the pending's lifetime for the ciphertext. Stated in the `stack_encrypt::target` rustdoc ("Plaintext fan-out"), as this section asked. **3. Orphan rule.** `impl EncryptFrom for IntegerOrdOre` in eql-bindings is legal — `Self` is local. The reverse-direction sugar (`EncryptInto::encrypt_into` on `i64`) is a blanket impl over a local trait, also fine. Worth a compile test pinning both, since the layout puts the trait, the source type and the target type in three different crates. diff --git a/languages/golang/encrypt/guest/Cargo.lock b/languages/golang/encrypt/guest/Cargo.lock index 0a33c5123d..ef9930eb52 100644 --- a/languages/golang/encrypt/guest/Cargo.lock +++ b/languages/golang/encrypt/guest/Cargo.lock @@ -231,6 +231,30 @@ version = "0.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9e2211b0817f061502a8dd9f11a37e879e79763e3c698d2418cf824d8cb2f21e" +[[package]] +name = "borsh" +version = "1.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "553c5d846a6ba5150c65e3b1b8ec073bcf1abc20f9b7220de384a4443ea4e20a" +dependencies = [ + "borsh-derive", + "bytes", + "cfg_aliases", +] + +[[package]] +name = "borsh-derive" +version = "1.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12cdfe656708a01f89b451a7d36466e6fe6c414de0aa18fc54f864f6f9ca9f56" +dependencies = [ + "once_cell", + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 3.0.4", +] + [[package]] name = "bumpalo" version = "3.20.3" @@ -309,6 +333,12 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" +[[package]] +name = "cfg_aliases" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" + [[package]] name = "chacha20" version = "0.10.2" @@ -921,6 +951,18 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "libc", + "r-efi 5.3.0", + "wasip2", +] + [[package]] name = "getrandom" version = "0.4.3" @@ -930,7 +972,7 @@ dependencies = [ "cfg-if", "js-sys", "libc", - "r-efi", + "r-efi 6.0.0", "rand_core 0.10.1", "wasm-bindgen", ] @@ -1205,6 +1247,39 @@ version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" +[[package]] +name = "jiff" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5d126d72eb017f10b302e73bdeca446bea405ee449af4d9e7866d6b082d83e" +dependencies = [ + "jiff-core", + "jiff-static", + "portable-atomic", + "portable-atomic-util", +] + +[[package]] +name = "jiff-core" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6b46a105a9874634dd96231021526bf24ca04955a5998c59a9c7666e634b7b8" +dependencies = [ + "log", +] + +[[package]] +name = "jiff-static" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0127e9bde3c6130d6169e7d8d68676e4be69c4bf7573c308b6f960a5089c428" +dependencies = [ + "jiff-core", + "proc-macro2", + "quote", + "syn 3.0.4", +] + [[package]] name = "jobserver" version = "0.1.35" @@ -1542,6 +1617,21 @@ dependencies = [ "universal-hash", ] +[[package]] +name = "portable-atomic" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" + +[[package]] +name = "portable-atomic-util" +version = "0.2.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10ab3eb7f3becc3a1cbc4f2c6f20267996cfc1a6467a873763411b136a122715" +dependencies = [ + "portable-atomic", +] + [[package]] name = "potential_utf" version = "0.1.6" @@ -1652,6 +1742,12 @@ dependencies = [ "proc-macro2", ] +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + [[package]] name = "r-efi" version = "6.0.0" @@ -1671,10 +1767,20 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c" dependencies = [ "libc", - "rand_chacha", + "rand_chacha 0.3.1", "rand_core 0.6.4", ] +[[package]] +name = "rand" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41" +dependencies = [ + "rand_chacha 0.9.0", + "rand_core 0.9.5", +] + [[package]] name = "rand" version = "0.10.2" @@ -1696,6 +1802,16 @@ dependencies = [ "rand_core 0.6.4", ] +[[package]] +name = "rand_chacha" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +dependencies = [ + "ppv-lite86", + "rand_core 0.9.5", +] + [[package]] name = "rand_core" version = "0.6.4" @@ -1705,6 +1821,15 @@ dependencies = [ "getrandom 0.2.17", ] +[[package]] +name = "rand_core" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" +dependencies = [ + "getrandom 0.3.4", +] + [[package]] name = "rand_core" version = "0.10.1" @@ -1733,7 +1858,7 @@ dependencies = [ "hex-literal", "opaque-debug", "rand 0.8.8", - "rand_chacha", + "rand_chacha 0.3.1", "serde", "serde_cbor", "sha2 0.10.9", @@ -1829,6 +1954,23 @@ dependencies = [ "serde", ] +[[package]] +name = "rust_decimal" +version = "1.43.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7653272e75dcac41dc199fbea6f5797633994fafd339943c06c9af16bf29cd3a" +dependencies = [ + "arrayvec", + "borsh", + "bytes", + "num-traits", + "rand 0.8.8", + "rand 0.9.5", + "serde", + "serde_json", + "wasm-bindgen", +] + [[package]] name = "rustc_version" version = "0.4.1" @@ -2738,6 +2880,8 @@ checksum = "6fcccedca9d80812af295cba43dc2ac388f4fbb0415faa3ebec783d072d014d8" dependencies = [ "bytes", "futures-util", + "jiff", + "rust_decimal", "serde", "thiserror 2.0.20", "vitaminc-aead-derive 0.10.0", @@ -2860,12 +3004,15 @@ version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9a1d92d394e577ee424b4f35479a101896aecbce98f00c37bca5af1aa0d3b2c0" dependencies = [ + "jiff", + "rust_decimal", "thiserror 2.0.20", "unicode-general-category", "unicode-normalization", "vitaminc-aead 0.10.0", "vitaminc-context 0.10.0", "vitaminc-normalize", + "vitaminc-prf", "vitaminc-protected 0.10.0", "zeroize", ] @@ -3031,6 +3178,15 @@ version = "0.11.1+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" +[[package]] +name = "wasip2" +version = "1.0.4+wasi-0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" +dependencies = [ + "wit-bindgen", +] + [[package]] name = "wasm-bindgen" version = "0.2.129" @@ -3267,6 +3423,12 @@ dependencies = [ "memchr", ] +[[package]] +name = "wit-bindgen" +version = "0.57.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" + [[package]] name = "writeable" version = "0.6.4" diff --git a/packages/eql/Cargo.lock b/packages/eql/Cargo.lock index d6f1776e9e..e511cddeec 100644 --- a/packages/eql/Cargo.lock +++ b/packages/eql/Cargo.lock @@ -1173,7 +1173,9 @@ dependencies = [ "base85-simd", "eql-domains", "hex", + "jiff", "proptest", + "rust_decimal", "schemars", "serde", "serde_json", @@ -4225,11 +4227,9 @@ dependencies = [ "base85-simd", "clww-ore", "futures", - "jiff", "miette", "ore-rs 0.12.0", "rand 0.10.1", - "rust_decimal", "serde", "serde_json", "serdect", @@ -5238,12 +5238,15 @@ version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9a1d92d394e577ee424b4f35479a101896aecbce98f00c37bca5af1aa0d3b2c0" dependencies = [ + "jiff", + "rust_decimal", "thiserror 2.0.20", "unicode-general-category", "unicode-normalization", "vitaminc-aead 0.10.0", "vitaminc-context 0.10.0", "vitaminc-normalize", + "vitaminc-prf", "vitaminc-protected 0.10.0", "zeroize", ] diff --git a/packages/eql/crates/eql-bindings/CHANGELOG.md b/packages/eql/crates/eql-bindings/CHANGELOG.md index 412302ddb3..1ce2e2930f 100644 --- a/packages/eql/crates/eql-bindings/CHANGELOG.md +++ b/packages/eql/crates/eql-bindings/CHANGELOG.md @@ -359,6 +359,22 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Breaking +- **A plaintext no longer needs `Clone`** (#1734). The `Ciphertext` and + `Hmac256` targets and the query targets bound their plaintext on + `Encrypt + EncryptRef`, where it was `Encrypt + Clone`. `EncryptRef` + means `&T: Encrypt`. vitaminc's types and its derive provide it. +- **`v4::plaintext::Date`, `Timestamp`, and `Decimal` are vitaminc's + types** (#1734). The stored format is unchanged. + - Build a `Date` from a jiff `civil::Date`, a `Timestamp` from a jiff + `Timestamp`, and a `Decimal` from a rust_decimal `Decimal`, with + `new` or `From`. Read one back with `to_jiff` or `to_decimal`. + - The constructors from integers and the integer accessors are removed, + with `v4::plaintext::RangeError`. `Timestamp::new` returns + `v4::plaintext::OutOfRange`. + - None of the three is `Clone`. + - The `stack-encrypt` feature now depends on jiff and rust_decimal. The + `jiff` and `rust_decimal` features remain, and each only turns on + `stack-encrypt`. - **The EQL v4 types no longer implement `EncryptFrom` and `DecryptInto`** (#1661, #1662). Stack Encrypt removed those traits, with `encrypt_as`, `decrypt_as`, the plan builder and the query chain. Every type keeps diff --git a/packages/eql/crates/eql-bindings/Cargo.toml b/packages/eql/crates/eql-bindings/Cargo.toml index d287c8d011..e0f97fe6be 100644 --- a/packages/eql/crates/eql-bindings/Cargo.toml +++ b/packages/eql/crates/eql-bindings/Cargo.toml @@ -63,19 +63,26 @@ default = [] # The EQL v4 types as Stack Encrypt targets: `eql_bindings::v4`. Every # producible type implements `EncryptTarget` and `DecryptSource`, for a Rust # program that encrypts through `encrypt_into`. No `dynamic` layer. +# +# Turns on Stack Encrypt's `jiff` and `rust_decimal` features: the `date`, +# `timestamp` and `numeric` families take vitaminc's `Date`, `Timestamp` +# and `Decimal`, which exist only with them. stack-encrypt = [ "dep:stack-encrypt", + "stack-encrypt/jiff", + "stack-encrypt/rust_decimal", "dep:base64", "dep:base85-simd", "dep:hex", "dep:zeroize", "dep:thiserror", ] -# Conversions between jiff's `civil::Date` / `Timestamp` and -# `v4::plaintext::Date` / `Timestamp`. -jiff = ["stack-encrypt", "stack-encrypt/jiff"] -# Conversions between rust_decimal's `Decimal` and `v4::plaintext::Decimal`. -rust_decimal = ["stack-encrypt", "stack-encrypt/rust_decimal"] +# Both are the `stack-encrypt` feature under an older name, kept so a +# manifest that names one still resolves. `v4::plaintext::Date` and +# `Timestamp` are built from jiff's types, and `Decimal` from rust_decimal's, +# whenever `stack-encrypt` is on. +jiff = ["stack-encrypt"] +rust_decimal = ["stack-encrypt"] # The by-name dispatch a language binding needs (`encryption::targets`, # `v4::targets`): an EQL type named at run time, a `ValueFrame` plaintext, # and the target table a guest serializes. Turns on stack-encrypt's @@ -87,7 +94,7 @@ targets = [ ] [package.metadata.docs.rs] -features = ["targets", "jiff", "rust_decimal"] +features = ["targets"] [dev-dependencies] # Parity oracle: tests/catalog_parity.rs asserts the v3 domain inventory @@ -96,3 +103,7 @@ features = ["targets", "jiff", "rust_decimal"] eql-domains = { path = "../eql-domains" } # `encoding`'s round-trip properties. The version eql-domains uses. proptest = "1" +# The types `v4::plaintext::{Date, Timestamp, Decimal}` are built from, for +# the tests and doc examples that build one. +jiff = { version = "1.0.0", default-features = false } +rust_decimal = { version = "1", default-features = false } diff --git a/packages/eql/crates/eql-bindings/README.md b/packages/eql/crates/eql-bindings/README.md index bf54849022..ba27ffd57e 100644 --- a/packages/eql/crates/eql-bindings/README.md +++ b/packages/eql/crates/eql-bindings/README.md @@ -144,22 +144,27 @@ plaintext, or, for a date, a timestamp or a decimal, one of | `Boolean` | `bool` | | `Real`, `RealEq`, `RealOrd`, `RealOrdOpe`, `RealOrdOre` | `f32` | | `Double`, `DoubleEq`, `DoubleOrd`, `DoubleOrdOpe`, `DoubleOrdOre` | `f64` | -| `Date`, `DateEq` | `v4::plaintext::Date`: an `i32` of days since 1970-01-01 | -| `Timestamp`, `TimestampEq` | `v4::plaintext::Timestamp`: `i64` Unix seconds and `u32` nanoseconds, UTC, no leap seconds | -| `Numeric`, `NumericEq` | `v4::plaintext::Decimal`: an `i128` mantissa (below 2^96) and a `u8` scale (at most 28) | +| `Date`, `DateEq` | `v4::plaintext::Date`: a calendar date, built from jiff's `civil::Date` | +| `Timestamp`, `TimestampEq` | `v4::plaintext::Timestamp`: a UTC instant to the nanosecond, built from jiff's `Timestamp` | +| `Numeric`, `NumericEq` | `v4::plaintext::Decimal`: a mantissa (below 2^96) and a scale (at most 28), built from rust_decimal's `Decimal` | A date, a timestamp and a decimal have no Rust standard type, and jiff's -and rust_decimal's types cannot be wiped, so these three are this crate's -own. Each is built range checked (vitaminc's ranges, which are jiff's and -rust_decimal's: dates from `-009999-01-01` to `9999-12-31`, instants from -`-009999-01-02T01:59:59Z` to `9999-12-30T22:00:00.999999999Z`), refusing a -value outside them with an error that does not show it, and wipes its -integers when dropped. It is not `Copy`. The `jiff` and `rust_decimal` -features convert to and from jiff's `civil::Date` and `Timestamp` and -rust_decimal's `Decimal`; the value converted to is the caller's, and is not -wiped. One conversion can fail. jiff can make an instant before its own -`Timestamp::MIN` when it parses text with a UTC offset, and converting -that instant is refused. On `NumericEq`, +and rust_decimal's types cannot be wiped. So these three are vitaminc's +types, re-exported at `v4::plaintext`. + +- Each is built from the jiff or rust_decimal value: `Date::new`, + `Timestamp::new`, and `Decimal::new`. The ranges are jiff's and + rust_decimal's: dates from `-009999-01-01` to `9999-12-31`, instants from + `-009999-01-02T01:59:59Z` to `9999-12-30T22:00:00.999999999Z`. +- Each stores the value as integers and wipes them when dropped. None is + `Copy` or `Clone`. +- `to_jiff` and `to_decimal` return a jiff or rust_decimal value. That + value is the caller's. It is not wiped. +- `Timestamp::new` can fail. When jiff 1.0.0 parses text with a UTC + offset, it can make an instant before its own `Timestamp::MIN`. + `Timestamp::new` refuses that instant (`OutOfRange`). + +On `NumericEq`, `1.5 = 1.50` (the scale is normalised); on `TimestampEq`, an instant is truncated to the microsecond (the nanoseconds below it are dropped, not rounded), so two instants in the same microsecond are equal. Each opens as it was stored. Their ordered types order a date by its day, a timestamp by the microsecond (truncated, as on `TimestampEq`) and a decimal by value. @@ -665,20 +670,21 @@ async fn main() -> Result<(), Box> { // The field's context: the table, then the column. let column = Label::new(["users", "email"])?; - // The plaintext, as its transport frame. - let email = ValueFrame::of("alice@example.com")?; + // The plaintext, as its transport frame. A frame is moved into the call + // that uses it, and is not `Clone`, so each call is given its own. + let email = || ValueFrame::of("alice@example.com"); // Each call names the type, and returns the EQL value as JSON bytes. - let stored: Vec = targets::encrypt("TextEq", &keyset, &column, email.clone())?.await?; + let stored: Vec = targets::encrypt("TextEq", &keyset, &column, email()?)?.await?; // A query also names the index that answers its operator. let index = IndexSpec::Equality; - let probe: Vec = targets::query("TextEq", &index, &keyset, &column, email.clone())?.await?; + let probe: Vec = targets::query("TextEq", &index, &keyset, &column, email()?)?.await?; let stored_value: TextEq = serde_json::from_slice(&stored)?; let query: TextEqQuery = serde_json::from_slice(&probe)?; assert_eq!(query.hm, stored_value.hm); let opened: ValueFrame = targets::decrypt("TextEq", &cipher, &column, &stored)?.await?; - assert_eq!(opened, email); + assert_eq!(opened, email()?); Ok(()) } ``` diff --git a/packages/eql/crates/eql-bindings/src/encryption.rs b/packages/eql/crates/eql-bindings/src/encryption.rs index 6cf6f9b975..c3ed40c1e3 100644 --- a/packages/eql/crates/eql-bindings/src/encryption.rs +++ b/packages/eql/crates/eql-bindings/src/encryption.rs @@ -118,8 +118,8 @@ use stack_encrypt::target::{ }; use stack_encrypt::{ CipherText, ContextPiece, Decrypt, DecryptField, Decryptable, Decryption, Describe, - Description, Encrypt, Encryption, Error, IntoContext, MaybeEmpty, NonEmpty, SealedValue, - StackCipherText, + Description, Encrypt, EncryptRef, Encryption, Error, IntoContext, MaybeEmpty, NonEmpty, + SealedValue, StackCipherText, }; use zeroize::Zeroize; @@ -261,10 +261,10 @@ impl Reader for Ciphertext { // AEAD (authenticated encryption) half of the context, as Stack Encrypt's own // `StackCipherText` does. // -// The borrowed form clones the plaintext to seal it. The owned form is Stack +// The borrowed form reads the plaintext in place. The owned form is Stack // Encrypt's own owned form of `StackCipherText`: it moves the value into the -// seal, with no copy, and wipes it when the context is refused. -impl EncryptTarget for Ciphertext { +// seal, and wipes it when the context is refused. +impl EncryptTarget for Ciphertext { type ContextInput = RequiredContext; fn encryption<'s, K: 'static>() -> Encryption<'s, S, Self, K, Self::ContextInput> where @@ -334,7 +334,7 @@ impl Transcode for Hmac256 { EqualityVisitor } } -impl EncryptTarget for Hmac256 { +impl EncryptTarget for Hmac256 { type ContextInput = RequiredContext; fn encryption<'s, K: 'static>() -> Encryption<'s, S, Self, K, Self::ContextInput> where diff --git a/packages/eql/crates/eql-bindings/src/encryption/query.rs b/packages/eql/crates/eql-bindings/src/encryption/query.rs index eee6e8f51c..3570ca5a29 100644 --- a/packages/eql/crates/eql-bindings/src/encryption/query.rs +++ b/packages/eql/crates/eql-bindings/src/encryption/query.rs @@ -182,8 +182,9 @@ use serde::{Serialize, Serializer}; use stack_encrypt::kms::MaybeSend; use stack_encrypt::op::{self, Limit, Probabilistic, QueryTerm, QueryToken, Stats, Supports}; use stack_encrypt::sem::{EqualityTerm, MatchQuery, MatchTerms, QueryTokens}; -use stack_encrypt::target::{CallerContext, ConsumeSource, Encryption, Index, IndexSpec}; -use stack_encrypt::{Encrypt, Equality, Error, Label, Match, NonEmpty}; +use stack_encrypt::target::{CallerContext, Encryption, Index, IndexSpec, WipeSource}; +use stack_encrypt::{Encrypt, EncryptRef, Equality, Error, Label, Match, NonEmpty}; +use zeroize::Zeroize; use super::{bloom_filter, hmac256, EqlMatch}; use crate::v3::terms::{BloomFilter, Hmac256}; @@ -258,7 +259,7 @@ impl, Q> Index for TwinIndex { fn spec(&self) -> IndexSpec { self.index.spec() } - fn operation<'s, K: 'static, M: ConsumeSource<'s, S>>( + fn operation<'s, K: 'static, M: WipeSource<'s, S>>( &self, ) -> Encryption<'s, S, Self::Term, K, CallerContext, M> where @@ -334,7 +335,7 @@ fn column(token: &QueryToken) -> Identifier { impl Supports for TwinIndex where Q: QueryTwin + QueryTerm + MaybeSend + 'static, - Q::Plaintext: Encrypt + Clone + 'static, + Q::Plaintext: Encrypt + EncryptRef + Zeroize + 'static, { type Query = Q; type Verifier = (); @@ -358,7 +359,7 @@ where impl Supports for TwinIndex, Q> where Q: QueryTwin + MaybeSend + 'static, - Q::Plaintext: AsRef + 'static, + Q::Plaintext: AsRef + Zeroize + 'static, { type Query = MatchTwin; type Verifier = QueryTokens; diff --git a/packages/eql/crates/eql-bindings/src/v4/plaintext.rs b/packages/eql/crates/eql-bindings/src/v4/plaintext.rs index f455f3c6d6..94397a6ff1 100644 --- a/packages/eql/crates/eql-bindings/src/v4/plaintext.rs +++ b/packages/eql/crates/eql-bindings/src/v4/plaintext.rs @@ -2,13 +2,11 @@ //! families. //! //! The first three are a calendar date, a UTC instant and a decimal -//! number. These are Stack Encrypt's own types, re-exported here; see -//! [`stack_encrypt::value`] for what they hold, how they are wiped, and how -//! their equality and order terms treat a decimal's scale and a -//! timestamp's nanoseconds. -//! -//! With the `jiff` and `rust_decimal` features each converts to and from -//! jiff's `civil::Date` and `Timestamp`, or rust_decimal's `Decimal`. +//! number. These are vitaminc's types, re-exported here. Each is built +//! from jiff's `civil::Date` or `Timestamp`, or rust_decimal's `Decimal`. +//! See [`stack_encrypt::value`] for how they are wiped, and how their +//! equality and order terms treat a decimal's scale and a timestamp's +//! nanoseconds. //! //! The plaintext of the `json` family's storage-only type is //! [`JsonPlaintext`]: a JSON document that is wiped when it is dropped, and @@ -18,10 +16,10 @@ //! ``` //! use eql_bindings::v4::plaintext::Date; //! -//! let day = Date::from_days_since_epoch(19_782)?; // 2024-02-29 -//! assert_eq!(day.days_since_epoch(), 19_782); -//! # Ok::<(), eql_bindings::v4::plaintext::RangeError>(()) +//! let leap_day = jiff::civil::date(2024, 2, 29); +//! let date = Date::new(leap_day); +//! assert_eq!(date.to_jiff(), leap_day); //! ``` pub use stack_encrypt::json::{JsonPlaintext, JsonTextError}; -pub use stack_encrypt::value::{Date, Decimal, RangeError, Timestamp}; +pub use stack_encrypt::value::{Date, Decimal, OutOfRange, Timestamp}; diff --git a/packages/eql/tests/encryption/tests/common/mod.rs b/packages/eql/tests/encryption/tests/common/mod.rs index 3b58fcc35f..64db54f1c5 100644 --- a/packages/eql/tests/encryption/tests/common/mod.rs +++ b/packages/eql/tests/encryption/tests/common/mod.rs @@ -99,3 +99,30 @@ pub fn index_of(name: &str) -> stack_encrypt::target::IndexSpec { .and_then(|key| IndexSpec::parse(key)) .unwrap_or(IndexSpec::Equality) } + +/// The date `days` days after 1970-01-01, as the plaintext the `date` +/// family takes. +#[allow(dead_code)] +pub fn date_of_days(days: i32) -> eql_bindings::v4::plaintext::Date { + let day = jiff::civil::date(1970, 1, 1) + .checked_add(jiff::Span::new().days(days)) + .expect("a day in jiff's range"); + eql_bindings::v4::plaintext::Date::new(day) +} + +/// The instant `seconds` after the Unix epoch plus `nanoseconds`, as the +/// plaintext the `timestamp` family takes. +#[allow(dead_code)] +pub fn timestamp_of(seconds: i64, nanoseconds: i32) -> eql_bindings::v4::plaintext::Timestamp { + let instant = jiff::Timestamp::new(seconds, nanoseconds).expect("an instant in jiff's range"); + eql_bindings::v4::plaintext::Timestamp::new(instant).expect("an instant in range") +} + +/// The number `mantissa × 10^-scale`, as the plaintext the `numeric` +/// family takes. +#[allow(dead_code)] +pub fn decimal_of(mantissa: i128, scale: u32) -> eql_bindings::v4::plaintext::Decimal { + eql_bindings::v4::plaintext::Decimal::new(rust_decimal::Decimal::from_i128_with_scale( + mantissa, scale, + )) +} diff --git a/packages/eql/tests/encryption/tests/heap_hygiene.rs b/packages/eql/tests/encryption/tests/heap_hygiene.rs index 3e564efefa..480016a765 100644 --- a/packages/eql/tests/encryption/tests/heap_hygiene.rs +++ b/packages/eql/tests/encryption/tests/heap_hygiene.rs @@ -835,9 +835,9 @@ mod owned_seals { json!({"long": text, "short": marked("short")}) } - /// The owned forms do not copy the document: each makes one block - /// fewer of the length of the document's long string than the borrowed - /// form of the same type, which copies the document once. + /// No form copies the document: the owned form and the borrowed form of + /// each type make the same number of blocks of the length of the + /// document's long string. #[test] fn a_document_sealed_by_value_is_not_copied() { let rt = runtime(); @@ -864,10 +864,8 @@ mod owned_seals { }); }); assert_eq!( - borrowed, - owned + 1, - "JsonTreeDocument: the borrowed form copies the document once and the owned \ - form does not (borrowed {borrowed}, owned {owned})" + borrowed, owned, + "JsonTreeDocument: neither form copies the document (borrowed {borrowed}, owned {owned})" ); let source = JsonPlaintext::from(long()); @@ -894,10 +892,8 @@ mod owned_seals { }); }); assert_eq!( - borrowed, - owned + 1, - "Json: the borrowed form copies the document once and the owned form does not \ - (borrowed {borrowed}, owned {owned})" + borrowed, owned, + "Json: neither form copies the document (borrowed {borrowed}, owned {owned})" ); } } diff --git a/packages/eql/tests/encryption/tests/json_tree_owned.rs b/packages/eql/tests/encryption/tests/json_tree_owned.rs index 933f388bd0..7e3063c092 100644 --- a/packages/eql/tests/encryption/tests/json_tree_owned.rs +++ b/packages/eql/tests/encryption/tests/json_tree_owned.rs @@ -248,7 +248,7 @@ mod given_the_rows_of_a_read { mod given_a_document_that_is_a_field_of_a_record { use super::*; - #[derive(Clone, Zeroize)] + #[derive(Zeroize)] struct Lead { profile: JsonPlaintext, } diff --git a/packages/eql/tests/encryption/tests/record_fields.rs b/packages/eql/tests/encryption/tests/record_fields.rs index bcdeade027..6e59d31e36 100644 --- a/packages/eql/tests/encryption/tests/record_fields.rs +++ b/packages/eql/tests/encryption/tests/record_fields.rs @@ -176,7 +176,7 @@ async fn a_query_from_the_field_reference_gives_the_stored_term() { assert_ne!(other.hm, stored.email.hm); } -#[derive(Clone, Zeroize)] +#[derive(Zeroize)] struct Contact { email: String, name: String, @@ -534,7 +534,7 @@ async fn an_eql_field_opens_only_under_the_scope_and_the_binding_it_was_sealed_u assert_eq!(calls.lock().unwrap().retrieve.len(), before); } -#[derive(Clone, Zeroize)] +#[derive(Zeroize)] struct Lead { email: String, profile: JsonPlaintext, @@ -704,7 +704,7 @@ async fn the_derive_and_a_data_plan_write_the_same_row_under_a_scope_and_a_bindi assert_ne!(term(43).await.hm, derived.email.hm); } -#[derive(Clone, Zeroize)] +#[derive(Zeroize)] struct Note { id: u128, tenant: u64, @@ -1003,7 +1003,7 @@ async fn a_json_document_encrypts_from_a_json_plaintext() { assert_eq!(calls.lock().unwrap().retrieve.len(), before); } -#[derive(Clone, Zeroize)] +#[derive(Zeroize)] struct Customer { id: u64, profile: JsonPlaintext, diff --git a/packages/eql/tests/encryption/tests/typed_queries.rs b/packages/eql/tests/encryption/tests/typed_queries.rs index ec2b7caa94..a3ff25b286 100644 --- a/packages/eql/tests/encryption/tests/typed_queries.rs +++ b/packages/eql/tests/encryption/tests/typed_queries.rs @@ -86,7 +86,7 @@ fn typed_bytes(query: &Q) -> (Vec, String) { /// One plaintext for each EQL type that answers an operator. Each field is /// named after its type, and the name is its column. -#[derive(Clone, Zeroize)] +#[derive(Zeroize)] struct Columns { text_eq: String, integer_eq: i32, @@ -125,9 +125,9 @@ fn columns() -> Columns { text_eq: "bob@example.com".into(), integer_eq: -42, smallint_eq: -7, - date_eq: Date::from_days_since_epoch(19_000).expect("a day in range"), - timestamp_eq: Timestamp::new(1_700_000_000, 123_456_789).expect("an instant in range"), - numeric_eq: Decimal::new(-1_234_567, 4).expect("a decimal in range"), + date_eq: common::date_of_days(19_000), + timestamp_eq: common::timestamp_of(1_700_000_000, 123_456_789), + numeric_eq: common::decimal_of(-1_234_567, 4), bigint_eq: i64::MIN + 1, real_eq: -0.0, double_eq: f64::NAN, @@ -144,21 +144,21 @@ struct Typed { input: ValueFrame, } -/// The query `$field reference.$operator($value)` under `$keyset`, with `$value` as -/// the data path's input. +/// The query `$field reference.$operator(value)` under `$keyset`, where +/// `value` is the row's `$field`, with the same value as the data path's +/// input. The row is built twice: a plaintext is not `Clone`. macro_rules! typed { - ($keyset:expr, $reference:expr, $operator:ident, $value:expr) => {{ + ($keyset:expr, $reference:expr, $operator:ident, $field:ident) => {{ let reference = $reference; - let value = $value; let query = reference - .$operator(value.clone()) + .$operator(columns().$field) .encrypt($keyset) .await .unwrap(); Typed { bytes: typed_bytes(&query), column: reference.name(), - input: frame(value), + input: frame(columns().$field), } }}; } @@ -170,17 +170,17 @@ macro_rules! typed { async fn typed_and_input(keyset: &Keyset<'_>, name: &str, operator: &str) -> Typed { let row = columns(); match (name, operator) { - ("TextEq", "eq") => typed!(keyset, EncryptedColumns::TEXT_EQ, eq, row.text_eq), - ("IntegerEq", "eq") => typed!(keyset, EncryptedColumns::INTEGER_EQ, eq, row.integer_eq), - ("SmallintEq", "eq") => typed!(keyset, EncryptedColumns::SMALLINT_EQ, eq, row.smallint_eq), - ("DateEq", "eq") => typed!(keyset, EncryptedColumns::DATE_EQ, eq, row.date_eq), + ("TextEq", "eq") => typed!(keyset, EncryptedColumns::TEXT_EQ, eq, text_eq), + ("IntegerEq", "eq") => typed!(keyset, EncryptedColumns::INTEGER_EQ, eq, integer_eq), + ("SmallintEq", "eq") => typed!(keyset, EncryptedColumns::SMALLINT_EQ, eq, smallint_eq), + ("DateEq", "eq") => typed!(keyset, EncryptedColumns::DATE_EQ, eq, date_eq), ("TimestampEq", "eq") => { - typed!(keyset, EncryptedColumns::TIMESTAMP_EQ, eq, row.timestamp_eq) + typed!(keyset, EncryptedColumns::TIMESTAMP_EQ, eq, timestamp_eq) } - ("NumericEq", "eq") => typed!(keyset, EncryptedColumns::NUMERIC_EQ, eq, row.numeric_eq), - ("BigintEq", "eq") => typed!(keyset, EncryptedColumns::BIGINT_EQ, eq, row.bigint_eq), - ("RealEq", "eq") => typed!(keyset, EncryptedColumns::REAL_EQ, eq, row.real_eq), - ("DoubleEq", "eq") => typed!(keyset, EncryptedColumns::DOUBLE_EQ, eq, row.double_eq), + ("NumericEq", "eq") => typed!(keyset, EncryptedColumns::NUMERIC_EQ, eq, numeric_eq), + ("BigintEq", "eq") => typed!(keyset, EncryptedColumns::BIGINT_EQ, eq, bigint_eq), + ("RealEq", "eq") => typed!(keyset, EncryptedColumns::REAL_EQ, eq, real_eq), + ("DoubleEq", "eq") => typed!(keyset, EncryptedColumns::DOUBLE_EQ, eq, double_eq), ("TextMatch", "matches") => { let reference = EncryptedColumns::TEXT_MATCH; let query: MatchTwin = reference @@ -424,7 +424,7 @@ async fn a_field_reference_match_query_verifies_and_sizes_as_the_data_path_does( &plan, "value", Op::Matches, - input.clone(), + again(&input), page, &EqlTargets, ) @@ -664,3 +664,9 @@ async fn a_record_stores_a_null_in_an_eql_field_as_its_plan_says() { .unwrap(); assert_eq!(opened.risky_ref(), frame(&source).risky_ref()); } + +/// A second frame of the same bytes. A frame is not `Clone`. +fn again(frame: &ValueFrame) -> ValueFrame { + use stack_encrypt::AsProtectedRef as _; + ValueFrame::from_bytes(frame.as_protected_ref()).unwrap() +} diff --git a/packages/eql/tests/encryption/tests/v4_date_time_numeric.rs b/packages/eql/tests/encryption/tests/v4_date_time_numeric.rs index be6e301ca9..0aca9f7e23 100644 --- a/packages/eql/tests/encryption/tests/v4_date_time_numeric.rs +++ b/packages/eql/tests/encryption/tests/v4_date_time_numeric.rs @@ -107,23 +107,21 @@ async fn dates_round_trip_and_seal_the_leaf_a_jiff_date_seals() { let keyset = cipher.default_keyset(); for text in ["2024-02-29", "1969-12-31", "0001-01-01", "1970-01-01"] { let theirs = day(text); - let value = Date::from(theirs); - let stored: date::Date = value - .clone() + let value = || Date::from(theirs); + let stored: date::Date = value() .encrypt_into_with_context(&keyset, column()) .await .unwrap(); let opened = Date::decrypt_from_with_context(stored.clone(), &cipher, column()) .await .unwrap(); - assert_eq!(CivilDate::from(&opened), theirs, "{text}"); + assert_eq!(opened.to_jiff(), theirs, "{text}"); assert!( same(&as_frame(&cipher, stored.c.clone()).await, &frame(theirs)), "{text}: the leaf a jiff civil::Date seals" ); - let searchable: date::DateEq = value - .clone() + let searchable: date::DateEq = value() .encrypt_into_with_context(&keyset, column()) .await .unwrap(); @@ -148,7 +146,7 @@ async fn dates_round_trip_and_seal_the_leaf_a_jiff_date_seals() { let opened = Date::decrypt_from_with_context(stored, &cipher, column()) .await .unwrap(); - assert_eq!(CivilDate::from(&opened), edge); + assert_eq!(opened.to_jiff(), edge); } } @@ -162,23 +160,21 @@ async fn timestamps_round_trip_to_the_nanosecond_and_seal_the_leaf_a_jiff_timest "1970-01-01T00:00:00Z", ] { let theirs = instant(text); - let value = Timestamp::try_from(theirs).unwrap(); - let stored: timestamp::Timestamp = value - .clone() + let value = || Timestamp::try_from(theirs).unwrap(); + let stored: timestamp::Timestamp = value() .encrypt_into_with_context(&keyset, column()) .await .unwrap(); let opened = Timestamp::decrypt_from_with_context(stored.clone(), &cipher, column()) .await .unwrap(); - assert_eq!(jiff::Timestamp::from(&opened), theirs, "{text}"); + assert_eq!(opened.to_jiff(), theirs, "{text}"); assert!( same(&as_frame(&cipher, stored.c.clone()).await, &frame(theirs)), "{text}: the leaf a jiff Timestamp seals" ); - let searchable: timestamp::TimestampEq = value - .clone() + let searchable: timestamp::TimestampEq = value() .encrypt_into_with_context(&keyset, column()) .await .unwrap(); @@ -187,11 +183,7 @@ async fn timestamps_round_trip_to_the_nanosecond_and_seal_the_leaf_a_jiff_timest let opened = Timestamp::decrypt_from_with_context(searchable, &cipher, column()) .await .unwrap(); - assert_eq!( - jiff::Timestamp::from(&opened), - theirs, - "{text}: nanoseconds kept" - ); + assert_eq!(opened.to_jiff(), theirs, "{text}: nanoseconds kept"); } for edge in [jiff::Timestamp::MIN, jiff::Timestamp::MAX] { let stored: timestamp::TimestampEq = Timestamp::try_from(edge) @@ -202,7 +194,7 @@ async fn timestamps_round_trip_to_the_nanosecond_and_seal_the_leaf_a_jiff_timest let opened = Timestamp::decrypt_from_with_context(stored, &cipher, column()) .await .unwrap(); - assert_eq!(jiff::Timestamp::from(&opened), edge); + assert_eq!(opened.to_jiff(), edge); } } @@ -218,27 +210,21 @@ async fn decimals_round_trip_with_their_scale_and_seal_the_leaf_rust_decimal_sea "-0.0000000000000000000000000001", ] { let theirs = number(text); - let value = Decimal::from(theirs); - let stored: numeric::Numeric = value - .clone() + let value = || Decimal::from(theirs); + let stored: numeric::Numeric = value() .encrypt_into_with_context(&keyset, column()) .await .unwrap(); let opened = Decimal::decrypt_from_with_context(stored.clone(), &cipher, column()) .await .unwrap(); - assert_eq!( - rust_decimal::Decimal::from(&opened).to_string(), - text, - "the scale is kept" - ); + assert_eq!(opened.to_decimal().to_string(), text, "the scale is kept"); assert!( same(&as_frame(&cipher, stored.c.clone()).await, &frame(theirs)), "{text}: the leaf a rust_decimal Decimal seals" ); - let searchable: numeric::NumericEq = value - .clone() + let searchable: numeric::NumericEq = value() .encrypt_into_with_context(&keyset, column()) .await .unwrap(); @@ -316,22 +302,12 @@ async fn equality_terms_follow_the_baseline() { // A date, an instant and a number are separate domains: the same // integer underneath is no match. assert_ne!( - hm( - &keyset, - "DateEq", - frame(Date::from_days_since_epoch(0).unwrap()) - ) - .await, - hm(&keyset, "TimestampEq", frame(Timestamp::new(0, 0).unwrap())).await + hm(&keyset, "DateEq", frame(Date::from(day("1970-01-01")))).await, + hm(&keyset, "TimestampEq", frame(Timestamp::default())).await ); assert_ne!( - hm( - &keyset, - "DateEq", - frame(Date::from_days_since_epoch(0).unwrap()) - ) - .await, - hm(&keyset, "NumericEq", frame(Decimal::new(0, 0).unwrap())).await + hm(&keyset, "DateEq", frame(Date::from(day("1970-01-01")))).await, + hm(&keyset, "NumericEq", frame(Decimal::from(number("0")))).await ); } @@ -473,43 +449,37 @@ fn postgres_stores_and_finds_date_timestamp_and_numeric_rows() { ]; for (id, d, t, n) in rows { let (opened, due, created, posted, total, amount) = runtime.block_on(async { - let d = Date::from(day(d)); - let t = Timestamp::try_from(instant(t)).unwrap(); - let n = Decimal::from(number(n)); + let d = || Date::from(day(d)); + let t = || Timestamp::try_from(instant(t)).unwrap(); + let n = || Decimal::from(number(n)); ( json( - &d.clone() - .encrypt_into_with_context::(&keyset, column()) + &d().encrypt_into_with_context::(&keyset, column()) .await .unwrap(), ), json( - &d.clone() - .encrypt_into_with_context::(&keyset, column()) + &d().encrypt_into_with_context::(&keyset, column()) .await .unwrap(), ), json( - &t.clone() - .encrypt_into_with_context::(&keyset, column()) + &t().encrypt_into_with_context::(&keyset, column()) .await .unwrap(), ), json( - &t.clone() - .encrypt_into_with_context::(&keyset, column()) + &t().encrypt_into_with_context::(&keyset, column()) .await .unwrap(), ), json( - &n.clone() - .encrypt_into_with_context::(&keyset, column()) + &n().encrypt_into_with_context::(&keyset, column()) .await .unwrap(), ), json( - &n.clone() - .encrypt_into_with_context::(&keyset, column()) + &n().encrypt_into_with_context::(&keyset, column()) .await .unwrap(), ), @@ -540,11 +510,10 @@ fn postgres_stores_and_finds_date_timestamp_and_numeric_rows() { .collect() }; let date_query = |text: &str| { - let value = Date::from(day(text)); + let value = || Date::from(day(text)); runtime.block_on(async { json( - &value - .clone() + &value() .encrypt_into_with_context::(&keyset, column()) .await .unwrap(), @@ -552,11 +521,10 @@ fn postgres_stores_and_finds_date_timestamp_and_numeric_rows() { }) }; let timestamp_query = |text: &str| { - let value = Timestamp::try_from(instant(text)).unwrap(); + let value = || Timestamp::try_from(instant(text)).unwrap(); runtime.block_on(async { json( - &value - .clone() + &value() .encrypt_into_with_context::(&keyset, column()) .await .unwrap(), @@ -564,11 +532,10 @@ fn postgres_stores_and_finds_date_timestamp_and_numeric_rows() { }) }; let numeric_query = |text: &str| { - let value = Decimal::from(number(text)); + let value = || Decimal::from(number(text)); runtime.block_on(async { json( - &value - .clone() + &value() .encrypt_into_with_context::(&keyset, column()) .await .unwrap(), @@ -631,7 +598,7 @@ fn postgres_stores_and_finds_date_timestamp_and_numeric_rows() { ) .await .unwrap(); - assert_eq!(CivilDate::from(&opened), day("2024-02-29")); + assert_eq!(opened.to_jiff(), day("2024-02-29")); let created = Timestamp::decrypt_from_with_context( serde_json::from_str::(&created).unwrap(), &cipher, @@ -639,7 +606,7 @@ fn postgres_stores_and_finds_date_timestamp_and_numeric_rows() { ) .await .unwrap(); - assert_eq!(created.nanoseconds(), 123_456_999); + assert_eq!(created.to_jiff().subsec_nanosecond(), 123_456_999); let total = Decimal::decrypt_from_with_context( serde_json::from_str::(&total).unwrap(), &cipher, @@ -647,7 +614,7 @@ fn postgres_stores_and_finds_date_timestamp_and_numeric_rows() { ) .await .unwrap(); - assert_eq!(rust_decimal::Decimal::from(&total).to_string(), "1.50"); + assert_eq!(total.to_decimal().to_string(), "1.50"); }); // The storage-only columns have no equality operator. @@ -741,7 +708,7 @@ mod go_ledger { ) .await .unwrap(); - assert_eq!(CivilDate::from(&opened), day(&p.opened), "row {id} opened"); + assert_eq!(opened.to_jiff(), day(&p.opened), "row {id} opened"); let due = Date::decrypt_from_with_context( parsed::(row, "due"), cipher, @@ -749,7 +716,7 @@ mod go_ledger { ) .await .unwrap(); - assert_eq!(CivilDate::from(&due), day(&p.due), "row {id} due"); + assert_eq!(due.to_jiff(), day(&p.due), "row {id} due"); let created = Timestamp::decrypt_from_with_context( parsed::(row, "created"), cipher, @@ -757,11 +724,7 @@ mod go_ledger { ) .await .unwrap(); - assert_eq!( - jiff::Timestamp::from(&created), - instant(&p.created), - "row {id} created" - ); + assert_eq!(created.to_jiff(), instant(&p.created), "row {id} created"); let posted = Timestamp::decrypt_from_with_context( parsed::(row, "posted"), cipher, @@ -769,11 +732,7 @@ mod go_ledger { ) .await .unwrap(); - assert_eq!( - jiff::Timestamp::from(&posted), - instant(&p.posted), - "row {id} posted" - ); + assert_eq!(posted.to_jiff(), instant(&p.posted), "row {id} posted"); let total = Decimal::decrypt_from_with_context( parsed::(row, "total"), cipher, @@ -782,7 +741,7 @@ mod go_ledger { .await .unwrap(); assert_eq!( - rust_decimal::Decimal::from(&total).to_string(), + total.to_decimal().to_string(), p.total, "row {id} total keeps its scale" ); @@ -794,7 +753,7 @@ mod go_ledger { .await .unwrap(); assert_eq!( - rust_decimal::Decimal::from(&amount).to_string(), + amount.to_decimal().to_string(), p.amount, "row {id} amount keeps its scale" ); @@ -937,10 +896,9 @@ fn leaf_len(c: &Ciphertext) -> usize { async fn a_storage_only_type_stores_a_none_as_long_as_a_value() { let (cipher, _) = common::cipher().await; let keyset = cipher.default_keyset(); - let value = Date::from(day("2024-02-29")); + let value = || Date::from(day("2024-02-29")); - let present: date::Date = value - .clone() + let present: date::Date = value() .encrypt_into_with_context(&keyset, column()) .await .unwrap(); @@ -960,7 +918,7 @@ async fn a_storage_only_type_stores_a_none_as_long_as_a_value() { let refused = Date::decrypt_from_with_context(absent.clone(), &cipher, column()).await; assert!(refused.is_err(), "a None does not open as a value"); - let some: date::Date = Some(value.clone()) + let some: date::Date = Some(value()) .encrypt_into_with_context(&keyset, column()) .await .unwrap(); @@ -968,7 +926,7 @@ async fn a_storage_only_type_stores_a_none_as_long_as_a_value() { .await .unwrap(); assert_eq!( - CivilDate::from(&opened), + opened.to_jiff(), day("2024-02-29"), "Some seals the plaintext's own leaf" ); @@ -976,14 +934,14 @@ async fn a_storage_only_type_stores_a_none_as_long_as_a_value() { .await .unwrap(); assert_eq!( - opened.as_ref().map(CivilDate::from), + opened.as_ref().map(Date::to_jiff), Some(day("2024-02-29")), "and an Option opens a value" ); let null = stack_encrypt::Protected::new([0x00u8]); let null = ValueFrame::from_bytes(null.as_protected_ref().as_ref_of()).unwrap(); - let named: date::Date = by_name(&keyset, "Date", null.clone()).await; + let named: date::Date = by_name(&keyset, "Date", again(&null)).await; assert_eq!(leaf_len(&named.c), leaf_len(&absent.c), "by name too"); let opened = targets::decrypt( "Date", @@ -999,7 +957,7 @@ async fn a_storage_only_type_stores_a_none_as_long_as_a_value() { // A type whose term is equality's stores a null with a null's term, // the one a query of a null derives (#1298); a type with an order term // has no null to store, since its term column would show it. - let eq: date::DateEq = by_name(&keyset, "DateEq", null.clone()).await; + let eq: date::DateEq = by_name(&keyset, "DateEq", again(&null)).await; let present_eq: date::DateEq = by_name(&keyset, "DateEq", frame(day("2024-02-29"))).await; assert_eq!( leaf_len(&eq.c), @@ -1008,7 +966,7 @@ async fn a_storage_only_type_stores_a_none_as_long_as_a_value() { ); assert_ne!(eq.hm, present_eq.hm, "a null's term is no value's"); assert_eq!( - hm(&keyset, "DateEq", null.clone()).await, + hm(&keyset, "DateEq", again(&null)).await, eq.hm.0, "a query of a null finds it" ); @@ -1058,21 +1016,16 @@ fn postgres_stores_a_sealed_null_in_a_storage_only_column() { );", ) .unwrap(); - let rows: Vec<(i32, Option)> = vec![ - (1, None), - (2, Some(Date::from(day("2024-02-29")))), - (3, None), - ]; - for (id, value) in &rows { + let rows: Vec<(i32, Option)> = + vec![(1, None), (2, Some(day("2024-02-29"))), (3, None)]; + for (id, day) in &rows { let (entry, due): (date::Date, date::DateEq) = runtime.block_on(async { ( - value - .clone() + day.map(Date::from) .encrypt_into_with_context(&keyset, column()) .await .unwrap(), - value - .clone() + day.map(Date::from) .encrypt_into_with_context(&keyset, column()) .await .unwrap(), @@ -1120,3 +1073,9 @@ fn postgres_stores_a_sealed_null_in_a_storage_only_column() { .collect(); assert_eq!(found, [1, 3]); } + +/// A second frame of the same bytes. A frame is not `Clone`. +fn again(frame: &ValueFrame) -> ValueFrame { + use stack_encrypt::AsProtectedRef as _; + ValueFrame::from_bytes(frame.as_protected_ref()).unwrap() +} diff --git a/packages/eql/tests/encryption/tests/v4_order.rs b/packages/eql/tests/encryption/tests/v4_order.rs index 5fca5a70c6..6db342d335 100644 --- a/packages/eql/tests/encryption/tests/v4_order.rs +++ b/packages/eql/tests/encryption/tests/v4_order.rs @@ -18,7 +18,6 @@ use eql_bindings::encryption::targets::{self as targets}; use eql_bindings::v4::{bigint, double, integer, real, text}; use eql_bindings::Identifier; use stack_encrypt::dynamic::ValueFrame; -use stack_encrypt::value::{Date, Decimal, Timestamp}; use stack_encrypt::{DecryptFrom, Encrypt, EncryptInto, Label, NonEmpty}; fn frame(value: T) -> ValueFrame { @@ -132,15 +131,15 @@ async fn each_ordered_type_stores_its_catalog_terms() { } else if name.starts_with("Real") { frame::(7.0) } else if name.starts_with("Date") { - frame(Date::from_days_since_epoch(7).unwrap()) + frame(common::date_of_days(7)) } else if name.starts_with("Timestamp") { - frame(Timestamp::new(7, 8).unwrap()) + frame(common::timestamp_of(7, 8)) } else if name.starts_with("Numeric") { - frame(Decimal::new(750, 2).unwrap()) + frame(common::decimal_of(750, 2)) } else { frame::(7.0) }; - let json = stored(&keyset, name, value.clone()).await; + let json = stored(&keyset, name, again(&value)).await; let mut keys: Vec<&str> = json .as_object() .unwrap() @@ -156,7 +155,7 @@ async fn each_ordered_type_stores_its_catalog_terms() { assert_eq!(keys, expected, "{name}"); assert_eq!(json["v"], 4, "{name}"); - let q = query(&keyset, name, value.clone()).await; + let q = query(&keyset, name, again(&value)).await; assert!( q.get("c").is_none(), "{name}: a query carries no ciphertext" @@ -238,7 +237,7 @@ async fn integer_terms_order_by_value() { async fn date_timestamp_and_decimal_terms_order_by_value() { let (cipher, _) = common::cipher().await; let keyset = cipher.default_keyset(); - let day = |days| frame(Date::from_days_since_epoch(days).unwrap()); + let day = |days| frame(common::date_of_days(days)); for name in ["DateOrd", "DateOrdOpe"] { let values = vec![ (0, day(-719_162), "0001-01-01"), @@ -248,7 +247,7 @@ async fn date_timestamp_and_decimal_terms_order_by_value() { ]; sorts_as(&keyset, name, values).await; } - let at = |seconds, nanos| frame(Timestamp::new(seconds, nanos).unwrap()); + let at = |seconds, nanos| frame(common::timestamp_of(seconds, nanos)); for name in ["TimestampOrd", "TimestampOrdOpe"] { let values = vec![ (0, at(-1, 999_999_000), "-1us"), @@ -260,7 +259,7 @@ async fn date_timestamp_and_decimal_terms_order_by_value() { ]; sorts_as(&keyset, name, values).await; } - let number = |mantissa, scale| frame(Decimal::new(mantissa, scale).unwrap()); + let number = |mantissa, scale| frame(common::decimal_of(mantissa, scale)); for name in ["NumericOrd", "NumericOrdOpe"] { let values = vec![ (0, number(-1_000, 0), "-1000"), @@ -382,7 +381,7 @@ async fn ord_and_ord_ope_store_one_term() { ("TextOrd", "TextOrdOpe", frame("Zoë")), ]; for (ord, ope, value) in pairs { - let a = stored(&keyset, ord, value.clone()).await; + let a = stored(&keyset, ord, again(&value)).await; let b = stored(&keyset, ope, value).await; assert_eq!(op(&a), op(&b), "{ord} and {ope}"); } @@ -979,3 +978,9 @@ fn postgres_compares_rows_the_go_sdk_sealed() { ); } } + +/// A second frame of the same bytes. A frame is not `Clone`. +fn again(frame: &ValueFrame) -> ValueFrame { + use stack_encrypt::AsProtectedRef as _; + ValueFrame::from_bytes(frame.as_protected_ref()).unwrap() +} diff --git a/packages/eql/tests/encryption/tests/v4_ore_block.rs b/packages/eql/tests/encryption/tests/v4_ore_block.rs index ea4dfb8571..f059c5a4d6 100644 --- a/packages/eql/tests/encryption/tests/v4_ore_block.rs +++ b/packages/eql/tests/encryption/tests/v4_ore_block.rs @@ -30,8 +30,9 @@ use std::cmp::Ordering; use eql_bindings::encryption::targets; use stack_encrypt::dynamic::ValueFrame; -use stack_encrypt::sem::{Orderable, OreBlockTerm}; +use stack_encrypt::sem::OreBlockTerm; use stack_encrypt::value::{Date, Decimal, Timestamp}; +use stack_encrypt::Orderable; use stack_encrypt::{Encrypt, Label}; type Keyset<'a> = stack_encrypt::KeysetCipher<'a, common::RecordingKeySource>; @@ -125,19 +126,19 @@ async fn each_type_stores_one_block_ore_term_of_its_scheme() { ), ( "DateOrdOre", - frame(Date::from_days_since_epoch(7).unwrap()), + frame(common::date_of_days(7)), [2, 2], &["c", "i", "ob", "v"], ), ( "TimestampOrdOre", - frame(Timestamp::new(7, 8).unwrap()), + frame(common::timestamp_of(7, 8)), [2, 3], &["c", "i", "ob", "v"], ), ( "NumericOrdOre", - frame(Decimal::new(750, 2).unwrap()), + frame(common::decimal_of(750, 2)), [2, 3], &["c", "i", "ob", "v"], ), @@ -400,16 +401,17 @@ fn postgres_compares_fixed_width_terms_as_ore_rs_and_the_plaintexts_do() { } /// Each value's terms, two writes each, as `terms` makes them for a `Copy` -/// plaintext: the plaintexts here are wiped on drop, so are not `Copy`. -async fn terms_of( +/// plaintext. The plaintexts here are wiped on drop, so they are neither +/// `Copy` nor `Clone`: each item builds its value, once for each write. +async fn terms_of( keyset: &Keyset<'_>, name: &str, - values: impl IntoIterator, + values: impl IntoIterator T>, ) -> Vec> { let mut out = Vec::new(); for value in values { - out.push(ob(keyset, name, frame(value.clone())).await); - out.push(ob(keyset, name, frame(value)).await); + out.push(ob(keyset, name, frame(value())).await); + out.push(ob(keyset, name, frame(value())).await); } out } @@ -429,7 +431,7 @@ fn postgres_compares_date_timestamp_and_decimal_terms_as_ore_rs_and_the_plaintex let date_terms = runtime.block_on(terms_of( &keyset, "DateOrdOre", - days.map(|d| Date::from_days_since_epoch(d).unwrap()), + days.map(|d| move || common::date_of_days(d)), )); assert_agree::(&mut db, "DateOrdOre", &days, &date_terms); @@ -448,7 +450,7 @@ fn postgres_compares_date_timestamp_and_decimal_terms_as_ore_rs_and_the_plaintex let instant_terms = runtime.block_on(terms_of( &keyset, "TimestampOrdOre", - instants.map(|(s, n)| Timestamp::new(s, n).unwrap()), + instants.map(|(s, n)| move || common::timestamp_of(s, n as i32)), )); assert_agree::(&mut db, "TimestampOrdOre", µs, &instant_terms); @@ -466,7 +468,7 @@ fn postgres_compares_date_timestamp_and_decimal_terms_as_ore_rs_and_the_plaintex let number_terms = runtime.block_on(terms_of( &keyset, "NumericOrdOre", - numbers.map(|(m, s)| Decimal::new(m, s as u8).unwrap()), + numbers.map(|(m, s)| move || common::decimal_of(m, s)), )); assert_agree::(&mut db, "NumericOrdOre", &scaled, &number_terms); } diff --git a/packages/eql/tests/encryption/tests/v4_owned.rs b/packages/eql/tests/encryption/tests/v4_owned.rs index 52422fb5b6..d523c797c4 100644 --- a/packages/eql/tests/encryption/tests/v4_owned.rs +++ b/packages/eql/tests/encryption/tests/v4_owned.rs @@ -117,35 +117,35 @@ impl Seen for Option { impl Seen for DateValue { type View = CivilDate; fn view(&self) -> CivilDate { - CivilDate::from(self) + self.to_jiff() } } impl Seen for TimestampValue { type View = jiff::Timestamp; fn view(&self) -> jiff::Timestamp { - jiff::Timestamp::from(self) + self.to_jiff() } } impl Seen for DecimalValue { type View = String; fn view(&self) -> String { - rust_decimal::Decimal::from(self).to_string() + self.to_decimal().to_string() } } /// Writes each stored type twice, from the same plaintext under the same -/// column. Checks that the terms match, and that each ciphertext opens: under +/// column. The plaintext is built again for each write: it is not `Clone`. Checks that the terms match, and that each ciphertext opens: under /// the column it stores, and under the column the reader expects. macro_rules! stored_round_trips { ($keyset:expr, $plaintext:ty, $value:expr, [$($ty:ty),+ $(,)?]) => {$({ let value: $plaintext = $value; - let first: $ty = value - .clone() + let again: $plaintext = $value; + let first: $ty = again .encrypt_into_with_context(&$keyset, column()) .await .unwrap(); - let second: $ty = value - .clone() + let again: $plaintext = $value; + let second: $ty = again .encrypt_into_with_context(&$keyset, column()) .await .unwrap(); @@ -165,14 +165,13 @@ macro_rules! stored_round_trips { /// ORE operand is compared by the ORE scheme, as the type's `PartialEq` does. macro_rules! query_is_stable { ($keyset:expr, $plaintext:ty, $value:expr, [$($ty:ty),+ $(,)?]) => {$({ - let value: $plaintext = $value; - let first: $ty = value - .clone() + let again: $plaintext = $value; + let first: $ty = again .encrypt_into_with_context(&$keyset, column()) .await .unwrap(); - let second: $ty = value - .clone() + let again: $plaintext = $value; + let second: $ty = again .encrypt_into_with_context(&$keyset, column()) .await .unwrap(); @@ -640,9 +639,10 @@ fn the_traits_the_compile_fail_examples_refuse_exist_for_the_right_shapes() { encrypts::(); } -/// How many copies of the plaintext the ciphertext `c` makes. The owned form -/// that `encrypt_into` runs moves the plaintext into the seal. The borrowed -/// form, which a collection runs for each element, copies it once. +/// How many copies of the plaintext the ciphertext `c` makes: none. The +/// owned form that `encrypt_into` runs moves the plaintext into the seal. +/// The borrowed form, which a collection runs for each element, reads it in +/// place. mod the_ciphertext { use super::*; @@ -674,6 +674,12 @@ mod the_ciphertext { self.text.visit(sink) } } + /// Sealing a borrowed value reads the text in place. + impl Encrypt for &Counted { + fn visit(self, sink: S) -> Result { + self.text.as_str().visit(sink) + } + } /// The counter is not secret. impl Zeroize for Counted { fn zeroize(&mut self) { @@ -695,7 +701,7 @@ mod the_ciphertext { } #[tokio::test] - async fn the_owned_form_copies_nothing_and_the_borrowed_form_copies_once() { + async fn neither_the_owned_form_nor_the_borrowed_form_copies_the_plaintext() { let (cipher, _) = common::cipher().await; let keyset = cipher.default_keyset(); @@ -718,7 +724,7 @@ mod the_ciphertext { ); let (value, clones) = counted(); - let _: Ciphertext = keyset + let borrowed: Ciphertext = keyset .run( >::encryption(), &value, @@ -726,7 +732,11 @@ mod the_ciphertext { ) .await .unwrap(); - assert_eq!(clones.load(Ordering::SeqCst), 1, "the borrowed form"); + assert_eq!(clones.load(Ordering::SeqCst), 0, "the borrowed form"); + let opened: String = String::decrypt_from_with_context(borrowed, &cipher, aead()) + .await + .unwrap(); + assert_eq!(opened, "ada@example.com", "the borrowed value is sealed"); } /// A refused context requests no key. diff --git a/packages/eql/tests/encryption/tests/v4_range.rs b/packages/eql/tests/encryption/tests/v4_range.rs index 81cf3e534a..e62d597bc8 100644 --- a/packages/eql/tests/encryption/tests/v4_range.rs +++ b/packages/eql/tests/encryption/tests/v4_range.rs @@ -23,7 +23,6 @@ use eql_bindings::v4::{self, integer, text, DomainType}; use serde_json::{json, Value}; use stack_encrypt::dynamic::ValueFrame; use stack_encrypt::target::IndexSpec; -use stack_encrypt::value::{Date, Decimal, Timestamp}; use stack_encrypt::{Encrypt, KeysetCipher, Label}; fn identifier() -> Value { @@ -705,9 +704,9 @@ fn frame_of(family: &str, value: &Value) -> ValueFrame { "real" => frame(value.as_f64().unwrap() as f32), "double" => frame(value.as_f64().unwrap()), "text" => frame(value.as_str().unwrap().to_owned()), - "date" => frame(Date::from_days_since_epoch(value.as_i64().unwrap() as i32).unwrap()), - "timestamp" => frame(Timestamp::new(value.as_i64().unwrap(), 0).unwrap()), - "numeric" => frame(Decimal::new(i128::from(value.as_i64().unwrap()), 2).unwrap()), + "date" => frame(common::date_of_days(value.as_i64().unwrap() as i32)), + "timestamp" => frame(common::timestamp_of(value.as_i64().unwrap(), 0)), + "numeric" => frame(common::decimal_of(i128::from(value.as_i64().unwrap()), 2)), other => panic!("no plaintext for the ordered family {other:?}"), } } diff --git a/packages/eql/tests/encryption/tests/v4_terms.rs b/packages/eql/tests/encryption/tests/v4_terms.rs index d07052886d..12c98b496f 100644 --- a/packages/eql/tests/encryption/tests/v4_terms.rs +++ b/packages/eql/tests/encryption/tests/v4_terms.rs @@ -71,7 +71,6 @@ fn pinned_part(value: &T) -> Value { macro_rules! encrypt { ($keyset:expr, $value:expr, $ty:ty) => {{ let out: $ty = $value - .clone() .encrypt_into_with_context(&$keyset, column()) .await .unwrap(); @@ -100,12 +99,12 @@ async fn every_payload() -> BTreeMap { let mut out = BTreeMap::new(); { use text::*; - let value = "Ada Lovelace".to_owned(); + let value = || "Ada Lovelace".to_owned(); record!( out, keyset, "", - value, + value(), [ Text, TextEq, @@ -122,7 +121,7 @@ async fn every_payload() -> BTreeMap { TextOrdOpeQuery, ] ); - record!(out, keyset, value, [ + record!(out, keyset, value(), [ TextSearchOreEqualityQuery => TextSearchOreQuery, TextSearchOreOrderQuery => TextSearchOreQuery, TextSearchOreMatchQuery => TextSearchOreQuery, diff --git a/packages/eql/tests/encryption/tests/v4_types.rs b/packages/eql/tests/encryption/tests/v4_types.rs index 932198cf51..ad62e1a9e4 100644 --- a/packages/eql/tests/encryption/tests/v4_types.rs +++ b/packages/eql/tests/encryption/tests/v4_types.rs @@ -14,7 +14,7 @@ use eql_bindings::encryption::targets::{self as targets, TargetError}; use eql_bindings::encryption::{CiphertextVisitor, NativeCiphertextVisitor as NativeLeaf}; use eql_bindings::v3::terms::Ciphertext; use eql_bindings::v4::plaintext::JsonPlaintext; -use eql_bindings::v4::{bigint, boolean, double, integer, json, plaintext, real, smallint, text}; +use eql_bindings::v4::{bigint, boolean, double, integer, json, real, smallint, text}; use eql_bindings::Identifier; use serde::{de::DeserializeOwned, Serialize}; use stack_encrypt::dynamic::{ValueFrame, ValueKind}; @@ -123,9 +123,9 @@ fn sample(kind: ValueKind) -> ValueFrame { ValueKind::Float32 => frame::(-0.0), ValueKind::Float64 => frame::(f64::NAN), ValueKind::String => frame("a private note"), - ValueKind::Date => frame(plaintext::Date::from_days_since_epoch(-719_162).unwrap()), - ValueKind::Timestamp => frame(plaintext::Timestamp::new(-1, 999_999_999).unwrap()), - ValueKind::Decimal => frame(plaintext::Decimal::new(-123_450, 2).unwrap()), + ValueKind::Date => frame(common::date_of_days(-719_162)), + ValueKind::Timestamp => frame(common::timestamp_of(-1, 999_999_999)), + ValueKind::Decimal => frame(common::decimal_of(-123_450, 2)), other => panic!("no sample for {other:?}: add one with the type that takes it"), } } @@ -215,7 +215,7 @@ async fn eq_terms( name: &str, value: ValueFrame, ) -> (serde_json::Value, serde_json::Value) { - let stored: serde_json::Value = by_name(keyset, name, value.clone()).await; + let stored: serde_json::Value = by_name(keyset, name, again(&value)).await; let query = targets::query(name, &common::index_of(name), keyset, &label(), value) .unwrap() .await @@ -2630,3 +2630,9 @@ fn postgres_stores_and_queries_rows_the_go_sdk_sealed() { runtime.block_on(go_rows::open_row(&cipher, &round_tripped)); } } + +/// A second frame of the same bytes. A frame is not `Clone`. +fn again(frame: &ValueFrame) -> ValueFrame { + use stack_encrypt::AsProtectedRef as _; + ValueFrame::from_bytes(frame.as_protected_ref()).unwrap() +} diff --git a/packages/stack-encrypt-derive/src/lib.rs b/packages/stack-encrypt-derive/src/lib.rs index 9e3e75367e..75811172e6 100644 --- a/packages/stack-encrypt-derive/src/lib.rs +++ b/packages/stack-encrypt-derive/src/lib.rs @@ -33,14 +33,15 @@ //! .init() //! .await?; //! let keyset = cipher.default_keyset(); -//! let value = "alice@example.com".to_owned(); //! // The output type selects a ciphertext and an equality term. The context -//! // is stored in `identifier`. -//! let encrypted: TextEq = value.clone().encrypt_into_with_context(&keyset, nonempty!("users/email")).await?; +//! // is stored in `identifier`. The value is moved in, and wiped once it is +//! // sealed. +//! let value = String::from("alice@example.com"); +//! let encrypted: TextEq = value.encrypt_into_with_context(&keyset, nonempty!("users/email")).await?; //! // Passing the expected context refuses a value stored under any other //! // context, before any key is requested. //! let opened = Protected::::decrypt_from_with_context(encrypted, &cipher, nonempty!("users/email")).await?; -//! # assert_eq!(opened.risky_ref(), &value); +//! # assert_eq!(opened.risky_ref(), "alice@example.com"); //! # Ok::<(), Box> (()) //! # }).unwrap(); //! ``` @@ -225,8 +226,8 @@ //! use stack_encrypt::target::transcode::{Transcode, Visitor}; //! use stack_encrypt::target::{self, CallerContext, EncryptTarget, RequiredContext}; //! use stack_encrypt::{ -//! CipherText, Decryptable, EncryptInto, Encryption, Error, Encrypt, SealedValue, -//! StackCipher, nonempty, +//! CipherText, Controlled, Decryptable, EncryptInto, Encryption, Error, Encrypt, EncryptRef, +//! Protected, SealedValue, StackCipher, nonempty, //! }; //! use zeroize::Zeroize; //! @@ -255,7 +256,7 @@ //! } //! // The declaration: the canonical ciphertext operation, read into this type. //! // It seals under the AEAD half of the context the record threads to it. -//! impl EncryptTarget for LeafBytes { +//! impl EncryptTarget for LeafBytes { //! type ContextInput = RequiredContext; //! fn encryption<'s, K: 'static>() -> Encryption<'s, S, Self, K, Self::ContextInput> //! where @@ -283,14 +284,15 @@ //! .init() //! .await?; //! let keyset = cipher.default_keyset(); -//! let value = "alice@example.com".to_owned(); +//! let value = String::from("alice@example.com"); //! let context = nonempty!("users/email"); -//! let encrypted: TextEq = value.clone().encrypt_into_with_context(&keyset, context.clone()).await?; +//! let encrypted: TextEq = value.encrypt_into_with_context(&keyset, context.clone()).await?; //! //! // What the column holds is the leaf itself: the canonical path opens it. //! let leaf = SealedValue::from_bytes(&encrypted.c.0)?; -//! let opened: String = cipher.decrypt(CipherText::Single(leaf), context).await?; -//! assert_eq!(opened, value); +//! // Opened into `Protected`, so the plaintext is wiped when it drops. +//! let opened: Protected = cipher.decrypt(CipherText::Single(leaf), context).await?; +//! assert_eq!(opened.risky_ref(), "alice@example.com"); //! # Ok::<(), Box> (()) //! # }).unwrap(); //! ``` diff --git a/packages/stack-encrypt/CHANGELOG.md b/packages/stack-encrypt/CHANGELOG.md index a92c55534b..81e3730722 100644 --- a/packages/stack-encrypt/CHANGELOG.md +++ b/packages/stack-encrypt/CHANGELOG.md @@ -486,6 +486,87 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 returns `None` for a keyset that is not loaded yet, unless it was selected by its id. +- **A plaintext is read in place, and no longer needs `Clone`** (#1734). + One value that feeds a ciphertext and several terms is not copied. + - A sealed or indexed plaintext is bounded by `Encrypt + EncryptRef`, + where it was `Encrypt + Clone`. `EncryptRef` means `&T: Encrypt`. + vitaminc's types and its derive provide it. A type with only a + by-value `Encrypt` impl must add `impl Encrypt for &T`. + `stack_encrypt::EncryptRef` is a new re-export. + - `Encryption::zip` takes a borrowed description as its second + argument, and runs it first. The outputs keep their written order. + - `target::ShareSource` is removed. `target::ConsumeSource` stays for + `passthrough` only. + - `dynamic::ValueFrame` and `json::JsonPlaintext` are no longer `Clone`. + - A call on a keyset that is not loaded yet keeps no borrow of the + plaintext. The call keeps what it derived without the keyset: a + term's normalized form or order encoding, wiped on drop. A borrowed + JSON document is the one plaintext that is copied. That copy is made + once, and wiped. +- **An operation in `Owned` mode wipes the value it is handed** (#1734). + `ciphertext` dropped a value whose context was refused without wiping + it. A match term dropped every value it was handed without wiping it. + Both wipe the value now, as every other operation does. + - `ciphertext`, `equality`, `matching`, `ore`, `ope`, `ore_block`, and + `indexed` are bounded by the new `target::WipeSource`, where they + were bounded by `SourceMode`. `Borrowed` implements it for every + plaintext. `Owned` implements it for a plaintext that is `Zeroize`. + So a value sealed or indexed in `Owned` mode must be `Zeroize`. + - `Index::operation` and `Indexes::operations` are bounded by + `WipeSource`. An `Index` implemented outside this crate changes + `M: SourceMode<'s, S>` to `M: WipeSource<'s, S>`. + - A query's value is handed to its index by value, so it must be + `Zeroize` too. Every query value this crate and `eql-bindings` + accept already is. + - A JSON document keeps its own guard and needs no `Zeroize`. + `json_terms` and `json_document` stay bounded by `SourceMode`. + - `Encryption::zip` is bounded by `WipeSource` too. While its argument + reads an owned value, `zip` holds the value in a guard. If a reader + panics, the value is wiped as the stack unwinds. A match term guards + the value it reads in the same way. +- **An order index is bounded by vitaminc-ore's `Orderable`** (#1734). + `sem::Orderable` and `op::Ordered` are removed. `stack_encrypt::Orderable` + re-exports vitaminc-ore's trait, and its table is vitaminc-ore's. + - It covers the integers of 16 bits and wider, `f32`, `f64`, `String`, + `&str`, and `value::Date`, `value::Timestamp`, and `value::Decimal`. It + covers a reference to each. It does not cover bytes, an 8-bit integer, + or a `bool`. + - An order term, an order index, or an ordering operator over bytes does + not compile. Before, `OreTerm>` compiled, but no ordering + operator answered it. Its term revealed the order of the rows. + - To upgrade a record with an order index on bytes, remove the index. + Rows stored before stay readable. Opening reads only the ciphertext + and ignores the stored order term, so name the field + `StackCipherText`, or `Encrypted<..>` over the terms it keeps. + - `KeysetCipher::ore_term`, `ope_term`, and `ore_block_term` no longer + take bytes. They take a reference such as `&String` or `&str`, as well + as a value. + - An order index reads its value in place, so it is bounded by + `Orderable + EncryptRef`. A target or a query value of it is also + `Zeroize` and `'static`. + - A data plan still accepts an order index on bytes, and derives its term + as before. Stored rows and the conformance corpus do not change. + - The JSON index derives a string leaf's OPE term from the document in + place, and a data plan derives a text field's order term from the + frame in place. Each copied the text before. +- **`value::Date`, `value::Timestamp`, and `value::Decimal` are vitaminc's + types** (#1734). Stack Encrypt's own copies are removed. The stored + format is unchanged. + - Build a `Date` from a jiff `civil::Date`, a `Timestamp` from a jiff + `Timestamp`, and a `Decimal` from a rust_decimal `Decimal`, with + `new` or `From`. Read one back with `to_jiff` or `to_decimal`. + - These are removed: `Date::from_days_since_epoch`, + `Date::days_since_epoch`, `Timestamp::new(seconds, nanoseconds)`, + `Timestamp::seconds`, `Timestamp::nanoseconds`, + `Decimal::new(mantissa, scale)`, `Decimal::mantissa`, + `Decimal::scale`, and `value::RangeError`. + - `Timestamp::new` returns `value::OutOfRange` for an instant that jiff + 1.0.0 can make before its own minimum. `Date::new` and `Decimal::new` + cannot fail. + - None of the three is `Clone`. + - The `jiff` and `rust_decimal` features are on by default, and the + `dynamic` feature turns both on. With one off, its types do not + exist. A build with `default-features = false` must name them. - **The tree entry points return a `Pending`** (#1705), so they can take audit metadata like every other call. `KeysetCipher::encrypt_tree`, `KeysetCipher::decrypt_tree`, and `StackCipher::decrypt` were diff --git a/packages/stack-encrypt/CONTEXT.md b/packages/stack-encrypt/CONTEXT.md index eb9c0c7c0d..37fd9928c7 100644 --- a/packages/stack-encrypt/CONTEXT.md +++ b/packages/stack-encrypt/CONTEXT.md @@ -235,6 +235,8 @@ _Avoid_: plaintext field, skipped field, excluded field An operation that reads its plaintext through a reference: sealing a ciphertext, deriving a term, the JSON index, and a query's value. A declaration has any number of them over one value, and none copies it. +One exception: sealing a borrowed JSON document on a keyset that is not +loaded yet keeps one copy until the keyset arrives, and wipes it. _Avoid_: borrower, viewer **Taker**: diff --git a/packages/stack-encrypt/Cargo.toml b/packages/stack-encrypt/Cargo.toml index 3698e83b63..4c9888f48e 100644 --- a/packages/stack-encrypt/Cargo.toml +++ b/packages/stack-encrypt/Cargo.toml @@ -103,13 +103,9 @@ serde_json = { workspace = true, features = ["float_roundtrip"] } thiserror = { workspace = true } uuid = { workspace = true } zeroize = { workspace = true } -# `value::{Date, Timestamp}` to and from jiff's types (the `jiff` -# feature), and `value::Decimal` to and from rust_decimal's (`rust_decimal`). -jiff = { version = "1.0.0", optional = true, default-features = false } -rust_decimal = { version = "1", optional = true, default-features = false } [features] -default = ["http"] +default = ["http", "jiff", "rust_decimal"] # `StackCipher::new()` / `StackCipher::builder().init()` from the environment: # the default HTTP transport in stack-kms and the auto-detected auth strategy # in stack-auth. Off, a cipher is built over an explicit `DataKeySource` @@ -120,13 +116,19 @@ http = ["dep:stack-auth", "stack-auth/http", "stack-kms/http"] # only at runtime, as an FFI binding's are. Off by default — it is only of # use to a binding author. Its transport frames are vitaminc-aead's own, and # the crate they come from is always built (the storage profile `OpaqueBlob` -# uses lives there), so the feature adds no dependency. -dynamic = [] -# Conversions between jiff's `civil::Date` / `Timestamp` and -# `value::Date` / `value::Timestamp`. -jiff = ["dep:jiff", "vitaminc-aead/jiff"] -# Conversions between rust_decimal's `Decimal` and `value::Decimal`. -rust_decimal = ["dep:rust_decimal", "vitaminc-aead/rust_decimal"] +# uses lives there). +# +# It turns on `jiff` and `rust_decimal`: a binding is handed every kind of +# value, and an order term over a date, a timestamp or a decimal is derived +# from vitaminc's type for it. +dynamic = ["jiff", "rust_decimal"] +# `value::Date` and `value::Timestamp`: vitaminc's wipeable date and UTC +# instant, built from jiff's `civil::Date` and `Timestamp`, and their order +# terms. On by default. +jiff = ["vitaminc-aead/jiff", "vitaminc-ore/jiff"] +# `value::Decimal`: vitaminc's wipeable decimal, built from rust_decimal's +# `Decimal`, and its order terms. On by default. +rust_decimal = ["vitaminc-aead/rust_decimal", "vitaminc-ore/rust_decimal"] # `stack_encrypt::kms::FakeDataKeySource`: the in-memory key source for tests # with no ZeroKMS, so a caller's dev-dependency on stack-encrypt is enough and # no direct stack-kms dependency has to agree with this crate's. @@ -137,6 +139,10 @@ test-support = ["stack-kms/test-support"] testing = [] [dev-dependencies] +# The types `value::{Date, Timestamp, Decimal}` are built from, for the +# tests and doc examples that build one. +jiff = { version = "1.0.0", default-features = false } +rust_decimal = { version = "1", default-features = false } # Preserve JSON number spellings for the shared declaration projection. serde_json = { workspace = true, features = ["raw_value"] } # `default-features = false` here too: dev-dependency features unify into the diff --git a/packages/stack-encrypt/docs/adr/0009-operators-select-the-index-and-a-query-term-is-not-the-stored-term.md b/packages/stack-encrypt/docs/adr/0009-operators-select-the-index-and-a-query-term-is-not-the-stored-term.md index fda31d92f9..969c3b8e74 100644 --- a/packages/stack-encrypt/docs/adr/0009-operators-select-the-index-and-a-query-term-is-not-the-stored-term.md +++ b/packages/stack-encrypt/docs/adr/0009-operators-select-the-index-and-a-query-term-is-not-the-stored-term.md @@ -599,7 +599,7 @@ their canonical encoding), which belongs to the ORE crates. One call derives both bounds, under one context, so a caller cannot pair a bound from one column with a bound from another. The ordering operators are answered over the integer types, the -floats and text (`op::Ordered`), by the ORE index by default and by OPE +floats and text (`op::Ordered`; amended below), by the ORE index by default and by OPE through `.via(Ope)`. Each term is cllw-ore's encryption of the value's ADR-0002 order key at its type's target, so a float orders as Postgres's `float8` does (`-0.0` ties `0.0`, NaN sorts last), and an `f32` is ordered @@ -1273,3 +1273,12 @@ who read the column how its values order, for nothing. The ADR-0004 decision 5 history above is unchanged. ADR-0007's rule, one executor and never a second, is nearer: the dynamic path still has its own term derivation, which the API plan's step 4 moves onto the typed one. + +## Amended 2026-11-22 (#1737) + +`op::Ordered` is removed, and so is `sem::Orderable`. ADR 0014 decision 5 +bounds every order index, order term, and ordering operator on +vitaminc-ore's `Orderable`, which `stack_encrypt::Orderable` re-exports. +That trait covers the integers of 16 bits and wider, the floats, text, +dates, timestamps, and decimals. It does not cover bytes or an 8-bit +integer. Where this ADR names `op::Ordered`, read `Orderable`. diff --git a/packages/stack-encrypt/docs/adr/0014-operations-read-the-plaintext-and-at-most-one-takes-it.md b/packages/stack-encrypt/docs/adr/0014-operations-read-the-plaintext-and-at-most-one-takes-it.md index 0b07e104d8..9766f059ea 100644 --- a/packages/stack-encrypt/docs/adr/0014-operations-read-the-plaintext-and-at-most-one-takes-it.md +++ b/packages/stack-encrypt/docs/adr/0014-operations-read-the-plaintext-and-at-most-one-takes-it.md @@ -214,7 +214,8 @@ type. Two operations that both take the value therefore do not compile. - `ShareSource` is removed. `zip` lends the value. - `ConsumeSource` stays, for `passthrough` alone. No other operation asks for it. The public `Index` trait's `operation` is bounded by - `SourceMode`, where it was `ConsumeSource`. + `SourceMode`, where it was `ConsumeSource`. (Amended below: by + `WipeSource`.) - **A borrowed `passthrough` still copies its value, so that value is `Clone`.** This is ADR-0012's rule for a field stored in the clear, and it stands. The value is not sealed, so the copy is not a copy of a @@ -412,3 +413,27 @@ Three pull requests touch the same code. They land in this order: 4. **The dynamic interface.** It fits. A data plan's sealed and indexed fields read their `ValueFrame` in place, and a passthrough field's value is moved into the output. + +## Amended 2026-11-22 (#1737) + +Decision 4 left the form of the `Zeroize` bound to the implementation. +#1737 writes it as a third mode trait, `WipeSource`. + +- `Borrowed` implements it for every plaintext. `Owned` implements it for + a plaintext that is `Zeroize`. So the bound applies in `Owned` mode + only, as decision 4 says. A borrowed `&str` is still sealed. +- Every operation that seals or indexes is bounded by it: `ciphertext`, + `equality`, `matching`, the three order terms, and `indexed`. So are + `Index::operation` and `Indexes::operations`. Decision 3 named + `SourceMode` for `Index::operation`. That bound is now `WipeSource`. +- The JSON operations keep `SourceMode`. A document has its own guard + (`PlainJson`). `serde_json::Value` is not `Zeroize`. A JSON index + run in `Owned` mode calls `json_terms` directly, and not through + `Index`. +- A typed query hands its value to the index by value, so a query value + is `Zeroize`. +- #1737 also lands decision 5. The typed path has no order term of bytes. + A data plan can still declare an order index on bytes until #1611 refuses + it. Until then the dynamic path derives that term by naming the `Bytes` + target. So the stored rows and the conformance corpus do not change in + #1737. diff --git a/packages/stack-encrypt/fuzz/Cargo.lock b/packages/stack-encrypt/fuzz/Cargo.lock index 1943a2dc4d..1950f55291 100644 --- a/packages/stack-encrypt/fuzz/Cargo.lock +++ b/packages/stack-encrypt/fuzz/Cargo.lock @@ -240,6 +240,30 @@ version = "0.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9e2211b0817f061502a8dd9f11a37e879e79763e3c698d2418cf824d8cb2f21e" +[[package]] +name = "borsh" +version = "1.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "553c5d846a6ba5150c65e3b1b8ec073bcf1abc20f9b7220de384a4443ea4e20a" +dependencies = [ + "borsh-derive", + "bytes", + "cfg_aliases", +] + +[[package]] +name = "borsh-derive" +version = "1.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12cdfe656708a01f89b451a7d36466e6fe6c414de0aa18fc54f864f6f9ca9f56" +dependencies = [ + "once_cell", + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 3.0.3", +] + [[package]] name = "bumpalo" version = "3.19.1" @@ -318,6 +342,12 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" +[[package]] +name = "cfg_aliases" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" + [[package]] name = "chacha20" version = "0.10.2" @@ -1211,6 +1241,39 @@ version = "1.0.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "92ecc6618181def0457392ccd0ee51198e065e016d1d527a7ac1b6dc7c1f09d2" +[[package]] +name = "jiff" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5d126d72eb017f10b302e73bdeca446bea405ee449af4d9e7866d6b082d83e" +dependencies = [ + "jiff-core", + "jiff-static", + "portable-atomic", + "portable-atomic-util", +] + +[[package]] +name = "jiff-core" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6b46a105a9874634dd96231021526bf24ca04955a5998c59a9c7666e634b7b8" +dependencies = [ + "log", +] + +[[package]] +name = "jiff-static" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0127e9bde3c6130d6169e7d8d68676e4be69c4bf7573c308b6f960a5089c428" +dependencies = [ + "jiff-core", + "proc-macro2", + "quote", + "syn 3.0.3", +] + [[package]] name = "jobserver" version = "0.1.34" @@ -1559,6 +1622,21 @@ dependencies = [ "universal-hash", ] +[[package]] +name = "portable-atomic" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" + +[[package]] +name = "portable-atomic-util" +version = "0.2.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10ab3eb7f3becc3a1cbc4f2c6f20267996cfc1a6467a873763411b136a122715" +dependencies = [ + "portable-atomic", +] + [[package]] name = "potential_utf" version = "0.1.4" @@ -1683,10 +1761,20 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c" dependencies = [ "libc", - "rand_chacha", + "rand_chacha 0.3.1", "rand_core 0.6.4", ] +[[package]] +name = "rand" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41" +dependencies = [ + "rand_chacha 0.9.0", + "rand_core 0.9.5", +] + [[package]] name = "rand" version = "0.10.1" @@ -1708,6 +1796,16 @@ dependencies = [ "rand_core 0.6.4", ] +[[package]] +name = "rand_chacha" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +dependencies = [ + "ppv-lite86", + "rand_core 0.9.5", +] + [[package]] name = "rand_core" version = "0.6.4" @@ -1717,6 +1815,15 @@ dependencies = [ "getrandom 0.2.17", ] +[[package]] +name = "rand_core" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" +dependencies = [ + "getrandom 0.3.4", +] + [[package]] name = "rand_core" version = "0.10.0" @@ -1745,7 +1852,7 @@ dependencies = [ "hex-literal", "opaque-debug", "rand 0.8.8", - "rand_chacha", + "rand_chacha 0.3.1", "serde", "serde_cbor", "sha2 0.10.9", @@ -1821,6 +1928,23 @@ dependencies = [ "serde", ] +[[package]] +name = "rust_decimal" +version = "1.43.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7653272e75dcac41dc199fbea6f5797633994fafd339943c06c9af16bf29cd3a" +dependencies = [ + "arrayvec", + "borsh", + "bytes", + "num-traits", + "rand 0.8.8", + "rand 0.9.5", + "serde", + "serde_json", + "wasm-bindgen", +] + [[package]] name = "rustc_version" version = "0.4.1" @@ -2644,6 +2768,8 @@ checksum = "6fcccedca9d80812af295cba43dc2ac388f4fbb0415faa3ebec783d072d014d8" dependencies = [ "bytes", "futures-util", + "jiff", + "rust_decimal", "serde", "thiserror 2.0.18", "vitaminc-aead-derive 0.10.0", @@ -2766,12 +2892,15 @@ version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9a1d92d394e577ee424b4f35479a101896aecbce98f00c37bca5af1aa0d3b2c0" dependencies = [ + "jiff", + "rust_decimal", "thiserror 2.0.18", "unicode-general-category", "unicode-normalization", "vitaminc-aead 0.10.0", "vitaminc-context 0.10.0", "vitaminc-normalize", + "vitaminc-prf", "vitaminc-protected 0.10.0", "zeroize", ] diff --git a/packages/stack-encrypt/src/cipher.rs b/packages/stack-encrypt/src/cipher.rs index 148d7055ff..f4d20bb5ac 100644 --- a/packages/stack-encrypt/src/cipher.rs +++ b/packages/stack-encrypt/src/cipher.rs @@ -1459,7 +1459,7 @@ impl KeysetCipher<'_, K> { /// as its purpose or a request id. /// /// ``` - /// use stack_encrypt::{AuditMetadata, StackCipher}; + /// use stack_encrypt::{AuditMetadata, Controlled, Protected, StackCipher}; /// /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { /// // With no `.kms(..)`, the cipher uses ZeroKMS. It reads credentials from @@ -1471,11 +1471,11 @@ impl KeysetCipher<'_, K> { /// let keyset = cipher.default_keyset(); /// let stored = keyset.encrypt_tree(String::from("alice"), "users/name").await?; /// - /// let name: String = keyset + /// let name: Protected = keyset /// .decrypt_tree(stored, "users/name") /// .audit(AuditMetadata::new().with("purpose", "profile page")) /// .await?; - /// assert_eq!(name, "alice"); + /// assert_eq!(name.risky_ref(), "alice"); /// # Ok::<(), stack_encrypt::Error>(()) /// # }).unwrap(); /// ``` @@ -1562,7 +1562,7 @@ impl StackCipher { /// as its purpose or a request id. /// /// ``` - /// use stack_encrypt::{AuditMetadata, StackCipher}; + /// use stack_encrypt::{AuditMetadata, Controlled, Protected, StackCipher}; /// /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { /// // With no `.kms(..)`, the cipher uses ZeroKMS. It reads credentials from @@ -1574,11 +1574,11 @@ impl StackCipher { /// let keyset = cipher.default_keyset(); /// let stored = keyset.encrypt_tree(String::from("alice"), "users/name").await?; /// - /// let name: String = cipher + /// let name: Protected = cipher /// .decrypt(stored, "users/name") /// .audit(AuditMetadata::new().with("purpose", "profile page")) /// .await?; - /// assert_eq!(name, "alice"); + /// assert_eq!(name.risky_ref(), "alice"); /// # Ok::<(), stack_encrypt::Error>(()) /// # }).unwrap(); /// ``` diff --git a/packages/stack-encrypt/src/credential.rs b/packages/stack-encrypt/src/credential.rs index 738e9d7c25..762d65235e 100644 --- a/packages/stack-encrypt/src/credential.rs +++ b/packages/stack-encrypt/src/credential.rs @@ -297,7 +297,7 @@ pub(crate) async fn load_index_key, I>( /// /// ``` /// use stack_encrypt::kms::{FakeCredentialKeySource, SecretToken}; -/// use stack_encrypt::{Ciphertext, StackCipher}; +/// use stack_encrypt::{Ciphertext, Controlled, Protected, StackCipher}; /// /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { /// // Once, at startup. No request is made, so no user is needed. @@ -317,11 +317,11 @@ pub(crate) async fn load_index_key, I>( /// assert_eq!(cipher.kms().credentials_seen(), ["alice.jwt", "alice.jwt"]); /// /// // Bob's request, on the same cipher. Its only request is its own. -/// let api_key: String = keyset +/// let api_key: Protected = keyset /// .decrypt(stored) /// .with_credential(SecretToken::new("bob.jwt")) /// .await?; -/// assert_eq!(api_key, "sk_live_1234"); +/// assert_eq!(api_key.risky_ref(), "sk_live_1234"); /// assert_eq!( /// cipher.kms().credentials_seen(), /// ["alice.jwt", "alice.jwt", "bob.jwt"] diff --git a/packages/stack-encrypt/src/dynamic/planned.rs b/packages/stack-encrypt/src/dynamic/planned.rs index 12d1ae8ed9..d7bd6b6ac0 100644 --- a/packages/stack-encrypt/src/dynamic/planned.rs +++ b/packages/stack-encrypt/src/dynamic/planned.rs @@ -15,6 +15,7 @@ //! use stack_encrypt::dynamic::{record, Op, Planned, QueryTerm, ValueFrame}; //! use stack_encrypt::target::Scope; //! use stack_encrypt::{AsProtectedRef, DecryptFrom, EncryptInto, StackCipher, StackCipherText}; +//! use std::collections::BTreeMap; //! use vitaminc_aead_frame::serde::to_vec; //! //! # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { @@ -30,26 +31,33 @@ //! "age": { "context": ["users", "age"], "outputs": ["c", "ore"], "type": "uint64" }, //! }))?; //! let plan = record::plan(declaration.as_protected_ref())?; -//! let values = ValueFrame::from_bytes( -//! to_vec(&serde_json::json!({"email": "ada@example.com", "age": 36}))?.as_protected_ref(), -//! )?; //! -//! // A record under the plan, bound to its row. -//! let row: StackCipherText = Planned::new(&plan, values.clone()) +//! // Each value goes straight into a frame, which keeps its bytes under +//! // `Protected` and wipes them when it is dropped. A row is a map of them. +//! let row = || -> Result> { +//! let fields = BTreeMap::from([ +//! ("email", ValueFrame::of("ada@example.com")?), +//! ("age", ValueFrame::of(36u64)?), +//! ]); +//! Ok(ValueFrame::of(&fields)?) +//! }; +//! +//! // A record under the plan, bound to its row. The values are moved in: +//! // a frame is not `Clone`. +//! let stored: StackCipherText = Planned::new(&plan, row()?) //! .encrypt_into_with_context(&keyset, Scope::new(42u64).bind(9u128)) //! .await?; //! let opened = ValueFrame::decrypt_from_with_context( -//! Planned::new(&plan, row), +//! Planned::new(&plan, stored), //! &keyset, //! Scope::new(42u64).bind(9u128), //! ) //! .await?; -//! assert_eq!(opened, values); +//! assert_eq!(opened, row()?); //! //! // A query value under a query plan, by the scope alone. //! let by_email = plan.query("email", Op::Eq)?; -//! let probe = ValueFrame::from_bytes(to_vec("ada@example.com")?.as_protected_ref())?; -//! let term: QueryTerm = Planned::new(&by_email, probe.clone()) +//! let term: QueryTerm = Planned::new(&by_email, ValueFrame::of("ada@example.com")?) //! .encrypt_into_with_context(&keyset, Scope::new(42u64)) //! .await?; //! assert_eq!(term.operator(), Op::Eq); @@ -57,7 +65,7 @@ //! // Or through the field handle, checked against the plan where it is made. //! let same: QueryTerm = plan //! .field("email")? -//! .eq(probe)? +//! .eq(ValueFrame::of("ada@example.com")?)? //! .scope(Scope::new(42u64)) //! .encrypt(&keyset) //! .await?; @@ -80,9 +88,9 @@ use super::{Error, Op, Reason, TermBytes}; use crate::contexts::{self, CallerShape, Contexts, LeafContext, Placeholder}; use crate::plan::{field_label, join, FieldValues, IntoLabel, Slot, FROM_CALL, FROM_PLAN}; use crate::target::{ - ciphertext, indexed, inspect, open, passthrough, AeadContext, Borrowed, CallerContext, - DeclaredContext, DecryptSource, Decryption, EncryptTarget, Encrypted, Encryption, - ExpectedContext, IndexSpec, Indexes, OptionalContext, Owned, Pending, + ciphertext, indexed, inspect, open, AeadContext, Borrowed, CallerContext, DeclaredContext, + DecryptSource, Decryption, EncryptTarget, Encrypted, Encryption, ExpectedContext, IndexSpec, + Indexes, OptionalContext, Owned, Pending, }; use crate::{Encrypt, KeysetCipher, Label, NonEmpty, PlanError, StackCipherText}; @@ -360,7 +368,7 @@ where where Planned<'p, Plan, ValueFrame, R>: 's, { - Encryption::from_build( + Encryption::from_owned_build( contexts::caller_leaf(), move |source: Planned<'p, Plan, ValueFrame, R>, cipher, context: Self::ContextInput| { let Planned { @@ -524,7 +532,7 @@ where where Planned<'p, QueryPlan, ValueFrame, R>: 's, { - Encryption::from_build( + Encryption::from_owned_build( contexts::caller_leaf(), move |source: Planned<'p, QueryPlan, ValueFrame, R>, cipher, @@ -692,7 +700,11 @@ impl<'p, R: TargetResolver + ?Sized> DynamicQuery<'p, R> { /// without the fields in `absent`: a check that the values' fields are the /// plan's, then each field's verb as its combinator, read out of the /// record by name, under the field's label, zipped so every key request -/// settles in one batch, and the record assembled. This is the one +/// settles in one batch, and the record assembled. The description is +/// handed the values themselves. Every sealed or indexed field reads its +/// value in place, and then each passthrough field's value is moved into the +/// output, so no value is copied. The values left over are dropped, and a +/// frame wipes itself when it drops. This is the one /// lowering of a data plan, as the derive's generated code is of a typed /// record: `encrypt_with` and `contexts()` run it. The /// checks a binding asks without a cipher ([`check_values`], @@ -707,8 +719,10 @@ impl<'p, R: TargetResolver + ?Sized> DynamicQuery<'p, R> { pub(super) fn compose<'s, K: 'static>( plan: &Plan, absent: &Absent, -) -> Result, crate::Error> { +) -> Result, crate::Error> { let names = lowered_names(plan, absent); + // The passthrough fields, whose values are moved into the output. + let mut carried: Vec> = Vec::new(); let mut record: Encryption<'s, FieldValues, Vec<(Arc, Slot)>, K, DeclaredContext> = inspect::(move |values| check_names(values, &names)) .map(|()| Vec::new()); @@ -741,15 +755,33 @@ pub(super) fn compose<'s, K: 'static>( } } .named(&name); - record = - record - .zip(operation) - .map(move |(mut slots, slot): (Vec<(Arc, Slot)>, Slot)| { - slots.push((name, slot)); - slots - }); + if keys_nothing { + carried.push(Arc::clone(&name)); + } + record = record.zip(operation).map( + move |(mut slots, slot): (Vec<(Arc, Slot)>, Option)| { + slots.extend(slot.map(|slot| (name, slot))); + slots + }, + ); } - Ok(record.map(FieldValues::from_slots)) + // The record's checks have read the values by now, so a passthrough + // field that is missing has already failed the record. + let moved = Encryption::from_owned_build( + Vec::new(), + move |mut values: FieldValues, cipher, _: DeclaredContext| { + let slots: Vec<(Arc, Slot)> = carried + .into_iter() + .filter_map(|name| values.take_slot(&name).map(|slot| (name, slot))) + .collect(); + Pending::ready(cipher, Ok(slots)) + }, + ); + // The output's slots are read by name, so their order does not matter. + Ok(moved.zip(record).map(|(moved, mut slots)| { + slots.extend(moved); + FieldValues::from_slots(slots) + })) } /// The opening of a stored record's values under `plan`, without the @@ -826,10 +858,14 @@ fn lowered_names(plan: &Plan, absent: &Absent) -> Vec { /// One field's verb as its combinator over the field's value, lifted to /// read the field out of the record. `None` for a target field, which the /// resolver runs and the lowering never sees. +/// +/// A passthrough field's combinator only checks that the record has the +/// field, and yields no slot: its value is moved into the output afterwards +/// ([`compose`]), not copied here. fn operation_of<'s, K: 'static>( field: &FieldPlan, name: &Arc, -) -> Option> { +) -> Option, K, CallerContext>> { let indexes = field.indexes(); Some(match field.verb() { Verb::Encrypt => lift( @@ -841,10 +877,16 @@ fn operation_of<'s, K: 'static>( name, ), Verb::Index => lift(indexes.operations::(), name), - Verb::Passthrough => lift( - passthrough::(), - name, - ), + Verb::Passthrough => { + let name = Arc::clone(name); + inspect::(move |values| { + values + .get::(&name) + .map(drop) + .ok_or_else(|| field_type(&name, type_name::())) + }) + .map(|()| None) + } Verb::Target => return None, }) } @@ -862,7 +904,7 @@ fn lowered_fields<'p>(plan: &'p Plan, absent: &'p Absent) -> impl Iterator( operation: Encryption<'s, ValueFrame, T, K, CallerContext>, name: &Arc, -) -> Encryption<'s, FieldValues, Slot, K, CallerContext> +) -> Encryption<'s, FieldValues, Option, K, CallerContext> where T: std::any::Any + Send + 'static, K: 'static, @@ -874,7 +916,7 @@ where .get::(&name) .ok_or_else(|| field_type(&name, type_name::())) }) - .map(Slot::new) + .map(|output| Some(Slot::new(output))) } /// The values' fields against the plan's, both ways, and each at the type @@ -1135,7 +1177,7 @@ mod tests { keyset .run( description, - &values(Some(Tree::UInt32(34)), Some(Tree::UInt64(7))), + values(Some(Tree::UInt32(34)), Some(Tree::UInt64(7))), DeclaredContext::default(), ) .await diff --git a/packages/stack-encrypt/src/dynamic/query.rs b/packages/stack-encrypt/src/dynamic/query.rs index 0443dd74ee..1d35db374a 100644 --- a/packages/stack-encrypt/src/dynamic/query.rs +++ b/packages/stack-encrypt/src/dynamic/query.rs @@ -42,7 +42,7 @@ //! declares only one of them is answered through it. Every order term is //! derived over the value's order key: a float's ties `-0.0` with //! `0.0` and sorts every NaN last, and text's is its fold. An ordering over -//! bytes is not answered, as `op::Ordered` does not cover them. Nor is one +//! bytes is not answered, as `Orderable` does not cover them. Nor is one //! over an 8-bit integer, which has no order term. A timestamp orders by the //! microsecond and a decimal by value, so `1.5` ties `1.50`. //! @@ -213,7 +213,7 @@ impl Op { /// The kinds the ordering operators are answered over: the integers of 16 /// bits and wider, `int16` to `uint128`, the floats, text, and dates, -/// timestamps and decimals, as [`op::Ordered`](crate::op::Ordered) covers +/// timestamps and decimals, as [`Orderable`](crate::Orderable) covers /// them in the typed path. Not `int8` or `uint8`, which have no order term. /// Each orders by its order key; a `float32` is ordered as the /// `f64` it widens to, as the typed path asks. @@ -824,9 +824,14 @@ fn query_tokens(value: &ValueFrame, options: &MatchOptions) -> Result ValueFrame { -/// let input = json!({"predicate": predicate, "vars": r#"{"min": 18, "r": "sibling"}"#}); -/// ValueFrame::from_bytes(frame::serde::to_vec(&input).unwrap().as_protected_ref()).unwrap() +/// let parts = std::collections::BTreeMap::from([ +/// ("predicate", ValueFrame::of(predicate).unwrap()), +/// ("vars", ValueFrame::of(r#"{"min": 18, "r": "sibling"}"#).unwrap()), +/// ]); +/// ValueFrame::of(&parts).unwrap() /// }; /// let check = |predicate: &str| { /// check_query(&plan, "profile", Op::Match, input(predicate), &Documents) @@ -2287,7 +2292,8 @@ mod tests { .as_protected_ref(), ) .expect("context"); - let value = value.clone(); + // A frame is not `Clone`: the future owns a frame of the same bytes. + let value = ValueFrame::from_bytes(value.as_protected_ref()).expect("a frame"); async move { super::super::term(keyset, &value, &IndexSpec::Equality, ctx) .await @@ -2295,14 +2301,16 @@ mod tests { } }; let day = frame(Some(Logical::Date), Physical::Int(Int::I32(19_782))); - let term = ask("day", Op::Eq, day.clone()).await.unwrap(); - assert_eq!(term.operand(), &Operand::One(stored(&day, "day").await)); + let expected = stored(&day, "day").await; + let term = ask("day", Op::Eq, day).await.unwrap(); + assert_eq!(term.operand(), &Operand::One(expected)); let at = frame( Some(Logical::Timestamp(TimeUnit::Nanos)), Physical::Int(Int::I128(1_760_662_923_123_456_789)), ); - let term = ask("at", Op::Eq, at.clone()).await.unwrap(); - assert_eq!(term.operand(), &Operand::One(stored(&at, "at").await)); + let expected = stored(&at, "at").await; + let term = ask("at", Op::Eq, at).await.unwrap(); + assert_eq!(term.operand(), &Operand::One(expected)); let price = frame( Some(Logical::Decimal { scale: 2 }), Physical::Int(Int::I64(3400)), diff --git a/packages/stack-encrypt/src/dynamic/record.rs b/packages/stack-encrypt/src/dynamic/record.rs index 584de1ec64..d6ff7a6cd8 100644 --- a/packages/stack-encrypt/src/dynamic/record.rs +++ b/packages/stack-encrypt/src/dynamic/record.rs @@ -1837,7 +1837,7 @@ pub fn encrypt_with<'a, K: 'static>( let description = compose::(plan, &absent).map_err(|_| Error::Internal)?; let eql = Pending::all(cipher, pendings); cipher - .run(description, &values, extend) + .run(description, values, extend) .zip(eql) .try_map(move |(values, eql)| shape_record(values, eql, &shape, &absent)) } @@ -1862,7 +1862,7 @@ pub fn encrypt_with<'a, K: 'static>( let mut positions = Vec::with_capacity(groups.len()); for (absent, at, values) in groups { let mut rows = Vec::with_capacity(values.len()); - for values in &values { + for values in values { let description = compose::(plan, &absent).map_err(|_| Error::Internal)?; rows.push(cipher.run(description, values, extend.clone())); } diff --git a/packages/stack-encrypt/src/dynamic/term.rs b/packages/stack-encrypt/src/dynamic/term.rs index fc8a016252..1cc48a154d 100644 --- a/packages/stack-encrypt/src/dynamic/term.rs +++ b/packages/stack-encrypt/src/dynamic/term.rs @@ -48,10 +48,17 @@ use serde::{Deserialize, Serialize, Serializer}; use super::{Error, Reason}; use crate::json::{JsonOptions, JsonPath}; -use crate::sem::{DefaultMatch, MatchOptions, Orderable, TermError, Tokenizer}; -use crate::target::{chosen, CallerContext, ConsumeSource, Encryption, Index, IndexSpec, Pending}; +use crate::sem::{ + ope, order_error, order_pending, ore, ore_block, ore_block_error, target_of, DefaultMatch, + MatchOptions, TermError, Tokenizer, +}; +use crate::target::{ + chosen, CallerContext, Encryption, Index, IndexSpec, Pending, Source, WipeSource, +}; use crate::value::{Date, Decimal, Timestamp}; +use crate::Orderable; use crate::{Encrypt, IntoPrfContext, KeysetCipher, NonEmpty}; +use vitaminc_ore::OrderTarget; /// The runtime half of [`IndexSpec`]: the domain table, and the index's wire /// form in a record plan. @@ -457,11 +464,12 @@ pub async fn term<'c, K, P, D>( ) -> Result, Error> where K: DataKeySource + IndexKeySource + Sync + 'static, - P: Encrypt + Clone, + P: Encrypt + EncryptRef, D: IntoPrfContext<'c>, { - // A value the index does not take is refused as that kind, first. - if !kind.defines(value.clone()) { + // A value the index does not take is refused as that kind, first. The + // checks read the value in place. + if !kind.defines(value.lend()) { return Err(Error::Term { field: None, kind: kind.clone(), @@ -472,7 +480,7 @@ where // derived as the empty filter a stored value keeps. The value is read // as it is, not re-framed, so every scalar `defines` takes is one a // probe takes. - prepare_probe(kind, value.clone())?; + prepare_probe(kind, value.lend())?; derive(cipher, value, kind, context)? .await .map(TermBytes::into_bytes) @@ -634,12 +642,10 @@ enum OrderIndex { /// Rust type the typed path would have named; `None` for a scalar it does /// not order ([`ordered`]). /// -/// Text and bytes are copied out of the walk into an owned `String` or -/// `Vec` and moved to the encryptor, which wraps the one copy in a -/// `Zeroizing` on receipt: the order term takes its value by ownership -/// (the visitor carries it) and wipes it, so nothing is freed with the -/// plaintext still in it, in a guest's linear memory, where the host can -/// read it. +/// Text and bytes are read where the walk holds them, and not copied: +/// each term makes the scalar's order encoding first, under `Protected`, +/// so nothing is freed with the plaintext still in it, in a guest's linear +/// memory, where the host can read it. /// /// Each scalar is encoded at the target of the Rust type named here /// ([`Orderable`]), as on the typed path: text by its case and accent @@ -690,14 +696,14 @@ where Physical::Int(Int::U128(v)) => order(cipher, index, v, context), Physical::Float(Float::F32(v)) => order(cipher, index, v, context), Physical::Float(Float::F64(v)) => order(cipher, index, v, context), - Physical::Text(t) => order(cipher, index, t.to_owned(), context), - Physical::Bytes(b) => order(cipher, index, b.to_vec(), context), + Physical::Text(t) => order(cipher, index, t, context), + Physical::Bytes(b) => order_at(cipher, index, OrderTarget::Bytes, b, context), _ => return None, }) } -/// The term of `value` under `index`. The term's bytes are its frozen -/// encoding: the raw CLLW ciphertext, or the serialised block ORE one. +/// The term of `value` under `index`, encoded at the target of its own +/// type ([`Orderable`]). fn order<'a, 'c, K: 'static, T, D>( cipher: &'a KeysetCipher<'_, K>, index: OrderIndex, @@ -708,16 +714,60 @@ where T: Orderable, D: IntoPrfContext<'c>, { + order_at(cipher, index, target_of::(), value, context) +} + +/// The term of `value` under `index`, encoded as `target`. The term's +/// bytes are its frozen encoding: the raw CLLW ciphertext, or the +/// serialised block ORE one. +/// +/// Bytes are not [`Orderable`]: no ordering operator compares them, so the +/// typed path has no order term of bytes. A data plan can still declare an +/// order index on bytes, and the rows it stored carry the term, so this path +/// derives it as it did, by naming the `Bytes` target. +fn order_at<'a, 'c, K: 'static, V, D>( + cipher: &'a KeysetCipher<'_, K>, + index: OrderIndex, + target: OrderTarget, + value: V, + context: NonEmpty, +) -> Pending<'a, TermBytes, K> +where + V: Encrypt, + D: IntoPrfContext<'c>, +{ + let context = context.into_prf_context().into_owned(); match index { - OrderIndex::Ore => cipher - .ore_term(value, context) - .map(|term| TermBytes(term.as_ref().to_vec())), - OrderIndex::Ope => cipher - .ope_term(value, context) - .map(|term| TermBytes(term.as_ref().to_vec())), - OrderIndex::OreBlock => cipher - .ore_block_term(value, context) - .map(|term| TermBytes(term.into_bytes())), + OrderIndex::Ore => order_pending( + cipher, + target, + value, + context, + order_error, + |prf, encoding, context| { + ore(prf, encoding, context).map(|term| TermBytes(term.as_ref().to_vec())) + }, + ), + OrderIndex::Ope => order_pending( + cipher, + target, + value, + context, + order_error, + |prf, encoding, context| { + ope(prf, encoding, context).map(|term| TermBytes(term.as_ref().to_vec())) + }, + ), + OrderIndex::OreBlock => order_pending( + cipher, + target, + value, + context, + ore_block_error, + |prf, encoding, context| { + ore_block(prf, encoding, context).map(|term| TermBytes(term.into_bytes())) + }, + ), } } @@ -873,23 +923,25 @@ impl Index for IndexSpec { fn spec(&self) -> IndexSpec { self.clone() } - fn operation<'s, K: 'static, M: ConsumeSource<'s, ValueFrame>>( + fn operation<'s, K: 'static, M: WipeSource<'s, ValueFrame>>( &self, ) -> Encryption<'s, ValueFrame, TermBytes, K, CallerContext, M> { let spec = self.clone(); - chosen(move |source: M::Source, cipher, cx: CallerContext| { - // A term derives under the query context: the scopes, with no - // binding. - let (query, stored) = (cx.query(), cx.stored()); - let context = match cx.validated() { - Ok(context) => CallerContext::query_nonempty(context), - Err(error) => return Pending::failed(cipher, error), - }; - match derive(cipher, M::view(&source), &spec, context) { - Ok(pending) => pending.under_context(query, stored), - Err(error) => Pending::failed(cipher, error.into_crate()), - } - }) + chosen( + move |source: Source<'_, ValueFrame>, cipher, cx: CallerContext| { + // A term derives under the query context: the scopes, with no + // binding. + let (query, stored) = (cx.query(), cx.stored()); + let context = match cx.validated() { + Ok(context) => CallerContext::query_nonempty(context), + Err(error) => return Pending::failed(cipher, error), + }; + match derive(cipher, source.view(), &spec, context) { + Ok(pending) => pending.under_context(query, stored), + Err(error) => Pending::failed(cipher, error.into_crate()), + } + }, + ) } } @@ -1255,15 +1307,17 @@ mod tests { ordered!(1.5f32, Tree::Float32(1.5), "f32"); ordered!(2.5f64, Tree::Float64(2.5), "f64"); ordered!("alice".to_string(), s("alice"), "text"); - ordered!(b"ab".to_vec(), bytes(b"ab"), "bytes"); // A date, a timestamp and a decimal, as their `value` types. ordered!( - crate::value::Date::from_days_since_epoch(19_782).expect("in range"), + crate::value::Date::new(jiff::civil::date(2024, 2, 29)), Tree::Typed(Logical::Date, Box::new(Tree::Int32(19_782))), "date" ); ordered!( - crate::value::Timestamp::new(1_700_000_000, 123_456_789).expect("in range"), + crate::value::Timestamp::new( + jiff::Timestamp::new(1_700_000_000, 123_456_789).expect("in range") + ) + .expect("in range"), Tree::Typed( Logical::Timestamp(vitaminc_aead::plaintext::TimeUnit::Nanos), Box::new(Tree::Int128(1_700_000_000_123_456_789)) @@ -1271,7 +1325,7 @@ mod tests { "timestamp" ); ordered!( - crate::value::Decimal::new(-123_450, 2).expect("in range"), + crate::value::Decimal::new(rust_decimal::Decimal::new(-123_450, 2)), Tree::Typed( Logical::Decimal { scale: 2 }, Box::new(Tree::Int128(-123_450)) diff --git a/packages/stack-encrypt/src/dynamic/value_frame.rs b/packages/stack-encrypt/src/dynamic/value_frame.rs index 0420ee8d2f..d47035cff0 100644 --- a/packages/stack-encrypt/src/dynamic/value_frame.rs +++ b/packages/stack-encrypt/src/dynamic/value_frame.rs @@ -367,14 +367,6 @@ impl Decrypt for ValueFrame { } } -/// A deep copy into a fresh [`Protected`] buffer, which wipes on drop as the -/// original does. -impl Clone for ValueFrame { - fn clone(&self) -> Self { - Self(Equatable::new(self.0.risky_ref().to_vec())) - } -} - /// Two frames are equal when their bytes are. The bytes are compared in /// constant time, so the comparison does not reveal where two frames first /// differ. Frames of different lengths are unequal at once, which reveals @@ -1351,7 +1343,6 @@ mod tests { #[test] fn frames_with_the_same_bytes_are_equal() { let frame = ValueFrame::of("alice").unwrap(); - assert_eq!(frame, frame.clone()); assert_eq!( frame, ValueFrame::from_bytes(frame.as_protected_ref()).unwrap() @@ -1597,13 +1588,11 @@ mod tests { ); let back = Tree::from_frame(frame.risky_ref()).expect("reads back"); assert_eq!(back, value); - let copy = frame.clone(); - assert_eq!(copy.risky_ref(), frame.risky_ref()); - assert_ne!(copy.risky_ref().as_ptr(), frame.risky_ref().as_ptr()); - let bytes = copy.into_inner(); + let expected = value.to_frame().expect("frames"); + let bytes = frame.into_inner(); assert_eq!( bytes.risky_ref(), - frame.risky_ref(), + expected.risky_ref(), "the frame, still protected" ); } diff --git a/packages/stack-encrypt/src/field_reference.rs b/packages/stack-encrypt/src/field_reference.rs index c34ba674bc..07b3265571 100644 --- a/packages/stack-encrypt/src/field_reference.rs +++ b/packages/stack-encrypt/src/field_reference.rs @@ -648,10 +648,11 @@ owned_query_inputs!( f64, String, Vec, - crate::value::Date, - crate::value::Timestamp, - crate::value::Decimal, ); +#[cfg(feature = "jiff")] +owned_query_inputs!(crate::value::Date, crate::value::Timestamp); +#[cfg(feature = "rust_decimal")] +owned_query_inputs!(crate::value::Decimal); impl QueryInput for Option { type Value = Option; fn into_value(self) -> Self::Value { @@ -1042,7 +1043,6 @@ mod tests { /// owned one. #[test] fn a_query_input_is_owned_or_copied_in() { - use crate::value::{Date, Decimal, Timestamp}; macro_rules! owned_as_it_is { ($($value:expr),+ $(,)?) => {$( assert_eq!($value.into_value(), $value); @@ -1066,18 +1066,24 @@ mod tests { String::from("ada"), b"ada".to_vec(), ); - let date = Date::from_days_since_epoch(7).unwrap(); - assert_eq!(date.into_value().days_since_epoch(), 7); - let instant = Timestamp::new(7, 9).unwrap(); - let instant = instant.into_value(); - assert_eq!((instant.seconds(), instant.nanoseconds()), (7, 9)); - let decimal = Decimal::new(75, 1).unwrap(); - let decimal = decimal.into_value(); - assert_eq!((decimal.mantissa(), decimal.scale()), (75, 1)); assert_eq!("ada".into_value(), String::from("ada")); assert_eq!((&String::from("ada")).into_value(), String::from("ada")); assert_eq!(b"ada"[..].into_value(), b"ada".to_vec()); assert_eq!((&b"ada".to_vec()).into_value(), b"ada".to_vec()); } + + /// A date, a timestamp and a decimal are the query's as they are. + #[cfg(all(feature = "jiff", feature = "rust_decimal"))] + #[test] + fn a_date_a_timestamp_and_a_decimal_are_owned_query_inputs() { + use crate::value::{Date, Decimal, Timestamp}; + let day = jiff::civil::date(1970, 1, 8); + assert_eq!(Date::new(day).into_value().to_jiff(), day); + let instant = jiff::Timestamp::new(7, 9).unwrap(); + let held = Timestamp::new(instant).unwrap(); + assert_eq!(held.into_value().to_jiff(), instant); + let number = rust_decimal::Decimal::new(75, 1); + assert_eq!(Decimal::new(number).into_value().to_decimal(), number); + } } diff --git a/packages/stack-encrypt/src/json/derive.rs b/packages/stack-encrypt/src/json/derive.rs index 36484acca3..c277314a40 100644 --- a/packages/stack-encrypt/src/json/derive.rs +++ b/packages/stack-encrypt/src/json/derive.rs @@ -35,6 +35,7 @@ use super::{JsonDocument, JsonEntry, JsonExtracted, JsonHeader, JsonOptions, Jso use crate::keyset::KeysetState; use crate::sem::TermError; use crate::target::{AeadContext, Decryption, Pending, Request, RequiredContext}; +use crate::target::{Held, Source}; use crate::ContextPiece; use crate::{DecryptSource, Descriptor, Error, KeysetCipher, NonEmpty, StackCipher}; @@ -523,21 +524,18 @@ fn leaf_op( context: &Context<'_>, value: &Value, ) -> Result>, TermError> { - Ok(match value { - Value::Number(n) => Some( - crate::sem::ope(prf, n.as_f64().unwrap_or(0.0), context.clone())? - .into_inner() - .as_ref() - .to_vec(), - ), - Value::String(s) => Some( - crate::sem::ope(prf, s.clone(), context.clone())? - .into_inner() - .as_ref() - .to_vec(), - ), - _ => None, - }) + use crate::sem::{ope, order_encoding, order_error, target_of}; + // The leaf read in place, encoded as the scalar index encodes an `f64` + // or a `String`. + let encoding = match value { + Value::Number(n) => order_encoding(target_of::(), n.as_f64().unwrap_or(0.0)), + Value::String(s) => order_encoding(target_of::(), s.as_str()), + _ => return Ok(None), + } + .map_err(order_error)?; + Ok(Some( + ope(prf, &encoding, context.clone())?.as_ref().to_vec(), + )) } // ============================================================================= @@ -808,23 +806,29 @@ fn query_terms( }) } -/// Seal `value` into a [`JsonDocument`]: one data key for the document, +/// Seal the document `source` holds into a [`JsonDocument`]: one data key for +/// the document, /// requested under the descriptor of the stored context `stored`, and every /// entry sealed under it with the AAD that binds the entry to the document, /// the column and its ordinal. The selectors and the other terms derive /// under the query context `query`, as [`terms_pending`] derives a query's, /// so a document bound to its row is still found by a query under the /// scopes. The two are one context for a caller with no binding. +/// +/// The document is read in place. A document `source` was given is wiped +/// when this returns, or when the pending that keeps it is dropped. A +/// borrowed document is copied only when the keyset is not loaded yet: the +/// pending then keeps its own copy until it settles, wiped on drop. pub(crate) fn seal_pending<'a, K: 'static>( - value: Value, + source: Source<'_, Value>, options: &JsonOptions, cipher: &'a KeysetCipher<'_, K>, query: NonEmpty>, stored: NonEmpty>, ) -> Pending<'a, JsonDocument, K> { - // The caller's document, owned here: wiped when this returns, also when - // the context is refused below. - let value = PlainJson::protect(value); + // Guarded from here, so a document this call was given is wiped on + // every return below. + let document = Sealing::from(source); let piece = stored.into_context(); let descriptor = Descriptor::from_piece(&piece); if let Err(error) = descriptor.check() { @@ -844,7 +848,7 @@ pub(crate) fn seal_pending<'a, K: 'static>( let loaded = cipher.loaded_state().cloned(); let walked = match &loaded { Some(keyset) => match walk( - value.risky_ref().value(), + document.view(), options, &keyset.prf, &prf_context, @@ -860,10 +864,10 @@ pub(crate) fn seal_pending<'a, K: 'static>( let opens = |number: &serde_json::Number| { number_text(number).is_some_and(|text| number_text_opens(&text)) }; - if !every_number(value.risky_ref().value(), &opens) { + if !every_number(document.view(), &opens) { return Pending::failed(cipher, Error::Aead); } - match sealed_root_plaintext(value.risky_ref().value()) { + match sealed_root_plaintext(document.view()) { Ok(bytes) => Some(bytes), Err(error) => return Pending::failed(cipher, Error::Other(Box::new(error))), } @@ -886,6 +890,7 @@ pub(crate) fn seal_pending<'a, K: 'static>( // The pending asks for the keyset beside the data key. It keeps the // document, wiped on drop, and walks it once the keyset is loaded. _ => { + let value = document.into_guarded(); let options = options.clone(); Pending::request( cipher, @@ -910,6 +915,40 @@ pub(crate) fn seal_pending<'a, K: 'static>( } } +/// The document [`seal_pending`] reads: the caller's borrow, or the value it +/// was given, guarded so that it is wiped on drop. +enum Sealing<'b> { + Lent(&'b Value), + Given(Protected), +} + +impl<'b> From> for Sealing<'b> { + fn from(source: Source<'b, Value>) -> Self { + match source.into_held() { + Held::Lent(value) => Self::Lent(value), + Held::Given(value) => Self::Given(PlainJson::protect(value)), + } + } +} + +impl Sealing<'_> { + /// The document, read in place. + fn view(&self) -> &Value { + match self { + Self::Lent(value) => value, + Self::Given(value) => value.risky_ref().value(), + } + } + /// The document for a pending to keep until it settles: the value this + /// was given, or a guarded copy of the borrow. + fn into_guarded(self) -> Protected { + match self { + Self::Lent(value) => PlainJson::protect(value.clone()), + Self::Given(value) => value, + } + } +} + /// The AAD an entry is sealed and opened under, PAE-framed: the domain; /// `keyset_id`, the keyset the document's data key was minted under; /// `column`, the column's own AAD (its caller context); `key_tag`, the diff --git a/packages/stack-encrypt/src/json/inputs.rs b/packages/stack-encrypt/src/json/inputs.rs index 80e1c8936d..78d1eff4a4 100644 --- a/packages/stack-encrypt/src/json/inputs.rs +++ b/packages/stack-encrypt/src/json/inputs.rs @@ -24,7 +24,7 @@ use super::{ }; use crate::refusal::{Error, Reason}; use crate::sem::TermError; -use crate::target::{AeadContext, CallerContext, DeclaredContext, Index, Json, Owned}; +use crate::target::{AeadContext, CallerContext, DeclaredContext, Owned}; use crate::{ContextPiece, KeysetCipher, Label, NonEmpty, Pending}; /// A document parsed from an input, wiped when it drops. @@ -449,7 +449,11 @@ fn terms<'a, K: 'static>( value: Value, ) -> Pending<'a, crate::json::JsonTerms, K> { keyset.run( - Index::::operation::(&Json::new(options.clone())).under(under.column()), + // A refused context wipes the document through its own guard. + crate::target::json_terms::(options.clone()) + .under_refusing(under.column(), |source| { + source.release(|value| drop(crate::json::PlainJson::protect(value))) + }), value, under.parts.clone(), ) @@ -489,28 +493,27 @@ pub(crate) fn derive<'a, K: 'static>( ) -> Result, Error> { Ok(match input { Input::Document(document) => { - // Checked before the clone, which recurses once per level: a - // document a caller built deeper than the index reads is - // refused as the walk would refuse it, not cloned first. + // A document a caller built deeper than the index reads is + // refused as the walk would refuse it, before it is handed on. if !super::text::nests_within(&document.0, super::MAX_DEPTH) { return Err(term(TermError::JsonTooDeep)); } - terms(keyset, options, under, document.0.clone()) + // Each operand below is moved into its terms, not copied, and + // wiped there. + terms(keyset, options, under, document.take()) .map(|terms| Derived::Query(JsonQuery::of_terms(terms))) } - Input::EqAt(path, value) => terms(keyset, options, under, path.holding(value.0.clone())) + Input::EqAt(path, value) => terms(keyset, options, under, path.holding(value.take())) .map(|terms| Derived::Query(JsonQuery::at_path(terms))), Input::Ordering(_, path, value) => { - terms(keyset, options, under, path.holding(value.0.clone())) + terms(keyset, options, under, path.holding(value.take())) .map(|terms| Derived::Leaf(JsonLeafQuery::of_leaf(&terms))) } - Input::Between(path, low, high) => { - terms(keyset, options, under, path.holding(low.0.clone())) - .zip(terms(keyset, options, under, path.holding(high.0.clone()))) - .map(|(lo, hi)| { - Derived::Range(JsonLeafQuery::of_leaf(&lo), JsonLeafQuery::of_leaf(&hi)) - }) - } + Input::Between(path, low, high) => terms(keyset, options, under, path.holding(low.take())) + .zip(terms(keyset, options, under, path.holding(high.take()))) + .map(|(lo, hi)| { + Derived::Range(JsonLeafQuery::of_leaf(&lo), JsonLeafQuery::of_leaf(&hi)) + }), // The three below derive under the keyset's index key. With the // keyset loaded they derive now, so a refusal is this call's own // error. With a keyset that is not loaded yet, the pending diff --git a/packages/stack-encrypt/src/json/plaintext.rs b/packages/stack-encrypt/src/json/plaintext.rs index 712942e2c9..624e62f203 100644 --- a/packages/stack-encrypt/src/json/plaintext.rs +++ b/packages/stack-encrypt/src/json/plaintext.rs @@ -149,7 +149,8 @@ use crate::Encrypt; /// # What wiping covers /// /// The document is wiped when the `JsonPlaintext` is dropped -/// ([`ZeroizeOnDrop`]). A clone is wiped when it is dropped too. The JSON +/// ([`ZeroizeOnDrop`]). It is not `Clone`, so there is one document to +/// wipe. The JSON /// text written to seal the document is built in a buffer of its final /// size, and that buffer is wiped when the document has been sealed. /// @@ -207,12 +208,6 @@ impl From for JsonPlaintext { } } -impl Clone for JsonPlaintext { - fn clone(&self) -> Self { - Self(self.0.clone()) - } -} - impl Zeroize for JsonPlaintext { /// Wipe the document. What is left is a JSON `null`. fn zeroize(&mut self) { @@ -452,12 +447,10 @@ mod tests { } #[test] - fn zeroize_leaves_a_null_and_a_clone_is_its_own_copy() { + fn zeroize_leaves_a_null() { let mut document = JsonPlaintext::from(json!({"secret": "hunter2", "pin": 1234})); - let copy = document.clone(); document.zeroize(); assert_eq!(document.value(), &Value::Null); - assert_eq!(copy.value(), &json!({"secret": "hunter2", "pin": 1234})); } #[test] diff --git a/packages/stack-encrypt/src/json/target.rs b/packages/stack-encrypt/src/json/target.rs index 0ddb4e5328..e409e0ad91 100644 --- a/packages/stack-encrypt/src/json/target.rs +++ b/packages/stack-encrypt/src/json/target.rs @@ -51,7 +51,7 @@ pub trait JsonTarget: EncryptTarget { where S: 's, { - Encryption::from_build( + Encryption::from_owned_build( Self::json_encryption::(options.clone()).shapes(), move |source: S, cipher, context| { let guarded = Protected::new(source); @@ -104,7 +104,7 @@ impl + MaybeSend> JsonTarget> for Option< { Encryption::from_build( T::json_encryption::(options.clone()).shapes(), - move |source: &'s Option, cipher, context: T::ContextInput| match source { + move |source: &Option, cipher, context: T::ContextInput| match source { Some(value) => cipher .run(T::json_encryption(options), value, context) .map(Some), @@ -119,7 +119,7 @@ impl + MaybeSend> JsonTarget> for Option< where S: 's, { - Encryption::from_build( + Encryption::from_owned_build( T::json_owned_encryption::(options.clone()).shapes(), move |source: Option, cipher, context: T::ContextInput| { // Building the target's declaration can panic, so the value @@ -319,7 +319,7 @@ where { match options { Ok(options) => T::json_owned_encryption(options), - Err(error) => Encryption::from_build(Vec::new(), move |mut source: S, cipher, _| { + Err(error) => Encryption::from_owned_build(Vec::new(), move |mut source: S, cipher, _| { source.zeroize(); Pending::failed(cipher, error.into()) }), diff --git a/packages/stack-encrypt/src/lib.rs b/packages/stack-encrypt/src/lib.rs index 86ed6c0d42..d380753ec2 100644 --- a/packages/stack-encrypt/src/lib.rs +++ b/packages/stack-encrypt/src/lib.rs @@ -93,7 +93,8 @@ assert_eq!(plaintext, "secret message"); //! # async fn example(cipher: stack_encrypt::StackCipher) -> Result<(), stack_encrypt::Error> { //! # let keyset = cipher.default_keyset(); //! let ct = keyset.encrypt_with_context("4111 1111 1111 1111".to_owned(), "users/42/card").await?; -//! let card: String = keyset.decrypt_with_context(ct, "users/42/card").await?; // ok +//! let card: stack_encrypt::Protected = +//! keyset.decrypt_with_context(ct, "users/42/card").await?; // ok //! # Ok(()) //! # } //! ``` @@ -753,9 +754,66 @@ 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, IntoAad, - IntoContext, Node, PassthroughFrame, Unspecified, + CipherText, Context, ContextPiece, ContextTag, DecodeError, Decrypt, Encrypt, EncryptRef, + IntoAad, IntoContext, Node, PassthroughFrame, Unspecified, }; +/// A type with an order target of its own: what an order index +/// ([`Ore`], [`Ope`], [`OreBlock`]), an order term ([`sem::OreTerm`], +/// [`sem::OpeTerm`], [`sem::OreBlockTerm`]) and the ordering operators +/// ([`op::Lt`] and the others) are bounded by. It is vitaminc-ore's trait, +/// and its table is vitaminc-ore's. This crate names no target. +/// +/// | Type | Target | +/// | --- | --- | +/// | `u16` to `u128`, `i16` to `i128` | the integer at its own width | +/// | `f32`, `f64` | `F64`: an `f32` widens to it exactly, `-0.0` ties `0.0`, every NaN is one value after `+Infinity` | +/// | `String`, `&str` | `Text`: Unicode 16 NFC with case and accents folded | +/// | `value::Date` | `Date`: the day | +/// | `value::Timestamp` | `Timestamp`: the instant truncated to the microsecond, so instants in one microsecond tie | +/// | `value::Decimal` | `Decimal`: the number with its scale normalised, so `1.5` ties `1.50` | +/// +/// A reference to each is `Orderable` too. An order index reads its value +/// in place, so it also asks for [`EncryptRef`], and in `Owned` mode for +/// `Zeroize` ([`target::WipeSource`]). +/// +/// vitaminc-ore's table also has jiff's `civil::Date` and `Timestamp`, and +/// rust_decimal's `Decimal`. Those types are `Copy` and are not `Zeroize`, +/// so nothing wipes them. A target and an owned index need `Zeroize`, so +/// neither takes them. The keyset's term functions +/// ([`KeysetCipher::ore_term`] and the others) and a borrowed index do take +/// them: a value passed by value is a copy the caller still holds. To have +/// the plaintext wiped, use `value::Date`, `value::Timestamp`, or +/// `value::Decimal`. +/// +/// Bytes have no order term. No ordering operator compares bytes, so such +/// a term would answer no query, and would still reveal the order of the +/// rows. vitaminc-ore orders bytes only into a target that is named, and +/// this crate does not name one. +/// +/// A `bool`, a `u8` and an `i8` have no target. An order term over a domain +/// that small tells anyone holding the column too much: with two values it +/// says which rows are `true`, and with 256 it puts every row in one of +/// 256 ranks, which a few known rows resolve to the values. Each keeps its +/// equality term. +/// +/// ```compile_fail +/// use stack_encrypt::sem::OreTerm; +/// +/// let _: Option> = None; // `bool` is not `Orderable` +/// ``` +/// +/// ```compile_fail +/// use stack_encrypt::sem::OpeTerm; +/// +/// let _: Option> = None; // `u8` is not `Orderable` +/// ``` +/// +/// ```compile_fail +/// use stack_encrypt::sem::OreTerm; +/// +/// let _: Option>> = 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)] diff --git a/packages/stack-encrypt/src/op/mod.rs b/packages/stack-encrypt/src/op/mod.rs index a7477733c3..bf6c1eef27 100644 --- a/packages/stack-encrypt/src/op/mod.rs +++ b/packages/stack-encrypt/src/op/mod.rs @@ -123,11 +123,11 @@ pub(crate) mod stats; pub use stats::{Limit, Stats, DEFAULT_CONFIDENCE, MAX_ROWS}; use crate::sem::{ - query, EqualityTerm, MatchConfig, MatchQuery, MatchTerms, OpeTerm, Orderable, OreBlockTerm, - OreTerm, QueryTokens, RangeQuery, + query, EqualityTerm, MatchConfig, MatchQuery, MatchTerms, OpeTerm, OreBlockTerm, OreTerm, + QueryTokens, RangeQuery, }; use crate::target::{DeclaredContext, Equality, Index, Match, Ope, Ore, OreBlock, Owned, Pending}; -use crate::{Error, KeysetCipher, Label, NonEmpty}; +use crate::{Error, KeysetCipher, Label, NonEmpty, Orderable}; /// A query operator: a unit type naming what a query asks of the server, /// and how many plaintexts it asks about ([`Arity`]). @@ -524,7 +524,7 @@ pub trait Input: Sized + 'static { K: 'static; } -impl Input for S { +impl Input for S { type Plaintext = S; type Terms = T; @@ -540,7 +540,9 @@ impl Input for S { K: 'static, { keyset.run( - index.operation::().under(NonEmpty::from(label)), + index + .operation::() + .under_field(NonEmpty::from(label)), self, extend, ) @@ -548,7 +550,7 @@ impl Input for S { } /// Both bounds under the one label, settled together. -impl Input for (S, S) { +impl Input for (S, S) { type Plaintext = S; type Terms = (T, T); @@ -567,12 +569,14 @@ impl Input for (S, S) { let lo = keyset.run( index .operation::() - .under(NonEmpty::from(label.clone())), + .under_field(NonEmpty::from(label.clone())), lo, extend.clone(), ); let hi = keyset.run( - index.operation::().under(NonEmpty::from(label)), + index + .operation::() + .under_field(NonEmpty::from(label)), hi, extend, ); @@ -580,64 +584,6 @@ impl Input for (S, S) { } } -/// A plaintext the ordering operators ([`Lt`], [`Lte`], [`Gt`], [`Gte`], -/// [`Between`]) are answered over: the integers of 16 bits and wider, the -/// floats (`f32` and `f64`), text (`String`), and dates, timestamps and -/// decimals ([`value`](crate::value)). Not `u8` or `i8`, which have no -/// order term ([`Orderable`] says why), as `bool` has none. Each is encoded -/// as its [`Orderable`] target and its terms order as clww-ore orders that -/// encoding: integers as numbers; floats as Postgres's `float8` does, -/// `-0.0` tied with `0.0` and every NaN one value above `+Infinity`, an -/// `f32` as the `f64` it widens to; text by its fold, -/// Unicode 16 NFC with case and accents folded, so `Café`, `cafe` and -/// `CAFÉ` tie and `alice` orders before `Zoe`; dates by day; -/// timestamps by the microsecond, so instants within one microsecond tie; -/// and decimals by value, so `1.5` ties `1.50`. -/// -/// Sealed: a type joins only when the order its terms compare in is the -/// one its operators promise, so a type whose terms could order otherwise -/// (a newtype over folded text, say) must not be able to join. A type that -/// meets every other bound is still refused: -/// -/// ```compile_fail -/// use stack_encrypt::op::Ordered; -/// -/// struct Folded(u32); -/// -/// impl Ordered for Folded {} // `Ordered` is sealed -/// ``` -/// -/// [`Orderable`]: crate::sem::Orderable -#[diagnostic::on_unimplemented( - message = "`{Self}` is not ordered: the ordering operators are answered over the integers of 16 bits and wider, the floats, text, dates, timestamps and decimals", - label = "no ordering operator over this type", - note = "`Lt`, `Lte`, `Gt`, `Gte` and `Between` take `u16` to `u128`, `i16` to `i128`, `f32`, `f64`, a `String`, or a `value::Date`, `value::Timestamp` or `value::Decimal`; a `u8`, an `i8` and a `bool` have no order term" -)] -pub trait Ordered: sealed::Sealed + Orderable {} - -macro_rules! ordered { - ($($ty:ty),+ $(,)?) => {$( - impl sealed::Sealed for $ty {} - impl Ordered for $ty {} - )+}; -} -ordered!( - u16, - u32, - u64, - u128, - i16, - i32, - i64, - i128, - f32, - f64, - String, - crate::value::Date, - crate::value::Timestamp, - crate::value::Decimal, -); - mod sealed { pub trait Sealed {} impl Sealed for super::One {} @@ -850,16 +796,15 @@ impl QueryToken { /// The equality index answers `Eq` over any plaintext with an equality /// domain, and refuses text it cannot normalize (a code point unassigned /// in Unicode 16) before any keyset is resolved, as the dynamic path does. -/// The check normalizes a copy of the value, which vitaminc wipes as it -/// reads it, so the plaintext is `Clone`, as every scalar is. +/// The check reads the value in place, so nothing is copied. impl Supports for Equality where - S: crate::Encrypt + Clone + 'static, + S: crate::Encrypt + vitaminc_aead::EncryptRef + zeroize::Zeroize + 'static, { type Query = EqualityTerm; type Verifier = (); fn prepare(&self, value: &S) -> Result<(), Error> { - Ok(query::equality(value.clone())?) + Ok(query::equality(vitaminc_aead::EncryptRef::lend(value))?) } fn query((): (), term: EqualityTerm, _: QueryToken) -> EqualityTerm { term @@ -874,7 +819,7 @@ impl Equality { impl Supports for Match where - S: AsRef + 'static, + S: AsRef + zeroize::Zeroize + 'static, O: MatchConfig, { type Query = MatchQuery; @@ -898,7 +843,7 @@ impl Match { } /// The ordering operators on the ORE, OPE and block ORE indexes, over the -/// [`Ordered`] types. The query term for a comparison is the index's own +/// types vitaminc-ore orders ([`Orderable`]). The query term for a comparison is the index's own /// term for the value. CLLW ORE's ciphertext has no left half to send /// alone, so what is sent is what is stored, as for an HMAC. Block ORE's /// does, but EQL v4's comparator reads the right half of the operand a @@ -908,7 +853,7 @@ impl Match { macro_rules! orders { ($($index:ident => $term:ident, block: $block:literal),+ $(,)?) => {$( orders!(@one $index => $term, $block; Lt, Lte, Gt, Gte); - impl Supports for $index { + impl Supports for $index { type Query = RangeQuery<$term>; type Verifier = (); fn prepare(&self, (lo, hi): &(S, S)) -> Result<(), Error> { @@ -919,7 +864,7 @@ macro_rules! orders { RangeQuery::new(lo, hi) } } - impl Answers for $term { + impl Answers for $term { type Via = $index; } impl $index { @@ -929,7 +874,7 @@ macro_rules! orders { } )+}; (@one $index:ident => $term:ident, $block:literal; $($op:ident),+) => {$( - impl Supports<$op, S> for $index { + impl Supports<$op, S> for $index { type Query = $term; type Verifier = (); fn prepare(&self, value: &S) -> Result<(), Error> { @@ -939,7 +884,7 @@ macro_rules! orders { term } } - impl Answers<$op, S> for $term { + impl Answers<$op, S> for $term { type Via = $index; } )+}; @@ -1011,14 +956,14 @@ impl LabelledTarget for crate::target::Encrypted {} impl Answers for EqualityTerm where - S: crate::Encrypt + Clone + 'static, + S: crate::Encrypt + vitaminc_aead::EncryptRef + zeroize::Zeroize + 'static, { type Via = Equality; } impl Answers for MatchTerms where - S: AsRef + 'static, + S: AsRef + zeroize::Zeroize + 'static, O: MatchConfig, { type Via = Match; @@ -1425,6 +1370,7 @@ mod tests { /// A date, a timestamp and a decimal are ordered, through every order /// index, and `Between` takes a pair of each. + #[cfg(all(feature = "jiff", feature = "rust_decimal"))] #[test] fn dates_timestamps_and_decimals_are_ordered() { use crate::value::{Date, Decimal, Timestamp}; @@ -1432,9 +1378,12 @@ mod tests { answers::>(); answers::>(); answers::>>(); - let day = || Date::from_days_since_epoch(19_782).expect("in range"); - let at = || Timestamp::new(1_700_000_000, 5).expect("in range"); - let price = || Decimal::new(150, 2).expect("in range"); + let day = || Date::new(jiff::civil::date(2024, 2, 29)); + let at = || { + let instant = jiff::Timestamp::new(1_700_000_000, 5).expect("in range"); + Timestamp::new(instant).expect("in range") + }; + let price = || Decimal::new(rust_decimal::Decimal::new(150, 2)); assert!(Supports::::prepare(&Ore, &day()).is_ok()); assert!(Supports::::prepare(&Ope, &at()).is_ok()); assert!(Supports::::prepare(&OreBlock, &price()).is_ok()); diff --git a/packages/stack-encrypt/src/plan/values.rs b/packages/stack-encrypt/src/plan/values.rs index be2dc8d381..cfa529284b 100644 --- a/packages/stack-encrypt/src/plan/values.rs +++ b/packages/stack-encrypt/src/plan/values.rs @@ -131,6 +131,16 @@ impl FieldValues { } } +/// Let go of every field. A record a data plan encrypts holds its fields as +/// [`ValueFrame`](crate::dynamic::ValueFrame)s, which keep their bytes under +/// `Protected` and wipe them as they drop. So clearing the record wipes +/// each field once. +impl zeroize::Zeroize for FieldValues { + fn zeroize(&mut self) { + self.slots.clear(); + } +} + impl fmt::Debug for FieldValues { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let mut map = f.debug_map(); @@ -145,6 +155,28 @@ impl fmt::Debug for FieldValues { mod tests { use super::*; + /// Wiping a record lets go of every field, so each one drops, and a + /// frame wipes itself as it drops. + #[test] + fn zeroize_drops_every_field() { + use std::sync::atomic::{AtomicUsize, Ordering}; + use zeroize::Zeroize; + struct Counted(Arc); + impl Drop for Counted { + fn drop(&mut self) { + let _ = self.0.fetch_add(1, Ordering::SeqCst); + } + } + let drops = Arc::new(AtomicUsize::new(0)); + let mut values = FieldValues::new(); + let _ = values + .insert("a", Counted(drops.clone())) + .insert("b", Counted(drops.clone())); + values.zeroize(); + assert_eq!(drops.load(Ordering::SeqCst), 2, "both fields dropped"); + assert_eq!(values.names().count(), 0, "no field is left"); + } + #[test] fn insert_replaces_a_field_in_place_and_keeps_order() { let mut values = FieldValues::new(); diff --git a/packages/stack-encrypt/src/scalar.rs b/packages/stack-encrypt/src/scalar.rs index bf8e8bd5c6..553be54483 100644 --- a/packages/stack-encrypt/src/scalar.rs +++ b/packages/stack-encrypt/src/scalar.rs @@ -324,7 +324,7 @@ impl KeysetCipher<'_, K> { /// as its purpose or a request id. /// /// ``` - /// use stack_encrypt::{AuditMetadata, Ciphertext, StackCipher}; + /// use stack_encrypt::{AuditMetadata, Ciphertext, Controlled, Protected, StackCipher}; /// /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { /// // With no `.kms(..)`, the cipher uses ZeroKMS. It reads credentials from @@ -336,7 +336,7 @@ impl KeysetCipher<'_, K> { /// let keyset = cipher.default_keyset(); /// let stored: Ciphertext = keyset.encrypt(String::from("sk_live_1234")).await?; /// - /// let api_key: String = keyset + /// let api_key: Protected = keyset /// .decrypt(stored) /// .audit( /// AuditMetadata::new() @@ -344,7 +344,7 @@ impl KeysetCipher<'_, K> { /// .with("request_id", "req_01J9Z3"), /// ) /// .await?; - /// assert_eq!(api_key, "sk_live_1234"); + /// assert_eq!(api_key.risky_ref(), "sk_live_1234"); /// # Ok::<(), stack_encrypt::Error>(()) /// # }).unwrap(); /// ``` diff --git a/packages/stack-encrypt/src/sem/mod.rs b/packages/stack-encrypt/src/sem/mod.rs index 7426cb7ff6..9427b5527a 100644 --- a/packages/stack-encrypt/src/sem/mod.rs +++ b/packages/stack-encrypt/src/sem/mod.rs @@ -174,16 +174,20 @@ use std::marker::PhantomData; use clww_ore::{ClwwOpe, ClwwOre}; pub use clww_ore::{OpeClww8VariableV1, OreClww8VariableV1}; use vitaminc_aead::Encrypt; +use vitaminc_aead::EncryptRef; use vitaminc_hmac::HmacSha256Prf; use vitaminc_normalize::{terms, NormalizeError, Normalized}; -use vitaminc_ore::{OrderEncrypt, OrderError, OrderKeyInit, OrderScheme, OrderTarget}; +use vitaminc_ore::{ + OrderEncrypt, OrderError, OrderKeyInit, OrderPlaintext, OrderScheme, OrderTarget, Orderable, + SchemeVisitor, Target as _, +}; use vitaminc_prf::{ BlockVisitor, Context, IntoPrfContext, MapAccess, PrfError, PrfValue, PrfVisitor, PrfVisitorError, SeqAccess, }; use vitaminc_protected::NonEmpty; use vitaminc_protected::Protected; -use zeroize::{Zeroize, Zeroizing}; +use zeroize::Zeroizing; use stack_kms::MaybeSend; @@ -1382,131 +1386,14 @@ where // ORE / OPE // ============================================================================= -/// A plaintext type an order term ([`OreTerm`], [`OpeTerm`]) is derived -/// over, and the `vitaminc-ore` order target its values are encoded as. -/// This crate is the layer above the order schemes: it names each type's -/// target, and clww-ore encodes the value as that target and encrypts it. -/// The encoding (integer width, the canonical float, text's fold) is the -/// scheme's, through `vitaminc-ore`, and never this crate's. The value goes -/// to the scheme as a `vitaminc-aead` [`Encrypt`] source, by reference, so -/// the engine keeps the one copy it was handed and wipes it -/// ([`Zeroizing`]) when the term is derived or refused. -/// -/// | Type | Target | -/// | --- | --- | -/// | `u16` to `u128`, `i16` to `i128` | the integer at its own width | -/// | `f32`, `f64` | `F64`: an `f32` widens to it exactly, `-0.0` ties `0.0`, every NaN is one value after `+Infinity` | -/// | `String` | `Text`: Unicode 16 NFC with case and accents folded | -/// | `Vec` | `Bytes`, as they are | -/// | [`value::Date`](crate::value::Date) | `Date`: the day | -/// | [`value::Timestamp`](crate::value::Timestamp) | `Timestamp`: the instant truncated to the microsecond, so instants in one microsecond tie | -/// | [`value::Decimal`](crate::value::Decimal) | `Decimal`: the number with its scale normalised, so `1.5` ties `1.50` | -/// -/// A borrowed text or byte string is not a source: an order term takes -/// its value by ownership (the visitor carries it), so pass a `String` or -/// a `Vec`. -/// -/// A `bool`, a `u8` and an `i8` have no target. An order term over a -/// domain that small tells anyone holding the column too much: with two -/// values it says which rows are `true`, and with 256 it puts every row in -/// one of 256 ranks, which a few known rows resolve to the values. So -/// `OreTerm`, `OreTerm` and `OreTerm` do not compile (nor -/// the `OpeTerm`s), as the dynamic path refuses the same scalars -/// (`dynamic::admits`); each keeps its equality term. `vitaminc-ore` has -/// no one-byte target either, since 0.7. -/// -/// ```compile_fail -/// use stack_encrypt::sem::OreTerm; -/// -/// let _: Option> = None; // `bool` is not `Orderable` -/// ``` -/// -/// ```compile_fail -/// use stack_encrypt::sem::OpeTerm; -/// -/// let _: Option> = None; // `u8` is not `Orderable` -/// ``` -/// -/// Sealed: the target is part of the stored format, so a type cannot pick -/// its own. -/// -/// This table is a stand-in. `vitaminc-ore` leaves the target to whoever -/// opens the column, so the type's own target is written here; once -/// `vitaminc-ore` names it itself (tracked at -/// ), this trait and -/// the private `encrypt_in` it rests on go, and the bound becomes -/// vitaminc's own `Encrypt` with `Zeroize`. -pub trait Orderable: sealed::Sealed + Zeroize + Send + 'static { - /// The target this type's values are encoded as. - const TARGET: OrderTarget; -} - -mod sealed { - use vitaminc_ore::{OrderError, OrderScheme, OrderSpace, OrderTarget, Supports}; - - /// Hands `&self` to the space as the `vitaminc-aead` `Encrypt` source - /// it is (`&String`, `&i32`, ...), so the owner keeps the one copy and - /// wipes it. Not public, and one body for every type: it is here, and - /// not a `&Self: Encrypt` bound on `Orderable`, because such a bound is - /// not implied at the trait's use sites and would have to be repeated on - /// each. - pub trait Sealed { - fn encrypt_in>( - &self, - space: &OrderSpace<'_, S>, - ) -> Result>; - /// What an order query of this value is refused for before any - /// key is requested: nothing, for a value whose order encoding - /// always exists. Text overrides it (`query::order`). - fn check_query(&self, block: bool) -> Result<(), super::TermError> { - let _ = block; - Ok(()) - } - } -} +// The plaintext types an order term is derived over are vitaminc-ore's +// `Orderable` types: each has an order target of its own, which vitaminc-ore +// names, and this crate names none. The crate root re-exports the trait and +// documents its table (`crate::Orderable`). -macro_rules! orderable { - ($($ty:ty => $target:ident),* $(,)?) => {$( - impl sealed::Sealed for $ty { - fn encrypt_in>( - &self, - space: &vitaminc_ore::OrderSpace<'_, S>, - ) -> Result> { - space.encrypt_checked(self).map(vitaminc_ore::OrderTerm::into_raw) - } - } - impl Orderable for $ty { - const TARGET: OrderTarget = OrderTarget::$target; - } - )*}; -} -orderable!( - u16 => U16, u32 => U32, u64 => U64, u128 => U128, - i16 => I16, i32 => I32, i64 => I64, i128 => I128, - f32 => F64, f64 => F64, - Vec => Bytes, - crate::value::Date => Date, crate::value::Timestamp => Timestamp, - crate::value::Decimal => Decimal, -); -// Text by hand: its order encoding is the ADR-0002 fold, which refuses a -// code point Unicode 16 does not assign, and block ORE bounds its length. -// A query of such text is refused before any key, where every other -// orderable value has nothing to refuse. -impl sealed::Sealed for String { - fn encrypt_in>( - &self, - space: &vitaminc_ore::OrderSpace<'_, S>, - ) -> Result> { - space - .encrypt_checked(self) - .map(vitaminc_ore::OrderTerm::into_raw) - } - fn check_query(&self, block: bool) -> Result<(), TermError> { - query::order_text(self, block) - } -} -impl Orderable for String { - const TARGET: OrderTarget = OrderTarget::Text; +/// The order target `T` is encoded as: the one vitaminc-ore gives it. +pub(crate) fn target_of() -> OrderTarget { + ::default().runtime() } /// Why clww-ore produced no order term, as a [`TermError`]: the value's @@ -1515,7 +1402,7 @@ impl Orderable for String { /// arrives. A scalar of an [`Orderable`] type is never a container and /// never unsupported by a CLLW scheme, so those refusals cannot occur; /// they read as a scheme failure rather than a panic. -fn order_error(error: OrderError) -> TermError { +pub(crate) fn order_error(error: OrderError) -> TermError { match error { OrderError::Term(error) => TermError::Normalize(error), _ => TermError::Ore(clww_ore::Error), @@ -1854,90 +1741,33 @@ impl PartialOrd for OreBlockTerm { } } -/// A [`PrfVisitor`] that carries the plaintext in and hands the CLLW ORE -/// ciphertext out. The PRF block keys clww-ore's vitaminc ORE scheme -/// *inside* `visit_block` and dies there: the block arrives by value, is -/// copied into the scheme's key (wiped when the scheme drops) and wiped -/// here, the value is encrypted, and only the ciphertext leaves. No key is -/// ever returned to the caller. +/// Key the order scheme `S` of one index from the PRF, under `domain` and +/// the index's context. +/// +/// The PRF block keys the scheme inside Vitamin C's [`SchemeVisitor`] and +/// is wiped there: the block is copied into the scheme's key, which is wiped +/// when the scheme drops. The visitor holds no plaintext, so the value is +/// never passed to the PRF call, and a backend that derives the block later +/// keeps no copy of it. The caller then encrypts the value on the scheme, by +/// reference. /// /// The column is opened with the value's target and the empty context: /// the key is already this index's own, derived under the index's /// descriptor, so there is nothing left for a context to separate. The /// column's salt still binds the scheme and the target. -/// -/// This is the shape a 2-party PRF needs: the caller supplies a PRF input -/// (the context) and receives a term, and where the key comes from — or -/// whether one exists at all — is the visitor's business. Swapping the -/// backend for one that returns per-prefix PRF outputs instead of a key -/// changes this visitor, not its callers. -/// -/// The plaintext is owned (`T: 'static`) because the visitor outlives the -/// call under an asynchronous backend; `Send` for the same reason. Scheme -/// failures surface through the visitor's `Value` rather than -/// [`PrfVisitorError`] so they keep their own error type. -/// -/// The plaintext is held in a [`Zeroizing`], so it is wiped when the -/// visitor drops: after `visit_block`, or unvisited if the PRF fails first. -/// `encrypt_in` reads it by reference and clww-ore copies nothing out of it -/// unwiped, so that drop is the last place its bytes live. -struct OreVisitor(Zeroizing); - -impl PrfVisitor<[u8; 32], P> for OreVisitor +fn keyed(prf: &HmacSha256Prf, domain: &[u8], context: &Context<'_>) -> Result where - T: Orderable, - P: Send + 'static, + S: OrderKeyInit> + Send + 'static, { - type Value = Result; - - fn visit_block(self, mut block: [u8; 32]) -> Result { - let scheme = ClwwOre::new(Protected::new(block)); - block.zeroize(); - let space = scheme.target(T::TARGET); - Ok(sealed::Sealed::encrypt_in(&*self.0, &space).map_err(order_error)) - } -} - -/// The OPE twin of [`OreVisitor`]: same key handling, produces a CLLW OPE -/// ciphertext (byte order is plaintext order). -struct OpeVisitor(Zeroizing); - -impl PrfVisitor<[u8; 32], P> for OpeVisitor -where - T: Orderable, - P: Send + 'static, -{ - type Value = Result; - - fn visit_block(self, mut block: [u8; 32]) -> Result { - let scheme = ClwwOpe::new(Protected::new(block)); - block.zeroize(); - let space = scheme.target(T::TARGET); - Ok(sealed::Sealed::encrypt_in(&*self.0, &space).map_err(order_error)) - } -} - -/// The block ORE twin of [`OreVisitor`]: same key handling, under its own -/// domain. ore-rs's `BlockOre` routes the space to its 6-bit or chained -/// engine by the target's width, and derives the one ORE key both use from -/// the block under a label of its own. The plaintext is held in a -/// [`Zeroizing`], as [`OreVisitor`]'s is: ore-rs reads it by reference and -/// works on scrubbed copies, so that drop is the last place its bytes live. -struct OreBlockVisitor(Zeroizing); - -impl PrfVisitor<[u8; 32], P> for OreBlockVisitor -where - T: Orderable, - P: Send + 'static, -{ - type Value = Result; - - fn visit_block(self, mut block: [u8; 32]) -> Result { - let scheme = ore_rs::BlockOre::new(Protected::new(block)); - block.zeroize(); - let term = sealed::Sealed::encrypt_in(&*self.0, &scheme.target(T::TARGET)); - Ok(term.map_err(ore_block_error)) - } + let context_bytes = context.as_bytes(); + context_bytes + .prf_visit_with_context( + prf, + Context::pae(&[domain, context_bytes]), + SchemeVisitor::new(), + ) + .into_result() + .map_err(TermError::from_prf) } /// Why ore-rs produced no block ORE term, as a [`TermError`]: the value's @@ -1945,7 +1775,7 @@ where /// scheme failed. ore-rs's errors name no part of the value. A target the /// scheme does not take cannot occur (`BlockOre` takes every target), and /// reads as a scheme failure rather than a panic. -fn ore_block_error(error: OrderError) -> TermError { +pub(crate) fn ore_block_error(error: OrderError) -> TermError { use ore_rs::OreError; match error { OrderError::Term(error) => TermError::Normalize(error), @@ -1956,74 +1786,108 @@ fn ore_block_error(error: OrderError) -> TermError { } } -/// Derive an ORE term: PRF of the encoded context under a PAE-encoded -/// `[domain, context]` framing — the same framing every other term kind uses -/// (see the module docs), so no reimplementation of this derivation can -/// collide with an equality or match derivation. Only the context enters the -/// PRF — never the plaintext, which rides in the visitor and is encrypted -/// there. Deterministic, so write-time and query-time terms agree; under a -/// 2-party PRF backend this derivation is a visible ZeroKMS event. -fn ore( - prf: &HmacSha256Prf, - value: T, - context: Context<'_>, -) -> Result, TermError> { - // Wrapped before anything can fail, so a refused value is wiped too. - let value = Zeroizing::new(value); - let context_bytes = context.as_bytes(); - context_bytes - .prf_visit_with_context( - prf, - Context::pae(&[ORE_KEY_DOMAIN, context_bytes]), - OreVisitor(value), - ) - .into_result() - .map_err(TermError::from_prf)? - .map(OreTerm::new) +/// The order encoding of `value` as `target`. It needs no key, so a term +/// makes it first, before it keys its scheme, and a term whose keyset is +/// not loaded yet keeps it, not the value, until the keyset arrives. +/// vitaminc-ore holds it under `Protected`, which wipes it on drop. A value +/// handed over by value is wiped by the walk that reads it. +pub(crate) fn order_encoding( + target: OrderTarget, + value: V, +) -> Result> { + match vitaminc_ore::order_terms(target, value) { + Ok(mut terms) => terms + .pop() + .map(|term| term.normalized) + .ok_or(OrderError::NotScalar), + Err(error) => Err(match error.term() { + Some(term) => OrderError::Term(term.error()), + None => OrderError::NotScalar, + }), + } +} + +/// An order term of `value`, which `derive` makes from the value's +/// encoding under the keyset's index key: during the build when the keyset +/// is loaded, and when the pending has loaded it otherwise. The encoding is +/// made first in both cases, so the value is read once, here, and not kept. +pub(crate) fn order_pending<'a, K, V, U, E>( + cipher: &'a KeysetCipher<'_, K>, + target: OrderTarget, + value: V, + context: Context<'static>, + refused: fn(OrderError) -> TermError, + derive: fn(&HmacSha256Prf, &OrderPlaintext, Context<'_>) -> Result, +) -> Pending<'a, U, K> +where + V: Encrypt, + U: MaybeSend + 'a, +{ + let encoding = match order_encoding(target, value) { + Ok(encoding) => encoding, + Err(error) => return Pending::ready(cipher, Err(refused(error).into())), + }; + match cipher.loaded_state() { + Some(keyset) => { + let term = derive(&keyset.prf, &encoding, context).map_err(Error::from); + Pending::ready(cipher, term) + } + None => cipher + .deferred(move |keyset| derive(&keyset.prf, &encoding, context).map_err(Error::from)), + } } -/// Derive an OPE term — as [`ore`], under the OPE domain so the two schemes -/// never share a key. Crate-visible: the JSON index derives its leaf -/// ordering terms through it, under the column's context, so a leaf's `op` -/// is the term the scalar `Ope` index would store for the same value. -pub(crate) fn ope( +/// The ORE term of an order encoding, at the target it was made for: PRF +/// of the encoded context under a PAE-encoded `[domain, context]` framing, +/// the same framing every other term kind uses (see the module docs), so no +/// reimplementation of this derivation can collide with an equality or +/// match derivation. Only the context enters the PRF, never the plaintext, +/// whose encoding the keyed scheme encrypts. Deterministic, so write-time +/// and query-time terms agree; under a 2-party PRF backend this derivation +/// is a visible ZeroKMS event. +pub(crate) fn ore( prf: &HmacSha256Prf, - value: T, + encoding: &OrderPlaintext, context: Context<'_>, -) -> Result, TermError> { - // Wrapped before anything can fail, so a refused value is wiped too. - let value = Zeroizing::new(value); - let context_bytes = context.as_bytes(); - context_bytes - .prf_visit_with_context( - prf, - Context::pae(&[OPE_KEY_DOMAIN, context_bytes]), - OpeVisitor(value), - ) - .into_result() - .map_err(TermError::from_prf)? - .map(OpeTerm::new) -} - -/// Derive a block ORE term — as [`ore`], under the block ORE domain, so -/// no CLLW scheme shares its key. -fn ore_block( +) -> Result { + let scheme: ClwwOre = keyed(prf, ORE_KEY_DOMAIN, &context)?; + scheme + .target(encoding.target()) + .encrypt_term(encoding) + .map(vitaminc_ore::OrderTerm::into_raw) + .map_err(order_error) +} + +/// The OPE term of an order encoding, as [`ore`], under the OPE domain so +/// the two schemes never share a key. The JSON index derives a leaf's +/// ordering term through it, so a leaf's `op` is the term the scalar `Ope` +/// index stores for the same value. +pub(crate) fn ope( prf: &HmacSha256Prf, - value: T, + encoding: &OrderPlaintext, context: Context<'_>, -) -> Result, TermError> { - // Wrapped before anything can fail, so a refused value is wiped too. - let value = Zeroizing::new(value); - let context_bytes = context.as_bytes(); - context_bytes - .prf_visit_with_context( - prf, - Context::pae(&[ORE_BLOCK_KEY_DOMAIN, context_bytes]), - OreBlockVisitor(value), - ) - .into_result() - .map_err(TermError::from_prf)? - .map(|term| OreBlockTerm(term, PhantomData)) +) -> Result { + let scheme: ClwwOpe = keyed(prf, OPE_KEY_DOMAIN, &context)?; + scheme + .target(encoding.target()) + .encrypt_term(encoding) + .map(vitaminc_ore::OrderTerm::into_raw) + .map_err(order_error) +} + +/// The block ORE term of an order encoding, as [`ore`], under the block ORE +/// domain, so no CLLW scheme shares its key. +pub(crate) fn ore_block( + prf: &HmacSha256Prf, + encoding: &OrderPlaintext, + context: Context<'_>, +) -> Result { + let scheme: ore_rs::BlockOre = keyed(prf, ORE_BLOCK_KEY_DOMAIN, &context)?; + scheme + .target(encoding.target()) + .encrypt_term(encoding) + .map(vitaminc_ore::OrderTerm::into_raw) + .map_err(ore_block_error) } /// Whether block ORE takes `text` as order text: its order encoding (the @@ -2031,9 +1895,16 @@ fn ore_block( /// exist, fit the chained scheme's 1024 bytes, and not end in NUL. These /// are the refusals derivation makes, stated without a key, so a query is /// refused at its boundary on both paths ([`query::order`]). +#[cfg(feature = "dynamic")] pub(crate) fn ore_block_text(text: &str) -> Result<(), TermError> { let encoded = vitaminc_ore::text(text)?; - let encoded = vitaminc_protected::Controlled::risky_ref(&encoded); + ore_block_fits(vitaminc_protected::Controlled::risky_ref(&encoded)) +} + +/// Whether block ORE takes a text order encoding (the marker byte, then +/// the fold): the rule `ore_block_text` applies, over an encoding already +/// made. +pub(crate) fn ore_block_fits(encoded: &[u8]) -> Result<(), TermError> { if encoded.len() > ORE_BLOCK_MAX_BYTES { return Err(TermError::OreBlockTooLong); } @@ -2048,95 +1919,62 @@ pub(crate) fn ore_block_text(text: &str) -> Result<(), TermError> { /// puts in front of the fold, so the fold itself is at most 1023. const ORE_BLOCK_MAX_BYTES: usize = ore_rs::scheme::chained::DEFAULT_MAX_STR_BYTES.get(); -/// An ORE term of any [`Orderable`] source. Under the local HMAC -/// backend, derived during the synchronous build — the returned [`Pending`] -/// carries no requests. -impl<'c, S, K, T> Term> for OreTerm -where - S: Orderable, - T: IntoPrfContext<'c>, -{ - // Derived locally: no data key, no descriptor. - - fn encrypt_from<'a>( - source: S, - cipher: &'a KeysetCipher<'_, K>, - context: NonEmpty, - ) -> Pending<'a, Self, K> - where - Self: 'a, - { - let context = context.into_prf_context().into_owned(); - match cipher.loaded_state() { - Some(keyset) => { - let term = ore(&keyset.prf, source, context).map_err(Error::from); - Pending::ready(cipher, term) +/// The order terms of any [`Orderable`] source, by value or read in place. +/// Under the local HMAC backend each is derived during the synchronous +/// build when the keyset is loaded, and the returned [`Pending`] carries no +/// requests. A term derives no descriptor and requests no data key. +/// +/// A value handed over by value is wiped by the walk that encodes it. A +/// value read in place stays with the caller, and is not copied. When the +/// keyset is not loaded yet, the pending keeps the value's order encoding +/// until it is, and wipes it. +macro_rules! order_term { + ($($term:ident: $scheme:ident, $refused:ident, $wrap:expr;)+) => {$( + impl<'c, S, K, T> Term> for $term + where + S: Orderable, + T: IntoPrfContext<'c>, + { + fn encrypt_from<'a>( + source: S, + cipher: &'a KeysetCipher<'_, K>, + context: NonEmpty, + ) -> Pending<'a, Self, K> + where + Self: 'a, + { + let context = context.into_prf_context().into_owned(); + order_pending(cipher, target_of::(), source, context, $refused, |prf, encoding, context| { + $scheme(prf, encoding, context).map($wrap) + }) } - None => cipher - .deferred(move |keyset| ore(&keyset.prf, source, context).map_err(Error::from)), } - } -} -/// An OPE term of any [`Orderable`] source. Under the local HMAC -/// backend, derived during the synchronous build — the returned [`Pending`] -/// carries no requests. -impl<'c, S, K, T> Term> for OpeTerm -where - S: Orderable, - T: IntoPrfContext<'c>, -{ - // Derived locally: no data key, no descriptor. - - fn encrypt_from<'a>( - source: S, - cipher: &'a KeysetCipher<'_, K>, - context: NonEmpty, - ) -> Pending<'a, Self, K> - where - Self: 'a, - { - let context = context.into_prf_context().into_owned(); - match cipher.loaded_state() { - Some(keyset) => { - let term = ope(&keyset.prf, source, context).map_err(Error::from); - Pending::ready(cipher, term) + impl<'c, S, K, T> Term<&S, K, NonEmpty> for $term + where + S: Orderable + EncryptRef, + T: IntoPrfContext<'c>, + { + fn encrypt_from<'a>( + source: &S, + cipher: &'a KeysetCipher<'_, K>, + context: NonEmpty, + ) -> Pending<'a, Self, K> + where + Self: 'a, + { + let context = context.into_prf_context().into_owned(); + order_pending(cipher, target_of::(), source.lend(), context, $refused, |prf, encoding, context| { + $scheme(prf, encoding, context).map($wrap) + }) } - None => cipher - .deferred(move |keyset| ope(&keyset.prf, source, context).map_err(Error::from)), } - } + )+}; } - -/// A block ORE term of any [`Orderable`] source. Under the local HMAC -/// backend, derived during the synchronous build — the returned [`Pending`] -/// carries no requests. -impl<'c, S, K, T> Term> for OreBlockTerm -where - S: Orderable, - T: IntoPrfContext<'c>, -{ - // Derived locally: no data key, no descriptor. - - fn encrypt_from<'a>( - source: S, - cipher: &'a KeysetCipher<'_, K>, - context: NonEmpty, - ) -> Pending<'a, Self, K> - where - Self: 'a, - { - let context = context.into_prf_context().into_owned(); - match cipher.loaded_state() { - Some(keyset) => { - let term = ore_block(&keyset.prf, source, context).map_err(Error::from); - Pending::ready(cipher, term) - } - None => cipher.deferred(move |keyset| { - ore_block(&keyset.prf, source, context).map_err(Error::from) - }), - } - } +order_term! { + OreTerm: ore, order_error, OreTerm::new; + OpeTerm: ope, order_error, OpeTerm::new; + OreBlockTerm: ore_block, ore_block_error, |term| OreBlockTerm(term, PhantomData); } // ============================================================================= @@ -2305,30 +2143,17 @@ impl KeysetCipher<'_, K> { /// under it in one step. The key never leaves the visitor. /// /// Supported inputs: every [`Orderable`] type, each encoded as its - /// target. The value must be owned because the visitor carries it and - /// wipes it; pass a `String` for borrowed text. Returns the raw CLLW - /// ciphertext; the target-directed path wraps the same bytes in - /// [`OreTerm`]. + /// target. Bytes are not one. A value handed over by value is wiped by + /// the walk that encodes it, and a reference (`&String`, `&str`) is read + /// in place. Returns the raw CLLW ciphertext; the target-directed path + /// wraps the same bytes in [`OreTerm`]. pub fn ore_term<'c, T: Orderable>( &self, value: T, descriptor: NonEmpty>, ) -> Pending<'_, OreClww8VariableV1, K> { - match self.loaded_state() { - Some(keyset) => { - let term = - ore(&keyset.prf, value, descriptor.into_prf_context()).map(OreTerm::into_inner); - Pending::ready(self, term.map_err(Error::from)) - } - None => { - let context = descriptor.into_prf_context().into_owned(); - self.deferred(move |keyset| { - ore(&keyset.prf, value, context) - .map(OreTerm::into_inner) - .map_err(Error::from) - }) - } - } + let context = descriptor.into_prf_context().into_owned(); + order_pending(self, target_of::(), value, context, order_error, ore) } /// Generate an order-preserving (CLLW OPE) term: ciphertexts compare with @@ -2340,21 +2165,8 @@ impl KeysetCipher<'_, K> { value: T, descriptor: NonEmpty>, ) -> Pending<'_, OpeClww8VariableV1, K> { - match self.loaded_state() { - Some(keyset) => { - let term = - ope(&keyset.prf, value, descriptor.into_prf_context()).map(OpeTerm::into_inner); - Pending::ready(self, term.map_err(Error::from)) - } - None => { - let context = descriptor.into_prf_context().into_owned(); - self.deferred(move |keyset| { - ope(&keyset.prf, value, context) - .map(OpeTerm::into_inner) - .map_err(Error::from) - }) - } - } + let context = descriptor.into_prf_context().into_owned(); + order_pending(self, target_of::(), value, context, order_error, ope) } /// Generate a block ORE term: ore-rs's 6-bit block ORE, the scheme @@ -2368,18 +2180,17 @@ impl KeysetCipher<'_, K> { value: T, descriptor: NonEmpty>, ) -> Pending<'_, OreBlockTerm, K> { - match self.loaded_state() { - Some(keyset) => { - let term = ore_block(&keyset.prf, value, descriptor.into_prf_context()); - Pending::ready(self, term.map_err(Error::from)) - } - None => { - let context = descriptor.into_prf_context().into_owned(); - self.deferred(move |keyset| { - ore_block(&keyset.prf, value, context).map_err(Error::from) - }) - } - } + let context = descriptor.into_prf_context().into_owned(); + order_pending( + self, + target_of::(), + value, + context, + ore_block_error, + |prf, encoding, context| { + ore_block(prf, encoding, context).map(|term| OreBlockTerm(term, PhantomData)) + }, + ) } } @@ -2696,3 +2507,115 @@ mod tests { ); } } + +/// An order term of a value read in place, through a keyset that is not +/// loaded yet. The pending keeps the value's order encoding, and no borrow +/// of the value. +#[cfg(test)] +mod order_terms_before_the_keyset_loads { + use stack_kms::{FakeCredentialKeySource, SecretToken}; + + use super::*; + use crate::{nonempty, StackCipher}; + + async fn not_loaded() -> StackCipher { + StackCipher::builder() + .kms(FakeCredentialKeySource::new()) + .init() + .await + .unwrap() + } + fn jwt() -> SecretToken { + SecretToken::new("alice.jwt") + } + + /// The term made before the load is the term made after it, for each of + /// the three order schemes, and it still orders against another value's. + #[tokio::test] + async fn a_borrowed_value_has_the_term_a_loaded_keyset_derives() { + let cipher = not_loaded().await; + let keyset = cipher.default_keyset(); + let context = || nonempty!("readings").with("level"); + macro_rules! term { + ($term:ty, $value:expr) => { + <$term as Term<&_, _, _>>::encrypt_from($value, &keyset, context()) + .with_credential(jwt()) + .await + .unwrap() + }; + } + + // Each first call is built while the keyset is not loaded. + assert!(keyset.loaded_state().is_none()); + let before = as Term<&u32, _, _>>::encrypt_from(&7, &keyset, context()); + let ope_before = as Term<&u32, _, _>>::encrypt_from(&7, &keyset, context()); + let block_before = as Term<&String, _, _>>::encrypt_from( + &String::from("ada"), + &keyset, + context(), + ); + let before = before.with_credential(jwt()).await.unwrap(); + let ope_before = ope_before.with_credential(jwt()).await.unwrap(); + let block_before = block_before.with_credential(jwt()).await.unwrap(); + + assert!( + keyset.loaded_state().is_some(), + "the calls loaded the keyset" + ); + assert_eq!(before.as_bytes(), term!(OreTerm, &7).as_bytes()); + assert_eq!(ope_before.as_bytes(), term!(OpeTerm, &7).as_bytes()); + let ada = String::from("ada"); + let bob = String::from("bob"); + assert_eq!( + block_before.compare(&term!(OreBlockTerm, &ada)), + Some(std::cmp::Ordering::Equal) + ); + assert_eq!( + block_before.compare(&term!(OreBlockTerm, &bob)), + Some(std::cmp::Ordering::Less) + ); + } + + /// A value with no order encoding is refused with the same error + /// before the load as after it. + #[tokio::test] + async fn a_refused_value_reads_the_same_before_and_after_the_load() { + // U+0378 is not assigned in Unicode 16. + let unassigned = String::from("\u{378}"); + let context = || nonempty!("readings").with("level"); + + let cipher = not_loaded().await; + let keyset = cipher.default_keyset(); + assert!(keyset.loaded_state().is_none()); + let before = as Term<&String, _, _>>::encrypt_from( + &unassigned, + &keyset, + context(), + ) + .with_credential(jwt()) + .await + .map(drop) + .unwrap_err(); + + // A term that is not refused loads the keyset. + let _ = as Term<&u32, _, _>>::encrypt_from(&7, &keyset, context()) + .with_credential(jwt()) + .await + .unwrap(); + assert!(keyset.loaded_state().is_some()); + let after = as Term<&String, _, _>>::encrypt_from( + &unassigned, + &keyset, + context(), + ) + .with_credential(jwt()) + .await + .map(drop) + .unwrap_err(); + assert_eq!(format!("{before:?}"), format!("{after:?}")); + assert!( + matches!(before, Error::Term(TermError::Normalize(_))), + "{before:?}" + ); + } +} diff --git a/packages/stack-encrypt/src/sem/query.rs b/packages/stack-encrypt/src/sem/query.rs index 2e7b6e99d8..6c06a5ca96 100644 --- a/packages/stack-encrypt/src/sem/query.rs +++ b/packages/stack-encrypt/src/sem/query.rs @@ -17,14 +17,17 @@ //! ([`TermError::OreBlockTooLong`], [`TermError::OreBlockTrailingNul`]). //! A range whose low bound is above its high bound is not refused: as //! SQL's `BETWEEN`, it matches nothing. -use vitaminc_aead::Encrypt; +use vitaminc_aead::{Encrypt, EncryptRef}; +use vitaminc_ore::OrderTarget; -use super::{normalized, sealed, MatchOptions, Orderable, QueryTokens, TermError}; +use super::{normalized, MatchOptions, QueryTokens, TermError}; +use crate::Orderable; /// An equality query of `value`: refused when the value has no equality /// term, or is text the index cannot normalize. The value is consumed as -/// it is normalized, so a caller that still needs it passes a copy, as the -/// typed `Equality::prepare` does; vitaminc wipes what it reads. +/// it is normalized. A caller that still needs it lends it +/// (`EncryptRef::lend`), as the typed `Equality::prepare` does, and then +/// nothing is copied. /// /// # Errors /// @@ -44,8 +47,18 @@ pub(crate) fn equality(value: T) -> Result<(), TermError> { /// /// [`TermError::Normalize`], [`TermError::OreBlockTooLong`], /// [`TermError::OreBlockTrailingNul`]. -pub(crate) fn order(value: &T, block: bool) -> Result<(), TermError> { - sealed::Sealed::check_query(value, block) +pub(crate) fn order(value: &T, block: bool) -> Result<(), TermError> { + if super::target_of::() != OrderTarget::Text { + return Ok(()); + } + // The value read in place. Its encoding is the marker byte and the + // fold, which `order_text` checks for text read from a frame. + let encoding = + super::order_encoding(OrderTarget::Text, value.lend()).map_err(super::order_error)?; + if block { + return super::ore_block_fits(vitaminc_protected::Controlled::risky_ref(encoding.bytes())); + } + Ok(()) } /// [`order`] for text read from a frame, where the type is known only at @@ -54,6 +67,7 @@ pub(crate) fn order(value: &T, block: bool) -> Result<(), TermErro /// # Errors /// /// As [`order`]. +#[cfg(feature = "dynamic")] pub(crate) fn order_text(text: &str, block: bool) -> Result<(), TermError> { if block { return super::ore_block_text(text); diff --git a/packages/stack-encrypt/src/target/collections.rs b/packages/stack-encrypt/src/target/collections.rs index 246406d6b1..bf23bc6da4 100644 --- a/packages/stack-encrypt/src/target/collections.rs +++ b/packages/stack-encrypt/src/target/collections.rs @@ -49,7 +49,7 @@ where // refused context is reported once rather than once per row. Encryption::from_build( T::encryption::().shapes(), - move |source: &'s Vec, cipher, context: T::ContextInput| { + move |source: &Vec, cipher, context: T::ContextInput| { Pending::collect( cipher, source @@ -69,7 +69,7 @@ where where S: 's, { - Encryption::from_build( + Encryption::from_owned_build( T::owned_encryption::().shapes(), move |source: Vec, cipher, context: T::ContextInput| { // Run every element, whatever happened to the elements before it. @@ -152,7 +152,7 @@ impl + MaybeSend> EncryptTarget> for O { Encryption::from_build( T::encryption::().shapes(), - move |source: &'s Option, cipher, context: T::ContextInput| match source { + move |source: &Option, cipher, context: T::ContextInput| match source { Some(value) => cipher.run(T::encryption(), value, context).map(Some), None => Pending::ready(cipher, Ok(None)), }, @@ -166,7 +166,7 @@ impl + MaybeSend> EncryptTarget> for O where S: 's, { - Encryption::from_build( + Encryption::from_owned_build( T::owned_encryption::().shapes(), move |source: Option, cipher, context: T::ContextInput| { // Building the target's declaration can panic, so the value stays diff --git a/packages/stack-encrypt/src/target/conversion.rs b/packages/stack-encrypt/src/target/conversion.rs index 448749025b..950d72c8b2 100644 --- a/packages/stack-encrypt/src/target/conversion.rs +++ b/packages/stack-encrypt/src/target/conversion.rs @@ -47,7 +47,7 @@ pub trait EncryptTarget: Sized + 'static { where S: 's, { - Encryption::from_build( + Encryption::from_owned_build( Self::encryption::().shapes(), move |source: S, cipher, context| { let guarded = Protected::new(source); diff --git a/packages/stack-encrypt/src/target/index.rs b/packages/stack-encrypt/src/target/index.rs index 86362682b3..d35c9a456e 100644 --- a/packages/stack-encrypt/src/target/index.rs +++ b/packages/stack-encrypt/src/target/index.rs @@ -62,10 +62,8 @@ use std::fmt; use std::marker::PhantomData; use super::context::{AeadContext, CallerContext}; -use super::operations::{ - ciphertext, equality, json_terms, matching, ope, open, ore, ore_block, wiping_ciphertext, -}; -use super::source::{ConsumeSource, Owned, ShareSource}; +use super::operations::{ciphertext, equality, json_terms, matching, ope, open, ore, ore_block}; +use super::source::{Owned, WipeSource}; use super::{ DecryptField, DecryptSource, Decryptable, Decryption, EncryptTarget, Encryption, RequiredContext, @@ -268,7 +266,7 @@ pub trait Index { /// /// A fresh description per call: a description is single-use, and an /// index is not, so a saved plan asks again each time it runs. - fn operation<'s, K: 'static, M: ConsumeSource<'s, S>>( + fn operation<'s, K: 'static, M: WipeSource<'s, S>>( &self, ) -> Encryption<'s, S, Self::Term, K, CallerContext, M> where @@ -381,12 +379,12 @@ impl fmt::Debug for Match { } } -impl Index for Equality { +impl Index for Equality { type Term = EqualityTerm; fn spec(&self) -> IndexSpec { IndexSpec::Equality } - fn operation<'s, K: 'static, M: ConsumeSource<'s, S>>( + fn operation<'s, K: 'static, M: WipeSource<'s, S>>( &self, ) -> Encryption<'s, S, Self::Term, K, CallerContext, M> where @@ -400,7 +398,7 @@ impl, O: MatchConfig + 'static> Index for Match { fn spec(&self) -> IndexSpec { IndexSpec::Match(O::options()) } - fn operation<'s, K: 'static, M: ConsumeSource<'s, S>>( + fn operation<'s, K: 'static, M: WipeSource<'s, S>>( &self, ) -> Encryption<'s, S, Self::Term, K, CallerContext, M> where @@ -411,13 +409,13 @@ impl, O: MatchConfig + 'static> Index for Match { } impl Index for Ore where - S: crate::sem::Orderable, + S: crate::Orderable + vitaminc_aead::EncryptRef + 'static, { type Term = OreTerm; fn spec(&self) -> IndexSpec { IndexSpec::Ore } - fn operation<'s, K: 'static, M: ConsumeSource<'s, S>>( + fn operation<'s, K: 'static, M: WipeSource<'s, S>>( &self, ) -> Encryption<'s, S, Self::Term, K, CallerContext, M> where @@ -428,13 +426,13 @@ where } impl Index for Ope where - S: crate::sem::Orderable, + S: crate::Orderable + vitaminc_aead::EncryptRef + 'static, { type Term = OpeTerm; fn spec(&self) -> IndexSpec { IndexSpec::Ope } - fn operation<'s, K: 'static, M: ConsumeSource<'s, S>>( + fn operation<'s, K: 'static, M: WipeSource<'s, S>>( &self, ) -> Encryption<'s, S, Self::Term, K, CallerContext, M> where @@ -445,13 +443,13 @@ where } impl Index for OreBlock where - S: crate::sem::Orderable, + S: crate::Orderable + vitaminc_aead::EncryptRef + 'static, { type Term = OreBlockTerm; fn spec(&self) -> IndexSpec { IndexSpec::OreBlock } - fn operation<'s, K: 'static, M: ConsumeSource<'s, S>>( + fn operation<'s, K: 'static, M: WipeSource<'s, S>>( &self, ) -> Encryption<'s, S, Self::Term, K, CallerContext, M> where @@ -469,7 +467,7 @@ impl Index for Json { fn spec(&self) -> IndexSpec { IndexSpec::Json(self.options.clone()) } - fn operation<'s, K: 'static, M: ConsumeSource<'s, serde_json::Value>>( + fn operation<'s, K: 'static, M: WipeSource<'s, serde_json::Value>>( &self, ) -> Encryption<'s, serde_json::Value, Self::Term, K, CallerContext, M> { json_terms::(self.options.clone()) @@ -498,12 +496,13 @@ pub trait Indexes { /// The description that derives every term, under the one /// [`CallerContext`] it is handed, settling them in one batch. /// - /// Several indexes over one owned plaintext share it, so in - /// [`Owned`](super::Owned) mode `S` must be `Clone` (see [`ShareSource`]). + /// Several indexes over one plaintext all read it in place, so nothing + /// is copied in either mode. In [`Owned`](super::Owned) mode the first + /// index is handed the value, once the others have read it. fn operations<'s, K: 'static, M>(&self) -> Encryption<'s, S, Self::Terms, K, CallerContext, M> where S: 's, - M: ConsumeSource<'s, S> + ShareSource<'s, S>; + M: WipeSource<'s, S>; /// The one index of type `I` in this set, for the query side, where a /// query asks one index for one term and needs no ciphertext; its /// [`operation`](Index::operation) is that term alone. @@ -587,7 +586,7 @@ macro_rules! single_index { ) -> Encryption<'s, S, Self::Terms, K, CallerContext, M> where S: 's, - M: ConsumeSource<'s, S> + ShareSource<'s, S>, + M: WipeSource<'s, S>, { self.operation() } @@ -610,7 +609,7 @@ macro_rules! tuple_of_indexes { ) -> Encryption<'s, S, Self::Terms, K, CallerContext, M> where S: 's, - M: ConsumeSource<'s, S> + ShareSource<'s, S>, + M: WipeSource<'s, S>, { tuple_of_indexes!(@zip self, $($at),+) .map(|$nested| ($($name,)+)) @@ -619,7 +618,7 @@ macro_rules! tuple_of_indexes { tuple_of_indexes!(@select [$($name),+] $($name $at),+); )+}; (@zip $self:ident, $first:tt $(, $rest:tt)*) => { - $self.$first.operation()$(.zip($self.$rest.operation()))* + $self.$first.operation()$(.zip($self.$rest.operation::()))* }; // One `Select` impl per position, each over the whole tuple. (@select [$($all:ident),+] $name:ident $at:tt $(, $rest:ident $rest_at:tt)*) => { @@ -663,17 +662,19 @@ impl> Indexes for Vec { fn operations<'s, K: 'static, M>(&self) -> Encryption<'s, S, Self::Terms, K, CallerContext, M> where S: 's, - M: ConsumeSource<'s, S> + ShareSource<'s, S>, + M: WipeSource<'s, S>, { let mut indexes = self.iter(); let Some(first) = indexes.next() else { return Encryption::failed(crate::PlanError::EmptyIndexes.into()); }; indexes.fold(first.operation().map(|term| vec![term]), |terms, index| { - terms.zip(index.operation()).map(|(mut terms, term)| { - terms.push(term); - terms - }) + terms + .zip(index.operation::()) + .map(|(mut terms, term)| { + terms.push(term); + terms + }) }) } } @@ -707,12 +708,12 @@ pub struct Encrypted { /// indexes ([`TermSet`]), and the description is [`indexed`] over them, under /// the one caller context that the record field or the caller supplies. /// -/// The owned form is handed the value. The ciphertext takes a copy, and the -/// terms take the value. When the context is refused, the ciphertext wipes its -/// copy, and each term scheme consumes its own. +/// The owned form is handed the value. The terms read it in place, and then +/// the ciphertext takes it. Vitamin C wipes it when it is sealed, and the +/// ciphertext wipes it when the context is refused. Nothing is copied. impl EncryptTarget for Encrypted where - S: crate::Encrypt + Clone + zeroize::Zeroize, + S: crate::Encrypt + vitaminc_aead::EncryptRef + zeroize::Zeroize, Terms: TermSet, { type ContextInput = RequiredContext; @@ -732,15 +733,11 @@ where where S: 's, { - let described = - indexed_beside(wiping_ciphertext::(), Terms::INDEXES).accepting(); + let described = indexed::(Terms::INDEXES).accepting(); if let Err(error) = check_indexes(&Terms::INDEXES.specs()) { // The refused value is the description's to wipe. The leaves' // contexts are kept, as in the borrowed form. - return Encryption::from_build(described.shapes(), move |mut source: S, cipher, _| { - zeroize::Zeroize::zeroize(&mut source); - super::Pending::failed(cipher, error) - }); + return described.refused_wiping(error); } described } @@ -793,7 +790,7 @@ pub trait TermSet: Sized + 'static { /// Those indexes, as a value. const INDEXES: Self::Indexes; } -impl TermSet for EqualityTerm { +impl TermSet for EqualityTerm { type Indexes = Equality; const INDEXES: Equality = Equality; } @@ -803,21 +800,21 @@ impl, O: MatchConfig + 'static> TermSet for MatchTerms { } impl TermSet for OreTerm where - S: crate::sem::Orderable, + S: crate::Orderable + vitaminc_aead::EncryptRef + 'static, { type Indexes = Ore; const INDEXES: Ore = Ore; } impl TermSet for OpeTerm where - S: crate::sem::Orderable, + S: crate::Orderable + vitaminc_aead::EncryptRef + 'static, { type Indexes = Ope; const INDEXES: Ope = Ope; } impl TermSet for OreBlockTerm where - S: crate::sem::Orderable, + S: crate::Orderable + vitaminc_aead::EncryptRef + 'static, { type Indexes = OreBlock; const INDEXES: OreBlock = OreBlock; @@ -858,10 +855,9 @@ mod term_tuples { /// so a field with indexes is one line and its output is an /// [`Encrypted`]. The bytes are exactly the hand composition's. /// -/// The ciphertext and every term share the plaintext, so in -/// [`Owned`](super::Owned) mode `S` must be `Clone`; a plaintext that must -/// never be copied can still be sealed alone ([`ciphertext`]) or indexed -/// alone ([`Index::operation`]). +/// The ciphertext and every term read the same plaintext in place, so +/// nothing is copied in either mode. In [`Owned`](super::Owned) mode the +/// terms read the value first, and then the ciphertext takes it. /// /// The type parameters are in the order [`ciphertext`]'s are, with the /// indexes last: `indexed::((Equality, Ore))`. @@ -874,28 +870,13 @@ pub fn indexed<'s, S, K, M, X>( indexes: X, ) -> Encryption<'s, S, Encrypted, K, CallerContext, M> where - S: crate::Encrypt + 's, - K: 'static, - M: ConsumeSource<'s, S> + ShareSource<'s, S>, - X: Indexes, -{ - indexed_beside(ciphertext::(), indexes) -} -/// The terms of `indexes` beside the ciphertext that `sealed` describes. This -/// is the body of [`indexed`]. The owned declaration of [`Encrypted`] passes a -/// ciphertext that wipes its plaintext when the context is refused. -fn indexed_beside<'s, S, K, M, X>( - sealed: Encryption<'s, S, StackCipherText, K, AeadContext, M>, - indexes: X, -) -> Encryption<'s, S, Encrypted, K, CallerContext, M> -where - S: crate::Encrypt + 's, + S: crate::Encrypt + vitaminc_aead::EncryptRef + 's, K: 'static, - M: ConsumeSource<'s, S> + ShareSource<'s, S>, + M: WipeSource<'s, S>, X: Indexes, { - sealed + ciphertext::() .accepting::() - .zip(indexes.operations()) + .zip(indexes.operations::()) .map(|(ciphertext, terms)| Encrypted { ciphertext, terms }) } diff --git a/packages/stack-encrypt/src/target/mod.rs b/packages/stack-encrypt/src/target/mod.rs index edbb7325f1..c9356d16d9 100644 --- a/packages/stack-encrypt/src/target/mod.rs +++ b/packages/stack-encrypt/src/target/mod.rs @@ -116,13 +116,14 @@ //! ``` //! use stack_encrypt::sem::EqualityTerm; //! use stack_encrypt::target::{self, CallerContext, EncryptTarget, RequiredContext}; -//! use stack_encrypt::{Encrypt, Encryption}; +//! use stack_encrypt::{Encrypt, EncryptRef, Encryption}; //! use zeroize::Zeroize; //! //! /// An equality term, stored as its bytes. //! struct StoredEquality([u8; 32]); //! -//! impl EncryptTarget for StoredEquality { +//! // The term reads the plaintext in place, by reference (`EncryptRef`). +//! impl EncryptTarget for StoredEquality { //! type ContextInput = RequiredContext; //! fn encryption<'s, K: 'static>() -> Encryption<'s, S, Self, K, Self::ContextInput> //! where @@ -140,12 +141,11 @@ //! New cryptographic operations belong in core; output adapters cannot install an //! execution callback. //! -//! Those schemes consume the plaintext. A description is handed it by -//! reference by default, and an operation clones it before consuming it, so a -//! declaration's plaintext is `Clone`. A plaintext that must not be copied -//! runs in [`Owned`] mode through [`KeysetCipher::run`](crate::KeysetCipher::run): -//! a single operation takes the value with no copy, and only -//! [`Encryption::zip`] asks for `Clone`. See [`SourceMode`]. +//! Every operation reads the plaintext in place, so a plaintext does not +//! need to be `Clone`. A description is handed the plaintext by reference by +//! default, and the plaintext stays with the caller. In [`Owned`] mode, +//! through [`KeysetCipher::run`](crate::KeysetCipher::run), the description +//! is handed the value, and wipes it once. See [`SourceMode`]. //! //! # Collections and authentication //! @@ -204,7 +204,8 @@ pub use operations::{ pub(crate) use pending::KeysetSelector; pub use pending::{CipherRef, Pending, PendingFuture}; pub use request::{Request, Responses}; -pub use source::{Borrowed, ConsumeSource, Owned, ShareSource, SourceMode}; +pub(crate) use source::Held; +pub use source::{Borrowed, ConsumeSource, Owned, Source, SourceMode, WipeSource}; pub use stack_encrypt_derive::{DecryptSource, EncryptTarget}; /// The cleanup trait that every owned plaintext must implement. It is /// re-exported here so that the derives can name it, even when the caller's diff --git a/packages/stack-encrypt/src/target/operations.rs b/packages/stack-encrypt/src/target/operations.rs index efeaa5baff..49dde00189 100644 --- a/packages/stack-encrypt/src/target/operations.rs +++ b/packages/stack-encrypt/src/target/operations.rs @@ -20,33 +20,31 @@ use super::context::{ use super::conversion::{DecryptSource, EncryptTarget}; use super::core::{encrypt_native, open_native, Term}; use super::input::{AcceptsContext, NoCallerContext, RequiredContext}; -use super::source::{Borrowed, ConsumeSource, Owned, ShareSource, SourceMode}; +use super::source::{ + Borrowed, ConsumeSource, Guarded, Held, Owned, Source, SourceMode, WipeSource, +}; use super::{CipherRef, Pending}; use crate::contexts::{self, Contexts, Placeholder, Shape, Shapes, SuppliedContext}; use crate::json::{JsonDocument, JsonOptions, JsonPlaintext, JsonTerms}; use crate::{Error, IntoContext, KeysetCipher, MaybeEmpty, NonEmpty, StackCipher, StackCipherText}; use stack_kms::MaybeSend; use std::fmt; +use std::marker::PhantomData; +use vitaminc_aead::EncryptRef; -// What the description is handed is `M::Source`: `&'s S` in the default -// `Borrowed` mode, `S` itself in `Owned` mode (see `SourceMode`). +// What a description is handed is a `Source`: a borrow in the default +// `Borrowed` mode, the value itself in `Owned` mode (see `SourceMode`). The +// borrow's lifetime is the closure's own, so one owned value can be lent to +// a description and then handed to another. #[cfg(not(target_arch = "wasm32"))] -type Build<'s, S, T, K, Ctx, M> = Box< - dyn for<'a, 'k> FnOnce( - >::Source, - &'a KeysetCipher<'k, K>, - Ctx, - ) -> Pending<'a, T, K> +type Build<'s, S, T, K, Ctx> = Box< + dyn for<'a, 'k, 'b> FnOnce(Source<'b, S>, &'a KeysetCipher<'k, K>, Ctx) -> Pending<'a, T, K> + Send + 's, >; #[cfg(target_arch = "wasm32")] -type Build<'s, S, T, K, Ctx, M> = Box< - dyn for<'a, 'k> FnOnce( - >::Source, - &'a KeysetCipher<'k, K>, - Ctx, - ) -> Pending<'a, T, K> +type Build<'s, S, T, K, Ctx> = Box< + dyn for<'a, 'k, 'b> FnOnce(Source<'b, S>, &'a KeysetCipher<'k, K>, Ctx) -> Pending<'a, T, K> + 's, >; #[cfg(not(target_arch = "wasm32"))] @@ -87,16 +85,18 @@ type Open = Box FnOnce(&'a StackCipher) -> Pending<'a, T, K /// `M` is how the description is handed its plaintext ([`SourceMode`]): /// by reference in the default [`Borrowed`] mode, which a declaration that /// takes a field out of a borrowed struct runs in, or by value in -/// [`Owned`] mode, which [`EncryptInto`](super::EncryptInto) runs. In owned mode -/// a single operation consumes the plaintext without copying it, so `S` need -/// not be `Clone`; [`zip`](Self::zip) is the one place that asks for it. +/// [`Owned`] mode, which [`EncryptInto`](super::EncryptInto) runs. Every +/// operation reads the plaintext in place, so in neither mode does `S` need +/// to be `Clone`. In owned mode the operation handed the value wipes it. #[must_use = "an encryption description does nothing until a keyset cipher executes it"] pub struct Encryption<'s, S: 's, T, K, Ctx, M: SourceMode<'s, S> = Borrowed> { - build: Build<'s, S, T, K, Ctx, M>, + build: Build<'s, S, T, K, Ctx>, /// The context of each leaf, in terms of the context this description /// is handed. Kept beside the closure by every combinator, so /// [`contexts`](Self::contexts) shows what the closure will do. shapes: Shapes, + /// Which of the two a [`Source`] this description is handed holds. + mode: PhantomData M>, } /// A composable description of how `T` is recovered from a stored target. /// @@ -134,26 +134,6 @@ impl fmt::Debug for Decryption { impl<'s, S: 's, T: 'static, K: 'static, Ctx: 's, M: SourceMode<'s, S>> Encryption<'s, S, T, K, Ctx, M> { - /// A description built from its execution closure. This constructor is - /// crate-internal, because it gives a closure the source and the cipher - /// together, and the public constructors never do that. The collection - /// declarations use it to run an element's description once for each - /// element. - /// - /// `shapes` is the context of each leaf the closure will run, in terms - /// of the context it is handed. A closure that runs another - /// description passes that description's [`shapes`](Self::shapes). - pub(crate) fn from_build(shapes: Shapes, build: F) -> Self - where - F: for<'a, 'k> FnOnce(M::Source, &'a KeysetCipher<'k, K>, Ctx) -> Pending<'a, T, K> - + MaybeSend - + 's, - { - Self { - build: Box::new(build), - shapes, - } - } /// The shapes of this description's leaves, for a description that runs /// this one inside its closure. pub(crate) fn shapes(&self) -> Shapes { @@ -189,6 +169,7 @@ impl<'s, S: 's, T: 'static, K: 'static, Ctx: 's, M: SourceMode<'s, S>> Self { build: Box::new(move |_, cipher, _| Pending::ready(cipher, result)), shapes: Vec::new(), + mode: PhantomData, } } /// Reject the declaration: execution yields `error` without I/O, and any @@ -197,6 +178,7 @@ impl<'s, S: 's, T: 'static, K: 'static, Ctx: 's, M: SourceMode<'s, S>> Self { build: Box::new(move |_, cipher, _| Pending::failed(cipher, error)), shapes: Vec::new(), + mode: PhantomData, } } /// Reject this declaration as [`failed`](Self::failed) does, but keep @@ -210,6 +192,7 @@ impl<'s, S: 's, T: 'static, K: 'static, Ctx: 's, M: SourceMode<'s, S>> Self { build: Box::new(move |_, cipher, _| Pending::failed(cipher, error)), shapes: self.shapes, + mode: PhantomData, } } /// Build the destination from the completed output. `f` sees ciphertext @@ -218,10 +201,11 @@ impl<'s, S: 's, T: 'static, K: 'static, Ctx: 's, M: SourceMode<'s, S>> where F: FnOnce(T) -> U + MaybeSend + 'static, { - let Self { build, shapes } = self; + let Self { build, shapes, .. } = self; Encryption { build: Box::new(move |source, cipher, cx| build(source, cipher, cx).map(f)), shapes, + mode: PhantomData, } } /// [`map`](Self::map) for a conversion that can fail, such as reading @@ -230,10 +214,11 @@ impl<'s, S: 's, T: 'static, K: 'static, Ctx: 's, M: SourceMode<'s, S>> where F: FnOnce(T) -> Result + MaybeSend + 'static, { - let Self { build, shapes } = self; + let Self { build, shapes, .. } = self; Encryption { build: Box::new(move |source, cipher, cx| build(source, cipher, cx).try_map(f)), shapes, + mode: PhantomData, } } /// Drive the destination's [`Visitor`](super::transcode::Visitor) from @@ -257,33 +242,42 @@ impl<'s, S: 's, T: 'static, K: 'static, Ctx: 's, M: SourceMode<'s, S>> /// composes fields with different contexts — and `zip` cannot tell that /// from a target's two halves. /// - /// Both sides also receive the same plaintext. In the default - /// [`Borrowed`] mode that is the same reference, and costs nothing. In - /// [`Owned`] mode this side gets a clone and `other` takes - /// ownership, so a chain of `n` operations makes `n - 1` copies rather - /// than `n`, and only here does an owned plaintext need to be `Clone`. - /// In Owned mode, a match term next to an operation that consumes the - /// value still needs `S: Clone`. + /// Both sides read the same plaintext, and neither needs a copy of it. + /// `other` is a [`Borrowed`] description: it reads the plaintext in place, + /// and runs first. Then this description is handed what it would be + /// handed alone: the same borrow in [`Borrowed`] mode, or the value itself + /// in [`Owned`] mode. So several operations over one owned value put the + /// one that takes the value first, and the ones that only read it after. + /// The outputs are in the order written. + /// + /// While `other` reads an owned value, the value is held in a guard. If + /// `other` panics, the value is wiped as the stack unwinds + /// ([`WipeSource`]). pub fn zip( self, - other: Encryption<'s, S, U, K, Ctx, M>, + other: Encryption<'s, S, U, K, Ctx>, ) -> Encryption<'s, S, (T, U), K, Ctx, M> where Ctx: Clone, - M: ShareSource<'s, S>, + M: WipeSource<'s, S>, { - let Self { build, mut shapes } = self; + let Self { + build, mut shapes, .. + } = self; let Encryption { build: other_build, shapes: other_shapes, + .. } = other; shapes.extend(other_shapes); Encryption { build: Box::new(move |source, cipher, cx| { - let (mine, theirs) = M::share(source); - build(mine, cipher, cx.clone()).zip(other_build(theirs, cipher, cx)) + let guarded = Guarded::::new(source); + let theirs = other_build(guarded.source().lend(), cipher, cx.clone()); + build(guarded.take(), cipher, cx).zip(theirs) }), shapes, + mode: PhantomData, } } /// Take a different context type, converting on the way in. @@ -310,10 +304,11 @@ impl<'s, S: 's, T: 'static, K: 'static, Ctx: 's, M: SourceMode<'s, S>> C2: 's, F: FnOnce(C2) -> Ctx + MaybeSend + 's, { - let Self { build, shapes } = self; + let Self { build, shapes, .. } = self; Encryption { build: Box::new(move |source, cipher, cx| build(source, cipher, derive(cx))), shapes, + mode: PhantomData, } } /// Run this whole subtree under `own`, extended by the surrounding @@ -337,7 +332,7 @@ impl<'s, S: 's, T: 'static, K: 'static, Ctx: 's, M: SourceMode<'s, S>> where Ctx: From, { - self.under_refusing(own, drop) + self.under_refusing(own, |source| drop(source)) } /// [`under`](Self::under), for a field of a derived `struct = ..` /// record. A context that is refused here wipes a plaintext that was @@ -357,24 +352,24 @@ impl<'s, S: 's, T: 'static, K: 'static, Ctx: 's, M: SourceMode<'s, S>> S: zeroize::Zeroize, { self.under_refusing(own, |source| { - M::release(source, |value| { - drop(vitaminc_protected::Protected::new(value)) - }) + source.release(|value| drop(vitaminc_protected::Protected::new(value))) }) } /// The body of [`under`](Self::under). `refused` is given the source - /// when the context is refused, before the subtree has seen it. - fn under_refusing( + /// when the context is refused, before the subtree has seen it. The + /// JSON index's query passes one that wipes a document through its own + /// guard. + pub(crate) fn under_refusing( mut self, own: NonEmpty + MaybeSend + 's>, - refused: fn(M::Source), + refused: for<'b> fn(Source<'b, S>), ) -> Encryption<'s, S, T, K, DeclaredContext, M> where Ctx: From, { let own = contexts::piece_of(own); self.shapes = contexts::substitute(self.shapes, &Shape::under(own.get().clone())); - let Self { build, shapes } = self; + let Self { build, shapes, .. } = self; Encryption { build: Box::new(move |source, cipher, cx: DeclaredContext| { match cx.checked_under(own) { @@ -386,6 +381,7 @@ impl<'s, S: 's, T: 'static, K: 'static, Ctx: 's, M: SourceMode<'s, S>> } }), shapes, + mode: PhantomData, } } /// Run this whole subtree under the parts the plaintext stores, then the @@ -411,16 +407,17 @@ impl<'s, S: 's, T: 'static, K: 'static, Ctx: 's, M: SourceMode<'s, S>> Ctx: From, C: Into + 's, { - let Self { build, shapes } = self; + let Self { build, shapes, .. } = self; let shapes = contexts::substitute(shapes, &Shape::stored_parts(scope, bind)); Encryption { build: Box::new(move |source, cipher, caller: C| { - let stored = read(M::view(&source)); + let stored = read(source.view()); let mut context = DeclaredContext::from(CallerContext::from_stored(stored)); context.append(caller.into()); build(source, cipher, context.into()) }), shapes, + mode: PhantomData, } } /// Name the caller's parts, for [`contexts`](Self::contexts): the @@ -468,12 +465,11 @@ impl<'s, S: 's, T: 'static, K: 'static, Ctx: 's, M: SourceMode<'s, S>> { Self { build: Box::new(move |source, cipher, _| { - M::release(source, |value| { - drop(vitaminc_protected::Protected::new(value)) - }); + source.release(|value| drop(vitaminc_protected::Protected::new(value))); Pending::failed(cipher, error) }), shapes: self.shapes, + mode: PhantomData, } } /// The body of [`storing`](Encryption::storing). `refused` is given the @@ -482,14 +478,14 @@ impl<'s, S: 's, T: 'static, K: 'static, Ctx: 's, M: SourceMode<'s, S>> fn storing_refusing( self, store: F, - refused: fn(M::Source), + refused: for<'b> fn(Source<'b, S>), ) -> Encryption<'s, S, U, K, StoredContext, M> where Ctx: From, C: MaybeSend + 'static, F: FnOnce(T, C) -> U + MaybeSend + 'static, { - let Self { build, shapes } = self; + let Self { build, shapes, .. } = self; Encryption { build: Box::new( move |source, cipher, cx: StoredContext| match cx.into_parts() { @@ -503,11 +499,33 @@ impl<'s, S: 's, T: 'static, K: 'static, Ctx: 's, M: SourceMode<'s, S>> }, ), shapes, + mode: PhantomData, } } } impl<'s, S: 's, T: 'static, K: 'static, Ctx: 's> Encryption<'s, S, T, K, Ctx> { + /// A description built from its execution closure. This constructor is + /// crate-internal, because it gives a closure the source and the cipher + /// together, and the public constructors never do that. The collection + /// declarations use it to run an element's description once for each + /// element. + /// + /// `shapes` is the context of each leaf the closure will run, in terms + /// of the context it is handed. A closure that runs another + /// description passes that description's [`shapes`](Self::shapes). + pub(crate) fn from_build(shapes: Shapes, build: F) -> Self + where + F: for<'a, 'k, 'b> FnOnce(&'b S, &'a KeysetCipher<'k, K>, Ctx) -> Pending<'a, T, K> + + MaybeSend + + 's, + { + Self { + build: Box::new(move |source, cipher, cx| build(source.borrowed(), cipher, cx)), + shapes, + mode: PhantomData, + } + } /// Lift a description of a field to a description of the struct that /// holds it, which is how a `struct = T` derive composes its fields. /// @@ -523,10 +541,13 @@ impl<'s, S: 's, T: 'static, K: 'static, Ctx: 's> Encryption<'s, S, T, K, Ctx> { self, select: for<'borrow> fn(&'borrow P) -> &'borrow S, ) -> Encryption<'s, P, T, K, Ctx> { - let Self { build, shapes } = self; + let Self { build, shapes, .. } = self; Encryption { - build: Box::new(move |source, cipher, cx| build(select(source), cipher, cx)), + build: Box::new(move |source, cipher, cx| { + build(Source::lent(select(source.borrowed())), cipher, cx) + }), shapes, + mode: PhantomData, } } /// Store the context this description runs under, for a record that @@ -557,7 +578,7 @@ impl<'s, S: 's, T: 'static, K: 'static, Ctx: 's> Encryption<'s, S, T, K, Ctx> { C: MaybeSend + 'static, F: FnOnce(T, C) -> U + MaybeSend + 'static, { - self.storing_refusing(store, drop) + self.storing_refusing(store, |source| drop(source)) } /// Takes the context from a field of the plaintext. The caller then /// supplies no context. @@ -670,7 +691,7 @@ impl<'s, S: 's, T: 'static, K: 'static, Ctx: 's> Encryption<'s, S, T, K, Ctx> { Ctx: AcceptsContext>, C: Clone + MaybeEmpty + 's, { - let Self { build, shapes } = self; + let Self { build, shapes, .. } = self; let shapes = contexts::substitute( shapes, &Shape::Placeholder(Placeholder::from_plaintext( @@ -681,13 +702,14 @@ impl<'s, S: 's, T: 'static, K: 'static, Ctx: 's> Encryption<'s, S, T, K, Ctx> { Encryption { build: Box::new( move |source, cipher, _: NoCallerContext| match super::context::nonempty( - pick(source).clone(), + pick(source.view()).clone(), ) { Ok(context) => build(source, cipher, Ctx::supplied(context)), Err(error) => Pending::failed(cipher, error), }, ), shapes, + mode: PhantomData, } } /// [`under`](Encryption::under) for a context read out of the source @@ -712,7 +734,7 @@ impl<'s, S: 's, T: 'static, K: 'static, Ctx: 's> Encryption<'s, S, T, K, Ctx> { Ctx: From, G: for<'b> FnOnce(&'b S) -> Result + MaybeSend + 's, { - let Self { build, shapes } = self; + let Self { build, shapes, .. } = self; let shapes = contexts::substitute( shapes, &Shape::under_label( @@ -722,12 +744,13 @@ impl<'s, S: 's, T: 'static, K: 'static, Ctx: 's> Encryption<'s, S, T, K, Ctx> { ); Encryption { build: Box::new( - move |source, cipher, cx: DeclaredContext| match own(source) { + move |source, cipher, cx: DeclaredContext| match own(source.view()) { Ok(label) => build(source, cipher, cx.under(NonEmpty::from(label)).into()), Err(error) => Pending::failed(cipher, error), }, ), shapes, + mode: PhantomData, } } /// [`project`](Self::project) for a field picked by name at run time, as @@ -743,18 +766,36 @@ impl<'s, S: 's, T: 'static, K: 'static, Ctx: 's> Encryption<'s, S, T, K, Ctx> { where G: for<'b> FnOnce(&'b P) -> Result<&'b S, Error> + MaybeSend + 's, { - let Self { build, shapes } = self; + let Self { build, shapes, .. } = self; Encryption { - build: Box::new(move |source, cipher, cx| match select(source) { - Ok(field) => build(field, cipher, cx), + build: Box::new(move |source, cipher, cx| match select(source.borrowed()) { + Ok(field) => build(Source::lent(field), cipher, cx), Err(error) => Pending::failed(cipher, error), }), shapes, + mode: PhantomData, } } } impl<'s, S: 's, T: 'static, K: 'static, Ctx: 's> Encryption<'s, S, T, K, Ctx, Owned> { + /// A description built from its execution closure, which is handed the + /// plaintext by value. Crate-internal, as + /// [`from_build`](Encryption::from_build) is, and for the same reason. + /// The closure is responsible for wiping what it does not move into the + /// output. + pub(crate) fn from_owned_build(shapes: Shapes, build: F) -> Self + where + F: for<'a, 'k> FnOnce(S, &'a KeysetCipher<'k, K>, Ctx) -> Pending<'a, T, K> + + MaybeSend + + 's, + { + Self { + build: Box::new(move |source, cipher, cx| build(source.owned(), cipher, cx)), + shapes, + mode: PhantomData, + } + } /// [`project`](Self::project) for a plaintext passed by value. It turns a /// description of one field into a description of the struct that contains /// the field. `select` moves that field out of the struct. @@ -774,10 +815,13 @@ impl<'s, S: 's, T: 'static, K: 'static, Ctx: 's> Encryption<'s, S, T, K, Ctx, Ow /// move values. #[doc(hidden)] pub fn project_owned(self, select: fn(P) -> S) -> Encryption<'s, P, T, K, Ctx, Owned> { - let Self { build, shapes } = self; + let Self { build, shapes, .. } = self; Encryption { - build: Box::new(move |source, cipher, cx| build(select(source), cipher, cx)), + build: Box::new(move |source, cipher, cx| { + build(Source::given(select(source.owned())), cipher, cx) + }), shapes, + mode: PhantomData, } } /// [`storing`](Encryption::storing) for a plaintext passed by value. @@ -804,7 +848,7 @@ impl<'s, S: 's, T: 'static, K: 'static, Ctx: 's> Encryption<'s, S, T, K, Ctx, Ow S: zeroize::Zeroize, { self.storing_refusing(store, |source| { - drop(vitaminc_protected::Protected::new(source)) + source.release(|value| drop(vitaminc_protected::Protected::new(value))) }) } /// Divide a plaintext passed by value between two descriptions, under the @@ -842,24 +886,28 @@ impl<'s, S: 's, T: 'static, K: 'static, Ctx: 's> Encryption<'s, S, T, K, Ctx, Ow where Ctx: Clone, { - let Self { build, mut shapes } = self; + let Self { + build, mut shapes, .. + } = self; let Encryption { build: other_build, shapes: other_shapes, + .. } = other; shapes.extend(other_shapes); Encryption { build: Box::new(move |source, cipher, cx: Ctx| { let first_cx = cx.clone(); - let (mine, theirs) = divide(source); + let (mine, theirs) = divide(source.owned()); let waiting = Waiting { part: Some(theirs), wipe, }; - let first = build(mine, cipher, first_cx); - first.zip(other_build(waiting.hand_over(), cipher, cx)) + let first = build(Source::given(mine), cipher, first_cx); + first.zip(other_build(Source::given(waiting.hand_over()), cipher, cx)) }), shapes, + mode: PhantomData, } } } @@ -926,11 +974,15 @@ pub(crate) fn chosen<'s, S: 's, T: 'static, K: 'static, Ctx: 's, M: SourceMode<' choose: G, ) -> Encryption<'s, S, T, K, Ctx, M> where - G: for<'a, 'k> FnOnce(M::Source, &'a KeysetCipher<'k, K>, Ctx) -> Pending<'a, T, K> + G: for<'a, 'k, 'b> FnOnce(Source<'b, S>, &'a KeysetCipher<'k, K>, Ctx) -> Pending<'a, T, K> + MaybeSend + 's, { - Encryption::from_build(contexts::caller_leaf(), choose) + Encryption { + build: Box::new(choose), + shapes: contexts::caller_leaf(), + mode: PhantomData, + } } /// A description that only checks the borrowed source, yielding `()` or the @@ -944,8 +996,9 @@ where C: FnOnce(&S) -> Result<(), Error> + MaybeSend + 's, { Encryption { - build: Box::new(move |source, cipher, _| Pending::ready(cipher, check(source))), + build: Box::new(move |source, cipher, _| Pending::ready(cipher, check(source.view()))), shapes: Vec::new(), + mode: PhantomData, } } @@ -964,13 +1017,14 @@ where where F: FnOnce(T, Ctx) -> U + MaybeSend + 'static, { - let Self { build, shapes } = self; + let Self { build, shapes, .. } = self; Encryption { build: Box::new(move |source, cipher, cx: Ctx| { let carried = cx.clone(); build(source, cipher, cx).map(move |value| f(value, carried)) }), shapes, + mode: PhantomData, } } } @@ -985,47 +1039,33 @@ where /// [`accepting`](Encryption::accepting) lets it take the term's context — /// the AEAD half of the same value — so the two zip under one context. /// -/// `Encrypt` consumes the plaintext. In [`Owned`] mode it is -/// handed over, so `S` need not be `Clone`; in the default [`Borrowed`] mode -/// it is cloned once, which is what `M: ConsumeSource<'s, S>` asks. +/// The plaintext is read in place and never copied. In the default +/// [`Borrowed`] mode it is walked as a borrow, and it stays with the caller. +/// In [`Owned`] mode it is walked by value, so Vitamin C wipes what the value +/// owns when the walk is done. A source is `Encrypt` both by value and by +/// reference, which is what the two bounds ask. /// -/// The context is checked before the plaintext is taken. So in [`Borrowed`] -/// mode a refused context makes no copy. In [`Owned`] mode a refused context -/// drops the value without wiping it, because `S` need not be `Zeroize`. The -/// owned declarations of this crate's leaves wipe it instead. -pub fn ciphertext<'s, S: crate::Encrypt + 's, K: 'static, M: ConsumeSource<'s, S>>( -) -> Encryption<'s, S, StackCipherText, K, AeadContext, M> { - sealing(drop) -} -/// [`ciphertext`] for a plaintext that is wiped when the context is refused. -/// The owned declarations of [`StackCipherText`] and -/// [`Encrypted`](crate::Encrypted) run this form. -pub(crate) fn wiping_ciphertext<'s, S, K: 'static, M: ConsumeSource<'s, S>>( +/// The context is checked before the plaintext is read. In [`Owned`] mode +/// a refused context wipes the value, so there `S` is `Zeroize` +/// ([`WipeSource`]). +pub fn ciphertext<'s, S, K: 'static, M: WipeSource<'s, S>>( ) -> Encryption<'s, S, StackCipherText, K, AeadContext, M> where - S: crate::Encrypt + zeroize::Zeroize + 's, + S: crate::Encrypt + EncryptRef + 's, { - sealing(|source| { - M::release(source, |value| { - drop(vitaminc_protected::Protected::new(value)) - }) - }) -} -/// The body of [`ciphertext`]. `refused` is given the source when the context -/// is refused. The check runs before [`ConsumeSource::take`], so a refused -/// context never makes a copy of the plaintext. -fn sealing<'s, S: crate::Encrypt + 's, K: 'static, M: ConsumeSource<'s, S>>( - refused: fn(M::Source), -) -> Encryption<'s, S, StackCipherText, K, AeadContext, M> { Encryption { build: Box::new(move |source, cipher, cx: AeadContext| match cx.sealable() { - Ok(ctx) => encrypt_native(M::take(source), cipher, ctx), + Ok(ctx) => match source.into_held() { + Held::Lent(source) => encrypt_native(source.lend(), cipher, ctx), + Held::Given(source) => encrypt_native(source, cipher, ctx), + }, Err(e) => { - refused(source); + M::wipe(source); Pending::failed(cipher, e) } }), shapes: contexts::caller_leaf(), + mode: PhantomData, } } /// Encrypt a supported scalar, or an [`OpaqueBlob`](crate::OpaqueBlob), as @@ -1047,11 +1087,12 @@ pub fn scalar_ciphertext<'s, S: crate::OpaqueEncode, K: 'static>( build: Box::new( move |source, cipher, context: super::OptionalContext| { let piece = context.piece(); - crate::scalar::sealed::Encode::seal(source, cipher, piece.clone()) + crate::scalar::sealed::Encode::seal(source.borrowed(), cipher, piece.clone()) .under_context(piece.clone(), piece) }, ), shapes: contexts::caller_leaf(), + mode: PhantomData, } } @@ -1066,9 +1107,10 @@ pub fn scalar_ciphertext<'s, S: crate::OpaqueEncode, K: 'static>( /// beside it for lookup ([`indexed`](super::indexed) with /// [`Equality`](super::Equality)). /// -/// In [`Owned`] mode the value is moved through; in the -/// default [`Borrowed`] mode it is cloned once, which is what -/// `M: ConsumeSource<'s, S>` asks. `Ctx` is whatever the surrounding tree +/// In [`Owned`] mode the value is moved through. In the default +/// [`Borrowed`] mode the value is the caller's, so the output is a copy of +/// it, and `S` must be `Clone`. That is what `M: ConsumeSource<'s, S>` asks, +/// and no other operation asks for it. `Ctx` is whatever the surrounding tree /// hands its fields, so a passthrough zips beside any of them. pub fn passthrough<'s, S, K, M, Ctx>() -> Encryption<'s, S, S, K, Ctx, M> where @@ -1080,22 +1122,25 @@ where Encryption { build: Box::new(move |source, cipher, _| Pending::ready(cipher, Ok(M::take(source)))), shapes: Vec::new(), + mode: PhantomData, } } /// A term operation: `$function` produces `$output` from any `S` satisfying /// the bounds, under the [`CallerContext`] the tree hands it. /// -/// `consume` terms (equality, ORE, OPE) take the plaintext by value, as their -/// scheme does, so they ask the same `M: ConsumeSource<'s, S>` as -/// [`ciphertext`]. A `view` term (match) only reads it, so it works in any -/// mode and never clones. +/// Every term reads the plaintext in place, so it runs in either mode +/// without a copy. `$lend` is how a borrow of `S` becomes the source its +/// scheme reads. In [`Owned`] mode a `wipe` term hands the value to its +/// scheme, which wipes it. A `view` term (match) reads a borrow in either +/// mode, and then wipes a value it was handed. Either kind wipes a value it +/// was handed when the context is refused ([`WipeSource`]). macro_rules! term_operation { ( $(#[$doc:meta])* - $function:ident, $output:ty, consume, [$($generics:tt)*], [$($bounds:tt)*] + $function:ident, $output:ty, wipe($lend:expr), [$($generics:tt)*], [$($bounds:tt)*] ) => { $(#[$doc])* - pub fn $function<'s, S, K: 'static, M: ConsumeSource<'s, S>, $($generics)*>( + pub fn $function<'s, S, K: 'static, M: WipeSource<'s, S>, $($generics)*>( ) -> Encryption<'s, S, $output, K, CallerContext, M> where S: 's, @@ -1105,16 +1150,28 @@ macro_rules! term_operation { build: Box::new(move |source, cipher, cx: CallerContext| { let (query, stored) = (cx.query(), cx.stored()); match cx.validated() { - Ok(ctx) => <$output as Term>::encrypt_from( - M::take(source), - cipher, - CallerContext::query_nonempty(ctx), - ) - .under_context(query, stored), - Err(e) => Pending::failed(cipher, e), + Ok(ctx) => { + let context = CallerContext::query_nonempty(ctx); + match source.into_held() { + Held::Lent(source) => <$output as Term<_, K, _>>::encrypt_from( + $lend(source), + cipher, + context, + ), + Held::Given(source) => <$output as Term>::encrypt_from( + source, cipher, context, + ), + } + .under_context(query, stored) + } + Err(e) => { + M::wipe(source); + Pending::failed(cipher, e) + } } }), shapes: contexts::caller_leaf(), + mode: PhantomData, } } }; @@ -1123,7 +1180,7 @@ macro_rules! term_operation { $function:ident, $output:ty, view, [$($generics:tt)*], [$($bounds:tt)*] ) => { $(#[$doc])* - pub fn $function<'s, S, K: 'static, M: SourceMode<'s, S>, $($generics)*>( + pub fn $function<'s, S, K: 'static, M: WipeSource<'s, S>, $($generics)*>( ) -> Encryption<'s, S, $output, K, CallerContext, M> where S: 's, @@ -1131,10 +1188,13 @@ macro_rules! term_operation { { Encryption { build: Box::new(move |source, cipher, cx: CallerContext| { + // Wiped when the guard drops: after the read, and if + // the read panics. + let guarded = Guarded::::new(source); let (query, stored) = (cx.query(), cx.stored()); match cx.validated() { Ok(ctx) => <$output as Term<&S, K, _>>::encrypt_from( - M::view(&source), + guarded.source().view(), cipher, CallerContext::query_nonempty(ctx), ) @@ -1143,6 +1203,7 @@ macro_rules! term_operation { } }), shapes: contexts::caller_leaf(), + mode: PhantomData, } } }; @@ -1151,7 +1212,7 @@ term_operation!( /// The equality term of `S` under the context the tree hands it. Requires /// only that `S` describes itself (`Encrypt`), as one scalar with an /// equality domain; not recoverable encryption. - equality, crate::sem::EqualityTerm, consume, [], [S: crate::Encrypt] + equality, crate::sem::EqualityTerm, wipe(EncryptRef::lend), [], [S: crate::Encrypt + EncryptRef] ); term_operation!( /// The match term of any text `S` under the context the tree hands it, @@ -1161,20 +1222,20 @@ term_operation!( term_operation!( /// The order-revealing term of `S` under the context the tree hands it. /// The bound is the leaf's own: it says which `S` has an order target. - ore, crate::sem::OreTerm, consume, [], - [S: crate::sem::Orderable] + ore, crate::sem::OreTerm, wipe(std::convert::identity), [], + [S: crate::Orderable + EncryptRef + 'static] ); term_operation!( /// The order-preserving term of `S` under the context the tree hands it, /// with the same bounds as [`ore`]. - ope, crate::sem::OpeTerm, consume, [], - [S: crate::sem::Orderable] + ope, crate::sem::OpeTerm, wipe(std::convert::identity), [], + [S: crate::Orderable + EncryptRef + 'static] ); term_operation!( /// The block ORE term of `S` under the context the tree hands it, with /// the same bounds as [`ore`]. - ore_block, crate::sem::OreBlockTerm, consume, [], - [S: crate::sem::Orderable] + ore_block, crate::sem::OreBlockTerm, wipe(std::convert::identity), [], + [S: crate::Orderable + EncryptRef + 'static] ); /// The JSON index's terms of a document under the context the tree hands @@ -1192,7 +1253,7 @@ pub fn json_terms<'s, K: 'static, M: SourceMode<'s, serde_json::Value>>( let (query, stored) = (cx.query(), cx.stored()); let pending = match cx.validated() { Ok(ctx) => crate::json::terms_pending( - M::view(&source), + source.view(), &options, cipher, CallerContext::query_nonempty(ctx), @@ -1202,9 +1263,10 @@ pub fn json_terms<'s, K: 'static, M: SourceMode<'s, serde_json::Value>>( }; // The terms are derived by now; a document this description // owns (the one a query asks about) is wiped rather than dropped. - M::release(source, |value| drop(crate::json::PlainJson::protect(value))); + source.release(|value| drop(crate::json::PlainJson::protect(value))); pending }), + mode: PhantomData, } } @@ -1212,10 +1274,11 @@ pub fn json_terms<'s, K: 'static, M: SourceMode<'s, serde_json::Value>>( /// its terms, request one data key under the context's descriptor and seal /// every node under it, into a [`JsonDocument`]. The stored form of a JSON /// field; what [`JsonDocument`]'s own [`EncryptTarget`] runs. The -/// document is consumed, so in the default [`Borrowed`] mode it is cloned -/// once, as [`ciphertext`] clones its plaintext. In [`Owned`] mode it is -/// moved, and wiped when it has been sealed or the context is refused. -pub fn json_document<'s, K: 'static, M: ConsumeSource<'s, serde_json::Value>>( +/// document is read in place. In [`Owned`] mode it is wiped once it is +/// sealed, and when the context is refused. In [`Borrowed`] mode it is +/// copied only when the keyset is not loaded yet: the sealing then keeps +/// its own copy until the keyset arrives, and wipes it. +pub fn json_document<'s, K: 'static, M: SourceMode<'s, serde_json::Value>>( options: JsonOptions, ) -> Encryption<'s, serde_json::Value, JsonDocument, K, CallerContext, M> { Encryption { @@ -1224,8 +1287,9 @@ pub fn json_document<'s, K: 'static, M: ConsumeSource<'s, serde_json::Value>>( match cx.validated() { Ok(ctx) => { let (query_context, stored_context) = CallerContext::both_nonempty(ctx); + // The sealing wipes a document it is given. crate::json::seal_pending( - M::take(source), + source, &options, cipher, query_context, @@ -1234,14 +1298,13 @@ pub fn json_document<'s, K: 'static, M: ConsumeSource<'s, serde_json::Value>>( .under_context(query, stored) } Err(e) => { - // A document this description owns is wiped rather - // than dropped. - M::release(source, |value| drop(crate::json::PlainJson::protect(value))); + source.release(|value| drop(crate::json::PlainJson::protect(value))); Pending::failed(cipher, e) } } }), shapes: contexts::caller_leaf(), + mode: PhantomData, } } @@ -1275,8 +1338,9 @@ pub fn json_document<'s, K: 'static, M: ConsumeSource<'s, serde_json::Value>>( /// /// The plaintext is wiped when the document has been sealed, and when the /// context is refused. `encrypt_into` moves the document into the sealing, -/// with no copy. Sealing a borrowed plaintext, such as an element of a -/// collection, reads the document through one copy, which is wiped too. +/// and the sealing reads it in place. A borrowed document is read in place +/// too. It is copied only when the keyset is not loaded yet: the sealing +/// then keeps one copy until the keyset arrives, and wipes it. impl EncryptTarget for JsonDocument { type ContextInput = RequiredContext; fn encryption<'s, K: 'static>() -> Encryption<'s, JsonPlaintext, Self, K, Self::ContextInput> @@ -1487,9 +1551,9 @@ impl KeysetCipher<'_, K> { /// /// `source` is what the description's mode hands its operations: `&S` /// for a [`Borrowed`]-mode description (the default), or `S` itself for - /// an [`Owned`]-mode one. Owned mode is how a plaintext - /// that is not `Clone` reaches an operation: a single operation consumes - /// it without a copy. + /// an [`Owned`]-mode one. Neither mode copies the plaintext. In owned + /// mode the description takes the value, and wipes it once it is read. + /// A caller that keeps the value after the call runs it borrowed. /// /// ``` /// # async fn example() -> Result<(), stack_encrypt::Error> { @@ -1539,7 +1603,7 @@ impl KeysetCipher<'_, K> { source: M::Source, context: Ctx, ) -> Pending<'a, T, K> { - (encryption.build)(source, self, context) + (encryption.build)(M::source(source), self, context) } /// Run a [`Decryption`] held in a variable under this keyset: the /// counterpart of [`run`](Self::run), and what @@ -1596,16 +1660,14 @@ impl StackCipher { // context out, because a structural leaf takes no empty context. `Default` // does not change that. // -// The borrowed form of a ciphertext clones the plaintext, as the structural -// declaration does. It checks the context first, so a refused context makes no -// copy. The owned form of a ciphertext is handed the value and seals it without -// a copy. When the context is refused, it wipes the value. +// The borrowed form of a ciphertext reads the plaintext in place, as the +// structural declaration does. The owned form of a ciphertext is handed the +// value and seals it. When the context is refused, it wipes the value. // // The owned term targets keep the default owned form. It guards the value and -// runs the borrowed form over it, so each term takes a copy. A term derives no -// descriptor, so no context is refused there. Each term scheme consumes its -// copy. -impl EncryptTarget for StackCipherText { +// runs the borrowed form over it, so each term reads the value in place. A +// term derives no descriptor, so no context is refused there. +impl EncryptTarget for StackCipherText { type ContextInput = RequiredContext; fn encryption<'s, K: 'static>() -> Encryption<'s, S, Self, K, Self::ContextInput> where @@ -1617,7 +1679,7 @@ impl EncryptTarget for StackCip where S: 's, { - wiping_ciphertext().accepting() + ciphertext().accepting() } } impl DecryptSource

for StackCipherText { @@ -1626,7 +1688,9 @@ impl DecryptSource

for open(self, context.into_inner()) } } -impl EncryptTarget for crate::sem::EqualityTerm { +impl EncryptTarget + for crate::sem::EqualityTerm +{ type ContextInput = RequiredContext; fn encryption<'s, K: 'static>() -> Encryption<'s, S, Self, K, Self::ContextInput> where @@ -1654,7 +1718,9 @@ impl + zeroize::Zeroize, O: crate::sem::MatchConfig + 'static> Enc } macro_rules! owned_order_term { ($($ty:ident, $operation:ident, $spec:ident;)+) => {$( - impl EncryptTarget for crate::sem::$ty { + impl EncryptTarget + for crate::sem::$ty + { type ContextInput = RequiredContext; fn encryption<'s, K: 'static>() -> Encryption<'s, S, Self, K, Self::ContextInput> where diff --git a/packages/stack-encrypt/src/target/source.rs b/packages/stack-encrypt/src/target/source.rs index 94514bdfc7..8d4cbf0c84 100644 --- a/packages/stack-encrypt/src/target/source.rs +++ b/packages/stack-encrypt/src/target/source.rs @@ -2,17 +2,19 @@ //! explanation is on [`SourceMode`], which is what the public docs show; this //! module is private and its items are re-exported from `target`. +use vitaminc_protected::OpaqueDebug; + /// A description's plaintext is handed to it by reference: the default mode, /// and the one a record runs each field in when it takes the field out of a -/// borrowed struct. An operation that consumes the plaintext clones it. +/// borrowed struct. Every operation reads the plaintext in place. /// /// This is a mode, not a value: the enum is uninhabited, so no `Borrowed` /// ever exists and it never holds a plaintext. Its `Debug` can print nothing. #[derive(Debug)] pub enum Borrowed {} -/// A description's plaintext is handed to it by value. A single operation -/// consumes it without a copy; only fan-out over it needs `Clone`. +/// A description's plaintext is handed to it by value. The description +/// reads it without a copy, and wipes it or moves it into the output. /// /// Uninhabited like [`Borrowed`]: a mode that never holds the plaintext. The /// value itself lives only inside the description's closure, which has no @@ -29,89 +31,212 @@ mod sealed { /// How a description receives its plaintext: the `M` parameter of /// [`Encryption`](super::Encryption). /// -/// Vitamin C's `Encrypt` and `PrfValue`, and the order terms, consume the value -/// they are given, so an operation needs the plaintext by value. A -/// description can be handed it two ways, and because the mode is a type -/// parameter the difference is settled at compile time: +/// An operation reads the plaintext in place. It never needs a copy, so no +/// mode asks for `Clone`. A description can be handed the plaintext two ways, +/// and because the mode is a type parameter the difference is settled at +/// compile time: /// /// - [`Borrowed`], the default: the description is handed `&S`. This is /// what [`EncryptTarget::encryption`](super::EncryptTarget::encryption) -/// describes, and what lets a record -/// pick its fields out of a borrowed struct. An operation that consumes the -/// plaintext clones it first ([`ConsumeSource`]), so here, and only here, -/// `S` must be `Clone`. +/// describes, and what lets a record pick its fields out of a borrowed +/// struct. The plaintext stays with the caller, who wipes it. /// - [`Owned`]: the description is handed `S` itself, through -/// [`KeysetCipher::run`](crate::KeysetCipher::run). A single operation -/// consumes it with no copy, so a plaintext that is deliberately not -/// `Clone` (one that is moved and wiped, such as a zeroizing FFI value) can -/// be sealed or indexed. Running two operations over one value -/// ([`zip`](super::Encryption::zip)) hands a copy to every side but the -/// last, which takes ownership ([`ShareSource`]); that, and only that, -/// needs `Clone`. +/// [`KeysetCipher::run`](crate::KeysetCipher::run). The operation that is +/// handed the value reads it and then lets go of it: a ciphertext and a +/// term wipe it through Vitamin C, and a passthrough moves it into the +/// output. Several operations over one owned value +/// ([`zip`](super::Encryption::zip)) read it in place first, and the one +/// written first is handed the value. /// -/// A match term only reads its text, so it runs in either mode without a -/// copy. The traits are sealed: these two modes are the only ones. +/// The trait is sealed: these two modes are the only ones. pub trait SourceMode<'s, S: 's>: sealed::Sealed + 's { /// What the description is handed: `&'s S` or `S`. type Source; - /// Read the plaintext in place, for an operation that does not consume - /// it (a match term reads text through `AsRef`). - fn view(source: &Self::Source) -> &S; - /// Let go of the plaintext after reading it in place: in [`Owned`] - /// mode the description owns it, and hands it to `wipe`; in - /// [`Borrowed`] mode it is the caller's, and nothing is done. - fn release(source: Self::Source, wipe: impl FnOnce(S)); + /// The source as the engine passes it between descriptions. + #[doc(hidden)] + fn source(source: Self::Source) -> Source<'s, S>; } -/// A mode in which an operation can take the plaintext by value: always for -/// [`Owned`]; for [`Borrowed`] when `S: Clone`, by cloning it. -pub trait ConsumeSource<'s, S: 's>: SourceMode<'s, S> { - /// The plaintext, by value. - fn take(source: Self::Source) -> S; +/// A plaintext on its way to an operation: a borrow of it, or the value. +/// +/// The mode of a description says which one it is handed, so the two are +/// never confused: a [`Borrowed`] description is handed a borrow, and an +/// [`Owned`] one the value. This type exists so that one owned value can be +/// lent to several descriptions and then handed to the last. +#[doc(hidden)] +#[derive(OpaqueDebug)] +pub struct Source<'b, S>(Held<'b, S>); + +/// What a [`Source`] holds. +pub(crate) enum Held<'b, S> { + Lent(&'b S), + Given(S), } -/// A mode in which one plaintext can be handed to two operations: always -/// for [`Borrowed`], where the reference is copied; for [`Owned`] when -/// `S: Clone`, where the first side gets a clone and the second the value. -pub trait ShareSource<'s, S: 's>: SourceMode<'s, S> { - /// The plaintext for the first side, and for the second. - fn share(source: Self::Source) -> (Self::Source, Self::Source); +impl<'b, S> Source<'b, S> { + pub(crate) fn lent(source: &'b S) -> Self { + Self(Held::Lent(source)) + } + pub(crate) fn given(source: S) -> Self { + Self(Held::Given(source)) + } + /// Read the plaintext in place. + pub(crate) fn view(&self) -> &S { + match &self.0 { + Held::Lent(source) => source, + Held::Given(source) => source, + } + } + /// Lend the plaintext to another description, keeping this source. + pub(crate) fn lend(&self) -> Source<'_, S> { + Source::lent(self.view()) + } + /// Let go of the plaintext after reading it in place. A value the + /// description was given is handed to `wipe`. A borrow is the + /// caller's, and nothing is done. + pub(crate) fn release(self, wipe: impl FnOnce(S)) { + if let Held::Given(source) = self.0 { + wipe(source); + } + } + /// The borrow or the value, for an operation that treats them + /// differently. + pub(crate) fn into_held(self) -> Held<'b, S> { + self.0 + } + /// The borrow a [`Borrowed`] description is handed. + pub(crate) fn borrowed(self) -> &'b S { + match self.0 { + Held::Lent(source) => source, + Held::Given(_) => unreachable!("a borrowed description is handed a borrow"), + } + } + /// The value an [`Owned`] description is handed. + pub(crate) fn owned(self) -> S { + match self.0 { + Held::Given(source) => source, + Held::Lent(_) => unreachable!("an owned description is handed its value"), + } + } } impl<'s, S: 's> SourceMode<'s, S> for Borrowed { type Source = &'s S; - fn view(source: &Self::Source) -> &S { - source + fn source(source: Self::Source) -> Source<'s, S> { + Source::lent(source) } - fn release(_: Self::Source, _: impl FnOnce(S)) {} } -impl<'s, S: Clone + 's> ConsumeSource<'s, S> for Borrowed { - fn take(source: Self::Source) -> S { - source.clone() + +impl<'s, S: 's> SourceMode<'s, S> for Owned { + type Source = S; + fn source(source: Self::Source) -> Source<'s, S> { + Source::given(source) } } -impl<'s, S: 's> ShareSource<'s, S> for Borrowed { - fn share(source: Self::Source) -> (Self::Source, Self::Source) { - (source, source) + +/// A mode in which an operation that seals or indexes the plaintext can let +/// go of it. Every such operation asks for it, and +/// [`passthrough`](super::passthrough) does not. +/// +/// - [`Borrowed`] always can: the plaintext is the caller's, and the +/// operation leaves it there. +/// - [`Owned`] can when `S` is `Zeroize`. The operation that is handed the +/// value wipes it on every path: once it has read the value, and when the +/// context is refused or an operation fails. +/// +/// So in `Owned` mode a plaintext that is sealed or indexed is `Zeroize`, +/// and in `Borrowed` mode it need not be. +pub trait WipeSource<'s, S: 's>: SourceMode<'s, S> { + /// Let go of the plaintext. A value is wiped, and a borrow is left with + /// the caller. + #[doc(hidden)] + fn wipe(source: Source<'_, S>); +} +impl<'s, S: 's> WipeSource<'s, S> for Borrowed { + // A borrow is the caller's: letting go of it does nothing. + fn wipe(_: Source<'_, S>) {} +} +impl<'s, S: zeroize::Zeroize + 's> WipeSource<'s, S> for Owned { + fn wipe(source: Source<'_, S>) { + source.release(|value| drop(vitaminc_protected::Protected::new(value))); } } -impl<'s, S: 's> SourceMode<'s, S> for Owned { - type Source = S; - fn view(source: &Self::Source) -> &S { - source +/// A source that is wiped if it is dropped before an operation takes it. +/// An operation that reads an owned value before handing it on holds it in +/// one, so a reader that panics still lets the value go through +/// [`WipeSource::wipe`]: a value is wiped, and a borrow is left alone. +pub(crate) struct Guarded<'b, 's, M: WipeSource<'s, S>, S: 's> { + source: Option>, + mode: std::marker::PhantomData (M, &'s ())>, +} + +impl<'b, 's, M: WipeSource<'s, S>, S: 's> Guarded<'b, 's, M, S> { + pub(crate) fn new(source: Source<'b, S>) -> Self { + Self { + source: Some(source), + mode: std::marker::PhantomData, + } + } + /// The source, to read in place. + pub(crate) fn source(&self) -> &Source<'b, S> { + match &self.source { + Some(source) => source, + None => unreachable!("a guard holds its source until it is taken"), + } + } + /// Hand the source on: the guard no longer wipes it. + pub(crate) fn take(mut self) -> Source<'b, S> { + match self.source.take() { + Some(source) => source, + None => unreachable!("a guard holds its source until it is taken"), + } } - fn release(source: Self::Source, wipe: impl FnOnce(S)) { - wipe(source); +} + +impl<'s, M: WipeSource<'s, S>, S: 's> Drop for Guarded<'_, 's, M, S> { + fn drop(&mut self) { + if let Some(source) = self.source.take() { + M::wipe(source); + } + } +} + +/// A mode in which an operation can take the plaintext by value. Only +/// [`passthrough`](super::passthrough) asks for it, because its output is +/// the plaintext itself. [`Owned`] always can: the value is moved. In +/// [`Borrowed`] mode the value is the caller's, so the output is a copy of +/// it, and `S` must be `Clone`. A passthrough is stored in the clear, so +/// that copy is not a copy of a secret. +pub trait ConsumeSource<'s, S: 's>: SourceMode<'s, S> { + /// The plaintext, by value. + #[doc(hidden)] + fn take(source: Source<'_, S>) -> S; +} +impl<'s, S: Clone + 's> ConsumeSource<'s, S> for Borrowed { + fn take(source: Source<'_, S>) -> S { + source.borrowed().clone() } } impl<'s, S: 's> ConsumeSource<'s, S> for Owned { - fn take(source: Self::Source) -> S { - source + fn take(source: Source<'_, S>) -> S { + source.owned() } } -impl<'s, S: Clone + 's> ShareSource<'s, S> for Owned { - fn share(source: Self::Source) -> (Self::Source, Self::Source) { - (source.clone(), source) + +#[cfg(test)] +mod tests { + use super::Source; + + /// A source's `Debug` masks what it holds, lent or given. + #[test] + fn a_source_prints_no_plaintext() { + let secret = String::from("4111 1111 1111 1111"); + let lent = format!("{:?}", Source::lent(&secret)); + let given = format!("{:?}", Source::given(secret.clone())); + for printed in [lent, given] { + assert!(!printed.contains("4111"), "{printed}"); + assert!(printed.contains("***"), "{printed}"); + } } } diff --git a/packages/stack-encrypt/src/target/transcode.rs b/packages/stack-encrypt/src/target/transcode.rs index 38996a296a..72ad484bbc 100644 --- a/packages/stack-encrypt/src/target/transcode.rs +++ b/packages/stack-encrypt/src/target/transcode.rs @@ -109,7 +109,7 @@ pub trait Visitor: Sized { /// # Errors /// /// Refuses with [`Error::UnsupportedShape`] unless overridden. - fn ore(self, _: OreTerm) -> Result { + fn ore(self, _: OreTerm) -> Result { Err(Error::UnsupportedShape) } /// An order-preserving term. One-way, and not authenticated. @@ -117,7 +117,7 @@ pub trait Visitor: Sized { /// # Errors /// /// Refuses with [`Error::UnsupportedShape`] unless overridden. - fn ope(self, _: OpeTerm) -> Result { + fn ope(self, _: OpeTerm) -> Result { Err(Error::UnsupportedShape) } /// A block ORE term. One-way, and not authenticated. @@ -125,7 +125,7 @@ pub trait Visitor: Sized { /// # Errors /// /// Refuses with [`Error::UnsupportedShape`] unless overridden. - fn ore_block(self, _: OreBlockTerm) -> Result { + fn ore_block(self, _: OreBlockTerm) -> Result { Err(Error::UnsupportedShape) } } @@ -201,17 +201,17 @@ impl Reader for MatchTerms { visitor.matching(self) } } -impl Reader for OreTerm { +impl Reader for OreTerm { fn read(self, visitor: V) -> Result { visitor.ore(self) } } -impl Reader for OpeTerm { +impl Reader for OpeTerm { fn read(self, visitor: V) -> Result { visitor.ope(self) } } -impl Reader for OreBlockTerm { +impl Reader for OreBlockTerm { fn read(self, visitor: V) -> Result { visitor.ore_block(self) } diff --git a/packages/stack-encrypt/src/value.rs b/packages/stack-encrypt/src/value.rs index 56ec5ac491..9dd5c89bad 100644 --- a/packages/stack-encrypt/src/value.rs +++ b/packages/stack-encrypt/src/value.rs @@ -1,52 +1,36 @@ //! Plaintexts with no Rust standard type: a calendar date, a UTC instant -//! and a decimal number, each held as the integers vitaminc's value model -//! stores it as. +//! and a decimal number. //! -//! The types the ecosystem offers (jiff's `civil::Date` and `Timestamp`, -//! rust_decimal's `Decimal`) keep their fields private, so their bytes -//! cannot be wiped. A plaintext this crate copies, to seal it or to derive -//! a term from it, must be wiped when it is dropped, so these types stand -//! in for them. With the `jiff` and `rust_decimal` features each converts -//! to and from its ecosystem type. +//! These are vitaminc-aead's types, re-exported so a caller needs no +//! dependency on vitaminc of their own. Each one is built from the type the +//! ecosystem offers, and wipes its value when it is dropped: //! -//! vitaminc-aead has wipeable `Date`, `Timestamp` and `Decimal` types of -//! its own, and they are not reused: this crate hands each term of a type -//! its own copy of the plaintext, so a target with several terms needs a -//! `Clone` plaintext, and vitaminc's types are deliberately not `Clone`. -//! They are also built only from jiff's and rust_decimal's types, which -//! would make those crates a dependency of every build. The types here are -//! `Clone`, and a clone is wiped too. +//! | Type | Built from | Feature | Range | +//! |---|---|---|---| +//! | `Date` | jiff's `civil::Date` | `jiff` | `-009999-01-01` to `9999-12-31` | +//! | `Timestamp` | jiff's `Timestamp` | `jiff` | `-009999-01-02T01:59:59Z` to `9999-12-30T22:00:00.999999999Z` | +//! | `Decimal` | rust_decimal's `Decimal` | `rust_decimal` | scale at most 28, mantissa below 2^96 in magnitude | //! -//! | Type | Holds | Range | -//! |---|---|---| -//! | [`Date`] | an `i32` count of days since 1970-01-01, in the proleptic Gregorian calendar | `-009999-01-01` to `9999-12-31` | -//! | [`Timestamp`] | an `i64` count of seconds since the Unix epoch and a `u32` of nanoseconds below one second, UTC, with no leap seconds | `-009999-01-02T01:59:59Z` to `9999-12-30T22:00:00.999999999Z` | -//! | [`Decimal`] | an `i128` mantissa and a `u8` scale: the value is `mantissa × 10^-scale` | scale at most 28, mantissa below 2^96 in magnitude | +//! Both features are on by default. The ranges are jiff's and +//! rust_decimal's. Every language's SDK uses the same ranges, so a value +//! one SDK encrypts, every SDK can decrypt. //! -//! The ranges are vitaminc's, which are jiff's and rust_decimal's. Every -//! language's binding uses the same ranges, so a value one binding -//! encrypts, every binding can decrypt. A value outside them has no -//! encoding and is refused when the type is built, so a value of one of -//! these types always encrypts. A refusal ([`RangeError`]) names what was -//! out of range, never the value. +//! # Why not jiff's and rust_decimal's types directly //! -//! # What wiping covers +//! A jiff `civil::Date` or `Timestamp`, and a rust_decimal `Decimal`, keep +//! their fields private and are `Copy`. Their bytes cannot be wiped, and a +//! copy leaves no trace. The types here hold the same value as integers +//! and wipe them when dropped ([`Zeroize`](zeroize::Zeroize), +//! [`ZeroizeOnDrop`](zeroize::ZeroizeOnDrop)). //! -//! Each type implements [`Zeroize`] and wipes its integers when it is -//! dropped ([`ZeroizeOnDrop`]). That covers every owned copy this crate -//! makes. The integer a value describes itself to vitaminc's sink with is a -//! `Copy` stack temporary, as it is for the primitive, jiff and -//! rust_decimal sources, and is not wiped. Nor is a value the caller builds -//! the type from, or converts it to: a jiff `civil::Date` or `Timestamp`, -//! or a rust_decimal `Decimal` (with the `jiff` and `rust_decimal` features), -//! or the integers read through an accessor, are ordinary values the caller -//! looks after. +//! None of the types is `Copy` or `Clone`. This crate reads a plaintext in +//! place, so one value with a ciphertext and several terms is never +//! copied. `Debug` is redacted, and there is no `Ord` or `Hash`, which +//! would compare plaintext in variable time. //! -//! None of the types is `Copy`, so a copy is never made without a trace. -//! Each is `Clone`, because each term of a type takes its own copy of the -//! plaintext; a clone is wiped when it is dropped too. `Debug` is redacted, -//! and there is no `PartialEq`, `Ord` or `Hash`, which would compare -//! plaintext in variable time: compare the accessors' integers. +//! The value a type is built from, and the value an accessor returns +//! (`to_jiff`, `to_decimal`), are ordinary jiff and rust_decimal values. +//! The caller looks after those: they are not wiped. //! //! # Equality and order //! @@ -64,753 +48,43 @@ //! store's rounding; //! - a date is its day. -use std::fmt; - -use crate::Encrypt; -use vitaminc_aead::plaintext::depth; -use vitaminc_aead::plaintext::kinds::{timestamp_nanos, MAX_DECIMAL_SCALE}; -use vitaminc_aead::{FixedType, FromScalar, Int, Logical, Physical, Sink, TimeUnit, Width}; -use zeroize::{Zeroize, ZeroizeOnDrop}; - -const NANOS_PER_SECOND: u32 = 1_000_000_000; - -/// Why a value could not be built as one of this module's plaintexts. -/// -/// The message names the range, never the value: the value is plaintext, -/// and an error is what a program logs. -#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)] -#[non_exhaustive] -pub enum RangeError { - /// A day count outside jiff's date range, `-009999-01-01` to - /// `9999-12-31`. - #[error("the date is outside the representable range, years -9999 to 9999")] - Date, - /// An instant outside jiff's range, `-009999-01-02T01:59:59Z` to - /// `9999-12-30T22:00:00.999999999Z`. - #[error( - "the timestamp is outside the representable range, -009999-01-02T01:59:59Z to 9999-12-30T22:00:00.999999999Z" - )] - Timestamp, - /// Nanoseconds of one second or more, which are not a nanosecond - /// field. - #[error("the timestamp's nanoseconds must be below one second")] - Nanoseconds, - /// A decimal scale above 28. - #[error("the decimal's scale is above 28")] - DecimalScale, - /// A decimal mantissa of 2^96 or more in magnitude. - #[error("the decimal's mantissa does not fit 96 bits")] - DecimalMantissa, -} - -/// A calendar date with no time of day and no time zone: a count of days -/// since 1970-01-01 in the proleptic Gregorian calendar. -/// -/// 1970-01-01 is day 0 and 1969-12-31 is day -1: the day count vitaminc's -/// value model stores a date as, and the one a jiff `civil::Date` converts -/// to with the `jiff` feature. See the [module documentation](self) for what -/// wiping covers. +/// A calendar date with no time of day and no time zone. /// /// ``` /// use stack_encrypt::value::Date; /// -/// let day = Date::from_days_since_epoch(19_782)?; // 2024-02-29 -/// assert_eq!(day.days_since_epoch(), 19_782); -/// # Ok::<(), stack_encrypt::value::RangeError>(()) +/// let leap_day = jiff::civil::date(2024, 2, 29); +/// let date = Date::new(leap_day); +/// assert_eq!(date.to_jiff(), leap_day); /// ``` -#[derive(Clone)] -pub struct Date { - days: i32, -} - -impl Date { - /// The date `days` after 1970-01-01, or before it for a negative count. - /// - /// # Errors - /// - /// [`RangeError::Date`] outside `-009999-01-01` to `9999-12-31`. - pub fn from_days_since_epoch(days: i32) -> Result { - Logical::Date - .admits(&Physical::Int(Int::I32(days))) - .then_some(Self { days }) - .ok_or(RangeError::Date) - } - - /// The count of days since 1970-01-01. The integer is the caller's to - /// look after: it is a copy, and is not wiped. - pub fn days_since_epoch(&self) -> i32 { - self.days - } -} +#[cfg(feature = "jiff")] +pub use vitaminc_aead::Date; -/// A UTC instant with nanosecond precision and no leap seconds: whole -/// seconds since the Unix epoch, and nanoseconds past them. -/// -/// The ciphertext keeps the nanoseconds; an equality or order term keeps -/// the microseconds, truncated rather than rounded (see the [module -/// documentation](self#equality-and-order), which also says what wiping -/// covers). +/// A UTC instant. /// /// ``` -/// use stack_encrypt::value::{RangeError, Timestamp}; +/// use stack_encrypt::value::Timestamp; /// -/// let instant = Timestamp::new(1_700_000_000, 500)?; -/// assert_eq!((instant.seconds(), instant.nanoseconds()), (1_700_000_000, 500)); -/// assert_eq!(Timestamp::new(0, 1_000_000_000).unwrap_err(), RangeError::Nanoseconds); -/// # Ok::<(), RangeError>(()) +/// let instant = jiff::Timestamp::new(1_700_000_000, 123_456_789)?; +/// let timestamp = Timestamp::new(instant)?; +/// assert_eq!(timestamp.to_jiff(), instant); +/// # Ok::<(), Box>(()) /// ``` -#[derive(Clone)] -pub struct Timestamp { - seconds: i64, - nanos: u32, -} - -impl Timestamp { - /// The instant `seconds` after the Unix epoch, plus `nanoseconds`. - /// A negative `seconds` is before 1970; the nanoseconds still count - /// forward from it, so -0.5 seconds is `new(-1, 500_000_000)`. - /// - /// # Errors - /// - /// [`RangeError::Nanoseconds`] for nanoseconds of one second or more, - /// and [`RangeError::Timestamp`] outside `-009999-01-02T01:59:59Z` to - /// `9999-12-30T22:00:00.999999999Z`. - pub fn new(seconds: i64, nanoseconds: u32) -> Result { - if nanoseconds >= NANOS_PER_SECOND { - return Err(RangeError::Nanoseconds); - } - let instant = Self { - seconds, - nanos: nanoseconds, - }; - timestamp_nanos(TimeUnit::Nanos, Int::I128(instant.count())) - .map(|_| instant) - .ok_or(RangeError::Timestamp) - } - - /// Whole seconds since the Unix epoch, negative before 1970. A copy, - /// not wiped. - pub fn seconds(&self) -> i64 { - self.seconds - } - - /// Nanoseconds past [`seconds`](Self::seconds), below one second. A - /// copy, not wiped. - pub fn nanoseconds(&self) -> u32 { - self.nanos - } - - /// Nanoseconds since the epoch: the count vitaminc stores a timestamp - /// as, and the one a jiff `Timestamp` encrypts to, so the two seal the - /// same leaf. Cannot overflow: an `i64` of seconds times 10^9 is far - /// inside an `i128`. - fn count(&self) -> i128 { - i128::from(self.seconds) * i128::from(NANOS_PER_SECOND) + i128::from(self.nanos) - } +#[cfg(feature = "jiff")] +pub use vitaminc_aead::Timestamp; - /// The instant for a count of nanoseconds already checked to be in - /// range. - fn from_nanos(nanos: i128) -> Option { - let per_second = i128::from(NANOS_PER_SECOND); - Some(Self { - seconds: i64::try_from(nanos.div_euclid(per_second)).ok()?, - nanos: u32::try_from(nanos.rem_euclid(per_second)).ok()?, - }) - } -} +/// Why a jiff `Timestamp` could not become a [`Timestamp`]. +#[cfg(feature = "jiff")] +pub use vitaminc_aead::OutOfRange; -/// A finite decimal number with its scale: `mantissa × 10^-scale`. -/// -/// The scale is kept: `1.50` (mantissa 150, scale 2) opens as `1.50`, not -/// `1.5`. An equality or order term normalises it, so `1.5` and `1.50` -/// match under `=` and order as equal. There is no NaN and no infinity, and a negative zero is zero. See -/// the [module documentation](self) for what wiping covers. -/// -/// PostgreSQL's `numeric` holds values this type cannot (more than 28 -/// digits after the point, or a mantissa past 96 bits); such a value is -/// refused, never rounded. +/// A decimal number: a mantissa and a scale. /// /// ``` -/// use stack_encrypt::value::{Decimal, RangeError}; +/// use stack_encrypt::value::Decimal; /// -/// let price = Decimal::new(-123_450, 2)?; // -1234.50 -/// assert_eq!((price.mantissa(), price.scale()), (-123_450, 2)); -/// assert_eq!(Decimal::new(1, 29).unwrap_err(), RangeError::DecimalScale); -/// # Ok::<(), RangeError>(()) +/// let price = rust_decimal::Decimal::new(1999, 2); // 19.99 +/// let decimal = Decimal::new(price); +/// assert_eq!(decimal.to_decimal(), price); /// ``` -#[derive(Clone)] -pub struct Decimal { - mantissa: i128, - scale: u8, -} - -impl Decimal { - /// `mantissa × 10^-scale`. - /// - /// # Errors - /// - /// [`RangeError::DecimalScale`] for a scale above 28, and - /// [`RangeError::DecimalMantissa`] for a mantissa of 2^96 or more in - /// magnitude. - pub fn new(mantissa: i128, scale: u8) -> Result { - if scale > MAX_DECIMAL_SCALE { - return Err(RangeError::DecimalScale); - } - Logical::Decimal { scale } - .admits(&Physical::Int(Int::I128(mantissa))) - .then_some(Self { mantissa, scale }) - .ok_or(RangeError::DecimalMantissa) - } - - /// The mantissa: the value is `mantissa × 10^-scale`. A copy, not - /// wiped. - pub fn mantissa(&self) -> i128 { - self.mantissa - } - - /// The number of digits after the point, at most 28. A copy, not - /// wiped. - pub fn scale(&self) -> u8 { - self.scale - } -} - -/// `Zeroize`, `ZeroizeOnDrop` and a redacted `Debug` for each type: wiping -/// sets every integer to zero. -macro_rules! wiped { - ($($ty:ident { $($field:ident),+ }),+ $(,)?) => {$( - impl Zeroize for $ty { - fn zeroize(&mut self) { - $(self.$field.zeroize();)+ - } - } - - impl Drop for $ty { - fn drop(&mut self) { - self.zeroize(); - } - } - - impl ZeroizeOnDrop for $ty {} - - impl fmt::Debug for $ty { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.write_str(concat!(stringify!($ty), "()")) - } - } - )+}; -} -wiped!( - Date { days }, - Timestamp { seconds, nanos }, - Decimal { mantissa, scale }, -); - -/// Each type describes itself to vitaminc as the logical type over an int -/// it is, the same scalar the jiff and rust_decimal types describe, so a -/// value converted from one of those seals the same leaf. The owned form -/// visits through the borrowed one and is then dropped, and wiped. -/// -/// Each is fixed width, so `None` of one seals as a typed null as long as a -/// value, and an `Option` of one reads it back: the type's -/// own zero (the epoch, a zero decimal) is a value it reads, which is what -/// `Decrypt::reads_null` asks of it. -macro_rules! source { - ($($ty:ident ($fixed:expr) => |$value:ident| $scalar:expr),+ $(,)?) => {$( - impl Encrypt for &$ty { - const DEPTH: Option = depth::SCALAR; - const FIXED: Option = $fixed; - fn visit(self, sink: S) -> Result { - let $value = self; - let (logical, int) = $scalar; - sink.scalar(Some(logical), Physical::Int(int)) - } - } - - impl Encrypt for $ty { - const DEPTH: Option = depth::SCALAR; - const FIXED: Option = $fixed; - fn visit(self, sink: S) -> Result { - (&self).visit(sink) - } - } - )+}; -} -source!( - Date (FixedType::new(Some(Logical::Date), Width::I32)) - => |date| (Logical::Date, Int::I32(date.days)), - Timestamp (FixedType::new(Some(Logical::Timestamp(TimeUnit::Nanos)), Width::I128)) - => |instant| (Logical::Timestamp(TimeUnit::Nanos), Int::I128(instant.count())), - Decimal (FixedType::new(Some(Logical::Decimal { scale: 0 }), Width::I128)) - => |decimal| (Logical::Decimal { scale: decimal.scale }, Int::I128(decimal.mantissa)), -); - -/// A date reads exactly a date scalar, at any integer width, in range. -impl FromScalar for Date { - const EXPECTED: &'static str = "date"; - fn from_scalar(ty: Option, value: Physical<'_>) -> Option { - match (ty, value) { - (Some(Logical::Date), Physical::Int(days)) => { - Date::from_days_since_epoch(i32::try_from(days.to_i128()?).ok()?).ok() - } - _ => None, - } - } -} - -/// A timestamp reads a timestamp scalar in any unit (a JavaScript `Date` -/// is in milliseconds, a Rust or Go instant in nanoseconds), in range. -impl FromScalar for Timestamp { - const EXPECTED: &'static str = "timestamp"; - fn from_scalar(ty: Option, value: Physical<'_>) -> Option { - match (ty, value) { - (Some(Logical::Timestamp(unit)), Physical::Int(count)) => { - Timestamp::from_nanos(timestamp_nanos(unit, count)?) - } - _ => None, - } - } -} - -/// A decimal reads a decimal scalar, keeping its scale, in range. -impl FromScalar for Decimal { - const EXPECTED: &'static str = "decimal"; - fn from_scalar(ty: Option, value: Physical<'_>) -> Option { - match (ty, value) { - (Some(Logical::Decimal { scale }), Physical::Int(mantissa)) => { - Decimal::new(mantissa.to_i128()?, scale).ok() - } - _ => None, - } - } -} - -/// Conversions to and from jiff's `civil::Date` and `Timestamp`. The -/// ranges are the same (vitaminc pins them to jiff's), so every jiff date -/// converts. A jiff `Timestamp` converts unless it is the instant jiff -/// 1.0.0 can make up to a second before its own minimum, when it parses -/// text with a UTC offset; that one is refused. The jiff value is outside -/// this crate's care: it is not wiped. -#[cfg(feature = "jiff")] -mod jiff_conversions { - use super::{Date, RangeError, Timestamp}; - use jiff::civil::Date as CivilDate; - use vitaminc_aead::plaintext::kinds::jiff as conv; - use vitaminc_aead::{Int, TimeUnit}; - - impl From for Date { - /// Every jiff date is in range: jiff's range is the one a `Date` - /// checks. - fn from(date: CivilDate) -> Self { - Date { - days: conv::date_days(date), - } - } - } - - impl From<&Date> for CivilDate { - #[allow( - clippy::expect_used, - reason = "a Date is only built in jiff's civil::Date range (from_days_since_epoch checks it, and From starts inside it), and jiff has no unchecked constructor" - )] - fn from(date: &Date) -> Self { - // A `Date` is only built in jiff's range, so the conversion - // always succeeds. If the two ranges ever drifted apart, this - // fails loudly rather than returning a wrong date. - conv::date(Int::I32(date.days)).expect("a Date is built in jiff's civil::Date range") - } - } - - impl TryFrom for Timestamp { - type Error = RangeError; - - /// # Errors - /// - /// [`RangeError::Timestamp`] for an instant before jiff's own - /// `Timestamp::MIN`. jiff 1.0.0 (jiff-core 1.0.0) can make one when - /// it parses text with a UTC offset. jiff 1.0.1 refuses that text. - fn try_from(instant: jiff::Timestamp) -> Result { - let nanos = conv::timestamp_nanos(instant).ok_or(RangeError::Timestamp)?; - Timestamp::from_nanos(nanos).ok_or(RangeError::Timestamp) - } - } - - impl From<&Timestamp> for jiff::Timestamp { - #[allow( - clippy::expect_used, - reason = "a Timestamp is only built in jiff's Timestamp range (Timestamp::new checks it), and jiff has no unchecked constructor" - )] - fn from(instant: &Timestamp) -> Self { - // A `Timestamp` is only built in jiff's range. If the two - // ranges ever drifted apart, this fails loudly rather than - // returning a wrong instant. - conv::timestamp(TimeUnit::Nanos, Int::I128(instant.count())) - .expect("a Timestamp is built in jiff's Timestamp range") - } - } -} - -/// Conversions to and from rust_decimal's `Decimal`, whose range (scale at -/// most 28, a 96-bit mantissa) is the one a [`Decimal`] checks, so neither -/// direction can fail. A rust_decimal negative zero converts to zero at its -/// scale. The rust_decimal value is outside this crate's care: it is not -/// wiped. #[cfg(feature = "rust_decimal")] -mod rust_decimal_conversions { - use super::Decimal; - use vitaminc_aead::plaintext::kinds::decimal as conv; - use vitaminc_aead::Int; - - impl From for Decimal { - fn from(decimal: rust_decimal::Decimal) -> Self { - let (scale, mantissa) = conv::parts(decimal); - Decimal { mantissa, scale } - } - } - - impl From<&Decimal> for rust_decimal::Decimal { - #[allow( - clippy::expect_used, - reason = "a Decimal is only built in rust_decimal's range (Decimal::new checks the scale and mantissa, and From starts inside it)" - )] - fn from(decimal: &Decimal) -> Self { - // A `Decimal` is only built in rust_decimal's range. If the two - // ranges ever drifted apart, this fails loudly rather than - // returning a wrong number. - conv::decimal(decimal.scale, Int::I128(decimal.mantissa)) - .expect("a Decimal is built in rust_decimal's range") - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::Decrypt; - use vitaminc_aead::plaintext::kinds::{ - MAX_DATE_DAYS, MAX_TIMESTAMP_NANOS, MIN_DATE_DAYS, MIN_TIMESTAMP_NANOS, - }; - - /// The scalar a value describes itself as. - struct Scalar; - impl Sink for Scalar { - type Ok = (Option, Option); - type Error = vitaminc_aead::DecodeError; - type Seq = vitaminc_aead::typed::Never; - type Map = vitaminc_aead::typed::Never; - fn scalar(self, ty: Option, v: Physical<'_>) -> Result { - Ok(( - ty, - match v { - Physical::Int(i) => i.to_i128(), - _ => None, - }, - )) - } - fn typed_null(self, ty: vitaminc_aead::FixedType) -> Result { - Ok((ty.logical(), None)) - } - fn seq(self, _: Option) -> Result { - unreachable!("a plaintext here is a scalar") - } - fn map(self, _: Option) -> Result { - unreachable!("a plaintext here is a scalar") - } - fn passthrough( - self, - _: &P, - ) -> Result { - unreachable!("a plaintext here is a scalar") - } - } - - fn scalar(value: impl Encrypt) -> (Option, Option) { - value.visit(Scalar).unwrap() - } - - /// What the type's own decrypt sink builds from one scalar: the path - /// an opened leaf takes. - fn read(ty: Logical, int: Int) -> Option { - T::sink().scalar(Some(ty), Physical::Int(int)).ok() - } - - #[test] - fn a_date_is_its_day_count_and_refuses_one_outside_the_range() { - for days in [0, -1, 19_782, MIN_DATE_DAYS, MAX_DATE_DAYS] { - let date = Date::from_days_since_epoch(days).unwrap(); - assert_eq!(date.days_since_epoch(), days); - assert_eq!(scalar(&date), (Some(Logical::Date), Some(days.into()))); - let back: Date = read(Logical::Date, Int::I32(days)).unwrap(); - assert_eq!(back.days_since_epoch(), days); - } - for days in [MIN_DATE_DAYS - 1, MAX_DATE_DAYS + 1, i32::MIN, i32::MAX] { - assert_eq!( - Date::from_days_since_epoch(days).unwrap_err(), - RangeError::Date - ); - assert!(read::(Logical::Date, Int::I32(days)).is_none()); - } - // Another width reads too; another logical type does not. - let wide: Date = read(Logical::Date, Int::I64(-3)).unwrap(); - assert_eq!(wide.days_since_epoch(), -3); - assert!(read::(Logical::Date, Int::I64(i64::MAX)).is_none()); - assert!(read::(Logical::Timestamp(TimeUnit::Nanos), Int::I32(0)).is_none()); - assert!(::from_scalar(None, Physical::Int(Int::I32(0))).is_none()); - } - - #[test] - fn a_timestamp_is_its_nanosecond_count_and_refuses_a_whole_second_of_nanoseconds() { - for (seconds, nanos) in [ - (0, 0), - (1_700_000_000, 123_456_789), - (-1, 999_999_999), - (-1, 500_000_000), - ] { - let instant = Timestamp::new(seconds, nanos).unwrap(); - assert_eq!((instant.seconds(), instant.nanoseconds()), (seconds, nanos)); - let count = i128::from(seconds) * 1_000_000_000 + i128::from(nanos); - assert_eq!( - scalar(&instant), - (Some(Logical::Timestamp(TimeUnit::Nanos)), Some(count)) - ); - let back: Timestamp = - read(Logical::Timestamp(TimeUnit::Nanos), Int::I128(count)).unwrap(); - assert_eq!((back.seconds(), back.nanoseconds()), (seconds, nanos)); - } - // Any unit reads: a millisecond count is a JavaScript `Date`'s. - let millis: Timestamp = - read(Logical::Timestamp(TimeUnit::Millis), Int::I64(-1_500)).unwrap(); - assert_eq!((millis.seconds(), millis.nanoseconds()), (-2, 500_000_000)); - - assert_eq!( - Timestamp::new(0, 1_000_000_000).unwrap_err(), - RangeError::Nanoseconds - ); - assert_eq!( - Timestamp::new(0, u32::MAX).unwrap_err(), - RangeError::Nanoseconds - ); - // The range's two edges, and one nanosecond past each. - let edge = |nanos: i128| { - let n = i128::from(NANOS_PER_SECOND); - Timestamp::new( - i64::try_from(nanos.div_euclid(n)).unwrap(), - u32::try_from(nanos.rem_euclid(n)).unwrap(), - ) - }; - assert!(edge(MIN_TIMESTAMP_NANOS).is_ok()); - assert!(edge(MAX_TIMESTAMP_NANOS).is_ok()); - assert_eq!( - edge(MIN_TIMESTAMP_NANOS - 1).unwrap_err(), - RangeError::Timestamp - ); - assert_eq!( - edge(MAX_TIMESTAMP_NANOS + 1).unwrap_err(), - RangeError::Timestamp - ); - for seconds in [i64::MIN, i64::MAX] { - assert_eq!( - Timestamp::new(seconds, 0).unwrap_err(), - RangeError::Timestamp - ); - } - assert!(read::( - Logical::Timestamp(TimeUnit::Nanos), - Int::I128(MAX_TIMESTAMP_NANOS + 1) - ) - .is_none()); - assert!(read::(Logical::Date, Int::I128(0)).is_none()); - } - - #[test] - fn a_decimal_keeps_its_scale_and_refuses_what_rust_decimal_cannot_hold() { - let limit = 1i128 << 96; - for (mantissa, scale) in [(150, 2), (-1, 0), (0, 28), (limit - 1, 28), (1 - limit, 0)] { - let decimal = Decimal::new(mantissa, scale).unwrap(); - assert_eq!((decimal.mantissa(), decimal.scale()), (mantissa, scale)); - assert_eq!( - scalar(&decimal), - (Some(Logical::Decimal { scale }), Some(mantissa)) - ); - let back: Decimal = read(Logical::Decimal { scale }, Int::I128(mantissa)).unwrap(); - assert_eq!((back.mantissa(), back.scale()), (mantissa, scale)); - } - assert_eq!(Decimal::new(1, 29).unwrap_err(), RangeError::DecimalScale); - assert_eq!( - Decimal::new(1, u8::MAX).unwrap_err(), - RangeError::DecimalScale - ); - for mantissa in [limit, -limit, i128::MAX, i128::MIN] { - assert_eq!( - Decimal::new(mantissa, 0).unwrap_err(), - RangeError::DecimalMantissa - ); - assert!(read::(Logical::Decimal { scale: 0 }, Int::I128(mantissa)).is_none()); - } - assert!(read::(Logical::Date, Int::I128(1)).is_none()); - } - - #[test] - fn an_owned_value_seals_the_scalar_its_borrow_does() { - let date = Date::from_days_since_epoch(5).unwrap(); - assert_eq!(scalar(date.clone()), scalar(&date)); - let instant = Timestamp::new(5, 6).unwrap(); - assert_eq!(scalar(instant.clone()), scalar(&instant)); - let decimal = Decimal::new(5, 6).unwrap(); - assert_eq!(scalar(decimal.clone()), scalar(&decimal)); - } - - #[test] - fn zeroize_clears_every_field() { - let mut date = Date::from_days_since_epoch(-42).unwrap(); - date.zeroize(); - assert_eq!(date.days_since_epoch(), 0); - let mut instant = Timestamp::new(-7, 999).unwrap(); - instant.zeroize(); - assert_eq!((instant.seconds(), instant.nanoseconds()), (0, 0)); - let mut decimal = Decimal::new(-123, 4).unwrap(); - decimal.zeroize(); - assert_eq!((decimal.mantissa(), decimal.scale()), (0, 0)); - } - - /// Dropping wipes the value where it lies. Read through a - /// `ManuallyDrop` so the memory is still the test's after the drop - /// glue has run: `drop_in_place` runs `Drop` without freeing. The one - /// `unsafe` in this crate, in a test: nothing else observes memory - /// after a drop, and without it a `Drop` that wiped nothing would pass. - #[test] - #[allow(unsafe_code)] - fn dropping_wipes_the_value_in_place() { - use std::mem::ManuallyDrop; - let mut date = ManuallyDrop::new(Date::from_days_since_epoch(-42).unwrap()); - let mut instant = ManuallyDrop::new(Timestamp::new(-7, 999).unwrap()); - let mut decimal = ManuallyDrop::new(Decimal::new(-123, 4).unwrap()); - // SAFETY: each value is dropped once and only its integers, which - // need no drop of their own, are read afterwards. - unsafe { - ManuallyDrop::drop(&mut date); - ManuallyDrop::drop(&mut instant); - ManuallyDrop::drop(&mut decimal); - } - assert_eq!(date.days, 0); - assert_eq!((instant.seconds, instant.nanos), (0, 0)); - assert_eq!((decimal.mantissa, decimal.scale), (0, 0)); - } - - #[test] - fn debug_and_errors_never_show_the_value() { - let date = Date::from_days_since_epoch(19_782).unwrap(); - let instant = Timestamp::new(1_700_000_000, 0).unwrap(); - let decimal = Decimal::new(123_450, 2).unwrap(); - for shown in [ - format!("{date:?}"), - format!("{instant:?}"), - format!("{decimal:?}"), - ] { - assert!(shown.ends_with("()"), "{shown}"); - assert!(!shown.chars().any(|c| c.is_ascii_digit()), "{shown}"); - } - for error in [ - Date::from_days_since_epoch(i32::MAX).unwrap_err(), - Timestamp::new(i64::MAX, 0).unwrap_err(), - Timestamp::new(0, 1_234_567_890).unwrap_err(), - Decimal::new(i128::MAX, 0).unwrap_err(), - Decimal::new(1, 200).unwrap_err(), - ] { - let message = error.to_string(); - for value in ["2147483647", "9223372036854775807", "1234567890", "200"] { - assert!(!message.contains(value), "{message}"); - } - } - } - - #[cfg(feature = "jiff")] - #[test] - fn jiff_values_convert_both_ways() { - use jiff::civil::{date, Date as CivilDate}; - - for day in [ - date(2024, 2, 29), - date(1969, 12, 31), - date(1, 1, 1), - CivilDate::MIN, - CivilDate::MAX, - ] { - let ours = Date::from(day); - assert_eq!(CivilDate::from(&ours), day); - // The same scalar jiff's own source describes. - assert_eq!(scalar(&ours), scalar(day)); - } - assert_eq!(Date::from(date(1970, 1, 1)).days_since_epoch(), 0); - // The ends of the range a `Date` checks are jiff's ends: if the - // two drift apart, the `expect` in the conversion fires here. - for (days, day) in [ - (MIN_DATE_DAYS, CivilDate::MIN), - (MAX_DATE_DAYS, CivilDate::MAX), - ] { - let ours = Date::from_days_since_epoch(days).unwrap(); - assert_eq!(CivilDate::from(&ours), day); - } - - for instant in [ - jiff::Timestamp::new(1_700_000_000, 123_456_789).unwrap(), - jiff::Timestamp::new(-1, 1).unwrap(), - jiff::Timestamp::MIN, - jiff::Timestamp::MAX, - ] { - let ours = Timestamp::try_from(instant).unwrap(); - assert_eq!(jiff::Timestamp::from(&ours), instant); - assert_eq!(scalar(&ours), scalar(instant)); - } - // The same for a `Timestamp`'s range. - for (nanos, instant) in [ - (MIN_TIMESTAMP_NANOS, jiff::Timestamp::MIN), - (MAX_TIMESTAMP_NANOS, jiff::Timestamp::MAX), - ] { - let ours = - read::(Logical::Timestamp(TimeUnit::Nanos), Int::I128(nanos)).unwrap(); - assert_eq!(jiff::Timestamp::from(&ours), instant); - } - } - - #[cfg(feature = "rust_decimal")] - #[test] - fn rust_decimal_values_convert_both_ways() { - use std::str::FromStr; - - for text in [ - "1.50", - "-1234.5678", - "0", - "79228162514264337593543950335", - "-0.0000000000000000000000000001", - ] { - let theirs = rust_decimal::Decimal::from_str(text).unwrap(); - let ours = Decimal::from(theirs); - let back = rust_decimal::Decimal::from(&ours); - assert_eq!(back.to_string(), theirs.to_string(), "{text}"); - assert_eq!(scalar(&ours), scalar(theirs), "{text}"); - } - // The ends of rust_decimal's range, at the smallest and the largest - // scale: if the ranges drift apart, the `expect` in the conversion - // fires here. - let limit = 79_228_162_514_264_337_593_543_950_335_i128; - for theirs in [rust_decimal::Decimal::MIN, rust_decimal::Decimal::MAX] { - let ours = Decimal::from(theirs); - assert_eq!(rust_decimal::Decimal::from(&ours), theirs); - } - for mantissa in [limit, -limit] { - let ours = Decimal::new(mantissa, MAX_DECIMAL_SCALE).unwrap(); - let back = rust_decimal::Decimal::from(&ours); - assert_eq!((back.mantissa(), back.scale()), (mantissa, 28)); - } - let ours = Decimal::from(rust_decimal::Decimal::from_str("1.50").unwrap()); - assert_eq!((ours.mantissa(), ours.scale()), (150, 2)); - // A negative zero is zero, at its scale. - let mut negative_zero = rust_decimal::Decimal::new(0, 2); - negative_zero.set_sign_negative(true); - let ours = Decimal::from(negative_zero); - assert_eq!((ours.mantissa(), ours.scale()), (0, 2)); - assert_eq!(rust_decimal::Decimal::from(&ours).to_string(), "0.00"); - } -} +pub use vitaminc_aead::Decimal; diff --git a/packages/stack-encrypt/tests/combinators.rs b/packages/stack-encrypt/tests/combinators.rs index bf182c6090..8cfc517581 100644 --- a/packages/stack-encrypt/tests/combinators.rs +++ b/packages/stack-encrypt/tests/combinators.rs @@ -605,7 +605,16 @@ async fn one_tree_under_a_label_is_the_ciphertext_combinator_under_it() { /// descriptors, the same terms, and each opens through the other's reader. async fn same_field_bytes(value: F, indexes: X) where - F: Encrypt + Decrypt + Clone + Zeroize + Send + Sync + PartialEq + Debug + 'static, + F: Encrypt + + stack_encrypt::EncryptRef + + Decrypt + + Clone + + Zeroize + + Send + + Sync + + PartialEq + + Debug + + 'static, Terms: TermSet + PartialEq + Debug + Send, X: Indexes + Send + Sync + 'static, { diff --git a/packages/stack-encrypt/tests/conformance.rs b/packages/stack-encrypt/tests/conformance.rs index 1cfbddf736..9d59011935 100644 --- a/packages/stack-encrypt/tests/conformance.rs +++ b/packages/stack-encrypt/tests/conformance.rs @@ -237,8 +237,8 @@ async fn shared_record_scalar_profile() { } assert_eq!(case.kind, case.input.kind); let input = value(&case.input); - let expected_row = object(vec![(corpus.field.clone(), input.clone())]); - let fresh = record::encrypt(&keyset, expected_row.clone(), &plan) + let expected_row = object(vec![(corpus.field.clone(), value(&case.input))]); + let fresh = record::encrypt(&keyset, &expected_row, &plan) .unwrap() .await .unwrap(); @@ -259,7 +259,7 @@ async fn shared_record_scalar_profile() { &plan, &corpus.field, Op::Eq, - input.clone(), + value(&case.input), &NoTargets, ) .unwrap() diff --git a/packages/stack-encrypt/tests/context_conformance.rs b/packages/stack-encrypt/tests/context_conformance.rs index a98e46742d..51779d8300 100644 --- a/packages/stack-encrypt/tests/context_conformance.rs +++ b/packages/stack-encrypt/tests/context_conformance.rs @@ -301,7 +301,10 @@ async fn shared_context_composition() { object(vec![( "text", object(vec![ - ("context", context_frame.clone()), + ( + "context", + ValueFrame::from_bytes(context_frame.as_protected_ref()).unwrap(), + ), ("outputs", frame(vec!["c", "eq"])), ("type", frame("string")), ]), @@ -501,7 +504,7 @@ async fn shared_context_boundaries() { }) .collect::>(), ); - let mut stored = record::encrypt(&keyset, rows.clone(), &plan) + let mut stored = record::encrypt(&keyset, &rows, &plan) .unwrap() .await .unwrap(); diff --git a/packages/stack-encrypt/tests/derive.rs b/packages/stack-encrypt/tests/derive.rs index 4f91227c61..70f1e17155 100644 --- a/packages/stack-encrypt/tests/derive.rs +++ b/packages/stack-encrypt/tests/derive.rs @@ -13,12 +13,12 @@ mod common; use std::sync::atomic::Ordering as AtomicOrdering; use common::{counting_cipher, recording_cipher, stack_cipher}; -use stack_encrypt::sem::Orderable; use stack_encrypt::sem::{EqualityTerm, MatchConfig, MatchOptions, MatchTerms, OreTerm, TermError}; use stack_encrypt::target::{ AeadContext, CallerContext, DecryptSource, EncryptTarget, Encrypted, Encryption, RequiredContext, Scope, }; +use stack_encrypt::Orderable; use stack_encrypt::{ nonempty, ContextPiece, DecryptField, DecryptFrom, Decryptable, EncryptInto, Error, IntoContext, Label, MaybeEmpty, NonEmpty, StackCipherText, diff --git a/packages/stack-encrypt/tests/heap_hygiene.rs b/packages/stack-encrypt/tests/heap_hygiene.rs index 011ab80aea..ba277d425e 100644 --- a/packages/stack-encrypt/tests/heap_hygiene.rs +++ b/packages/stack-encrypt/tests/heap_hygiene.rs @@ -947,16 +947,6 @@ fn an_order_term_of_owned_text_or_bytes_leaves_no_plaintext_on_the_heap() { rt.block_on(async { keyset.ope_term(text, nonempty!("users/surname")).await }) .unwrap(); }); - let bytes = marked("order").into_bytes(); - watched("ore_term (Vec)", || { - rt.block_on(async { keyset.ore_term(bytes, nonempty!("users/blob")).await }) - .unwrap(); - }); - let bytes = marked("order").into_bytes(); - watched("ope_term (Vec)", || { - rt.block_on(async { keyset.ope_term(bytes, nonempty!("users/blob")).await }) - .unwrap(); - }); } #[test] @@ -1954,9 +1944,9 @@ mod json_plaintext { assert_eq!(generates.load(Ordering::SeqCst), 0, "no key is requested"); } - /// The owned form of a document field does not copy the document: it - /// makes one block fewer of the length of the document's one long - /// string than the borrowed form, which copies the document once. + /// Neither form of a document field copies the document: the owned + /// form and the borrowed form make the same number of blocks of the + /// length of the document's one long string. #[test] fn a_json_plaintext_sealed_into_a_document_field_is_not_copied() { use stack_encrypt::json::{JsonDocument, JsonOptions, JsonTarget}; @@ -1991,10 +1981,8 @@ mod json_plaintext { rt.block_on(async { keyset.run(description, source, context()).await.unwrap() }); }); assert_eq!( - borrowed, - owned + 1, - "the borrowed form copies the document once and the owned form does not \ - (borrowed {borrowed}, owned {owned})" + borrowed, owned, + "neither form copies the document (borrowed {borrowed}, owned {owned})" ); } diff --git a/packages/stack-encrypt/tests/index.rs b/packages/stack-encrypt/tests/index.rs index 0f3c63e84a..9856ca0122 100644 --- a/packages/stack-encrypt/tests/index.rs +++ b/packages/stack-encrypt/tests/index.rs @@ -635,6 +635,7 @@ mod given_encrypted_terms_as_a_target { async fn same_bytes(value: S, indexes: X) where S: stack_encrypt::Encrypt + + stack_encrypt::EncryptRef + stack_encrypt::Decrypt + zeroize::Zeroize + Send @@ -756,7 +757,7 @@ mod given_encrypted_terms_as_a_target { /// A boolean has no equality term, on the typed path as on the dynamic one /// (`dynamic::admits`): refused when the term is derived, before any key /// is minted. (It has no order term either, which is a compile error: -/// `bool` is not `sem::Orderable`, so `OreTerm`, `OpeTerm` and +/// `bool` is not `Orderable`, so `OreTerm`, `OpeTerm` and /// `indexed::(Ore)` do not build.) #[tokio::test] async fn a_boolean_has_no_equality_term() { diff --git a/packages/stack-encrypt/tests/op.rs b/packages/stack-encrypt/tests/op.rs index 4b6f09caad..83e1e6a00e 100644 --- a/packages/stack-encrypt/tests/op.rs +++ b/packages/stack-encrypt/tests/op.rs @@ -23,8 +23,8 @@ use stack_encrypt::sem::{ TermError, Tokenizer, }; use stack_encrypt::target::{ - CallerContext, ConsumeSource, DecryptSource, EncryptTarget, Encryption, Index, IndexSpec, - NoScope, Scope, + CallerContext, DecryptSource, EncryptTarget, Encryption, Index, IndexSpec, NoScope, Scope, + WipeSource, }; use stack_encrypt::{ nonempty, DecryptFrom, EncryptInto, Encrypted, Equality, Error, FieldReference, Label, @@ -460,7 +460,7 @@ impl Index for Labelled { fn spec(&self) -> IndexSpec { Index::::spec(&Equality) } - fn operation<'s, K: 'static, M: ConsumeSource<'s, String>>( + fn operation<'s, K: 'static, M: WipeSource<'s, String>>( &self, ) -> Encryption<'s, String, EqualityTerm, K, CallerContext, M> { Index::::operation(&Equality) @@ -515,7 +515,7 @@ impl Index for Unextendable { fn spec(&self) -> IndexSpec { Index::::spec(&Equality) } - fn operation<'s, K: 'static, M: ConsumeSource<'s, String>>( + fn operation<'s, K: 'static, M: WipeSource<'s, String>>( &self, ) -> Encryption<'s, String, EqualityTerm, K, CallerContext, M> { Index::::operation(&Equality) diff --git a/packages/stack-encrypt/tests/ore_block.rs b/packages/stack-encrypt/tests/ore_block.rs index 1b894daa2f..094c05a706 100644 --- a/packages/stack-encrypt/tests/ore_block.rs +++ b/packages/stack-encrypt/tests/ore_block.rs @@ -14,8 +14,10 @@ use std::cmp::Ordering; -use stack_encrypt::sem::{Orderable, OreBlockTerm, TermBytesError, TermError}; +use stack_encrypt::sem::{OreBlockTerm, TermBytesError, TermError}; +#[cfg(all(feature = "jiff", feature = "rust_decimal"))] use stack_encrypt::value::{Date, Decimal, Timestamp}; +use stack_encrypt::Orderable; use stack_encrypt::{nonempty, Error, KeysetCipher, StackCipher}; use stack_kms::FakeDataKeySource; @@ -31,7 +33,7 @@ fn hex(bytes: &[u8]) -> String { bytes.iter().map(|b| format!("{b:02x}")).collect() } -async fn term( +async fn term( keyset: &KeysetCipher<'_, FakeDataKeySource>, value: T, ) -> OreBlockTerm { @@ -125,17 +127,20 @@ async fn wide_integers_are_the_chained_scheme_unpadded() { /// scheme, unpadded. Each orders by value: a timestamp by the microsecond, /// floored, so a nanosecond before the epoch is a microsecond before it, /// and a decimal whatever its scale. +#[cfg(all(feature = "jiff", feature = "rust_decimal"))] #[tokio::test] async fn dates_timestamps_and_decimals_order_by_value() { let cipher = cipher().await; let keyset = cipher.default_keyset(); let mut dates = Vec::new(); - for days in [-719_162, -1, 0, 1, 19_782] { - let term = term( - &keyset, - Date::from_days_since_epoch(days).expect("in range"), - ) - .await; + for (year, month, day) in [ + (1, 1, 1), + (1969, 12, 31), + (1970, 1, 1), + (1970, 1, 2), + (2024, 2, 29), + ] { + let term = term(&keyset, Date::new(jiff::civil::date(year, month, day))).await; assert_eq!( &term.as_bytes()[..2], &[0x02, 0x02], @@ -146,7 +151,10 @@ async fn dates_timestamps_and_decimals_order_by_value() { } assert_sorted(&dates, "date"); - let instant = |seconds, nanos| Timestamp::new(seconds, nanos).expect("in range"); + let instant = |seconds, nanos| { + let instant = jiff::Timestamp::new(seconds, nanos).expect("in range"); + Timestamp::new(instant).expect("in range") + }; let mut instants = Vec::new(); for (seconds, nanos) in [(-1, 999_999_000), (0, 0), (0, 1_000), (1_700_000_000, 0)] { let term = term(&keyset, instant(seconds, nanos)).await; @@ -175,7 +183,7 @@ async fn dates_timestamps_and_decimals_order_by_value() { "a nanosecond before the epoch floors to the microsecond before it" ); - let decimal = |mantissa, scale| Decimal::new(mantissa, scale).expect("in range"); + let decimal = |mantissa, scale| Decimal::new(rust_decimal::Decimal::new(mantissa, scale)); let mut decimals = Vec::new(); for (mantissa, scale) in [(-1, 0), (15, 1), (2, 0), (100, 0)] { let term = term(&keyset, decimal(mantissa, scale)).await; @@ -299,44 +307,6 @@ async fn text_orders_by_its_fold_shortest_first() { } } -/// Bytes are the chained scheme unpadded, ordered as bytes: a trailing zero -/// byte is kept, and the empty value still makes a keyed block. -#[tokio::test] -async fn bytes_order_as_bytes() { - let cipher = cipher().await; - let keyset = cipher.default_keyset(); - let ordered: Vec> = vec![vec![], vec![0], vec![0, 0], vec![1], vec![1, 0], vec![255]]; - let mut terms = Vec::new(); - for value in ordered { - let term = term(&keyset, value).await; - assert_eq!(&term.as_bytes()[4..7], &[0, 0, 0], "bytes are not padded"); - assert!( - blocks(term.as_bytes()) >= 2, - "the marker byte is two blocks" - ); - terms.push(term); - } - assert_sorted(&terms, "bytes"); -} - -/// Bytes take a term up to 1023 bytes, as text's fold does: ore-rs's -/// 1024-byte ceiling counts the marker byte in front of them. -#[tokio::test] -async fn bytes_of_more_than_1023_bytes_have_no_term() { - let cipher = cipher().await; - let keyset = cipher.default_keyset(); - let longest = term(&keyset, vec![7u8; 1023]).await; - assert!(blocks(longest.as_bytes()) > 1023, "every byte is ordered"); - let too_long = keyset - .ore_block_term(vec![7u8; 1024], nonempty!("users/n")) - .await - .unwrap_err(); - assert!( - matches!(too_long, Error::Term(TermError::OreBlockTooLong)), - "{too_long:?}" - ); -} - /// One value encrypts to different bytes each time (the right half's /// nonce), and those terms compare equal; the left half is deterministic. #[tokio::test] @@ -486,7 +456,7 @@ async fn refusals_name_no_part_of_the_value() { ); // A boolean and an 8-bit integer have no block ORE term, as they have // no ORE or OPE term: `ore_block_term(true, ..)` and - // `ore_block_term(7u8, ..)` do not compile (`sem::Orderable`). + // `ore_block_term(7u8, ..)` do not compile (`Orderable`). } /// Decoding is structural: a ciphertext of either scheme decodes, and @@ -523,3 +493,21 @@ async fn decoding_checks_the_shape() { assert_eq!(a.compare(&b), None); assert!(a != b); } + +/// A reference to a local value takes a term too, read in place, and it +/// orders equal to the term of the value itself. +#[tokio::test] +async fn a_borrowed_value_takes_the_term_its_value_takes() { + let cipher = cipher().await; + let keyset = cipher.default_keyset(); + let local = String::from("ada"); + let borrowed = keyset + .ore_block_term(&local, nonempty!("users/n")) + .await + .unwrap(); + let owned = term(&keyset, String::from("ada")).await; + // The term of a `&String` is an `OreBlockTerm<&String>`; read its bytes + // back as a `String`'s to compare them. + let borrowed = OreBlockTerm::::try_from(borrowed.into_bytes()).unwrap(); + assert_eq!(borrowed.compare(&owned), Some(Ordering::Equal)); +} diff --git a/packages/stack-encrypt/tests/owned_records.rs b/packages/stack-encrypt/tests/owned_records.rs index 945a17fbde..f04ffd5d41 100644 --- a/packages/stack-encrypt/tests/owned_records.rs +++ b/packages/stack-encrypt/tests/owned_records.rs @@ -298,21 +298,13 @@ async fn the_owned_record_wipes_sealed_fields_when_the_context_is_refused() { // --- A refused context drops no copy of a sealed plaintext unwiped --------- -/// A sealed plaintext that the borrowed form of a `StackCipherText` leaf would -/// clone. Its `Drop` records whether it still held its value. So a copy that -/// is dropped without being wiped is seen, whichever copy it is. +/// A sealed plaintext that is not `Clone`. Its `Drop` records whether it +/// still held its value, so a value that is dropped without being wiped is +/// seen. struct Probe { value: String, leaked: Arc, } -impl Clone for Probe { - fn clone(&self) -> Self { - Probe { - value: self.value.clone(), - leaked: self.leaked.clone(), - } - } -} impl Zeroize for Probe { fn zeroize(&mut self) { self.value.zeroize(); @@ -330,6 +322,11 @@ impl stack_encrypt::Encrypt for Probe { std::mem::take(&mut self.value).visit(sink) } } +impl stack_encrypt::Encrypt for &Probe { + fn visit(self, sink: S) -> Result { + (&self.value).visit(sink) + } +} fn probe(leaked: &Arc) -> Probe { Probe { value: "secret".to_owned(), diff --git a/packages/stack-encrypt/tests/record_lowering.rs b/packages/stack-encrypt/tests/record_lowering.rs index c9160ba2d9..6344356239 100644 --- a/packages/stack-encrypt/tests/record_lowering.rs +++ b/packages/stack-encrypt/tests/record_lowering.rs @@ -48,7 +48,7 @@ use stack_encrypt::plan::IntoLabel; use stack_encrypt::sem::MatchOptions; use stack_encrypt::target::{ ciphertext, indexed, open, passthrough as carried, Borrowed, DeclaredContext, Encrypted, - Encryption, IndexSpec, + Encryption, IndexSpec, Owned, }; use stack_encrypt::{ nonempty, CipherText, Error, Label, NonEmpty, SealedValue, StackCipher, StackCipherText, @@ -639,17 +639,25 @@ fn text_label(tenant: &ValueFrame) -> Label { /// The declaration as the combinators write it for one note: the tenant /// is carried as it is, and `text` runs under the label read from it. The /// label is in the record, so the description is composed for each record. +/// +/// The description is handed the note itself. A frame is not `Clone`, so the +/// tenant is moved into the output, as a data plan moves a passthrough field. fn note_declaration<'s>( note: &Note, -) -> Encryption<'s, Note, TypedNote, DeterministicSource, DeclaredContext> { - carried::() - .project(|n: &Note| &n.tenant) - .zip( - indexed::(IndexSpec::Equality) +) -> Encryption<'s, Note, TypedNote, DeterministicSource, DeclaredContext, Owned> { + carried::() + .split( + indexed::(IndexSpec::Equality) .under(NonEmpty::from(text_label(¬e.tenant))) - .project(|n: &Note| &n.text), + .split( + carried::(), + |parts: (ValueFrame, u32)| parts, + |_| {}, + ), + |n: Note| (n.tenant, (n.text, n.id)), + |_| {}, ) - .zip(carried::().project(|n: &Note| &n.id)) + .map(|(tenant, (text, id))| ((tenant, text), id)) } /// The same declaration as a binding sends it: the plan-level @@ -701,7 +709,7 @@ async fn seal_note_typed(cipher: &StackCipher) -> StackCiph record_of_note( cipher .default_keyset() - .run(note_declaration(¬e), ¬e, DeclaredContext::default()) + .run(note_declaration(¬e), note, DeclaredContext::default()) .await .expect("the combinators seal the note"), ) diff --git a/packages/stack-encrypt/tests/source_mode.rs b/packages/stack-encrypt/tests/source_mode.rs index ce9c6c6205..63fb083264 100644 --- a/packages/stack-encrypt/tests/source_mode.rs +++ b/packages/stack-encrypt/tests/source_mode.rs @@ -1,25 +1,24 @@ //! How a description receives its plaintext (`target::{Borrowed, Owned}`). //! -//! Vitamin C's by-value `Encrypt` walk and `PrfValue` consume their input. A description -//! handed a borrow (the default, and what every `EncryptTarget::encryption` -//! declaration runs in) clones before an operation consumes; one handed the -//! value (`Owned`) gives it to the operation. These tests hold the two claims -//! that make owned mode worth having: +//! Every operation reads its plaintext in place, so no mode copies it. A +//! description handed a borrow (the default, and what every +//! `EncryptTarget::encryption` declaration runs in) leaves the value with the +//! caller. One handed the value (`Owned`) reads it and lets go of it. These +//! tests hold the claims that follow: //! -//! - a plaintext that is **not `Clone`** runs a single operation — a -//! ciphertext alone, or one term alone — and the output is the same as the -//! borrowed path's; -//! - the number of copies is exactly what the mode promises: none for one -//! owned operation, `n - 1` for an owned `zip` of `n`, one per consuming -//! operation when borrowed, and none ever for a match term, which only -//! reads its text. +//! - a plaintext that is **not `Clone`** runs one operation, or several over +//! the same value, and the output is the same as the borrowed path's; +//! - no operation copies the plaintext, in either mode, alone or beside +//! others; +//! - an owned plaintext is let go before its key request is sent. use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Arc; -use stack_encrypt::sem::{EqualityTerm, MatchTerms}; +use stack_encrypt::sem::{DefaultMatch, EqualityTerm, MatchTerms}; use stack_encrypt::target::{ - ciphertext, equality, matching, AeadContext, Borrowed, CallerContext, Encryption, Owned, + ciphertext, equality, matching, AeadContext, Borrowed, CallerContext, Encrypted, Encryption, + Owned, }; use stack_encrypt::target::{EncryptTarget, RequiredContext, StoredContext}; use stack_encrypt::{ @@ -61,6 +60,11 @@ impl Encrypt for Secret { self.0.visit(sink) } } +impl Encrypt for &Secret { + fn visit(self, sink: S) -> Result { + (&self.0).visit(sink) + } +} impl PrfValue for Secret { fn prf_visit_with_context<'a, P, V, C>(self, prf: &P, context: C, visitor: V) -> P::Ok where @@ -71,6 +75,12 @@ impl PrfValue for Secret { self.0.prf_visit_with_context(prf, context, visitor) } } +/// Replacing the guard drops the old one, which wipes the text. +impl Zeroize for Secret { + fn zeroize(&mut self) { + self.0 = Protected::new(String::new()); + } +} impl AsRef for Secret { fn as_ref(&self) -> &str { self.0.risky_ref() @@ -108,6 +118,11 @@ impl Encrypt for Counted { self.text.visit(sink) } } +impl Encrypt for &Counted { + fn visit(self, sink: S) -> Result { + (&self.text).visit(sink) + } +} impl PrfValue for Counted { fn prf_visit_with_context<'a, P, V, C>(self, prf: &P, context: C, visitor: V) -> P::Ok where @@ -214,7 +229,7 @@ async fn a_value_frame_seals_by_value_through_ciphertext_alone() { ); } -// --- How many copies each mode makes ---------------------------------------- +// --- No mode copies the plaintext -------------------------------------------- #[tokio::test] async fn one_owned_operation_makes_no_copy() { @@ -240,14 +255,14 @@ async fn one_owned_operation_makes_no_copy() { fn sealed_and_indexed<'s, S, M>( ) -> Encryption<'s, S, (StackCipherText, EqualityTerm), FakeDataKeySource, CallerContext, M> where - S: Encrypt + PrfValue + 's, - M: stack_encrypt::target::ConsumeSource<'s, S> + stack_encrypt::target::ShareSource<'s, S>, + S: Encrypt + vitaminc_aead::EncryptRef + Zeroize + 's, + M: stack_encrypt::target::WipeSource<'s, S>, { ciphertext().accepting().zip(equality()) } #[tokio::test] -async fn an_owned_zip_copies_for_every_side_but_the_last() { +async fn an_owned_zip_makes_no_copy() { let cipher = stack_cipher().await; let keyset = cipher.default_keyset(); @@ -258,8 +273,8 @@ async fn an_owned_zip_copies_for_every_side_but_the_last() { .unwrap(); assert_eq!( clones.load(Ordering::SeqCst), - 1, - "two owned operations should share one copy: the last takes the value" + 0, + "the term reads the value in place, and the ciphertext takes it" ); // And what each side made is what it would have made alone. @@ -271,18 +286,42 @@ async fn an_owned_zip_copies_for_every_side_but_the_last() { assert_eq!(term, expected, "the zipped term is the text's term"); let (value, clones) = Counted::new(NUMBER); - let three = sealed_and_indexed::<_, Owned>().zip(equality::<_, _, Owned>()); + let three = sealed_and_indexed::<_, Owned>().zip(equality()); let (_, again) = keyset.run(three, value, caller()).await.unwrap(); assert_eq!( clones.load(Ordering::SeqCst), - 2, - "three owned operations should make two copies" + 0, + "three operations over one owned value should make no copy" ); assert_eq!(again, expected, "the third side's term is the text's term"); } +/// A plaintext that is not `Clone` runs a ciphertext and a term over the one +/// value. Before, an owned `zip` needed a copy for every side but the last. #[tokio::test] -async fn a_borrowed_operation_copies_once_for_each_operation_that_consumes() { +async fn a_plaintext_that_is_not_clone_seals_beside_a_term() { + let cipher = stack_cipher().await; + let keyset = cipher.default_keyset(); + + let (sealed, term) = keyset + .run( + sealed_and_indexed::<_, Owned>(), + Secret::new(NUMBER), + caller(), + ) + .await + .unwrap(); + + let opened: String = String::decrypt_from_with_context(sealed, &cipher, aead()) + .await + .unwrap(); + assert_eq!(opened, NUMBER, "the ciphertext opens to the text"); + let expected = keyset.equality_term(NUMBER, context()).await.unwrap(); + assert_eq!(term, expected, "the term is the text's term"); +} + +#[tokio::test] +async fn a_borrowed_operation_makes_no_copy() { let cipher = stack_cipher().await; let keyset = cipher.default_keyset(); @@ -291,7 +330,7 @@ async fn a_borrowed_operation_copies_once_for_each_operation_that_consumes() { .run(ciphertext::<_, _, Borrowed>(), &value, aead()) .await .unwrap(); - assert_eq!(clones.load(Ordering::SeqCst), 1, "a borrowed ciphertext"); + assert_eq!(clones.load(Ordering::SeqCst), 0, "a borrowed ciphertext"); let opened: String = String::decrypt_from_with_context(sealed, &cipher, aead()) .await .unwrap(); @@ -304,8 +343,8 @@ async fn a_borrowed_operation_copies_once_for_each_operation_that_consumes() { .unwrap(); assert_eq!( clones.load(Ordering::SeqCst), - 2, - "a borrowed ciphertext beside a borrowed term copies once for each" + 0, + "a borrowed ciphertext beside a borrowed term reads the one value" ); let expected = keyset.equality_term(NUMBER, context()).await.unwrap(); assert_eq!(term, expected, "the borrowed term is the text's term"); @@ -352,7 +391,8 @@ struct SealedWithContext { } /// A record with two fields derived from the plaintext: its owned form is the -/// default, which reads the value through the borrowed form. +/// default, which reads the value through the borrowed form. Both fields read +/// the value in place. #[derive(EncryptTarget)] #[stash(plaintext = Counted)] struct SealedAndEqual { @@ -384,8 +424,8 @@ async fn a_record_with_one_derived_field_moves_the_value_into_it() { .unwrap(); assert_eq!(opened, NUMBER, "the moved value is what is sealed"); - // The borrowed form, which a collection runs for each element, copies - // the value once to seal it. + // The borrowed form, which a collection runs for each element, reads + // the value in place. let (value, clones) = Counted::new(NUMBER); let _: SealedOnly = keyset .run( @@ -397,8 +437,8 @@ async fn a_record_with_one_derived_field_moves_the_value_into_it() { .unwrap(); assert_eq!( clones.load(Ordering::SeqCst), - 1, - "the borrowed form copies once" + 0, + "the borrowed form reads the value in place" ); // A record that stores its context moves the value too. @@ -429,13 +469,13 @@ async fn a_record_with_one_derived_field_moves_the_value_into_it() { .unwrap(); assert_eq!( clones.load(Ordering::SeqCst), - 1, - "the borrowed form copies once" + 0, + "the borrowed form reads the value in place" ); } #[tokio::test] -async fn a_record_with_two_derived_fields_copies_the_value_for_each() { +async fn a_record_with_two_derived_fields_copies_nothing() { let cipher = stack_cipher().await; let keyset = cipher.default_keyset(); @@ -446,8 +486,8 @@ async fn a_record_with_two_derived_fields_copies_the_value_for_each() { .unwrap(); assert_eq!( clones.load(Ordering::SeqCst), - 2, - "the default owned form reads the value through the borrowed form" + 0, + "both fields read the value in place" ); let opened: String = String::decrypt_from_with_context(record.c, &cipher, aead()) .await @@ -487,6 +527,11 @@ impl Encrypt for Dropped { std::mem::take(&mut self.text).visit(sink) } } +impl Encrypt for &Dropped { + fn visit(self, sink: S) -> Result { + (&self.text).visit(sink) + } +} impl PrfValue for Dropped { fn prf_visit_with_context<'a, P, V, C>( mut self, @@ -502,6 +547,11 @@ impl PrfValue for Dropped { std::mem::take(&mut self.text).prf_visit_with_context(prf, context, visitor) } } +impl Zeroize for Dropped { + fn zeroize(&mut self) { + self.text.zeroize(); + } +} impl AsRef for Dropped { fn as_ref(&self) -> &str { &self.text @@ -569,3 +619,313 @@ async fn an_owned_plaintext_is_dropped_before_its_key_request_is_sent() { let expected: MatchTerms = keyset.match_terms(NUMBER, context()).await.unwrap(); assert_eq!(term, expected, "the term is the text's term"); } + +// --- An owned value is wiped once --------------------------------------------- + +/// A plaintext that counts its wipes, and is not `Clone`. Walked by value, +/// it reads its text and then wipes itself, as a Vitamin C type does. So a +/// wipe is counted whether the value was sealed or let go unread. +struct Wiped { + text: String, + wipes: Arc, +} + +impl Wiped { + fn new(text: &str) -> (Self, Arc) { + let wipes = Arc::new(AtomicUsize::new(0)); + let value = Self { + text: text.to_string(), + wipes: wipes.clone(), + }; + (value, wipes) + } +} +impl Zeroize for Wiped { + fn zeroize(&mut self) { + let _ = self.wipes.fetch_add(1, Ordering::SeqCst); + self.text.zeroize(); + } +} +impl Encrypt for Wiped { + fn visit(mut self, sink: S) -> Result { + let walked = self.text.as_str().visit(sink); + self.zeroize(); + walked + } +} +impl Encrypt for &Wiped { + fn visit(self, sink: S) -> Result { + self.text.as_str().visit(sink) + } +} +impl AsRef for Wiped { + fn as_ref(&self) -> &str { + &self.text + } +} + +/// A ciphertext and two terms over one value. +type SealedEqualAndMatched = Encrypted<(EqualityTerm, MatchTerms)>; + +fn an_empty_scope() -> RequiredContext { + RequiredContext::from(CallerContext::from(stack_encrypt::target::Scope::new( + String::new(), + ))) +} + +/// `encrypt_into` hands the value to the one operation written first. The +/// two terms read it in place, the ciphertext seals it, and the value is +/// wiped once. A refused context wipes it once too, and seals nothing. +#[tokio::test] +async fn a_value_with_a_ciphertext_and_two_terms_is_wiped_once() { + let cipher = stack_cipher().await; + let keyset = cipher.default_keyset(); + + let (value, wipes) = Wiped::new(NUMBER); + let sealed: SealedEqualAndMatched = value + .encrypt_into_with_context(&keyset, context()) + .await + .unwrap(); + assert_eq!(wipes.load(Ordering::SeqCst), 1, "sealed: one wipe"); + let opened: String = String::decrypt_from_with_context(sealed.ciphertext, &cipher, aead()) + .await + .unwrap(); + assert_eq!(opened, NUMBER); + let (equal, matched) = sealed.terms; + assert_eq!( + equal, + keyset.equality_term(NUMBER, context()).await.unwrap() + ); + let expected: MatchTerms = keyset.match_terms(NUMBER, context()).await.unwrap(); + assert_eq!(matched, expected); + + let (value, wipes) = Wiped::new(NUMBER); + let refused = keyset + .run( + >::owned_encryption(), + value, + an_empty_scope(), + ) + .await; + assert!(refused.is_err(), "an empty scope is refused"); + assert_eq!(wipes.load(Ordering::SeqCst), 1, "refused: one wipe"); + + // The borrowed form leaves the value with the caller. + let (value, wipes) = Wiped::new(NUMBER); + let _: SealedEqualAndMatched = keyset + .run( + >::encryption(), + &value, + RequiredContext::from(caller()), + ) + .await + .unwrap(); + assert_eq!(wipes.load(Ordering::SeqCst), 0, "borrowed: the caller's"); + drop(value); +} + +/// Each public operation, composed by hand in `Owned` mode, wipes the value +/// it is handed once: after it is read, and when the context is refused. +#[tokio::test] +async fn each_owned_operation_wipes_its_value_once() { + use stack_encrypt::target::Scope; + let cipher = stack_cipher().await; + let keyset = cipher.default_keyset(); + let empty = || CallerContext::from(Scope::new(String::new())); + + macro_rules! wiped_once { + ($operation:expr, $context:expr, $what:literal) => {{ + let (value, wipes) = Wiped::new(NUMBER); + let _ = keyset.run($operation, value, $context).await; + assert_eq!(wipes.load(Ordering::SeqCst), 1, $what); + }}; + } + wiped_once!(ciphertext::<_, _, Owned>(), aead(), "ciphertext, sealed"); + wiped_once!( + ciphertext::<_, _, Owned>(), + AeadContext::from(Scope::new(String::new())), + "ciphertext, refused" + ); + wiped_once!(equality::<_, _, Owned>(), caller(), "equality, derived"); + wiped_once!(equality::<_, _, Owned>(), empty(), "equality, refused"); + wiped_once!( + matching::<_, _, Owned, DefaultMatch>(), + caller(), + "matching, derived" + ); + wiped_once!( + matching::<_, _, Owned, DefaultMatch>(), + empty(), + "matching, refused" + ); +} + +// --- An owned value is wiped when a reader panics ------------------------------ + +/// A plaintext that cannot be read in place: `as_ref` and the by-reference +/// `Encrypt` panic. It counts its wipes, as [`Wiped`] does, and seals by +/// value. +struct Exploding { + text: String, + wipes: Arc, +} + +impl Exploding { + fn new() -> (Self, Arc) { + let wipes = Arc::new(AtomicUsize::new(0)); + let value = Self { + text: NUMBER.to_string(), + wipes: wipes.clone(), + }; + (value, wipes) + } +} +impl Zeroize for Exploding { + fn zeroize(&mut self) { + let _ = self.wipes.fetch_add(1, Ordering::SeqCst); + self.text.zeroize(); + } +} +impl Encrypt for Exploding { + fn visit(mut self, sink: S) -> Result { + let walked = self.text.as_str().visit(sink); + self.zeroize(); + walked + } +} +impl Encrypt for &Exploding { + fn visit(self, _: S) -> Result { + panic!("the value cannot be read in place") + } +} +impl AsRef for Exploding { + fn as_ref(&self) -> &str { + panic!("the text cannot be read") + } +} + +/// An owned value that a borrowed reader in `zip` panics over is wiped +/// once, as the stack unwinds, and so is one that a match term panics over +/// alone. +#[tokio::test] +async fn an_owned_value_is_wiped_once_when_a_reader_panics() { + use std::panic::{catch_unwind, AssertUnwindSafe}; + let cipher = stack_cipher().await; + let keyset = cipher.default_keyset(); + + let (value, wipes) = Exploding::new(); + let unwound = catch_unwind(AssertUnwindSafe(|| { + let sealed_and_matched = ciphertext::<_, _, Owned>() + .accepting::() + .zip(matching::<_, _, Borrowed, DefaultMatch>()); + drop(keyset.run(sealed_and_matched, value, caller())); + })); + assert!(unwound.is_err(), "the reader panicked"); + assert_eq!(wipes.load(Ordering::SeqCst), 1, "zip: one wipe"); + + let (value, wipes) = Exploding::new(); + let unwound = catch_unwind(AssertUnwindSafe(|| { + drop(keyset.run(matching::<_, _, Owned, DefaultMatch>(), value, caller())); + })); + assert!(unwound.is_err(), "the match term panicked"); + assert_eq!(wipes.load(Ordering::SeqCst), 1, "matching: one wipe"); + + // A target's equality term reads the value by reference beside the + // ciphertext that takes it. + let (value, wipes) = Exploding::new(); + let unwound = catch_unwind(AssertUnwindSafe(|| { + let indexed = stack_encrypt::target::indexed::<_, _, Owned, _>(stack_encrypt::Equality); + drop(keyset.run(indexed, value, caller())); + })); + assert!(unwound.is_err(), "the equality term panicked"); + assert_eq!(wipes.load(Ordering::SeqCst), 1, "indexed: one wipe"); +} + +// --- A query value is wiped when its context is refused ------------------------ + +/// A record whose one field is a [`Wiped`], so a query of it counts wipes. +#[derive(Zeroize)] +struct Card { + number: Wiped, +} + +/// A query takes a `Wiped` as it is, as it takes a `String`. +impl stack_encrypt::field_reference::QueryInput for Wiped { + type Value = Wiped; + fn into_value(self) -> Wiped { + self + } +} + +#[derive(EncryptTarget)] +#[stash(struct = Card, scope = "cards", scope(region: String))] +#[allow(dead_code)] +struct EncryptedCard { + number: Encrypted, +} + +/// A typed query hands its value to the index by value. A scope with an +/// empty part is refused, and the value is wiped once. +#[tokio::test] +async fn a_query_value_refused_for_its_scope_is_wiped_once() { + use stack_encrypt::target::Scope; + let cipher = stack_cipher().await; + let keyset = cipher.default_keyset(); + let (value, wipes) = Wiped::new(NUMBER); + let refused = EncryptedCard::NUMBER + .eq(value) + .scope(Scope::new(String::new())) + .encrypt(&keyset) + .await; + assert!(refused.is_err(), "an empty scope is refused"); + assert_eq!(wipes.load(Ordering::SeqCst), 1, "one wipe"); +} + +// --- A date with a ciphertext and several terms ------------------------------ + +/// A date is not `Clone`, so sealing it with a ciphertext, an equality term +/// and an order term cannot copy it. The owned form gives the same terms +/// as the borrowed form, and the ciphertext opens to the date. +#[cfg(feature = "jiff")] +#[tokio::test] +async fn a_date_with_a_ciphertext_and_two_terms_is_not_copied() { + use stack_encrypt::sem::{OreBlockTerm, OreTerm}; + use stack_encrypt::value::Date; + let cipher = stack_cipher().await; + let keyset = cipher.default_keyset(); + let date = || Date::new(jiff::civil::date(2024, 2, 29)); + + let sealed: Encrypted<(EqualityTerm, OreTerm)> = date() + .encrypt_into_with_context(&keyset, context()) + .await + .unwrap(); + let borrowed: Encrypted<(EqualityTerm, OreTerm)> = keyset + .run( + )> as EncryptTarget>::encryption(), + &date(), + RequiredContext::from(caller()), + ) + .await + .unwrap(); + assert_eq!(sealed.terms.0, borrowed.terms.0, "the equality term"); + assert_eq!(sealed.terms.1, borrowed.terms.1, "the order term"); + let opened = Date::decrypt_from_with_context(sealed.ciphertext, &cipher, aead()) + .await + .unwrap(); + assert_eq!(opened.to_jiff(), date().to_jiff()); + + // Block ORE, the scheme EQL v4 stores, the same way. + let sealed: Encrypted<(EqualityTerm, OreBlockTerm)> = date() + .encrypt_into_with_context(&keyset, context()) + .await + .unwrap(); + let later = keyset + .ore_block_term(Date::new(jiff::civil::date(2024, 3, 1)), context()) + .await + .unwrap(); + assert_eq!( + sealed.terms.1.compare(&later), + Some(std::cmp::Ordering::Less), + "the term orders as the date" + ); +} diff --git a/packages/stack-encrypt/tests/term_bytes.rs b/packages/stack-encrypt/tests/term_bytes.rs index ae5f5729e0..e08096d875 100644 --- a/packages/stack-encrypt/tests/term_bytes.rs +++ b/packages/stack-encrypt/tests/term_bytes.rs @@ -230,24 +230,6 @@ async fn text_order_terms_fold_case_and_accents() { } } -/// A text term is not the term of the same bytes as bytes: the column salt -/// binds the target, `Text` or `Bytes`. -#[tokio::test] -async fn a_text_order_term_is_keyed_apart_from_bytes() { - let cipher = cipher().await; - let keyset = cipher.default_keyset(); - let text = keyset - .ore_term("cafe".to_string(), nonempty!("users/surname")) - .await - .unwrap(); - let bytes = keyset - .ore_term(b"cafe".to_vec(), nonempty!("users/surname")) - .await - .unwrap(); - assert_eq!(text.as_ref().len(), bytes.as_ref().len()); - assert_ne!(text, bytes); -} - /// Text holding a code point Unicode 16 does not assign has no known fold, /// so it has no order term: vitaminc-ore refuses to encode it. #[tokio::test] diff --git a/packages/stack-encrypt/tests/term_serde.rs b/packages/stack-encrypt/tests/term_serde.rs index 961baef018..eb9797d962 100644 --- a/packages/stack-encrypt/tests/term_serde.rs +++ b/packages/stack-encrypt/tests/term_serde.rs @@ -4,7 +4,8 @@ use serde_json::{json, Value}; use stack_encrypt::nonempty; -use stack_encrypt::sem::{OpeTerm, Orderable, OreBlockTerm, OreTerm, TermBytesError}; +use stack_encrypt::sem::{OpeTerm, OreBlockTerm, OreTerm, TermBytesError}; +use stack_encrypt::Orderable; use stack_encrypt::{EncryptInto, KeysetCipher, StackCipher}; use stack_kms::FakeDataKeySource; @@ -21,7 +22,7 @@ fn hex(bytes: &[u8]) -> String { bytes.iter().map(|b| format!("{b:02x}")).collect() } -async fn block( +async fn block( keyset: &KeysetCipher<'_, FakeDataKeySource>, value: T, ) -> OreBlockTerm { diff --git a/packages/stack-encrypt/tests/transcode.rs b/packages/stack-encrypt/tests/transcode.rs index c2fb90f786..a515a317fc 100644 --- a/packages/stack-encrypt/tests/transcode.rs +++ b/packages/stack-encrypt/tests/transcode.rs @@ -57,7 +57,7 @@ impl Transcode for StoredLeaf { } // A ciphertext alone: it seals, and derives no term, so it requires the AEAD // context, as the canonical `StackCipherText` does. -impl EncryptTarget for StoredLeaf { +impl EncryptTarget for StoredLeaf { type ContextInput = RequiredContext; fn encryption<'s, K: 'static>() -> Encryption<'s, S, Self, K, Self::ContextInput> where @@ -300,7 +300,7 @@ async fn scalar_destination_refuses_a_sequence() { // A target whose declaration carries every context it needs asks its caller // for none: `ContextInput = NoCallerContext`. struct FixedLeaf(StoredLeaf); -impl EncryptTarget for FixedLeaf { +impl EncryptTarget for FixedLeaf { type ContextInput = NoCallerContext; fn encryption<'s, K: 'static>() -> Encryption<'s, S, Self, K, Self::ContextInput> where diff --git a/packages/stack-encrypt/tests/ui/derive_match_on_integer.stderr b/packages/stack-encrypt/tests/ui/derive_match_on_integer.stderr index 24c7c10062..55ebdb11af 100644 --- a/packages/stack-encrypt/tests/ui/derive_match_on_integer.stderr +++ b/packages/stack-encrypt/tests/ui/derive_match_on_integer.stderr @@ -9,7 +9,7 @@ help: the trait `EncryptTarget` is implemented for `Encrypted` | | / impl EncryptTarget for Encrypted | | where - | | S: crate::Encrypt + Clone + zeroize::Zeroize, + | | S: crate::Encrypt + vitaminc_aead::EncryptRef + zeroize::Zeroize, | | Terms: TermSet, | |______________________^ = note: required for `MatchTerms` to implement `TermSet` @@ -26,7 +26,7 @@ help: the trait `EncryptTarget` is implemented for `Encrypted` | | / impl EncryptTarget for Encrypted | | where - | | S: crate::Encrypt + Clone + zeroize::Zeroize, + | | S: crate::Encrypt + vitaminc_aead::EncryptRef + zeroize::Zeroize, | | Terms: TermSet, | |______________________^ = note: required for `MatchTerms` to implement `TermSet` diff --git a/packages/stack-encrypt/tests/ui/divergent_context_in_target.stderr b/packages/stack-encrypt/tests/ui/divergent_context_in_target.stderr index b532d4ea4f..f4391d267e 100644 --- a/packages/stack-encrypt/tests/ui/divergent_context_in_target.stderr +++ b/packages/stack-encrypt/tests/ui/divergent_context_in_target.stderr @@ -2,11 +2,11 @@ error[E0308]: mismatched types --> tests/ui/divergent_context_in_target.rs:30:18 | 30 | .zip(equality()) - | --- ^^^^^^^^^^ expected `Encryption<'_, _, _, _, ..., _>`, found `Encryption<'_, _, ..., _, ..., _>` + | --- ^^^^^^^^^^ expected `Encryption<'_, _, _, _, DeclaredContext>`, found `Encryption<'_, _, ..., _, ..., _>` | | | arguments to this method are incorrect | - = note: expected struct `Encryption<'_, _, _, _, DeclaredContext, _>` + = note: expected struct `Encryption<'_, _, _, _, DeclaredContext, stack_encrypt::target::Borrowed>` found struct `Encryption<'_, _, EqualityTerm, _, CallerContext, _>` note: method defined here --> src/target/operations.rs diff --git a/packages/stack-encrypt/tests/ui/execution_callback.stderr b/packages/stack-encrypt/tests/ui/execution_callback.stderr index 55f61e557a..7b6f890c45 100644 --- a/packages/stack-encrypt/tests/ui/execution_callback.stderr +++ b/packages/stack-encrypt/tests/ui/execution_callback.stderr @@ -8,7 +8,7 @@ error: cannot construct `Encryption<'_, _, _, _, _, _>` with struct literal synt 8 | | }), | |__________- private field | - = note: ...and other private field `shapes` that was not provided + = note: ...and other private fields `shapes` and `mode` that were not provided help: you might have meant to use an associated function to build this type | 5 - let _: Encryption<'_, u32, StackCipherText, (), CallerContext> = Encryption { @@ -16,19 +16,19 @@ help: you might have meant to use an associated function to build this type 7 - stack_encrypt::Pending::failed(cipher, stack_encrypt::Error::Aead) 8 - }), 9 - }; -5 + let _: Encryption<'_, u32, StackCipherText, (), CallerContext> = Encryption::from_build(_, _); +5 + let _: Encryption<'_, u32, StackCipherText, (), CallerContext> = Encryption::ready(_); | 5 - let _: Encryption<'_, u32, StackCipherText, (), CallerContext> = Encryption { 6 - build: Box::new(|_, cipher, _| { 7 - stack_encrypt::Pending::failed(cipher, stack_encrypt::Error::Aead) 8 - }), 9 - }; -5 + let _: Encryption<'_, u32, StackCipherText, (), CallerContext> = Encryption::ready(_); +5 + let _: Encryption<'_, u32, StackCipherText, (), CallerContext> = Encryption::failed(_); | 5 - let _: Encryption<'_, u32, StackCipherText, (), CallerContext> = Encryption { 6 - build: Box::new(|_, cipher, _| { 7 - stack_encrypt::Pending::failed(cipher, stack_encrypt::Error::Aead) 8 - }), 9 - }; -5 + let _: Encryption<'_, u32, StackCipherText, (), CallerContext> = Encryption::failed(_); +5 + let _: Encryption<'_, u32, StackCipherText, (), CallerContext> = Encryption::from_build(_, _); | diff --git a/packages/stack-encrypt/tests/ui/field_reference_operator_not_answered.stderr b/packages/stack-encrypt/tests/ui/field_reference_operator_not_answered.stderr index 697ba484ce..9d2449b8dd 100644 --- a/packages/stack-encrypt/tests/ui/field_reference_operator_not_answered.stderr +++ b/packages/stack-encrypt/tests/ui/field_reference_operator_not_answered.stderr @@ -13,8 +13,8 @@ help: the trait `Answers` is not implemented for `Equa | | / impl Answers for EqualityTerm | | where - | | S: crate::Encrypt + Clone + 'static, - | |________________________________________^ + | | S: crate::Encrypt + vitaminc_aead::EncryptRef + zeroize::Zeroize + 'static, + | |_______________________________________________________________________________^ = help: for that trait implementation, expected `stack_encrypt::op::Eq`, found `stack_encrypt::op::Gt` = note: required for `Encrypted` to implement `Answers` note: required by a bound in `FieldReference::::gt` diff --git a/packages/stack-encrypt/tests/ui/op_inexact_operator_needs_probabilistic.rs b/packages/stack-encrypt/tests/ui/op_inexact_operator_needs_probabilistic.rs index d99e3c1f53..e80a69f0d7 100644 --- a/packages/stack-encrypt/tests/ui/op_inexact_operator_needs_probabilistic.rs +++ b/packages/stack-encrypt/tests/ui/op_inexact_operator_needs_probabilistic.rs @@ -3,7 +3,7 @@ //! it. use stack_encrypt::op; use stack_encrypt::sem::EqualityTerm; -use stack_encrypt::target::{CallerContext, ConsumeSource, Encryption, Index, IndexSpec}; +use stack_encrypt::target::{CallerContext, WipeSource, Encryption, Index, IndexSpec}; use stack_encrypt::Equality; struct Shortcut; @@ -13,7 +13,7 @@ impl Index for Shortcut { fn spec(&self) -> IndexSpec { IndexSpec::Equality } - fn operation<'s, K: 'static, M: ConsumeSource<'s, String>>( + fn operation<'s, K: 'static, M: WipeSource<'s, String>>( &self, ) -> Encryption<'s, String, EqualityTerm, K, CallerContext, M> { Index::::operation(&Equality) diff --git a/packages/stack-encrypt/tests/ui/op_order_on_bytes.stderr b/packages/stack-encrypt/tests/ui/op_order_on_bytes.stderr index 71891efb2f..9abc876c56 100644 --- a/packages/stack-encrypt/tests/ui/op_order_on_bytes.stderr +++ b/packages/stack-encrypt/tests/ui/op_order_on_bytes.stderr @@ -1,40 +1,154 @@ -error[E0277]: `Vec` is not ordered: the ordering operators are answered over the integers of 16 bits and wider, the floats, text, dates, timestamps and decimals - --> tests/ui/op_order_on_bytes.rs:21:36 +error[E0277]: `Vec` is not `Orderable`: it has no order target of its own + --> tests/ui/op_order_on_bytes.rs:17:21 + | +17 | blob: Encrypted>>, + | ^^^^^^^^^^^^^^^^ has no order target of its own + | + = help: the trait `Orderable` is not implemented for `Vec` + = note: name the target: `scheme.target(I64).encrypt_checked(value)` + = note: there is no 8-bit target: an order term over 256 values reveals them, so an `i8` goes into `I16` or wider by name (`scheme.target(I16).encrypt(value)`), or into an equality index + = note: bytes order only into a target named for them, `scheme.target(Bytes)`: no ordering operator compares bytes + = help: the following other types implement trait `Orderable`: + &f32 + &f64 + &i128 + &i16 + &i32 + &i64 + &jiff::civil::date::Date + &jiff::timestamp::Timestamp + and $N others +note: required by a bound in `OreTerm` + --> src/sem/mod.rs + | + | pub struct OreTerm(OreClww8VariableV1, PhantomData T>); + | ^^^^^^^^^ required by this bound in `OreTerm` + +error[E0277]: `Vec` is not `Orderable`: it has no order target of its own + --> tests/ui/op_order_on_bytes.rs:17:11 + | +17 | blob: Encrypted>>, + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ has no order target of its own + | + = help: the trait `Orderable` is not implemented for `Vec` + = note: name the target: `scheme.target(I64).encrypt_checked(value)` + = note: there is no 8-bit target: an order term over 256 values reveals them, so an `i8` goes into `I16` or wider by name (`scheme.target(I16).encrypt(value)`), or into an equality index + = note: bytes order only into a target named for them, `scheme.target(Bytes)`: no ordering operator compares bytes + = help: the following other types implement trait `Orderable`: + &f32 + &f64 + &i128 + &i16 + &i32 + &i64 + &jiff::civil::date::Date + &jiff::timestamp::Timestamp + and $N others +note: required by a bound in `OreTerm` + --> src/sem/mod.rs + | + | pub struct OreTerm(OreClww8VariableV1, PhantomData T>); + | ^^^^^^^^^ required by this bound in `OreTerm` + +error[E0277]: `Vec` is not `Orderable`: it has no order target of its own + --> tests/ui/op_order_on_bytes.rs:17:11 + | +17 | blob: Encrypted>>, + | ^^^^^^^^^ has no order target of its own + | + = help: the trait `Orderable` is not implemented for `Vec` + = note: name the target: `scheme.target(I64).encrypt_checked(value)` + = note: there is no 8-bit target: an order term over 256 values reveals them, so an `i8` goes into `I16` or wider by name (`scheme.target(I16).encrypt(value)`), or into an equality index + = note: bytes order only into a target named for them, `scheme.target(Bytes)`: no ordering operator compares bytes + = help: the following other types implement trait `Orderable`: + &f32 + &f64 + &i128 + &i16 + &i32 + &i64 + &jiff::civil::date::Date + &jiff::timestamp::Timestamp + and $N others + = note: required for `OreTerm>` to implement `TermSet>` + = note: required for `Encrypted>>` to implement `EncryptTarget>` + +error[E0277]: `Vec` is not `Orderable`: it has no order target of its own + --> tests/ui/op_order_on_bytes.rs:14:10 + | +14 | #[derive(EncryptTarget)] + | ^^^^^^^^^^^^^ has no order target of its own + | + = help: the trait `Orderable` is not implemented for `Vec` + = note: name the target: `scheme.target(I64).encrypt_checked(value)` + = note: there is no 8-bit target: an order term over 256 values reveals them, so an `i8` goes into `I16` or wider by name (`scheme.target(I16).encrypt(value)`), or into an equality index + = note: bytes order only into a target named for them, `scheme.target(Bytes)`: no ordering operator compares bytes + = help: the following other types implement trait `Orderable`: + &f32 + &f64 + &i128 + &i16 + &i32 + &i64 + &jiff::civil::date::Date + &jiff::timestamp::Timestamp + and $N others +note: required by a bound in `OreTerm` + --> src/sem/mod.rs + | + | pub struct OreTerm(OreClww8VariableV1, PhantomData T>); + | ^^^^^^^^^ required by this bound in `OreTerm` + = note: this error originates in the derive macro `EncryptTarget` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0277]: `Vec` is not `Orderable`: it has no order target of its own + --> tests/ui/op_order_on_bytes.rs:14:10 + | +14 | #[derive(EncryptTarget)] + | ^ has no order target of its own + | + = help: the trait `Orderable` is not implemented for `Vec` + = note: name the target: `scheme.target(I64).encrypt_checked(value)` + = note: there is no 8-bit target: an order term over 256 values reveals them, so an `i8` goes into `I16` or wider by name (`scheme.target(I16).encrypt(value)`), or into an equality index + = note: bytes order only into a target named for them, `scheme.target(Bytes)`: no ordering operator compares bytes + = help: the following other types implement trait `Orderable`: + &f32 + &f64 + &i128 + &i16 + &i32 + &i64 + &jiff::civil::date::Date + &jiff::timestamp::Timestamp + and $N others +note: required by a bound in `OreTerm` + --> src/sem/mod.rs + | + | pub struct OreTerm(OreClww8VariableV1, PhantomData T>); + | ^^^^^^^^^ required by this bound in `OreTerm` + = note: this error originates in the derive macro `EncryptTarget` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0277]: `Vec` is not `Orderable`: it has no order target of its own + --> tests/ui/op_order_on_bytes.rs:21:13 | 21 | let _ = EncryptedFile::BLOB.lt(vec![1u8, 2]); - | -- ^^^^^^^^^^^^ no ordering operator over this type - | | - | required by a bound introduced by this call - | - = help: the trait `Ordered` is not implemented for `Vec` - = note: `Lt`, `Lte`, `Gt`, `Gte` and `Between` take `u16` to `u128`, `i16` to `i128`, `f32`, `f64`, a `String`, or a `value::Date`, `value::Timestamp` or `value::Decimal`; a `u8`, an `i8` and a `bool` have no order term - = help: the following other types implement trait `Ordered`: - f32 - f64 - i128 - i16 - i32 - i64 - stack_encrypt::value::Date - stack_encrypt::value::Decimal + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ has no order target of its own + | + = help: the trait `Orderable` is not implemented for `Vec` + = note: name the target: `scheme.target(I64).encrypt_checked(value)` + = note: there is no 8-bit target: an order term over 256 values reveals them, so an `i8` goes into `I16` or wider by name (`scheme.target(I16).encrypt(value)`), or into an equality index + = note: bytes order only into a target named for them, `scheme.target(Bytes)`: no ordering operator compares bytes + = help: the following other types implement trait `Orderable`: + &f32 + &f64 + &i128 + &i16 + &i32 + &i64 + &jiff::civil::date::Date + &jiff::timestamp::Timestamp and $N others - = note: required for `OreTerm>` to implement `Answers>` - = note: 1 redundant requirement hidden - = note: required for `Encrypted>>` to implement `Answers>` -note: required by a bound in `FieldReference::::lt` - --> src/field_reference.rs - | - | T: Answers<$op, Q::Value> + LabelledTarget, - | ^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `FieldReference::::lt` -... - | / operator_methods! { - | | /// Rows whose value equals `value` ([`op::Eq`](struct@Eq)). - | | eq => Eq; - | | /// Rows whose value is below `value` ([`op::Lt`](Lt)). - | | lt => Lt; - | | -- required by a bound in this associated function -... | - | | matches => Matches; - | | } - | |_- in this macro invocation - = note: this error originates in the macro `operator_methods` (in Nightly builds, run with -Z macro-backtrace for more info) +note: required by a bound in `OreTerm` + --> src/sem/mod.rs + | + | pub struct OreTerm(OreClww8VariableV1, PhantomData T>); + | ^^^^^^^^^ required by this bound in `OreTerm` diff --git a/packages/stack-encrypt/tests/ui/order_term_of_an_8_bit_integer.rs b/packages/stack-encrypt/tests/ui/order_term_of_an_8_bit_integer.rs index 5435964b6d..1a958f36cc 100644 --- a/packages/stack-encrypt/tests/ui/order_term_of_an_8_bit_integer.rs +++ b/packages/stack-encrypt/tests/ui/order_term_of_an_8_bit_integer.rs @@ -1,6 +1,6 @@ //! A `u8` and an `i8` have no order term, as a `bool` has none: with 256 //! values, an order term would rank every row among 256, which a few known -//! rows resolve to the values. So neither is `sem::Orderable`: an +//! rows resolve to the values. So neither is `Orderable`: an //! `OreTerm`, an `OpeTerm` and an `Ore` index on an `i8` do not //! compile. A field with no order term has no ordering query. Each keeps //! its equality term. diff --git a/packages/stack-encrypt/tests/ui/order_term_of_an_8_bit_integer.stderr b/packages/stack-encrypt/tests/ui/order_term_of_an_8_bit_integer.stderr index 0144abe909..59a276183a 100644 --- a/packages/stack-encrypt/tests/ui/order_term_of_an_8_bit_integer.stderr +++ b/packages/stack-encrypt/tests/ui/order_term_of_an_8_bit_integer.stderr @@ -1,18 +1,22 @@ -error[E0277]: the trait bound `u8: Orderable` is not satisfied +error[E0277]: `u8` is not `Orderable`: it has no order target of its own --> tests/ui/order_term_of_an_8_bit_integer.rs:11:15 | 11 | fn terms(ore: OreTerm, ope: OpeTerm) { - | ^^^^^^^^^^^ the trait `Orderable` is not implemented for `u8` + | ^^^^^^^^^^^ has no order target of its own | + = help: the trait `Orderable` is not implemented for `u8` + = note: name the target: `scheme.target(I64).encrypt_checked(value)` + = note: there is no 8-bit target: an order term over 256 values reveals them, so an `i8` goes into `I16` or wider by name (`scheme.target(I16).encrypt(value)`), or into an equality index + = note: bytes order only into a target named for them, `scheme.target(Bytes)`: no ordering operator compares bytes = help: the following other types implement trait `Orderable`: - f32 - f64 - i128 - i16 - i32 - i64 - u128 - u16 + &f32 + &f64 + &i128 + &i16 + &i32 + &i64 + &u128 + &u16 and $N others note: required by a bound in `OreTerm` --> src/sem/mod.rs @@ -20,21 +24,25 @@ note: required by a bound in `OreTerm` | pub struct OreTerm(OreClww8VariableV1, PhantomData T>); | ^^^^^^^^^ required by this bound in `OreTerm` -error[E0277]: the trait bound `i8: Orderable` is not satisfied +error[E0277]: `i8` is not `Orderable`: it has no order target of its own --> tests/ui/order_term_of_an_8_bit_integer.rs:11:33 | 11 | fn terms(ore: OreTerm, ope: OpeTerm) { - | ^^^^^^^^^^^ the trait `Orderable` is not implemented for `i8` + | ^^^^^^^^^^^ has no order target of its own | + = help: the trait `Orderable` is not implemented for `i8` + = note: name the target: `scheme.target(I64).encrypt_checked(value)` + = note: there is no 8-bit target: an order term over 256 values reveals them, so an `i8` goes into `I16` or wider by name (`scheme.target(I16).encrypt(value)`), or into an equality index + = note: bytes order only into a target named for them, `scheme.target(Bytes)`: no ordering operator compares bytes = help: the following other types implement trait `Orderable`: - f32 - f64 - i128 - i16 - i32 - i64 - u128 - u16 + &f32 + &f64 + &i128 + &i16 + &i32 + &i64 + &u128 + &u16 and $N others note: required by a bound in `OpeTerm` --> src/sem/mod.rs @@ -42,20 +50,24 @@ note: required by a bound in `OpeTerm` | pub struct OpeTerm(OpeClww8VariableV1, PhantomData T>); | ^^^^^^^^^ required by this bound in `OpeTerm` -error[E0277]: the trait bound `i8: Orderable` is not satisfied +error[E0277]: `i8` is not `Orderable`: it has no order target of its own --> tests/ui/order_term_of_an_8_bit_integer.rs:16:13 | 16 | let _ = indexed::(Ore); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `Orderable` is not implemented for `i8` + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ has no order target of its own | + = help: the trait `Orderable` is not implemented for `i8` + = note: name the target: `scheme.target(I64).encrypt_checked(value)` + = note: there is no 8-bit target: an order term over 256 values reveals them, so an `i8` goes into `I16` or wider by name (`scheme.target(I16).encrypt(value)`), or into an equality index + = note: bytes order only into a target named for them, `scheme.target(Bytes)`: no ordering operator compares bytes = help: the following other types implement trait `Orderable`: - f32 - f64 - i128 - i16 - i32 - i64 - u128 - u16 + &f32 + &f64 + &i128 + &i16 + &i32 + &i64 + &u128 + &u16 and $N others = note: required for `stack_encrypt::Ore` to implement `stack_encrypt::Index` diff --git a/packages/stack-encrypt/tests/ui/owned_fan_out_needs_clone.rs b/packages/stack-encrypt/tests/ui/owned_fan_out_needs_clone.rs deleted file mode 100644 index 4e607736da..0000000000 --- a/packages/stack-encrypt/tests/ui/owned_fan_out_needs_clone.rs +++ /dev/null @@ -1,19 +0,0 @@ -//! Owned mode hands the plaintext to an operation by value, so a single -//! operation needs no `Clone`. Two operations over one owned value are the -//! one place a copy is unavoidable — the first side gets a clone, the last -//! the value — and the refusal names `zip`, not the operations. -use stack_encrypt::target::{ciphertext, equality, CallerContext, Owned}; -use stack_encrypt::{nonempty, KeysetCipher, Encrypt}; -use stack_kms::FakeDataKeySource; - -fn seal_and_index( - keyset: &KeysetCipher<'_, FakeDataKeySource>, - value: S, -) { - let both = ciphertext::<_, _, Owned>() - .accepting::() - .zip(equality::<_, _, Owned>()); - let _ = keyset.run(both, value, CallerContext::from(nonempty!("column"))); -} - -fn main() {} diff --git a/packages/stack-encrypt/tests/ui/owned_fan_out_needs_clone.stderr b/packages/stack-encrypt/tests/ui/owned_fan_out_needs_clone.stderr deleted file mode 100644 index 0d16f0b944..0000000000 --- a/packages/stack-encrypt/tests/ui/owned_fan_out_needs_clone.stderr +++ /dev/null @@ -1,19 +0,0 @@ -error[E0277]: the trait bound `S: Clone` is not satisfied - --> tests/ui/owned_fan_out_needs_clone.rs:15:10 - | -15 | .zip(equality::<_, _, Owned>()); - | ^^^ the trait `Clone` is not implemented for `S` - | - = note: required for `stack_encrypt::target::Owned` to implement `ShareSource<'_, S>` -note: required by a bound in `Encryption::<'s, S, T, K, Ctx, M>::zip` - --> src/target/operations.rs - | - | pub fn zip( - | --- required by a bound in this associated function -... - | M: ShareSource<'s, S>, - | ^^^^^^^^^^^^^^^^^^ required by this bound in `Encryption::<'s, S, T, K, Ctx, M>::zip` -help: consider further restricting type parameter `S` with trait `Clone` - | - 9 | fn seal_and_index( - | +++++++++++++++++++ diff --git a/packages/stack-encrypt/tests/ui/pass/owned_fan_out_without_clone.rs b/packages/stack-encrypt/tests/ui/pass/owned_fan_out_without_clone.rs new file mode 100644 index 0000000000..770dd4c07c --- /dev/null +++ b/packages/stack-encrypt/tests/ui/pass/owned_fan_out_without_clone.rs @@ -0,0 +1,68 @@ +//! A ciphertext and several terms over one owned value ask for no `Clone`. +//! Each term reads the value in place, and then the ciphertext takes it. So a +//! value that is moved and wiped can be sealed and indexed in one call. +use stack_encrypt::sem::{EqualityTerm, MatchTerms, OreBlockTerm, OreTerm}; +use stack_encrypt::value::Date; +use stack_encrypt::target::{ + ciphertext, equality, indexed, matching, CallerContext, Encrypted, Equality, Match, Ore, + OreBlock, Owned, Pending, +}; +use stack_encrypt::{nonempty, Encrypt, EncryptRef, KeysetCipher, StackCipherText}; +use stack_kms::FakeDataKeySource; +use zeroize::Zeroize; + +// Bounded only by what the operations read, and `Zeroize` for the one that is +// handed the value. `Clone` returning to `zip`, or to either operation, fails +// this file. +fn seal_and_index<'a, S: Encrypt + EncryptRef + AsRef + Zeroize>( + keyset: &'a KeysetCipher<'_, FakeDataKeySource>, + value: S, +) -> Pending<'a, ((StackCipherText, EqualityTerm), MatchTerms), FakeDataKeySource> { + let all = ciphertext::<_, _, Owned>() + .accepting::() + .zip(equality()) + .zip(matching()); + keyset.run(all, value, CallerContext::from(nonempty!("column"))) +} + +// The same through `indexed`, as a target with terms composes it. +fn indexed_owned<'a, S: Encrypt + EncryptRef + AsRef + Zeroize>( + keyset: &'a KeysetCipher<'_, FakeDataKeySource>, + value: S, +) -> Pending<'a, Encrypted<(EqualityTerm, MatchTerms)>, FakeDataKeySource> { + keyset.run( + indexed::<_, _, Owned, _>((Equality, Match::new())), + value, + CallerContext::from(nonempty!("column")), + ) +} + +// A date, which is not `Clone`, with a ciphertext, an equality term and an +// order term over the one owned value: #1734's own example. +fn date_with_order_terms<'a>( + keyset: &'a KeysetCipher<'_, FakeDataKeySource>, + value: Date, +) -> Pending<'a, Encrypted<(EqualityTerm, OreTerm)>, FakeDataKeySource> { + keyset.run( + indexed::<_, _, Owned, _>((Equality, Ore)), + value, + CallerContext::from(nonempty!("column")), + ) +} + +// The same with block ORE, the scheme EQL v4 stores. +fn date_with_block_order<'a>( + keyset: &'a KeysetCipher<'_, FakeDataKeySource>, + value: Date, +) -> Pending<'a, Encrypted<(EqualityTerm, OreBlockTerm)>, FakeDataKeySource> { + keyset.run( + indexed::<_, _, Owned, _>((Equality, OreBlock)), + value, + CallerContext::from(nonempty!("column")), + ) +} + +fn main() { + let _ = (seal_and_index::, indexed_owned::); + let _ = (date_with_order_terms, date_with_block_order); +} diff --git a/packages/stack-encrypt/tests/ui/pass/owned_without_clone.rs b/packages/stack-encrypt/tests/ui/pass/owned_without_clone.rs index 98e07295c0..7a48c4ebc8 100644 --- a/packages/stack-encrypt/tests/ui/pass/owned_without_clone.rs +++ b/packages/stack-encrypt/tests/ui/pass/owned_without_clone.rs @@ -1,40 +1,44 @@ -//! A single operation in owned mode asks nothing of the plaintext beyond the -//! operation's own capability: no `Clone`, so a value that is moved and -//! wiped can be sealed or indexed. -use stack_encrypt::sem::{EqualityTerm, MatchTerms, OpeTerm, Orderable, OreTerm}; +//! An operation in owned mode asks nothing of the plaintext beyond the +//! operation's own capability and `Zeroize`: no `Clone`, so a value that is +//! moved and wiped can be sealed or indexed. A ciphertext and an equality +//! term read the value by reference as well as by value, which is +//! `EncryptRef`. The operation wipes the value it is handed, which is +//! `Zeroize`. +use stack_encrypt::sem::{EqualityTerm, MatchTerms, OpeTerm, OreTerm}; use stack_encrypt::target::{ ciphertext, equality, matching, ope, ore, CallerContext, Owned, Pending, }; -use stack_encrypt::{nonempty, KeysetCipher, Encrypt, StackCipherText}; +use stack_encrypt::{nonempty, Encrypt, EncryptRef, KeysetCipher, Orderable, StackCipherText}; use stack_kms::FakeDataKeySource; +use zeroize::Zeroize; -fn seal<'a, S: Encrypt>( +fn seal<'a, S: Encrypt + EncryptRef + Zeroize>( keyset: &'a KeysetCipher<'_, FakeDataKeySource>, value: S, ) -> Pending<'a, StackCipherText, FakeDataKeySource> { keyset.run(ciphertext::<_, _, Owned>(), value, nonempty!("column").into()) } -fn index<'a, S: Encrypt>( +fn index<'a, S: Encrypt + EncryptRef + Zeroize>( keyset: &'a KeysetCipher<'_, FakeDataKeySource>, value: S, ) -> Pending<'a, EqualityTerm, FakeDataKeySource> { keyset.run(equality::<_, _, Owned>(), value, CallerContext::from(nonempty!("column"))) } -fn search<'a, S: AsRef>( +fn search<'a, S: AsRef + Zeroize>( keyset: &'a KeysetCipher<'_, FakeDataKeySource>, value: S, ) -> Pending<'a, MatchTerms, FakeDataKeySource> { keyset.run(matching::<_, _, Owned, _>(), value, CallerContext::from(nonempty!("column"))) } -// Bounded only by the order terms' own trait: `Orderable` does not imply -// `Clone`, so `Clone` returning to either constructor's bounds fails this -// file. +// Bounded by vitaminc-ore's `Orderable`, read in place (`EncryptRef`), and +// wiped (`Zeroize`). `Orderable` does not imply `Clone`, so `Clone` +// returning to either constructor's bounds fails this file. fn order<'a, S>( keyset: &'a KeysetCipher<'_, FakeDataKeySource>, value: S, ) -> Pending<'a, OreTerm, FakeDataKeySource> where - S: Orderable, + S: Orderable + EncryptRef + Zeroize + 'static, { keyset.run(ore::<_, _, Owned>(), value, CallerContext::from(nonempty!("column"))) } @@ -43,7 +47,7 @@ fn order_preserving<'a, S>( value: S, ) -> Pending<'a, OpeTerm, FakeDataKeySource> where - S: Orderable, + S: Orderable + EncryptRef + Zeroize + 'static, { keyset.run(ope::<_, _, Owned>(), value, CallerContext::from(nonempty!("column"))) } diff --git a/packages/stack-encrypt/tests/ui/pass/query_only_and_borrowed.rs b/packages/stack-encrypt/tests/ui/pass/query_only_and_borrowed.rs index 82fa728e2e..6f2ce0888e 100644 --- a/packages/stack-encrypt/tests/ui/pass/query_only_and_borrowed.rs +++ b/packages/stack-encrypt/tests/ui/pass/query_only_and_borrowed.rs @@ -2,7 +2,7 @@ //! plaintext. use stack_encrypt::sem::EqualityTerm; use stack_encrypt::target::{CallerContext, EncryptTarget}; -use stack_encrypt::{nonempty, Encrypt, EncryptInto, StackCipher, StackCipherText}; +use stack_encrypt::{nonempty, Encrypt, EncryptInto, EncryptRef, StackCipher, StackCipherText}; use stack_kms::FakeDataKeySource; use zeroize::Zeroize; @@ -13,7 +13,7 @@ struct Probe { // No `Decrypt` bound: producing a term requires only that the value // describes itself, not that it can be read back. -fn query(cipher: &StackCipher, value: S) { +fn query(cipher: &StackCipher, value: S) { let keyset = cipher.default_keyset(); let _ = value.encrypt_into_with_context::(&keyset, nonempty!("column")); } diff --git a/packages/stack-encrypt/tests/ui/plaintext_needs_encrypt.stderr b/packages/stack-encrypt/tests/ui/plaintext_needs_encrypt.stderr index aa71a1bcdc..b259889268 100644 --- a/packages/stack-encrypt/tests/ui/plaintext_needs_encrypt.stderr +++ b/packages/stack-encrypt/tests/ui/plaintext_needs_encrypt.stderr @@ -33,3 +33,35 @@ note: there are multiple different versions of crate `vitaminc_aead` in the depe = note: required for `CipherText` to implement `EncryptTarget` = note: 1 redundant requirement hidden = note: required for `Target` to implement `EncryptTarget` + +error[E0277]: the trait bound `for<'a> &'a SerdeOnly: Encrypt` is not satisfied + --> tests/ui/plaintext_needs_encrypt.rs:20:23 + | +20 | let _ = plaintext.encrypt_into_with_context::(&keyset, nonempty!("column")); + | ^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `for<'a> Encrypt` is not implemented for `&'a SerdeOnly` + | +note: there are multiple different versions of crate `vitaminc_aead` in the dependency graph + --> $CARGO/vitaminc-aead-$VERSION/src/plaintext/mod.rs + | + | pub trait Encrypt { + | ^^^^^^^^^^^^^^^^^ this is the expected trait + | + ::: $CARGO/vitaminc-aead-$VERSION/src/encrypt/mod.rs + | + | pub trait Encrypt { + | ----------------- this is the found trait + = help: you can use `cargo tree` to explore your dependency tree + = help: the following other types implement trait `Encrypt`: + &&T + &BTreeMap + &HashMap + &JsonPlaintext + &Lent<'_, T> + &PassthroughFrame + &Protected + &ProtectedRef<'_, T> + and $N others + = note: required for `SerdeOnly` to implement `EncryptRef` + = note: required for `CipherText` to implement `EncryptTarget` + = note: 1 redundant requirement hidden + = note: required for `Target` to implement `EncryptTarget`