diff --git a/.cargo/mutants.toml b/.cargo/mutants.toml index 107f70367..1aefaca9f 100644 --- a/.cargo/mutants.toml +++ b/.cargo/mutants.toml @@ -186,6 +186,22 @@ exclude_re = [ # when they are equal `a > b` and `a >= b` return the same number. Its # other mutants stay gated. 'vitaminc-aead/src/plaintext/depth\.rs:\d+:\d+: replace > with >= in max$', + # vitaminc-normalize — equivalent. `widen_f32` builds an f64 by OR-ing bit + # fields that cannot share a set bit: complementary masks, or fields + # shifted into separate bit ranges. For two values with no common set bit, + # `a | b` equals `a ^ b`. Its other mutants stay gated. So does the `| 1` + # in `highest_set_bit`, where the two values can share a set bit. + 'vitaminc-normalize/src/scalar\.rs:\d+:\d+: replace \| with \^ in widen_f32$', + # vitaminc-normalize — equivalent. In the decimal encoder's `orderable`, + # three `|` join two values that cannot share a set bit, as in a select + # `(a & !mask) | (b & mask)`. The fourth, `x | x.wrapping_neg()`, differs + # from `^` only when `x = 2^127`, and no mantissa reaches 2^96. Its other + # mutants stay gated. + 'vitaminc-normalize/src/decimal\.rs:\d+:\d+: replace \| with \^ in orderable$', + # vitaminc-normalize — equivalent. `null` returns the one byte `0x00` in a + # protected vector. `Protected::new(vec![0])` and `Protected::from(vec![0])` + # return the same. Its other replacements stay gated. + 'vitaminc-normalize/src/scalar\.rs:\d+:\d+: replace null -> Protected> with Protected::(new|from)\(vec!\[0\]\)$', ] # Headroom over the measured baseline before a slow-but-correct mutant is diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 621d001a2..d3c64e18a 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -23,9 +23,11 @@ /languages/typescript/packages/profile/ @cipherstash/developers /languages/typescript/packages/stack-auth-wasm/ @cipherstash/developers -# vitaminc's AEAD crates, moved from cipherstash/vitaminc, and the value -# conformance corpus their tests read. Not published from here yet. +# vitaminc's AEAD crates and vitaminc-normalize, moved from +# cipherstash/vitaminc, and the value conformance corpus the AEAD crates' +# tests read. Not published from here yet. /packages/vitaminc-aead/ @cipherstash/developers /packages/recipher-frame/ @cipherstash/developers /packages/vitaminc-aead-derive/ @cipherstash/developers +/packages/vitaminc-normalize/ @cipherstash/developers /conformance/vitaminc-aead/ @cipherstash/developers diff --git a/.github/workflows/bench-eql.yml b/.github/workflows/bench-eql.yml index 6422ddb9a..8b6acdccc 100644 --- a/.github/workflows/bench-eql.yml +++ b/.github/workflows/bench-eql.yml @@ -71,6 +71,7 @@ on: - "packages/vitaminc-aead/**" - "packages/recipher-frame/**" - "packages/vitaminc-aead-derive/**" + - "packages/vitaminc-normalize/**" - "packages/stack-kms/**" - "packages/stack-auth/**" - "packages/stack-profile/**" diff --git a/.github/workflows/fuzz.yml b/.github/workflows/fuzz.yml index 7b4dbdf9e..8ba62d492 100644 --- a/.github/workflows/fuzz.yml +++ b/.github/workflows/fuzz.yml @@ -33,6 +33,7 @@ on: - packages/vitaminc-aead/** - packages/recipher-frame/** - packages/vitaminc-aead-derive/** + - packages/vitaminc-normalize/** - Cargo.toml - Cargo.lock - mise.toml diff --git a/.github/workflows/mutants.yml b/.github/workflows/mutants.yml index 5c161ebd6..685231bf8 100644 --- a/.github/workflows/mutants.yml +++ b/.github/workflows/mutants.yml @@ -5,9 +5,9 @@ name: Mutants # # Gates pull requests on mutation testing of the lines they change in # stack-auth, stack-encrypt, stack-encrypt-jsonpath (the path grammar, moved -# out of stack-encrypt), and vitaminc-aead, recipher-frame and -# vitaminc-aead-derive (imported from cipherstash/vitaminc, which gated them -# the same way). Ported from cipherstash-suite's `mutants.yml`. +# out of stack-encrypt), and vitaminc-aead, recipher-frame, +# vitaminc-aead-derive and vitaminc-normalize (imported from +# cipherstash/vitaminc, which gated them the same way). Ported from cipherstash-suite's `mutants.yml`. # # cargo-mutants rewrites small pieces of logic (flip `<` to `<=`, replace a # body with `Default::default()`) and reruns the tests; a mutant that survives @@ -40,6 +40,7 @@ on: - packages/vitaminc-aead/** - packages/recipher-frame/** - packages/vitaminc-aead-derive/** + - packages/vitaminc-normalize/** - Cargo.toml - Cargo.lock - mise.toml @@ -107,7 +108,7 @@ jobs: strategy: fail-fast: false matrix: - crate: ${{ fromJSON(github.event_name == 'pull_request' && '["all"]' || '["stack-auth","stack-encrypt","stack-encrypt-jsonpath","vitaminc-aead","recipher-frame","vitaminc-aead-derive"]') }} + crate: ${{ fromJSON(github.event_name == 'pull_request' && '["all"]' || '["stack-auth","stack-encrypt","stack-encrypt-jsonpath","vitaminc-aead","recipher-frame","vitaminc-aead-derive","vitaminc-normalize"]') }} permissions: contents: read # Posts and updates the report comment on the PR. @@ -177,7 +178,7 @@ jobs: CRATE: ${{ matrix.crate }} run: | set +e - crates=(-p stack-auth -p stack-encrypt -p stack-encrypt-jsonpath -p vitaminc-aead -p recipher-frame -p vitaminc-aead-derive) + crates=(-p stack-auth -p stack-encrypt -p stack-encrypt-jsonpath -p vitaminc-aead -p recipher-frame -p vitaminc-aead-derive -p vitaminc-normalize) if [ "$CRATE" = "all" ]; then cargo mutants --no-shuffle -vV "${crates[@]}" --in-diff pr.diff else @@ -198,7 +199,7 @@ jobs: timeout=$(count timeout.txt) { echo '' - echo "## Mutation testing (cargo-mutants, \`--in-diff\`, stack-auth, stack-encrypt, stack-encrypt-jsonpath, vitaminc-aead, recipher-frame, vitaminc-aead-derive)" + echo "## Mutation testing (cargo-mutants, \`--in-diff\`, stack-auth, stack-encrypt, stack-encrypt-jsonpath, vitaminc-aead, recipher-frame, vitaminc-aead-derive, vitaminc-normalize)" echo if [ ! -d "$out" ]; then # No output dir: either nothing to mutate (exit 0) or the run diff --git a/.github/workflows/supply-chain-vitaminc-aead.yml b/.github/workflows/supply-chain-vitaminc-aead.yml index cb2fceb8c..08d3c2ee6 100644 --- a/.github/workflows/supply-chain-vitaminc-aead.yml +++ b/.github/workflows/supply-chain-vitaminc-aead.yml @@ -1,14 +1,14 @@ name: Supply chain (vitaminc-aead) -# cargo deny and cargo vet over vitaminc-aead, recipher-frame and -# vitaminc-aead-derive and their dependency graph ONLY. Their config is -# supply-chain/vitaminc-aead/ (see its README.md). The rest of the root +# cargo deny and cargo vet over vitaminc-aead, recipher-frame, +# vitaminc-aead-derive and vitaminc-normalize, and their dependency graph +# ONLY. Their config is supply-chain/vitaminc-aead/ (see its README.md). The rest of the root # workspace is not checked by either tool; that is #1842. # # Neither tool compiles anything: both read `cargo metadata` and Cargo.lock, # so each job takes about a minute, most of it setup. # -# Pull requests that change the three crates, the lockfile or the config +# Pull requests that change the four crates, the lockfile or the config # run both jobs. The nightly schedule runs cargo deny only, on the default # branch: a RustSec advisory published against a version already in # Cargo.lock has no pull request to fail. cargo vet reads only the tree, so @@ -22,6 +22,7 @@ on: - packages/vitaminc-aead/** - packages/recipher-frame/** - packages/vitaminc-aead-derive/** + - packages/vitaminc-normalize/** - supply-chain/vitaminc-aead/** - Cargo.toml - Cargo.lock @@ -77,7 +78,7 @@ jobs: - name: cargo deny check, one crate at a time run: | status=0 - for crate in vitaminc-aead recipher-frame vitaminc-aead-derive; do + for crate in vitaminc-aead recipher-frame vitaminc-aead-derive vitaminc-normalize; do echo "::group::$crate" cargo deny --locked --config supply-chain/vitaminc-aead/deny.toml \ --manifest-path "packages/$crate/Cargo.toml" check || status=1 @@ -106,7 +107,7 @@ jobs: cache_key_prefix: mise-v1-ubuntu-2404 # The filter drops every other root workspace member, so the graph - # vetted is the three crates and their dependencies. `--locked` reads + # vetted is the four crates and their dependencies. `--locked` reads # imports.lock as committed rather than fetching the registries. - name: cargo vet id: vet diff --git a/.github/workflows/test-eql.yml b/.github/workflows/test-eql.yml index c6ea81eec..a45da10ce 100644 --- a/.github/workflows/test-eql.yml +++ b/.github/workflows/test-eql.yml @@ -105,8 +105,8 @@ on: # (`eql-bindings`' `stack-encrypt` feature): stack-encrypt, its derive # and stack-kms through `path =`, and stack-auth and stack-profile # through `workspace = true` entries the root `Cargo.toml` resolves to - # paths, and the vitaminc-aead crates through the patch table in - # packages/eql/Cargo.toml. The mise-task derivation in eql-workflow-filters.test.mjs + # paths, and the vitaminc-aead crates and vitaminc-normalize through the + # patch table in packages/eql/Cargo.toml. The mise-task derivation in eql-workflow-filters.test.mjs # cannot see them (a task body names a cargo package, not a path); the # manifest walk in eql-suite-ci.test.mjs does, and fails when one of them # is missing from this list. @@ -117,6 +117,7 @@ on: - "packages/vitaminc-aead/**" - "packages/recipher-frame/**" - "packages/vitaminc-aead-derive/**" + - "packages/vitaminc-normalize/**" - "packages/stack-kms/**" - "packages/stack-auth/**" - "packages/stack-profile/**" @@ -222,6 +223,7 @@ jobs: - "packages/vitaminc-aead/**" - "packages/recipher-frame/**" - "packages/vitaminc-aead-derive/**" + - "packages/vitaminc-normalize/**" - "packages/stack-kms/**" - "packages/stack-auth/**" - "packages/stack-profile/**" diff --git a/.github/workflows/tests-crates.yml b/.github/workflows/tests-crates.yml index 86f2ad9c3..c46231271 100644 --- a/.github/workflows/tests-crates.yml +++ b/.github/workflows/tests-crates.yml @@ -29,6 +29,7 @@ on: - packages/vitaminc-aead/** - packages/recipher-frame/** - packages/vitaminc-aead-derive/** + - packages/vitaminc-normalize/** - languages/typescript/packages/auth/** - languages/typescript/packages/profile/** - languages/typescript/packages/stack-auth-wasm/** @@ -59,6 +60,7 @@ on: - packages/vitaminc-aead/** - packages/recipher-frame/** - packages/vitaminc-aead-derive/** + - packages/vitaminc-normalize/** - languages/typescript/packages/auth/** - languages/typescript/packages/profile/** - languages/typescript/packages/stack-auth-wasm/** diff --git a/.github/workflows/tests-golang.yml b/.github/workflows/tests-golang.yml index 4b53760ef..928373684 100644 --- a/.github/workflows/tests-golang.yml +++ b/.github/workflows/tests-golang.yml @@ -48,6 +48,7 @@ on: - packages/vitaminc-aead/** - packages/recipher-frame/** - packages/vitaminc-aead-derive/** + - packages/vitaminc-normalize/** # The eql guest build links eql-bindings. - packages/eql/crates/eql-bindings/** - packages/eql/crates/eql-domains/** @@ -98,6 +99,7 @@ on: - packages/vitaminc-aead/** - packages/recipher-frame/** - packages/vitaminc-aead-derive/** + - packages/vitaminc-normalize/** # The eql guest build links eql-bindings. - packages/eql/crates/eql-bindings/** - packages/eql/crates/eql-domains/** diff --git a/.github/workflows/tests-recipher-js.yml b/.github/workflows/tests-recipher-js.yml index ef5f62a4f..ce7499ccc 100644 --- a/.github/workflows/tests-recipher-js.yml +++ b/.github/workflows/tests-recipher-js.yml @@ -29,6 +29,7 @@ on: - packages/vitaminc-aead/** - packages/recipher-frame/** - packages/vitaminc-aead-derive/** + - packages/vitaminc-normalize/** - Cargo.toml - mise.toml - pnpm-lock.yaml @@ -48,6 +49,7 @@ on: - packages/vitaminc-aead/** - packages/recipher-frame/** - packages/vitaminc-aead-derive/** + - packages/vitaminc-normalize/** - Cargo.toml - mise.toml - pnpm-lock.yaml diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 126b1dc00..904ad33e4 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -104,7 +104,9 @@ jobs: # stay in. The auth binding also compiles the vitaminc-aead # crates, through crates.io's `vitaminc` 0.10, but nothing these # jobs run reaches them: tests-crates.yml builds and tests the - # bindings and those crates when either changes. + # bindings and those crates when either changes. These jobs + # build nothing that uses vitaminc-normalize: only stack-encrypt + # reaches it. - '!languages/golang/**' - '!packages/stack-encrypt/**' - '!packages/stack-encrypt-derive/**' @@ -114,6 +116,7 @@ jobs: - '!packages/vitaminc-aead/**' - '!packages/recipher-frame/**' - '!packages/vitaminc-aead-derive/**' + - '!packages/vitaminc-normalize/**' - '!packages/stack-auth/fuzz/**' # The TypeScript SDK on Stack Encrypt. Nothing these jobs build # depends on it, and tests-recipher-js.yml runs its tests. diff --git a/.github/workflows/udeps.yml b/.github/workflows/udeps.yml index 3123e765a..e2121c7ac 100644 --- a/.github/workflows/udeps.yml +++ b/.github/workflows/udeps.yml @@ -21,6 +21,7 @@ on: - packages/vitaminc-aead/** - packages/recipher-frame/** - packages/vitaminc-aead-derive/** + - packages/vitaminc-normalize/** - languages/typescript/packages/auth/** - languages/typescript/packages/profile/** - languages/typescript/packages/stack-auth-wasm/** @@ -44,6 +45,7 @@ on: - packages/vitaminc-aead/** - packages/recipher-frame/** - packages/vitaminc-aead-derive/** + - packages/vitaminc-normalize/** - languages/typescript/packages/auth/** - languages/typescript/packages/profile/** - languages/typescript/packages/stack-auth-wasm/** diff --git a/AGENTS.md b/AGENTS.md index bc19d1955..378e35343 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -90,8 +90,9 @@ Every npm package except EQL lives under `languages/typescript/`: packages in `l EQL issues in this repository, never in the historical `cipherstash/encrypt-query-language` repository. Old upstream issue and PR links are provenance only. -- `packages/stack-auth`, `packages/stack-profile`, `packages/stack-kms`, `packages/stack-encrypt`, `packages/stack-encrypt-derive`, `packages/stack-encrypt-jsonpath`, `packages/stack-guest-abi`: The Rust crates imported from `cipherstash/cipherstash-suite` with their history, and one added here — `stack-auth` and `stack-profile` (published to crates.io, one version group), `stack-kms` (published to crates.io from 0.1.0, its own version group, re-exported by `stack-encrypt` as `stack_encrypt::kms`), `stack-encrypt` and `stack-encrypt-derive` (published to crates.io from 0.1.0, one version group; `eql-bindings`' `stack-encrypt` feature depends on them from the registry), `stack-encrypt-jsonpath` (the JSONPath grammar of the JSON index and the SQL/JSON path predicate grammar its `match` operator reads, moved out of `stack-encrypt` so the derive can check a field's declared paths, and `predicate!` a predicate's text, at compile time; in the `stack-encrypt` version group, re-exported at `stack_encrypt::json`; its first version is published by hand, as the others' were, before Trusted Publishing can take it), and `stack-guest-abi` (`publish = false`). They are the members of the **root Cargo workspace**, with the three AEAD crates and the three node binding crates below. See "Working on the Rust crates". +- `packages/stack-auth`, `packages/stack-profile`, `packages/stack-kms`, `packages/stack-encrypt`, `packages/stack-encrypt-derive`, `packages/stack-encrypt-jsonpath`, `packages/stack-guest-abi`: The Rust crates imported from `cipherstash/cipherstash-suite` with their history, and one added here — `stack-auth` and `stack-profile` (published to crates.io, one version group), `stack-kms` (published to crates.io from 0.1.0, its own version group, re-exported by `stack-encrypt` as `stack_encrypt::kms`), `stack-encrypt` and `stack-encrypt-derive` (published to crates.io from 0.1.0, one version group; `eql-bindings`' `stack-encrypt` feature depends on them from the registry), `stack-encrypt-jsonpath` (the JSONPath grammar of the JSON index and the SQL/JSON path predicate grammar its `match` operator reads, moved out of `stack-encrypt` so the derive can check a field's declared paths, and `predicate!` a predicate's text, at compile time; in the `stack-encrypt` version group, re-exported at `stack_encrypt::json`; its first version is published by hand, as the others' were, before Trusted Publishing can take it), and `stack-guest-abi` (`publish = false`). They are the members of the **root Cargo workspace**, with the three AEAD crates, `vitaminc-normalize` and the three node binding crates below. See "Working on the Rust crates". - `packages/vitaminc-aead`, `packages/recipher-frame`, `packages/vitaminc-aead-derive`: vitaminc's AEAD crates, imported from `cipherstash/vitaminc` with their history at the code of their crates.io 0.10.0 release (`docs/plans/2026-11-14-move-vitaminc-aead-into-the-stack.md`). They define the value types Stack Encrypt seals, the transport frame and storage profile (`recipher-frame`, whose storage corpus is `testdata/storage-v1.json`), and the derive macros. `vitaminc-aead` and `vitaminc-aead-derive` keep their crates.io names, because vitaminc crates that stay on crates.io depend on `vitaminc-aead`; the frame crate was `vitaminc-aead-frame` and is now `recipher-frame`, since only crates here depend on it. All three keep the MIT licence, are members of the root workspace, and are `publish = false` with `release = false` in `release-plz.toml`: crates.io's 0.10.0 was published from vitaminc, and they publish from here only before the next `stack-encrypt` release. Every Cargo workspace that resolves `vitaminc-aead` carries a `[patch.crates-io]` table pointing at these copies (see "Working on the Rust crates"). The cross-language value conformance corpus their tests read is `conformance/vitaminc-aead/value-conformance.json`. vitaminc's checks on them run here: the storage corpus append-only check (`storage-corpus.yml`), the Kani proofs of the storage reader (`kani.yml`), `cargo deny` and `cargo vet` over their dependency graph only (`supply-chain-vitaminc-aead.yml`, config in `supply-chain/vitaminc-aead/`; the rest of the workspace is #1842), and mutation testing (`mutants.yml`). See "Working on the Rust crates". +- `packages/vitaminc-normalize`: vitaminc's equality normalization crate, imported from `cipherstash/vitaminc` with its history at the code of its crates.io 0.10.0 release, the way the AEAD crates were. It gives each scalar kind that can be indexed for equality a domain label and the bytes an equality term is derived from. `stack-encrypt`'s equality index uses it, and so do `vitaminc-prf` (its `normalize` feature) and `vitaminc-ore`. It keeps its crates.io name, because `vitaminc-prf` and `vitaminc-ore` stay on crates.io and depend on it. It keeps the MIT licence. It is a member of the root workspace. It is `publish = false`, with `release = false` in `release-plz.toml`. Every Cargo workspace that resolves `vitaminc-normalize` lists it in its `[patch.crates-io]` table. Its tests, rustdoc and the mutants gate run here as for the AEAD crates. `supply-chain-vitaminc-aead.yml` does not check it as a crate of its own yet. See "Working on the Rust crates". - `languages/typescript/packages/auth`, `languages/typescript/packages/profile`, `languages/typescript/packages/stack-auth-wasm`: The node bindings of those crates. `@cipherstash/auth` (napi-rs v2) and its six `platforms/*` packages are published to npm from this repository by `release.yml` (`auth-artifacts`, `publish-auth`); a change to what it ships, the `stack-auth` crate included, needs an `@cipherstash/auth` changeset (`require-auth-npm-changeset.yml`). `@cipherstash/profile` and its platforms are private and never published; `@cipherstash/stack-auth-wasm` is private and builds the wasm that `@cipherstash/auth` ships. Their `build` and `test` scripts never invoke cargo; `build:native`, `build:debug` and `test:cargo` do. `@cipherstash/auth` also ships two pure-JS framework adapters over the wasm `OidcFederationStrategy`: `./next` (Next.js App Router, hands the token to the render on a request header) and `./start` (TanStack Start: `csFederateCurrent` is called inside a function middleware the app declares itself, which hands the token to the server function through `next({ context })`; `@tanstack/react-start` is an optional peer loaded only by that entry). - `languages/typescript/packages/recipher-js`: `@cipherstash/recipher`, the TypeScript SDK on the Stack Encrypt engine (design: `docs/plans/2026-11-22-recipher-typescript-sdk.md`). **Private and unpublished**: it has no platform packages and no release job yet, so it must stay `"private": true` (a public manifest would be published by `changeset publish` on merge) and takes no changeset. Its Rust is **two crates** in a **detached Cargo workspace** with its own `Cargo.lock`. The root workspace names its members, so it needs no `exclude` entry there; leave the root `Cargo.toml` alone, because a change to it starts every stack-* crate workflow. The two crates: `crate/` (crate `recipher-js`, napi-rs 3), which defines the `Cipher`, `Keyset`, `Ciphertext`, and `Json` classes the package exports, runs every operation through the engine, and reads and builds JavaScript values only through the value bridge beside it, `value-napi/` (crate `recipher-value-napi`, a copy of vitaminc's `vitaminc-aead-napi` 0.10.0, unpublished, with a detached test addon workspace of its own at `value-napi/tests/addon` and vitaminc's value conformance corpus at `value-napi/tests/testdata`; Biome does not check that directory). The bridge converts JSON documents too. `JsRef::to_json` writes a JavaScript value as a document's JSON text, with the JavaScript number rules. `JsBuilder::build_json` builds a decrypted document. The addon's `json.rs` contains only the `Json` class, and passes the text to the engine's `JsonPlaintext`. A test fails if it links `eql-bindings` or reaches the engine's `test-support` with its default features. `@napi-rs/cli` v3 builds it (`build:debug`, `build:native`) and writes its generated TypeScript declarations to the committed `native.d.ts`; CI fails when the build changes that file. Each native method returns the package's `Result` itself, and its public signature is written in Rust (napi-rs's `ts_type`, `ts_args_type` and `ts_return_type` attributes, with `native-header.d.ts` as the generated file's header), so `native.d.ts` is the public type: never add a TypeScript wrapper or hand-written interface over a native class. The TypeScript (`src/`) contains only `Result`, `RecipherError`, the loader, stand-ins for a build that did not load, and the types that the generated signatures name. The loader is `src/binding.ts`. The loader gives the addon the `Ok`, `Err`, and `RecipherError` classes. The types are in `src/kinds.ts` and `src/value-types.ts`. `native.d.ts` imports those types, so a module that `native.d.ts` imports from must never load the addon. If one did, the declarations would import themselves. The declaration build of tsup would then fail. Two kinds of call throw: a method called without its object (#1801), and `new` on a class whose type has no constructor (`Cipher`, `Keyset`, `Ciphertext`, and the wrapper classes, which an application makes with `RcDate.from(text)` and the like, each returning a `Result`). Every other call returns or resolves to a `Result`. Its `build` (tsup) and `test` (the suites in `__tests__/unit` and `tsc` over `src`, the tests and `type-tests`) never run cargo; `build:debug` (the addon with the deterministic test cipher behind `@cipherstash/recipher/testing`), `build:native`, `test:addon` (the suites that load `recipher.node`) and `test:cargo` do. `.github/workflows/tests-recipher-js.yml` runs all four, and fmt and clippy over the value bridge's test addon by its manifest: `tests.yml`'s live jobs skip a change that touches only this package, so apart from that file's ungated lint and repo checks it is the only workflow such a change runs. One Dependabot cargo entry covers both lockfiles, and `scripts/__tests__/recipher-js-lock-parity.test.mjs` fails when they resolve different napi or vitaminc crates. - `languages/golang`: The Go module — the SDK `encrypt` with its generated-code support `encrypt/gensupport`, its test package `encrypt/encrypttest` (context assertions, and `NewClient`: an offline client over the deterministic test builds, for an application's tests; a **nested Go module** of its own, so only a program that imports it downloads those builds, requiring the SDK at the zero pseudo-version with `replace ../..` in the tree, and `NewClient` fails when the two are at different versions) the policy packages `encrypt/policy` and `encrypt/policy/protosource`; the frame codec `encrypt/frame` and its value types `encrypt/value`; the credential package `auth`; the generator `stashgen` and its command `cmd/stashgen`; and `internal` (the shared guest plumbing, the `record` wire model, and `wasmtestrun`, the wazero runner that `wasm:auth-guest:test` runs the auth guest's wasm32 tests under). `encrypt/frame` encodes and decodes the bytes that the Go module exchanges with its guests, and the storage profile; it was vitaminc's Go package `vcffi`. `encrypt/value` declares the value types that the codec reads and writes (`Date`, `Decimal`, `Int128`, `Uint128`, `UUID`, `Object` and the rest); it was vitaminc's `vcvalue`, and imports nothing outside the standard library. `encrypt` names those types with aliases (`encrypt.Date` is `value.Date`), and `encrypt.Encryptable` and `encrypt.Encoder` are aliases of `frame`'s. The Rust crate `recipher-frame` implements the same encodings. The tests of `encrypt/frame` check it against `conformance/vitaminc-aead/value-conformance.json` and `packages/recipher-frame/testdata/storage-v1.json`. A wazero host with no cgo. Its two WASI guests (`encrypt/guest`, `auth/guest`) are detached Cargo workspaces built by `mise run wasm:guest:build` and `mise run wasm:auth-guest:build`; `mise run wasm:guest:build:deterministic` and `wasm:guest:build:eql:deterministic` build the seeded TEST builds into `encrypt/encrypttest/wasm`, which `encrypttest` embeds and the hermetic Go tests read; the `.wasm` files are gitignored. The stack-encrypt guest has a second build with the EQL types (`mise run wasm:guest:build:eql`, cargo feature `eql`, linking `eql-bindings` by path; `wasm:guest:build:eql:deterministic` is its test build), embedded by `encrypt/eql` and registered on import, so a program whose generated code names an EQL type runs it (ADR-0007, amended). `encrypt/eql`'s types and `Types` table are generated from the EQL catalog by `eql-codegen` (`eql_gen.go`, written by `mise run types:generate` in `packages/eql` and drift-gated by `types:check` and `cargo test -p eql-codegen`). Generated `*_stash.go` files are committed and CI fails when `go generate ./...` changes one. Releases are cut by hand with `.github/workflows/release-golang.yml` (`gh workflow run release-golang.yml -f version=X.Y.Z[-pre] --ref `): because the guests are gitignored on main and Go fetches a version as the files committed at its tag, the workflow builds them, commits them on a release-only commit no branch points at, with `encrypt/encrypttest/go.mod` pinned to the SDK version by `scripts/go-release-pin-encrypttest.sh` (run in `build` and in `publish`), tags it `languages/golang/vX.Y.Z` and `languages/golang/encrypt/encrypttest/vX.Y.Z` (the workflow's `MODULES`) and pushes the tags alone, then attaches the EQL v4 SQL bundle to the GitHub release. The ref must carry the EQL v4 bundle, or the build stops at "Build the EQL SQL bundles". `scripts/go-release-version.mjs` refuses, before anything is built, every version Go would refuse (non-canonical semver, `+build` metadata, a v2+ major on a module path with no `/vN` suffix, a version shaped like a pseudo-version), and a final version dispatched from anywhere but `main`. A pre-release may come from a branch. The build job also refuses a version the Go proxy already lists in `@v/list`, which catches a tag deleted after the proxy fetched it; it never asks the proxy for the version itself before the tag exists, because the proxy would cache "not found" for up to 30 minutes and `verify` would fail after the push. The build checks the `Cargo.lock` of the EQL workspace and both guest workspaces with `--locked` first, since none of those builds passes it. It runs in a job with no write token and hands the guests to a `publish` job that holds `contents: write` and runs only git and gh. `publish` fetches the commit with plain unauthenticated git rather than `actions/checkout`, whose `token` input defaults to the job's writable token, and refuses a release commit whose tree is not the one the build tested. `publish` takes the paths it commits from the workflow's fixed `GUESTS` list, never from the artifact, and refuses a `guests.sha256` that is not exactly one SHA-256 line for each of those five guests (the three production guests and the two test builds `encrypttest` embeds): the build job runs third-party code after writing that manifest, so a path read from it could put any file on the tag (`scripts/__tests__/go-release-artifact.test.mjs`). The release page's notes are the version's `## [X.Y.Z]` section of `languages/golang/CHANGELOG.md`, taken by `scripts/go-release-notes.mjs` in a `notes` job that runs no third-party code and that `build` waits for: a version with no section, or an empty one, is refused before anything is built, so write the section before dispatching. A version is immutable once the Go proxy has fetched it, so a tag is never moved or deleted: if `publish` or `verify` fails after the tag is pushed, use "Re-run failed jobs" on the same run, which keeps a tag that run pushed and creates or completes the release; a new dispatch of the same version is refused. Never tag a main commit by hand: `go get` would fetch a module with no guests. `encrypt/example` is a third nested module, never tagged: it requires both modules as an application does. `examples/s3` is a fourth, also never tagged: it encrypts S3 object bodies with a plain `encrypt` field through the AWS SDK for Go v2, and `mise run go:example:s3` runs its tests end to end against S3Mock in Docker (they skip in CI, which has no bucket). `./...` stops at a nested module, so `scripts/go-binding-test.sh`, `go:lint` and the generated-code check find each `go.mod` and run in its directory. @@ -748,32 +749,35 @@ requirements, because the published `stack-auth` inherits them, and an exact pin would stop the suite sharing one `cts-common` with it. vitaminc's AEAD crates (`vitaminc-aead`, `recipher-frame`, -`vitaminc-aead-derive`) live here, in `packages/`, and are not published from -here yet. The AES-256-GCM cipher is in `vitaminc-aead`, behind its `aes` -feature, so nothing here uses `vitaminc-encrypt` 0.10. The other vitaminc -crates come from crates.io at 0.10, and three of them depend on -`vitaminc-aead`: `vitaminc-normalize`, `vitaminc-prf` and `vitaminc-ore`, -with the `vitaminc` umbrella crate, `clww-ore` and `ore-rs` above them. So every Cargo workspace that resolves -`vitaminc-aead` 0.10 carries a `[patch.crates-io]` table, with relative paths, -that makes those crates build against the copies here. A workspace must have -exactly one `vitaminc-aead` 0.10, and it must be the path crate: check with -`cargo tree -i vitaminc-aead@0.10.0`. A new workspace that resolves it needs the -same table. The patch covers the 0.10 line only, so the `vitaminc-aead` 0.5.1 -that `cts-common` reaches through `vitaminc` 0.5.1 still comes from crates.io, -and a change to these crates must keep their version on 0.10 until they are -published from here. +`vitaminc-aead-derive`) and `vitaminc-normalize` live here, in `packages/`, +and are not published from here yet. The AES-256-GCM cipher is in +`vitaminc-aead`, behind its `aes` feature, so nothing here uses +`vitaminc-encrypt` 0.10. The other vitaminc crates come from crates.io at +0.10. Two of them depend on both `vitaminc-aead` and `vitaminc-normalize`: +`vitaminc-prf` and `vitaminc-ore`. The `vitaminc` umbrella crate, `clww-ore` +and `ore-rs` build on those two. So every Cargo workspace that resolves +`vitaminc-aead` 0.10 or `vitaminc-normalize` 0.10 has a `[patch.crates-io]` +table. Its relative paths make those crates build against the copies here. A +workspace must have exactly one of each at 0.10: the path crate. Check with +`cargo tree -i vitaminc-aead@0.10.0` and +`cargo tree -i vitaminc-normalize@0.10.0`. A new workspace that resolves +either needs the same table. The patch covers the 0.10 line only, so the +`vitaminc-aead` 0.5.1 that `cts-common` reaches through `vitaminc` 0.5.1 still +comes from crates.io. A change to these crates must keep their version on +0.10 until they are published from here. `cargo publish` drops `[patch]` tables, so a crate published from here (`stack-encrypt`, `stack-kms`, `stack-auth`) depends on crates.io's -`vitaminc-aead` 0.10.x, not on the copies. A change made in the copies +`vitaminc-aead` 0.10.x and `vitaminc-normalize` 0.10.x, not on the copies. A change made in the copies reaches a published crate only once the copies are published from here, which the plan schedules before the next `stack-encrypt` release. - **Three Cargo workspaces, not one.** The root workspace (the seven stack-* - crates, the three AEAD crates and the three node binding crates), - protect-ffi's and EQL's. The root `Cargo.toml` excludes the other two. EQL's - patches `vitaminc-aead` to the copies here, as the root does; protect-ffi's - resolves no `vitaminc-aead` 0.10. The + crates, the three AEAD crates, `vitaminc-normalize` and the three node + binding crates), protect-ffi's and EQL's. The root `Cargo.toml` excludes the + other two. EQL's patches `vitaminc-aead` and `vitaminc-normalize` to the + copies here, as the root does; protect-ffi's resolves no `vitaminc-aead` + 0.10. The TypeScript SDK's crates (`languages/typescript/packages/recipher-js`, napi-rs 3: the addon `crate` and the value bridge `value-napi`) are a detached workspace too, with its own `Cargo.lock`, depending on stack-encrypt by path. The value @@ -854,6 +858,8 @@ those when the AEAD crates change. Go fuzzes the decoders of its frame codec with three targets in `languages/golang/encrypt/frame`: `FuzzUnmarshal`, `FuzzUnmarshalCipherText`, and `FuzzUnmarshalStorage`. `go test` replays their seeds, and the nightly `go-fuzz-campaign` job fuzzes them. +`vitaminc-normalize` has no fuzz targets either, and `fuzz.yml` replays +stack-encrypt's targets when it changes too. Full walkthrough — layout, adding a target, the CI split — in [`docs/fuzzing.md`](docs/fuzzing.md). For cargo-fuzz mechanics (sanitizers, corpus, crash triage) use the Trail of Bits `cargo-fuzz` skill rather than a @@ -881,10 +887,10 @@ transport's response reclaim). Its hostile-input behaviour is pinned from the Go side (`mise run go:test`). Keep new pointer handling in `stack-guest-abi`, where Miri reaches it, not in a guest. -Miri and the sanitizers do not run on the AEAD crates. All three -`#![deny(unsafe_code)]`, and vitaminc ran neither on them: it ran both on -`vitaminc-protected`, which has the `unsafe` and stays in vitaminc. A crate -that adds `unsafe` needs both. +Miri and the sanitizers do not run on the AEAD crates or on +`vitaminc-normalize`. All four `#![deny(unsafe_code)]`. vitaminc ran neither +on them. It ran both on `vitaminc-protected`, the crate with the `unsafe` +code. That crate stays in vitaminc. A crate that adds `unsafe` needs both. ### Kani @@ -906,8 +912,8 @@ not `mise.test.toml`, so no other job installs it. ### Mutation testing The crates that opt in (stack-auth, stack-encrypt, stack-encrypt-jsonpath, -vitaminc-aead, recipher-frame, vitaminc-aead-derive) are mutation-tested -with cargo-mutants; config in `.cargo/mutants.toml`. CI (`mutants.yml`) +vitaminc-aead, recipher-frame, vitaminc-aead-derive, vitaminc-normalize) are +mutation-tested with cargo-mutants; config in `.cargo/mutants.toml`. CI (`mutants.yml`) gates every PR touching them with `--in-diff`: only the lines the PR changes are mutated, and a surviving mutant fails the job. For now the gate runs only on a pull request into main, and not on the release pull request. #2017 turns it diff --git a/Cargo.lock b/Cargo.lock index 058bba2b4..32e72147a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2482,6 +2482,15 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe" +[[package]] +name = "orderable-bytes" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c7d30b72ffca73d9936fe5fc80a9c9520c73f5b4f64839a810211903d5ace3c" +dependencies = [ + "rust_decimal", +] + [[package]] name = "ore-rs" version = "0.12.0" @@ -4013,18 +4022,9 @@ dependencies = [ [[package]] name = "tinyvec" -version = "1.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bfa5fdc3bce6191a1dbc8c02d5c8bffcf557bafa17c124c5264a458f1b0613fa" -dependencies = [ - "tinyvec_macros", -] - -[[package]] -name = "tinyvec_macros" -version = "0.1.1" +version = "1.13.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" [[package]] name = "tokio" @@ -4643,12 +4643,17 @@ dependencies = [ [[package]] name = "vitaminc-normalize" version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e333da8bb30eab39cc2c790cb860843229a0a06aefb807f4ce069a92a2e17e8d" dependencies = [ + "futures-executor", + "jiff", + "orderable-bytes", + "quickcheck", + "quickcheck_macros", + "rust_decimal", "thiserror 2.0.18", "unicode-general-category", "unicode-normalization", + "uuid", "vitaminc-aead 0.10.0", "vitaminc-protected 0.10.0", ] diff --git a/Cargo.toml b/Cargo.toml index 98419fe3a..9c54adb14 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -2,11 +2,12 @@ resolver = "2" # The stack-* crates imported from cipherstash-suite, the three node bindings -# that wrap them, and the three AEAD crates moved from cipherstash/vitaminc. +# that wrap them, and the crates moved from cipherstash/vitaminc: the three +# AEAD crates and vitaminc-normalize. # The root is one of three Cargo workspaces in this repository: EQL and -# protect-ffi keep their own (see `exclude`). EQL patches vitaminc-aead to the -# copies here, as this workspace does; protect-ffi resolves no vitaminc-aead -# 0.10. +# protect-ffi keep their own (see `exclude`). EQL patches vitaminc-aead and +# vitaminc-normalize to the copies here, as this workspace does. protect-ffi +# resolves no vitaminc-aead 0.10. members = [ "packages/stack-auth", "packages/stack-profile", @@ -23,6 +24,10 @@ members = [ "packages/vitaminc-aead", "packages/recipher-frame", "packages/vitaminc-aead-derive", + # Moved from cipherstash/vitaminc after the AEAD crates. It keeps its + # crates.io name, and is not published from here yet; see the patch table + # at the end. + "packages/vitaminc-normalize", "languages/typescript/packages/auth", "languages/typescript/packages/profile", "languages/typescript/packages/stack-auth-wasm", @@ -164,24 +169,29 @@ vitaminc-aead = { path = "./packages/vitaminc-aead", version = "0.10.0" } recipher-frame = { path = "./packages/recipher-frame", version = "0.10.0" } vitaminc-hmac = "0.10.0" # Normalized equality terms (Unicode 16 NFC text, one integer encoding for -# every width), which `vitaminc-prf`'s `normalize` feature derives over. -vitaminc-normalize = "0.10.0" +# every width). `vitaminc-prf`'s `normalize` feature derives over them. The +# crate is in this repository (packages/vitaminc-normalize). +vitaminc-normalize = { path = "./packages/vitaminc-normalize", version = "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 = { version = "0.10.0", features = ["prf"] } vitaminc-prf = { version = "0.10.0", features = ["normalize"] } vitaminc-protected = "0.10.0" -# vitaminc-aead and vitaminc-aead-derive moved here from cipherstash/vitaminc -# and are not published from here yet. The vitaminc crates that stay on -# crates.io (the `vitaminc` umbrella, vitaminc-normalize, -prf, -ore and -# -encrypt) and the order schemes clww-ore and ore-rs depend on vitaminc-aead -# 0.10. This table makes -# them build against the copy here, so the build has one vitaminc-aead 0.10, -# and its types are the ones stack-encrypt passes into them. It applies only -# to the 0.10 line: the vitaminc-aead 0.5.1 that cts-common reaches through -# vitaminc 0.5.1 still comes from crates.io. Every other workspace that -# resolves these crates carries the same table. +# vitaminc-aead, vitaminc-aead-derive and vitaminc-normalize moved here from +# cipherstash/vitaminc. They are not published from here yet. Crates from +# crates.io depend on them at 0.10: +# - vitaminc-aead: the `vitaminc` umbrella, vitaminc-prf and vitaminc-ore; +# - vitaminc-normalize: vitaminc-prf (its `normalize` feature) and +# vitaminc-ore. +# The order schemes clww-ore and ore-rs depend on vitaminc-prf and +# vitaminc-ore. This table makes all of them build against the copies here. +# So the build has one vitaminc-aead 0.10 and one vitaminc-normalize 0.10. +# Their types are the ones stack-encrypt passes into those crates. The table +# applies only to the 0.10 line. The vitaminc-aead 0.5.1 that cts-common +# reaches through vitaminc 0.5.1 still comes from crates.io. Every other +# workspace that resolves these crates has the same table. [patch.crates-io] vitaminc-aead = { path = "./packages/vitaminc-aead" } vitaminc-aead-derive = { path = "./packages/vitaminc-aead-derive" } +vitaminc-normalize = { path = "./packages/vitaminc-normalize" } diff --git a/SECURITY.md b/SECURITY.md index b037162ea..5b0fb7540 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -54,6 +54,17 @@ and 0.2.0-pre that some builds still reach come from crates.io. The three crates are licensed under MIT, and are in scope for security reports on the same terms as the npm packages above. +The source of a fourth crate, **`vitaminc-normalize`** +(`packages/vitaminc-normalize`), moved from `cipherstash/vitaminc` in the +same way. It derives the bytes an equality term is computed from. Its +crates.io releases up to 0.10.0 were published from `cipherstash/vitaminc`. +Every build made from this repository that uses `vitaminc-normalize` 0.10 +uses the copy here. A `stack-encrypt` from crates.io uses the crates.io +release, because `cargo publish` drops the patch that selects the copy. + +`vitaminc-normalize` is licensed under MIT. It is in scope for security +reports on the same terms as the npm packages above. + The `encrypttest` module ships test builds of the engine whose keys derive from a published seed. Those keys are not secret by design: the package is for tests only. A way for a production client to load diff --git a/docs/plans/2026-11-14-move-vitaminc-aead-into-the-stack.md b/docs/plans/2026-11-14-move-vitaminc-aead-into-the-stack.md index b506093cc..a79df9408 100644 --- a/docs/plans/2026-11-14-move-vitaminc-aead-into-the-stack.md +++ b/docs/plans/2026-11-14-move-vitaminc-aead-into-the-stack.md @@ -141,8 +141,10 @@ copy of `vitaminc-aead-napi` 0.10.0, and depends only on `vitaminc-aead` and - **Stays, and does not depend on the AEAD crates:** `vitaminc-context` (`vitaminc-aead` depends on it), `vitaminc-hmac` (it depends on `vitaminc-prf`), `vitaminc-traits`, and the rest. -- **Stays for now, and depends on `vitaminc-aead`:** `vitaminc-normalize`, - `vitaminc-prf`, `vitaminc-ore`, `vitaminc-encrypt`. See the next section. +- **Stays for now, and depends on `vitaminc-aead`:** `vitaminc-prf`, + `vitaminc-ore`, `vitaminc-encrypt`. See the next section. +- **Moved after this plan was written:** `vitaminc-normalize`, in #2052, + in the same way as the AEAD crates. It depends on `vitaminc-aead` too. `clww-ore` and `ore-rs` stay in `cipherstash/ore.rs`. diff --git a/languages/golang/encrypt/guest/Cargo.lock b/languages/golang/encrypt/guest/Cargo.lock index a5a75f311..d2f057893 100644 --- a/languages/golang/encrypt/guest/Cargo.lock +++ b/languages/golang/encrypt/guest/Cargo.lock @@ -2945,8 +2945,6 @@ dependencies = [ [[package]] name = "vitaminc-normalize" version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e333da8bb30eab39cc2c790cb860843229a0a06aefb807f4ce069a92a2e17e8d" dependencies = [ "thiserror 2.0.20", "unicode-general-category", diff --git a/languages/golang/encrypt/guest/Cargo.toml b/languages/golang/encrypt/guest/Cargo.toml index 0021505b3..d47d9d8af 100644 --- a/languages/golang/encrypt/guest/Cargo.toml +++ b/languages/golang/encrypt/guest/Cargo.toml @@ -98,9 +98,10 @@ opt-level = 3 lto = true strip = true -# vitaminc-aead 0.10 and its sibling crates live in this repository and are -# not published from here yet. Build against the copies, as the root -# workspace does (see its [patch.crates-io]). +# vitaminc-aead 0.10, its sibling crates and vitaminc-normalize 0.10 are in +# this repository. They are not published from here yet. Build against the +# copies, as the root workspace does (see its [patch.crates-io]). [patch.crates-io] vitaminc-aead = { path = "../../../../packages/vitaminc-aead" } vitaminc-aead-derive = { path = "../../../../packages/vitaminc-aead-derive" } +vitaminc-normalize = { path = "../../../../packages/vitaminc-normalize" } diff --git a/languages/typescript/packages/recipher-js/Cargo.lock b/languages/typescript/packages/recipher-js/Cargo.lock index e538eb4b4..a6965d0f5 100644 --- a/languages/typescript/packages/recipher-js/Cargo.lock +++ b/languages/typescript/packages/recipher-js/Cargo.lock @@ -3866,8 +3866,6 @@ dependencies = [ [[package]] name = "vitaminc-normalize" version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e333da8bb30eab39cc2c790cb860843229a0a06aefb807f4ce069a92a2e17e8d" dependencies = [ "thiserror 2.0.21", "unicode-general-category", diff --git a/languages/typescript/packages/recipher-js/Cargo.toml b/languages/typescript/packages/recipher-js/Cargo.toml index 85f4883f8..53ce0f90a 100644 --- a/languages/typescript/packages/recipher-js/Cargo.toml +++ b/languages/typescript/packages/recipher-js/Cargo.toml @@ -21,9 +21,10 @@ members = ["crate", "value-napi"] edition = "2021" repository = "https://github.com/cipherstash/stack" -# vitaminc-aead 0.10 and its sibling crates live in this repository and are -# not published from here yet. Build against the copies, as the root -# workspace does (see its [patch.crates-io]). +# vitaminc-aead 0.10, its sibling crates and vitaminc-normalize 0.10 are in +# this repository. They are not published from here yet. Build against the +# copies, as the root workspace does (see its [patch.crates-io]). [patch.crates-io] vitaminc-aead = { path = "../../../../packages/vitaminc-aead" } vitaminc-aead-derive = { path = "../../../../packages/vitaminc-aead-derive" } +vitaminc-normalize = { path = "../../../../packages/vitaminc-normalize" } diff --git a/mise.toml b/mise.toml index 5b4c2fdbb..cad9cf047 100644 --- a/mise.toml +++ b/mise.toml @@ -1,6 +1,7 @@ # The repository root is the root of the Rust and Go toolchains: the Cargo -# workspace in Cargo.toml (the stack-* crates, the three AEAD crates moved from -# vitaminc, and the three node bindings) and the Go module in languages/golang. +# workspace in Cargo.toml (the stack-* crates, the three AEAD crates and +# vitaminc-normalize moved from vitaminc, and the three node bindings) and the +# Go module in languages/golang. # # EQL (packages/eql) and protect-ffi (languages/typescript/packages/protect-ffi) # keep their own mise.toml. A tool they pin there overrides the pin here, in @@ -17,6 +18,7 @@ includes = [ "packages/vitaminc-aead/tasks.toml", "packages/recipher-frame/tasks.toml", "packages/vitaminc-aead-derive/tasks.toml", + "packages/vitaminc-normalize/tasks.toml", ] [tools] diff --git a/packages/eql/Cargo.lock b/packages/eql/Cargo.lock index 3aa6c47bf..6f5090a8b 100644 --- a/packages/eql/Cargo.lock +++ b/packages/eql/Cargo.lock @@ -5181,8 +5181,6 @@ dependencies = [ [[package]] name = "vitaminc-normalize" version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e333da8bb30eab39cc2c790cb860843229a0a06aefb807f4ce069a92a2e17e8d" dependencies = [ "thiserror 2.0.20", "unicode-general-category", diff --git a/packages/eql/Cargo.toml b/packages/eql/Cargo.toml index 72314769c..c697cf246 100644 --- a/packages/eql/Cargo.toml +++ b/packages/eql/Cargo.toml @@ -36,9 +36,10 @@ default-members = ["tests/sqlx"] dead_code = "deny" unused_imports = "deny" -# vitaminc-aead 0.10 and its sibling crates live in this repository and are -# not published from here yet. Build against the copies, as the root -# workspace does (see its [patch.crates-io]). +# vitaminc-aead 0.10, its sibling crates and vitaminc-normalize 0.10 are in +# this repository. They are not published from here yet. Build against the +# copies, as the root workspace does (see its [patch.crates-io]). [patch.crates-io] vitaminc-aead = { path = "../vitaminc-aead" } vitaminc-aead-derive = { path = "../vitaminc-aead-derive" } +vitaminc-normalize = { path = "../vitaminc-normalize" } diff --git a/packages/eql/tests/timing/ore_block_v2/ctgen/Cargo.lock b/packages/eql/tests/timing/ore_block_v2/ctgen/Cargo.lock index 02b9d1d35..532286039 100644 --- a/packages/eql/tests/timing/ore_block_v2/ctgen/Cargo.lock +++ b/packages/eql/tests/timing/ore_block_v2/ctgen/Cargo.lock @@ -791,8 +791,6 @@ dependencies = [ [[package]] name = "vitaminc-normalize" version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e333da8bb30eab39cc2c790cb860843229a0a06aefb807f4ce069a92a2e17e8d" dependencies = [ "thiserror 2.0.21", "unicode-general-category", diff --git a/packages/eql/tests/timing/ore_block_v2/ctgen/Cargo.toml b/packages/eql/tests/timing/ore_block_v2/ctgen/Cargo.toml index c6d868b09..4b3335898 100644 --- a/packages/eql/tests/timing/ore_block_v2/ctgen/Cargo.toml +++ b/packages/eql/tests/timing/ore_block_v2/ctgen/Cargo.toml @@ -24,9 +24,10 @@ hex = "0.4" [workspace] -# vitaminc-aead 0.10 and its sibling crates live in this repository and are -# not published from here yet. Build against the copies, as the root -# workspace does (see its [patch.crates-io]). +# vitaminc-aead 0.10, its sibling crates and vitaminc-normalize 0.10 are in +# this repository. They are not published from here yet. Build against the +# copies, as the root workspace does (see its [patch.crates-io]). [patch.crates-io] vitaminc-aead = { path = "../../../../../vitaminc-aead" } vitaminc-aead-derive = { path = "../../../../../vitaminc-aead-derive" } +vitaminc-normalize = { path = "../../../../../vitaminc-normalize" } diff --git a/packages/stack-encrypt/fuzz/Cargo.lock b/packages/stack-encrypt/fuzz/Cargo.lock index 6dfb2e63f..cee91dc55 100644 --- a/packages/stack-encrypt/fuzz/Cargo.lock +++ b/packages/stack-encrypt/fuzz/Cargo.lock @@ -2833,8 +2833,6 @@ dependencies = [ [[package]] name = "vitaminc-normalize" version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e333da8bb30eab39cc2c790cb860843229a0a06aefb807f4ce069a92a2e17e8d" dependencies = [ "thiserror 2.0.18", "unicode-general-category", diff --git a/packages/stack-encrypt/fuzz/Cargo.toml b/packages/stack-encrypt/fuzz/Cargo.toml index e91082049..c2fc6a885 100644 --- a/packages/stack-encrypt/fuzz/Cargo.toml +++ b/packages/stack-encrypt/fuzz/Cargo.toml @@ -83,9 +83,10 @@ bench = false [workspace] resolver = "2" -# vitaminc-aead 0.10 and its sibling crates live in this repository and are -# not published from here yet. Build against the copies, as the root -# workspace does (see its [patch.crates-io]). +# vitaminc-aead 0.10, its sibling crates and vitaminc-normalize 0.10 are in +# this repository. They are not published from here yet. Build against the +# copies, as the root workspace does (see its [patch.crates-io]). [patch.crates-io] vitaminc-aead = { path = "../../vitaminc-aead" } vitaminc-aead-derive = { path = "../../vitaminc-aead-derive" } +vitaminc-normalize = { path = "../../vitaminc-normalize" } diff --git a/packages/vitaminc-normalize/CHANGELOG.md b/packages/vitaminc-normalize/CHANGELOG.md new file mode 100644 index 000000000..65c6bf184 --- /dev/null +++ b/packages/vitaminc-normalize/CHANGELOG.md @@ -0,0 +1,72 @@ + +## [0.10.0] - 2026-11-19 + +### Index terms + +- Index terms for every value in the supported range are the same as in 0.9.1. + +### Breaking + +- **Breaking:** a date or timestamp outside years -9999 to 9999 no longer has an index term. + In 0.9.1, the range was years -262143 to 262142. + The 0.10.0 changelog for `vitaminc-aead` gives the exact limits. + +## [0.9.1] - 2026-11-06 + +## [0.9.0] - 2026-11-04 + +### Breaking + +- **Breaking:** the crate now needs Rust 1.89 or later. + Version 0.8.1 needed Rust 1.88. + +### Fixes + +- Normalizing an integer or a timestamp no longer passes the value through a stack slot that is not wiped. + The `vitaminc-aead` helpers that this crate calls are now inlined into this crate's code. + +## [0.8.1] - 2026-10-26 + +### Dependencies + +- `orderable-bytes` 0.2.1. It changes no encoding, so every term is the same as 0.8.0's, and terms you stored still compare. + +## [0.8.0] - 2026-10-21 + +Existing equality terms do not change: every domain label and encoding of 0.7 stays as it is, and the null term is a new label beside them. An index built by 0.7 holds a SQL `NULL` where a value was absent; 0.8 writes a term there instead. Both read correctly, but the rows 0.7 wrote still show their absences until they are re-indexed. + +### Breaking + +- **Breaking:** Every null, typed or plain, now has an equality term, under the new frozen domain `vitaminc/prf/value/null/v1` with the one byte `0x00`. A sealed `None` is now as long as a `Some` (`vitaminc-aead` 0.8.0), but the term column still held a SQL `NULL` exactly where a value was absent. So `normalize(None, Physical::Null)` succeeds where it returned `NoDomain`, and a walk over a value with a null returns one more term, at the null's path. A layer that must keep a SQL `NULL` for some column drops the term whose domain is `domain::NULL`; producing it is the default because dropping a term should be an explicit act. A boolean and an `undefined` still have no term. `domain::ALL` now lists nine labels. + +### Features + +- `NormalizeError::Reserved`, which an order space that places nulls returns for the one value it keeps for them (`vitaminc-ore` 0.8.0). `NormalizeError` is `#[non_exhaustive]`, so a match on it still compiles. + +### Not guaranteed + +- In an equality index the nulls are one more group of equal terms, as any repeated value is. That is never more than the SQL `NULL` it replaces, which needed no inference to read. + +## [0.7.0] - 2026-10-20 + +### Fixes + +- Each fixed-width and decimal encoder writes straight into the wiped buffer it returns, so no unwiped intermediate copy of an encoded value is made. The encoded bytes, and so stored terms, do not change. + +### Not guaranteed + +- `vitaminc_normalize::text` runs text through the `unicode-normalization` iterators, whose small internal buffers move to the heap as soon as a character's combining marks pass four code points (four marks followed by any character is enough), and are then freed without being wiped. This is outside this crate's control (#488). + +## [0.6.1] - 2026-10-18 + +## [0.6.0] - 2026-10-17 + +### Features + +- First release. `vitaminc-normalize` decides the equality terms for `vitaminc-aead`'s plaintext data model: for each scalar kind that can be indexed, a frozen domain label (the `domain` module) and an encoding to bytes. `normalize(logical, physical)` returns a `Normalized` (domain and protected bytes) that a PRF such as `vitaminc-prf` derives a term from. It has no cryptography. +- Equal values give equal terms whatever width or scale wrote them: every integer width shares one domain, `f32` widens exactly to `f64`, decimals normalize scale and signed zero, and timestamps in any unit truncate to microseconds. Values that only look alike do not match: a date, timestamp, decimal and uuid each have their own domain, separate from the physical value they are stored as. Text is Unicode 16 NFC with no case or accent folding. A code point unassigned in Unicode 16 is refused. A null, boolean or `undefined`, and any logical type the crate does not know, has no term (`NormalizeError::NoDomain`). The encodings are documented in the README and on `decimal`; changing one means a new domain label. +- `Terms` is a sink that collects one `Term` (path and normalized value) per indexable scalar. Run it beside encryption with `encrypt_with_terms` or `encrypt_with_terms_async`, which have every term before the first cipher call (and before the first await), with `plan_with_terms`, or alone with `terms`. `terms` refuses exactly what encryption refuses, at the same path: read a shape refusal with `TermsError::refusal`. +- A refused scalar is reported as a `TermError` holding the `NormalizeError`, the `Path` to the field and the index it was for. The error message names neither the field nor the value, because map keys can be user data; read the path with `TermError::path`. `Debug` masks the value of a `Normalized` or `Term`, and the map keys in a path. +- In a walk, a null, boolean or `undefined` produces no term and does not stop the walk. A logical type with no domain does stop it, so an index is never left silently incomplete. +- `Terms::by` and `terms_by` run the same walk under a normalizer of your own (the `Normalize` trait, which must be `Copy`). `vitaminc-ore`'s order index is the first. +- Text normalization is variable-time. The integer and float paths use no floating-point arithmetic. diff --git a/packages/vitaminc-normalize/Cargo.toml b/packages/vitaminc-normalize/Cargo.toml new file mode 100644 index 000000000..bf2c8c21e --- /dev/null +++ b/packages/vitaminc-normalize/Cargo.toml @@ -0,0 +1,51 @@ +[package] +name = "vitaminc-normalize" +description = "Normalized equality terms for the plaintext data model. Part of the Vitamin-C cryptographic suite." +documentation = "https://docs.rs/vitaminc-normalize" +version = "0.10.0" +repository = "https://github.com/cipherstash/stack" +authors = ["Dan Draper "] +edition = "2021" +homepage = "https://cipherstash.com" +license = "MIT" +keywords = ["cryptography", "security"] +categories = ["cryptography"] +rust-version = "1.89.0" +# Not published from this repository yet: crates.io serves 0.10.0, which was +# published from cipherstash/vitaminc. release-plz.toml lists it with +# `release = false`. Every workspace that resolves it patches crates.io's +# copy to this one. +publish = false + +[dependencies] +vitaminc-aead = { version = "0.10.0", path = "../vitaminc-aead" } +vitaminc-protected = "0.10.0" +thiserror = "2.0.18" + +# NFC is stable for assigned code points, and the Unicode 16 assignment check +# refuses everything else, so newer normalization releases are safe. +[dependencies.unicode-normalization] +version = "0.1.24" + +# Exact pin: this table defines which code points are assigned in Unicode 16, +# and a newer table would widen the accepted input of a frozen domain. +[dependencies.unicode-general-category] +version = "=1.1.0" + +[dev-dependencies] +# Path-only, so publish order does not matter. `test-support` for +# `plaintext::render`, the path notation the tests assert against, so there +# is one copy of it. +vitaminc-aead = { path = "../vitaminc-aead", features = ["jiff", "rust_decimal", "uuid", "test-support"] } +jiff = { version = "1.0.0", default-features = false } +uuid = { version = "1", default-features = false } +quickcheck = "1.1.0" +quickcheck_macros = "1.2.0" +futures-executor = "0.3.31" + +# The frozen release the decimal and float encodings were ported from, so +# the tests can check them byte for byte. It is not a dependency of the +# crate: ADR 0002 keeps `orderable-bytes` for cipherstash-client's stored +# terms and has vitaminc own its encodings. +orderable-bytes = { version = "=0.2.1", features = ["decimal"] } +rust_decimal = { version = "1.41", default-features = false, features = ["std"] } diff --git a/packages/vitaminc-normalize/LICENSE b/packages/vitaminc-normalize/LICENSE new file mode 100644 index 000000000..2212a9966 --- /dev/null +++ b/packages/vitaminc-normalize/LICENSE @@ -0,0 +1,25 @@ +Copyright (c) 2024-2026 CipherStash Inc + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/packages/vitaminc-normalize/README.md b/packages/vitaminc-normalize/README.md new file mode 100644 index 000000000..f32fa7074 --- /dev/null +++ b/packages/vitaminc-normalize/README.md @@ -0,0 +1,180 @@ +# Vitamin C Normalize + +[![Crates.io](https://img.shields.io/crates/v/vitaminc-normalize.svg)](https://crates.io/crates/vitaminc-normalize) +[![Workflow Status](https://github.com/cipherstash/vitaminc/actions/workflows/test.yml/badge.svg)](https://github.com/cipherstash/vitaminc/actions/workflows/test.yml) + +Normalized equality terms for the plaintext data model of +[`vitaminc-aead`](https://docs.rs/vitaminc-aead). Part of the +[Vitamin C](https://github.com/cipherstash/vitaminc) framework. + +An equality index derives a key from a value. Two values that are equal +must derive the same key whichever width, scale or spelling wrote them, +and two values that merely look alike (a date and the integer it is stored +as, a uuid and the same sixteen bytes) must not. This crate decides both: +each scalar kind that can be indexed has a frozen **domain label** and a +**normalization** to bytes, and everything else has no term. + +There is no cryptography here and no PAE: the crate's own dependencies +are the Unicode tables. (It builds on `vitaminc-aead` for the data model, +which brings that crate's dependencies with it.) The encodings are its +own, including the decimal one, which is ported from the frozen +`orderable-bytes` release and checked against it byte for byte. A PRF crate such as +[`vitaminc-prf`](https://docs.rs/vitaminc-prf) takes a [`Normalized`] +and derives under its domain. + +## Installation + +```sh +cargo add vitaminc-normalize +``` + +## One scalar + +```rust +use vitaminc_normalize::{domain, normalize}; +use vitaminc_aead::{Int, Logical, Physical}; +use vitaminc_protected::Controlled; + +// Every integer width is one term. +let a = normalize(None, Physical::Int(Int::I8(34)))?; +let b = normalize(None, Physical::Int(Int::U64(34)))?; +assert_eq!(a.domain, domain::INTEGER); +assert_eq!(a.bytes.risky_ref(), b.bytes.risky_ref()); + +// A date is not the integer it is stored as. +let day = normalize(Some(Logical::Date), Physical::Int(Int::I32(34)))?; +assert_eq!(day.domain, domain::DATE); +assert_ne!(day.bytes.risky_ref(), a.bytes.risky_ref()); +# Ok::<(), vitaminc_normalize::NormalizeError>(()) +``` + +Logical types opt in: a date, a timestamp, a decimal and a uuid have +domains of their own. A boolean, an `undefined` and a logical type this +crate does not know have no term, and `normalize` refuses them with +[`NormalizeError::NoDomain`]. + +Every null has a term, typed or plain, under a domain of its own. It is +the same term in every column, as SQL says `NULL IS NULL` whatever the +column; spaces that must not tie already differ in context. So the term +column of an index holds a term where the value was absent, as it does +where the value was there, and the nulls show only as one more group of +equal terms, which is what any repeated value shows. + +```rust +use vitaminc_normalize::{domain, normalize}; +use vitaminc_aead::Physical; +use vitaminc_protected::Controlled; + +let null = normalize(None, Physical::Null)?; +assert_eq!(null.domain, domain::NULL); +assert_eq!(null.bytes.risky_ref(), &[0x00]); +# Ok::<(), vitaminc_normalize::NormalizeError>(()) +``` + +A layer that must keep a SQL `NULL` in the term column for some column +drops the term it was handed. It knows the term is a null's because its +domain is [`domain::NULL`]. Producing the term is the default, because the +secure path should be the easy one, and dropping it is an explicit act. + +## A whole value, beside encryption + +[`Terms`] is a sink that collects one [`Term`] per indexable scalar, with +the path to it. Teed with the encrypting sink it sees the same walk, so +the terms are complete before any cipher call: + +```rust +use std::collections::BTreeMap; +use vitaminc_normalize::{domain, encrypt_with_terms, Step}; +# use vitaminc_aead::{seal::Cipher, Context}; +# use vitaminc_protected::{Controlled, Protected}; +# /// Keeps the plaintext in the clear, for the example. Any `Cipher` will do. +# struct Clear; +# impl Cipher for Clear { +# type Leaf = Vec; +# type Error = core::convert::Infallible; +# fn seal(&self, plaintext: Protected>, _: &Context<'_>) -> Result, Self::Error> { +# Ok(plaintext.risky_unwrap()) +# } +# fn open(&self, leaf: Vec, _: &Context<'_>) -> Result>, Self::Error> { +# Ok(Protected::new(leaf)) +# } +# } +# let cipher = Clear; + +let mut user = BTreeMap::new(); +user.insert("email", "ada@example.com"); +user.insert("name", "Ada"); + +let (ciphertext, terms) = encrypt_with_terms(user, &cipher, "users/v1")?; +assert_eq!(terms.len(), 2); +assert_eq!(terms[0].path.steps(), [Step::Key("email".into())]); +assert_eq!(terms[0].normalized.domain, domain::TEXT); +# Ok::<(), vitaminc_aead::EncryptError>(()) +``` + +`encrypt_with_terms_async` does the same through an async cipher and has +every term before its first await. `plan_with_terms` walks without +sealing at all, and `terms` collects the terms with no encryption in the +walk. + +`terms` refuses every value encryption refuses, for the same reason and +at the same path, so an index never holds terms for a value that cannot +be stored. It keeps the same shape rules, through the same code: no +duplicate key, no value nested too deep, every scalar valid for its +logical type, every passthrough framable, and something sealed in every +container with children, even though it seals nothing itself. Read such a +refusal with `TermsError::refusal`; encryption reports the same one as +`EncryptError::Shape`. + +A null, typed or plain, has its term at its own path. A scalar whose kind +has no domain (a boolean, an `undefined`) produces no term and does not +stop the walk; passthrough subtrees get none either. A scalar whose +*logical type* has no domain, one from a newer client, stops the walk: +encrypting it with no term and no error would leave an index silently +incomplete. That refusal and an unassigned code point +arrive as `EncryptError::Source` carrying a `TermError` (from `terms`, as +`TermsError::term`), which holds the `NormalizeError` and the path to the +refused field. Downcast to `TermError`; the `NormalizeError` is also its +`source()`, so a reporter that walks the error chain reaches it. The +message names neither the field nor the value, because map keys can be +user data; read the path with `TermError::path`. + +## Encodings + +These are protocol data. Changing any of them, or a domain label, means a +new label. + +| Kind | Domain | Bytes | +| --- | --- | --- | +| integer, any width | `vitaminc/prf/value/integer-orderable/v1` | sign byte (`0x00` negative, `0x01` otherwise), then the big-endian 128-bit two's-complement word | +| float, either width | `vitaminc/prf/value/float-orderable/v1` | the `f64` value's orderable bytes; `f32` widened exactly, zero signs and NaN payloads folded | +| date | `vitaminc/prf/value/date-orderable/v1` | orderable days from 0001-01-01 | +| timestamp, any unit | `vitaminc/prf/value/timestamp-micros-orderable/v1` | orderable seconds, then nanoseconds truncated to microseconds | +| decimal | `vitaminc/prf/value/decimal-orderable/v1` | the 14-byte orderable encoding of the value (see [`decimal`]), scale and signed zero normalized | +| text | `vitaminc/prf/value/text-nfc/unicode-16/v1` | Unicode 16 NFC; a code point unassigned in Unicode 16 is refused | +| bytes | `vitaminc/prf/value/bytes/v1` | as they are | +| uuid | `vitaminc/prf/value/uuid/v1` | the sixteen raw bytes | +| null, typed or plain | `vitaminc/prf/value/null/v1` | one byte, `0x00` | + +Text normalization is variable-time. The integer and float paths use no +floating-point arithmetic. + +## Cargo features + +This crate defines no Cargo feature flags. + +## Compatibility + +Requires Rust **1.89.0** and the Rust standard library (`std`). +MSRV increases require a minor release; patch releases retain the existing +floor. See the [workspace compatibility policy](https://github.com/cipherstash/vitaminc#compatibility). + +License: MIT. + + +[`NormalizeError::NoDomain`]: https://docs.rs/vitaminc-normalize/latest/vitaminc_normalize/enum.NormalizeError.html#variant.NoDomain +[`Normalized`]: https://docs.rs/vitaminc-normalize/latest/vitaminc_normalize/struct.Normalized.html +[`Term`]: https://docs.rs/vitaminc-normalize/latest/vitaminc_normalize/struct.Term.html +[`Terms`]: https://docs.rs/vitaminc-normalize/latest/vitaminc_normalize/struct.Terms.html +[`decimal`]: https://docs.rs/vitaminc-normalize/latest/vitaminc_normalize/fn.decimal.html +[`domain::NULL`]: https://docs.rs/vitaminc-normalize/latest/vitaminc_normalize/domain/constant.NULL.html diff --git a/packages/vitaminc-normalize/src/decimal.rs b/packages/vitaminc-normalize/src/decimal.rs new file mode 100644 index 000000000..ec9654c26 --- /dev/null +++ b/packages/vitaminc-normalize/src/decimal.rs @@ -0,0 +1,385 @@ +//! The canonical, order-preserving 14-byte encoding of a decimal. +//! +//! Ported from `orderable-bytes` 0.2.0, whose encoding is frozen: an +//! equality index stores terms under [`domain::DECIMAL`](crate::domain::DECIMAL) +//! made from these bytes, so they can never change, and this crate owns +//! them rather than reaching into a crate that is kept only for +//! cipherstash-client's stored terms. The tests check every value against +//! that release byte for byte. +//! +//! The input is the mantissa and scale a [`Logical::Decimal`](vitaminc_aead::Logical::Decimal) +//! leaf carries: `value = mantissa × 10^(-scale)`, with the mantissa in +//! `(-2^96, 2^96)` and the scale at most 28, which is `rust_decimal`'s +//! range. The encoder refuses anything outside it: a larger mantissa would +//! lose its top bits and take the bytes of another value. +//! +//! The layout is documented on [`decimal`](crate::decimal()), the public +//! function that wraps this encoder, so it is in the published docs. +//! +//! ## Constant time +//! +//! Past the range check, [`orderable`] is straight-line code with +//! fixed-iteration loops and branchless mask arithmetic: no branch on the +//! sign, the zero-ness, the digit count, the trailing-zero count or the +//! scale, and no hardware division, whose latency is data-dependent on +//! some targets. + +use vitaminc_aead::plaintext::kinds::{strip_trailing_zeros, MAX_DECIMAL_SCALE}; +use vitaminc_protected::Protected; + +use crate::scalar::fixed; + +/// Width of the padded-significand field in bytes (104 bits). +const MANTISSA_BYTES: usize = 13; + +/// Bias applied to `leading_exp` so it fits unsigned in the 7-bit field. +const EXP_BIAS: i32 = 64; + +/// The digit count the significand is padded to: the most a 96-bit +/// mantissa has. +const PADDED_DIGITS: u32 = 29; + +/// Top bit of byte 0: set for positives and zero, clear for negatives. +const SIGN_BIT: u8 = 0x80; + +/// The 7-bit exponent field of byte 0. +const EXP_MASK: u8 = 0x7F; + +/// One past the largest mantissa magnitude: a mantissa fits 96 bits. +const MANTISSA_LIMIT: u128 = 1 << 96; + +/// The length of the encoding. +pub(crate) const ENCODED_LEN: usize = 14; + +/// The encoding of `mantissa × 10^(-scale)`. Two equal values give the +/// same bytes, and the bytes sort as the values do. `None` if the mantissa +/// does not fit 96 bits or the scale is above 28. +/// +/// The encoder makes the protected vector it returns and writes every +/// byte of the encoding straight into it, so no caller has to supply a +/// buffer and remember to wipe it. The working values below are plain +/// integers, which the compiler keeps in registers or short-lived stack +/// slots that Rust cannot promise to wipe. +pub(crate) fn orderable(mantissa: i128, scale: u8) -> Option>> { + if scale > MAX_DECIMAL_SCALE || mantissa.unsigned_abs() >= MANTISSA_LIMIT { + return None; + } + let scale = u32::from(scale); + + // The pipeline runs unconditionally: zero goes through the same steps + // as every other value (the helpers give it significand 0, digits 0, + // trailing 0) and its byte 0 is fixed up by a mask at the end, rather + // than a short-circuit that would tell zero apart by timing. + // + // Branchless absolute value: `(x ^ s) - s` where `s` is the sign bit + // arithmetically shifted across the word. + let sign_extension = mantissa >> 127; + let abs_mantissa = ((mantissa ^ sign_extension).wrapping_sub(sign_extension)) as u128; + let (significand, trailing) = strip_trailing_zeros(abs_mantissa); + let digits = digit_count(significand); + + // value = ±significand × 10^trailing × 10^(-scale); the leading digit's + // exponent is in [-28, 28] for a non-zero value. For zero the formula + // gives -1 - scale, in [-29, -1]: a valid-looking positive byte that is + // overwritten below. + let leading_exp = digits as i32 - 1 + trailing - scale as i32; + debug_assert!( + (-29..=28).contains(&leading_exp), + "leading_exp {leading_exp} out of bounds: mantissa or scale out of range" + ); + let biased_exp = (leading_exp + EXP_BIAS) as u8; + debug_assert!(biased_exp <= EXP_MASK, "biased_exp overflowed 7 bits"); + + // Pad the significand to 29 digits. Not `pow`, whose work depends on + // its exponent: a fixed loop that multiplies by ten under a mask that + // is set while padding remains. The product is computed every + // iteration and never overflows: while the mask is set the value is + // below 10^28, and once clear the unstored product is below 10^30. + let mut padded_mantissa = significand; + for i in 0..PADDED_DIGITS { + let do_step = ((digits + i) < PADDED_DIGITS) as u128; + let mask = 0u128.wrapping_sub(do_step); + let stepped = padded_mantissa.wrapping_mul(10); + padded_mantissa = (padded_mantissa & !mask) | (stepped & mask); + } + debug_assert!( + padded_mantissa >> (8 * MANTISSA_BYTES) == 0, + "padded mantissa overflowed 104 bits" + ); + + // One mask handles the sign: 0xFF for a negative, 0x00 otherwise. Byte + // 0 keeps the sign bit only when positive and XORs the exponent bits + // with the mask; each significand byte is XORed with it too. + let neg_mask = (mantissa >> 127) as u8; + + // The zero plaintext, applied branchlessly: the tail is already all + // zero, so only byte 0 is replaced, by the bare sign bit, when the + // mantissa is zero. + let mant_nonzero_bit = ((abs_mantissa | abs_mantissa.wrapping_neg()) >> 127) as u8; + let zero_mask = 0u8.wrapping_sub(mant_nonzero_bit ^ 1); + + // Every byte is written. The significand bytes are taken from the + // integer by shifting, most significant first, rather than through a + // plain array of its bytes. + Some(fixed::(|out| { + let head = (SIGN_BIT & !neg_mask) | (biased_exp ^ (neg_mask & EXP_MASK)); + out[0] = (head & !zero_mask) | (SIGN_BIT & zero_mask); + for i in 0..MANTISSA_BYTES { + let shift = 8 * (MANTISSA_BYTES - 1 - i); + out[1 + i] = (padded_mantissa >> shift) as u8 ^ neg_mask; + } + })) +} + +/// The number of decimal digits in `m`, `0` for zero: how many powers of +/// ten below `10^PADDED_DIGITS` it is at least, each test a borrow. +fn digit_count(m: u128) -> u32 { + let mut n: u32 = 0; + let mut pow: u128 = 1; + for _ in 0..PADDED_DIGITS { + let (_, borrow) = m.overflowing_sub(pow); + n = n.wrapping_add((borrow as u32) ^ 1); + pow = pow.wrapping_mul(10); + } + n +} + +#[cfg(test)] +mod tests { + use super::*; + use orderable_bytes::OrderableBytes; + use quickcheck_macros::quickcheck; + use rust_decimal::Decimal; + use vitaminc_protected::Controlled; + + const U96_MAX: u128 = (1u128 << 96) - 1; + + /// The encoding of an in-range value, copied out of its protected + /// vector into a plain array. The tests below index, sort and compare + /// the bytes against another crate's plain arrays, so this is the one + /// place they leave the wrapper. The inputs are test values, not real + /// plaintext, so a plain array of them is fine here. + /// + /// The bytes are copied through a read-only borrow, so the vector + /// itself is never taken out of its `Protected`, and it is wiped when it + /// drops at the end of this function. The returned array is the one + /// plain copy, and it is deliberate. + fn encode(mantissa: i128, scale: u32) -> [u8; ENCODED_LEN] { + let scale = u8::try_from(scale).expect("scale fits u8"); + let encoded = orderable(mantissa, scale).expect("in range"); + <[u8; ENCODED_LEN]>::try_from(encoded.risky_ref().as_slice()) + .expect("the encoding is ENCODED_LEN bytes") + } + + /// Whether the encoder accepts `mantissa` and `scale`. + fn accepts(mantissa: i128, scale: u8) -> bool { + orderable(mantissa, scale).is_some() + } + + /// The frozen encoding this one was ported from. + fn oracle(mantissa: i128, scale: u32) -> [u8; ENCODED_LEN] { + Decimal::try_from_i128_with_scale(mantissa, scale) + .expect("in range") + .to_orderable_bytes() + } + + #[test] + fn zero_in_any_scale_or_sign_is_the_bare_sign_bit() { + let mut expected = [0u8; ENCODED_LEN]; + expected[0] = SIGN_BIT; + for scale in [0, 1, 3, 28] { + assert_eq!(encode(0, scale), expected, "scale {scale}"); + } + assert_eq!(encode(-0, 0), expected); + } + + #[test] + fn equivalent_forms_encode_identically() { + let one = encode(1, 0); + assert_eq!(encode(10, 1), one); + assert_eq!(encode(100, 2), one); + assert_eq!(encode(1_000, 3), one); + // 100 strips to significand 1 at exponent 2: the same significand + // bytes as 1, and an exponent two higher. + let hundred = encode(100, 0); + assert_eq!(&one[1..], &hundred[1..]); + assert_eq!(one[0], SIGN_BIT | EXP_BIAS as u8); + assert_eq!(hundred[0], SIGN_BIT | (2 + EXP_BIAS) as u8); + } + + #[test] + fn worked_examples() { + assert_eq!(encode(5, 1)[0], SIGN_BIT | (-1 + EXP_BIAS) as u8); + assert_eq!(encode(10, 0)[0], SIGN_BIT | (1 + EXP_BIAS) as u8); + let (neg_one, pos_one) = (encode(-1, 0), encode(1, 0)); + assert_eq!(neg_one[0] & SIGN_BIT, 0); + assert_eq!(neg_one[0] & EXP_MASK, !(EXP_BIAS as u8) & EXP_MASK); + for i in 1..ENCODED_LEN { + assert_eq!(neg_one[i], !pos_one[i]); + } + } + + #[test] + fn byte_order_is_value_order() { + let values: [(i128, u32); 13] = [ + (-(U96_MAX as i128), 0), + (-1_000_000_000, 0), + (-15, 1), + (-105, 2), + (-1, 0), + (-1, 3), + (0, 0), + (1, 3), + (1, 0), + (105, 2), + (15, 1), + (1_000_000_000, 0), + (U96_MAX as i128, 0), + ]; + for pair in values.windows(2) { + let (a, b) = (pair[0], pair[1]); + assert!(encode(a.0, a.1) < encode(b.0, b.1), "{a:?} < {b:?} failed"); + } + } + + #[test] + fn digit_count_counts_digits() { + assert_eq!(digit_count(0), 0); + assert_eq!(digit_count(1), 1); + assert_eq!(digit_count(9), 1); + assert_eq!(digit_count(10), 2); + assert_eq!(digit_count(U96_MAX), 29); + } + + fn u96(m: u128) -> u128 { + m & U96_MAX + } + + #[quickcheck] + fn strip_reconstructs_and_is_canonical(m: u128) -> bool { + let m = u96(m); + let (s, c) = strip_trailing_zeros(m); + (0..=28).contains(&c) + && s.wrapping_mul(10u128.pow(c as u32)) == m + && (s == 0 || s % 10 != 0) + && (m == 0) == (s == 0) + && strip_trailing_zeros(s) == (s, 0) + } + + #[quickcheck] + fn strip_distributes_over_powers_of_ten(m: u128, k: u8) -> bool { + let (s, _) = strip_trailing_zeros(u96(m)); + let k = u32::from(k) % 29; + match s.checked_mul(10u128.pow(k)) { + Some(extended) if s != 0 && extended <= U96_MAX => { + strip_trailing_zeros(extended) == (s, k as i32) + } + _ => true, + } + } + + /// Every value encodes exactly as the frozen `orderable-bytes` release + /// encodes it. + #[quickcheck] + fn matches_orderable_bytes_byte_for_byte(m: u128, negative: bool, scale: u8) -> bool { + let magnitude = u96(m) as i128; + let mantissa = if negative { -magnitude } else { magnitude }; + let scale = u32::from(scale) % 29; + encode(mantissa, scale) == oracle(mantissa, scale) + } + + #[test] + fn the_extremes_match_orderable_bytes() { + for (mantissa, scale) in [ + (U96_MAX as i128, 0), + (-(U96_MAX as i128), 0), + (U96_MAX as i128, 28), + (-(U96_MAX as i128), 28), + (1, 28), + (-1, 28), + (0, 28), + ] { + assert_eq!(encode(mantissa, scale), oracle(mantissa, scale)); + } + } + + #[quickcheck] + fn byte_order_matches_decimal_order(a: u64, b: u64, sa: u8, sb: u8, neg: (bool, bool)) -> bool { + let (sa, sb) = (u32::from(sa) % 29, u32::from(sb) % 29); + let (a, b) = ( + if neg.0 { -(a as i128) } else { a as i128 }, + if neg.1 { -(b as i128) } else { b as i128 }, + ); + let (x, y) = ( + Decimal::try_from_i128_with_scale(a, sa).expect("in range"), + Decimal::try_from_i128_with_scale(b, sb).expect("in range"), + ); + encode(a, sa).cmp(&encode(b, sb)) == x.cmp(&y) + } + + /// The encoder checks its own range, so no caller can hand it a + /// mantissa whose top bits it would drop. + mod given_a_mantissa_or_scale_at_the_edge_of_the_range { + use super::*; + + #[test] + fn returns_an_encoding() { + let limit = 1i128 << 96; + assert!(accepts(limit - 1, 0), "the largest mantissa is accepted"); + assert!(accepts(1 - limit, 0), "the smallest mantissa is accepted"); + assert!(accepts(1, 28), "the largest scale is accepted"); + } + } + + mod given_a_mantissa_or_scale_one_past_the_range { + use super::*; + + #[test] + fn returns_none() { + let limit = 1i128 << 96; + assert!( + !accepts(limit, 0), + "one past the largest mantissa is refused" + ); + assert!( + !accepts(-limit, 0), + "one past the smallest mantissa is refused" + ); + assert!(!accepts(1, 29), "one past the largest scale is refused"); + } + } + + /// Every digit count, with and without trailing zeros, at every scale + /// and both signs. Random 96-bit mantissas almost all have 28 or 29 + /// digits, so the quickcheck oracle above rarely reaches short ones. + #[test] + fn every_digit_count_scale_and_sign_matches_orderable_bytes() { + for k in 0..=28u32 { + let p = 10i128.pow(k); + for magnitude in [p, p - 1, 7 * p, 123_456_789 * p] { + if magnitude as u128 > U96_MAX { + continue; + } + for scale in 0..=28u32 { + for mantissa in [magnitude, -magnitude] { + assert_eq!( + encode(mantissa, scale), + oracle(mantissa, scale), + "{mantissa} at scale {scale}" + ); + } + } + } + } + } + + /// Built from a short significand, so `s * 10^k` stays in range and + /// every case reaches the comparison. + #[quickcheck] + fn strip_distributes_over_powers_of_ten_for_short_significands(base: u32, k: u8) -> bool { + let (s, _) = strip_trailing_zeros(u128::from(base)); + // `s` has at most 10 digits, so `s * 10^k` stays below 10^28. + let k = u32::from(k) % (29 - digit_count(s)); + s == 0 || strip_trailing_zeros(s * 10u128.pow(k)) == (s, k as i32) + } +} diff --git a/packages/vitaminc-normalize/src/lib.rs b/packages/vitaminc-normalize/src/lib.rs new file mode 100644 index 000000000..a935af9ec --- /dev/null +++ b/packages/vitaminc-normalize/src/lib.rs @@ -0,0 +1,26 @@ +// These definitions precede the README so rustdoc links to the version being built. +// The README supplies published-API URLs for GitHub. See docs/documentation.md. +//! [`NormalizeError::NoDomain`]: crate::NormalizeError::NoDomain +//! [`Normalized`]: crate::Normalized +//! [`Term`]: crate::Term +//! [`Terms`]: crate::Terms +//! [`decimal`]: crate::decimal() +//! [`domain::NULL`]: crate::domain::NULL +//! +#![deny(missing_docs)] +#![deny(clippy::unwrap_used, clippy::todo, unsafe_code, unused_imports)] +#![doc = include_str!("../README.md")] + +mod decimal; +mod scalar; +mod terms; + +pub use scalar::{ + bytes, date, decimal, domain, domain_of, float, integer, normalize, null, text, timestamp, + uuid, NormalizeError, Normalized, +}; +pub use terms::{ + encrypt_with_terms, encrypt_with_terms_async, plan_with_terms, terms, terms_by, Equality, + Normalize, Term, TermError, Terms, TermsError, TermsMap, TermsSeq, WithTerms, +}; +pub use vitaminc_aead::plaintext::{Path, Step}; diff --git a/packages/vitaminc-normalize/src/scalar.rs b/packages/vitaminc-normalize/src/scalar.rs new file mode 100644 index 000000000..84330dde3 --- /dev/null +++ b/packages/vitaminc-normalize/src/scalar.rs @@ -0,0 +1,420 @@ +//! One normalized equality term per scalar. +//! +//! [`normalize`] turns a physical value and its optional logical type into +//! the bytes an equality index derives under, and the frozen domain label +//! those bytes belong to. The encoders are public, one per kind, so an index +//! layer that already knows a value's kind can call them directly. +//! +//! Every integer width shares one 17-byte encoding and domain, and both +//! float widths share one 8-byte encoding and domain, so equal numbers +//! match whichever width wrote them. Text is Unicode 16 NFC. These bytes +//! and their [`domain`] labels are protocol data: changing either requires +//! a new domain. Text processing is variable-time; this module makes no +//! constant-time claim for Unicode normalization. +//! +//! Logical types opt in. A date, a timestamp, a decimal and a uuid each +//! have a domain of their own, separate from the physical value they are +//! stored as, so a date's day count never matches the integer it equals and +//! a uuid never matches the same sixteen bytes written as bytes. Every other +//! logical type, [`Logical::Unknown`] included, has no term and is refused +//! with [`NormalizeError::NoDomain`]. +//! +//! A null has a term too, under [`domain::NULL`]: one byte, the same in +//! every column, so an absent value is indexed like any other value and +//! the nulls show only as one more tied group. A boolean and an +//! `undefined` have none. + +use unicode_general_category::{get_general_category, GeneralCategory}; +use unicode_normalization::UnicodeNormalization; +use vitaminc_aead::plaintext::kinds::{timestamp_nanos, MAX_DATE_DAYS, MIN_DATE_DAYS}; +use vitaminc_aead::{Float, Int, Logical, Physical, TimeUnit}; +use vitaminc_protected::{Controlled, OpaqueDebug, Protected}; + +/// Frozen domain labels for equality terms, one per kind that has one. +pub mod domain { + /// Every integer width, `i8` through `u128`. + pub const INTEGER: &str = "vitaminc/prf/value/integer-orderable/v1"; + /// `f32` and `f64`, as `f64`. + pub const FLOAT: &str = "vitaminc/prf/value/float-orderable/v1"; + /// A date, over its day count. + pub const DATE: &str = "vitaminc/prf/value/date-orderable/v1"; + /// A timestamp, truncated to microseconds. + pub const TIMESTAMP: &str = "vitaminc/prf/value/timestamp-micros-orderable/v1"; + /// A decimal, with scale and signed zero normalized. + pub const DECIMAL: &str = "vitaminc/prf/value/decimal-orderable/v1"; + /// Text, as Unicode 16 NFC. + pub const TEXT: &str = "vitaminc/prf/value/text-nfc/unicode-16/v1"; + /// Bytes. + pub const BYTES: &str = "vitaminc/prf/value/bytes/v1"; + /// A uuid, over its sixteen raw bytes. + pub const UUID: &str = "vitaminc/prf/value/uuid/v1"; + /// A null, typed or plain, whatever column it sits in: the one byte + /// `0x00`. + pub const NULL: &str = "vitaminc/prf/value/null/v1"; + /// Every domain, for a test or an index layer that enumerates them. A + /// slice, so a domain added later does not change its type. + pub const ALL: &[&str] = &[ + INTEGER, FLOAT, DATE, TIMESTAMP, DECIMAL, TEXT, BYTES, UUID, NULL, + ]; +} + +/// The normalized bytes for one equality term and the domain they belong +/// to. +/// +/// The fields are public so an index layer can build a term of its own, +/// and whatever consumes a `Normalized` trusts them: a PRF derives under +/// the `domain` it is handed. The only way to get the frozen encodings is +/// through [`normalize`] or the per-kind encoders here. +/// +/// `Debug` shows the domain and masks the bytes. +#[derive(OpaqueDebug)] +pub struct Normalized { + /// The frozen domain label, one of the [`domain`] constants. + #[non_sensitive] + pub domain: &'static str, + /// The normalized plaintext, protected. + pub bytes: Protected>, +} + +/// Why a scalar has no term. Never includes plaintext. +#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)] +#[non_exhaustive] +pub enum NormalizeError { + /// The scalar has no domain under the normalizer: an `undefined`, a + /// boolean, a logical type outside its opt-in table, or a null under + /// an index that gives nulls no term (an order index whose space does + /// not place them). The message does not name an index, because the + /// equality and order normalizers both report it; whatever wraps it + /// says which. + #[error("no domain for this kind of value")] + NoDomain, + /// The value is not valid for its logical type. + #[error("the value is not valid for its logical type")] + Invalid, + /// Text contains a code point unassigned in Unicode 16. + #[error("text contains a code point unassigned in Unicode 16")] + UnassignedCodePoint, + /// The value is of another kind than the type the index declares: text + /// for an integer column, say. Not reported by the equality + /// normalizer, which declares no type. + #[error("the value is not of the kind the index declares")] + Mismatch, + /// The value is of the kind the index declares but does not fit it: an + /// integer outside the declared width. Not reported by the equality + /// normalizer, which declares no type. + #[error("the value does not fit the type the index declares")] + OutOfRange, + /// The value is of the kind the index declares, and fits it, but its + /// code is the one the index keeps for nulls: the maximum of an + /// integer or uuid target in an order space that places nulls first + /// or last. Not reported by the equality normalizer, which gives a + /// null a domain of its own. + #[error("the value's code is the one this space keeps for the null")] + Reserved, +} + +/// The opt-in table: the domain for a scalar, or `None` for one that has +/// no term. A logical type decides on its own; a value without one goes by +/// its kind. Neither looks at the value: [`normalize`] checks that. +pub fn domain_of(ty: Option, v: &Physical<'_>) -> Option<&'static str> { + match (ty, v) { + (None, Physical::Int(_)) => Some(domain::INTEGER), + (None, Physical::Float(_)) => Some(domain::FLOAT), + (None, Physical::Text(_)) => Some(domain::TEXT), + (None, Physical::Bytes(_)) => Some(domain::BYTES), + (None, Physical::Null) => Some(domain::NULL), + (None, Physical::Bool(_)) => None, + (Some(Logical::Date), _) => Some(domain::DATE), + (Some(Logical::Timestamp(_)), _) => Some(domain::TIMESTAMP), + (Some(Logical::Decimal { .. }), _) => Some(domain::DECIMAL), + (Some(Logical::Uuid), _) => Some(domain::UUID), + // `Logical` is non-exhaustive: a type this build does not know, and + // any added later, has no term until it is given a domain here. + (Some(_), _) => None, + } +} + +/// Encode one scalar for equality, with the domain its term belongs to. +/// +/// Integers of every width share [`domain::INTEGER`]: a sign byte (`0x00` +/// negative, `0x01` otherwise) then the value as a big-endian 128-bit +/// two's-complement word, which orders correctly across `i128::MIN` to +/// `u128::MAX`. Both float widths share [`domain::FLOAT`]: an `f32` widens +/// exactly to `f64`, so it matches an `f64` only when the numbers are equal +/// (`f32` 1.5 matches, `f32` 0.1 does not match `f64` 0.1). Float zero +/// signs and NaN payloads are folded. A timestamp in any unit is truncated +/// to microseconds. A decimal's scale is normalized, so `1.50` and `1.5` +/// are one term, as are `-0.00` and `0`. A null is [`domain::NULL`] and +/// the one byte `0x00`; a typed null is walked as a plain one, so it is +/// the same term. +/// +/// # Examples +/// +/// ``` +/// use vitaminc_aead::Physical; +/// use vitaminc_normalize::{domain, normalize}; +/// use vitaminc_protected::Controlled; +/// +/// let null = normalize(None, Physical::Null)?; +/// assert_eq!(null.domain, domain::NULL); +/// assert_eq!(null.bytes.risky_ref(), &[0x00]); +/// # Ok::<(), vitaminc_normalize::NormalizeError>(()) +/// ``` +pub fn normalize(ty: Option, v: Physical<'_>) -> Result { + // A value that does not fit its logical type is refused as invalid + // before the type is looked up, so `undefined` over an int is `Invalid` + // rather than "nothing to index". + if ty.is_some_and(|ty| !ty.admits(&v)) { + return Err(NormalizeError::Invalid); + } + let domain = domain_of(ty, &v).ok_or(NormalizeError::NoDomain)?; + let bytes = match (ty, v) { + (None, Physical::Int(i)) => Some(integer(i)), + (None, Physical::Float(f)) => Some(float(f)), + (None, Physical::Text(s)) => Some(text(s)?), + (None, Physical::Bytes(b)) => Some(bytes(b)), + (None, Physical::Null) => Some(null()), + (Some(Logical::Date), Physical::Int(days)) => date(days), + (Some(Logical::Timestamp(unit)), Physical::Int(count)) => timestamp(unit, count), + (Some(Logical::Decimal { scale }), Physical::Int(mantissa)) => decimal(scale, mantissa), + (Some(Logical::Uuid), Physical::Bytes(b)) => uuid(b), + // `admits` has already refused a logical type over the wrong kind, + // and `domain_of` everything without a term. Each encoder checks + // its own range as well, for a caller that goes to it directly. + _ => None, + } + .ok_or(NormalizeError::Invalid)?; + Ok(Normalized { domain, bytes }) +} + +/// An integer of any width: a sign byte, then the big-endian 128-bit word. +pub fn integer(value: Int) -> Protected> { + // `sign_and_word` is `#[inline]`, so it is compiled into this function + // and the sign and word stay in registers until they are written to the + // buffer, rather than coming back through an unwiped stack slot + // (checked in the compiled code for AArch64; Rust does not promise it). + let (negative, word) = value.sign_and_word(); + fixed::<17>(|b| { + b[0] = u8::from(!negative); + b[1..].copy_from_slice(&word.to_be_bytes()); + }) +} + +/// A float of either width, as the orderable bytes of its `f64` value with +/// zero signs and NaN payloads folded. +pub fn float(value: Float) -> Protected> { + let value = match value { + Float::F32(f) => widen_f32(f), + Float::F64(f) => f, + }; + orderable_f64(canonical_f64(value)) +} + +/// A date's day count since 1970-01-01, as the orderable bytes of its +/// count of days from 0001-01-01, so the bytes order as the dates do. +/// `None` outside the date range. +pub fn date(days: Int) -> Option>> { + let days = i32::try_from(days.to_i128()?).ok()?; + if !(MIN_DATE_DAYS..=MAX_DATE_DAYS).contains(&days) { + return None; + } + let from_ce = days.checked_add(EPOCH_DAYS_FROM_CE)?; + Some(fixed(|b| { + *b = ((from_ce as u32) ^ (1u32 << 31)).to_be_bytes() + })) +} + +/// A count of `unit`s since the Unix epoch, as orderable seconds then +/// big-endian nanoseconds truncated to microseconds, so the bytes order as +/// the instants do, to the microsecond. `None` outside the timestamp +/// range. +pub fn timestamp(unit: TimeUnit, count: Int) -> Option>> { + // `timestamp_nanos` is `#[inline]` for the same reason as + // `sign_and_word` in `integer`: so the count is not returned through + // an unwiped stack slot. + let nanos = timestamp_nanos(unit, count)?; + let seconds = i64::try_from(nanos.div_euclid(NANOS_PER_SECOND)).ok()?; + let sub = (nanos.rem_euclid(NANOS_PER_SECOND) as u32) / 1_000 * 1_000; + Some(fixed::<12>(|b| { + b[..8].copy_from_slice(&((seconds as u64) ^ (1u64 << 63)).to_be_bytes()); + b[8..].copy_from_slice(&sub.to_be_bytes()); + })) +} + +/// A decimal's mantissa and scale, as the 14-byte orderable encoding of +/// its value, ported from the frozen `orderable-bytes` release and checked +/// against it, which normalizes the scale and a signed zero. `None` +/// if the mantissa does not fit 96 bits or the scale is above 28, the +/// range `rust_decimal` represents. +/// +/// # Encoding (scientific form, base 10) +/// +/// Each non-zero value is re-expressed in signed scientific form: +/// +/// ```text +/// value = ±significand × 10^(leading_exp − digits(significand) + 1) +/// ``` +/// +/// where `significand` is the mantissa with trailing zeros stripped and +/// `leading_exp` is the decimal exponent of the leading significant digit, +/// in `[-28, 28]`. The 14 bytes are: +/// +/// ```text +/// byte 0 : [sign:1][biased_exp:7] +/// bytes 1..=13 : padded_significand (104 bits, big-endian) +/// ``` +/// +/// - The sign bit is `1` for positive and zero, `0` for negative, so every +/// negative sorts below zero and zero below every positive. +/// - The biased exponent is `leading_exp + 64`, in `[36, 92]` for a +/// non-zero value. Zero uses `0`, which no non-zero value reaches. +/// - The padded significand is the significand left-justified to 29 +/// digits by appending zeros, so values at one exponent compare +/// byte-wise however many digits they have. A 96-bit mantissa has at +/// most 29 digits, so the padded value fits 104 bits. +/// +/// For a negative, the exponent bits and the significand are inverted, so +/// a larger magnitude sorts lower. `1`, `1.0` and `1.00` reduce to the +/// same significand and exponent, and `+0` and `-0` to the same zero, so +/// equal values are equal bytes, as `rust_decimal` compares them. +pub fn decimal(scale: u8, mantissa: Int) -> Option>> { + crate::decimal::orderable(mantissa.to_i128()?, scale) +} + +/// NFC in the pinned Unicode version, without case or accent folding. +/// +/// The result is written into one protected buffer sized exactly up front, +/// so it never reallocates and frees an unwiped partial copy. +/// +/// The `unicode-normalization` iterators keep pending code points in small +/// buffers of their own, with room for four code points inside the +/// iterator. Decomposition holds the combining marks that follow a +/// character in the same buffer as the decomposed form of the next +/// character, so the buffer moves to the heap as soon as those together +/// pass four code points: four marks followed by any character is enough. +/// Composition moves its buffer to the heap when five marks after one +/// character do not combine with it. Once a buffer is on the heap it stays +/// there for the rest of the string, so every later character passes +/// through it, and it is freed without being wiped. That is out of this +/// crate's control (see #488). +pub fn text(text: &str) -> Result>, NormalizeError> { + if text + .chars() + .any(|c| get_general_category(c) == GeneralCategory::Unassigned) + { + return Err(NormalizeError::UnassignedCodePoint); + } + // NFC can grow UTF-8 (U+0344 is two bytes, its NFC form four), so measure + // the output first rather than sizing from the input. + let len = text.nfc().map(char::len_utf8).sum(); + let mut result = Protected::new(Vec::with_capacity(len)); + for c in text.nfc() { + let mut encoded = Protected::new([0u8; 4]); + result + .risky_inner_mut() + .extend_from_slice(c.encode_utf8(encoded.risky_inner_mut()).as_bytes()); + } + Ok(result) +} + +/// Bytes, as they are. +pub fn bytes(value: &[u8]) -> Protected> { + Protected::new(value.to_vec()) +} + +/// A null, typed or plain: the one byte `0x00`, under [`domain::NULL`]. +/// Every null is this one term, whatever column it sits in, as SQL says +/// `NULL IS NULL` whatever the column. Spaces that must not tie already +/// differ in context. +pub fn null() -> Protected> { + fixed::<1>(|b| *b = [0x00]) +} + +/// A uuid's sixteen raw bytes. `None` for any other length. +pub fn uuid(value: &[u8]) -> Option>> { + (value.len() == 16).then(|| Protected::new(value.to_vec())) +} + +/// A fixed-width encoding, written by `write` straight into the protected +/// vector that is returned. +/// +/// The vector is allocated once at its final size, so it never +/// reallocates, and `write` fills it in place. No separate array of the +/// encoding is made and copied, so there is no extra copy to wipe. The +/// compiler can still make short-lived temporaries while `write` runs, for +/// example the array that `to_be_bytes` returns, and Rust cannot promise +/// to wipe those. +/// +/// `vitaminc-ore` has its own private copy of this function rather than +/// sharing this one, so it stays out of this crate's public API. +pub(crate) fn fixed(mut write: impl FnMut(&mut [u8; N])) -> Protected> { + let mut bytes = Protected::new(vec![0u8; N]); + bytes.update(|bytes| { + let array = <&mut [u8; N]>::try_from(bytes.as_mut_slice()) + .expect("the vector was made with exactly N bytes"); + write(array); + }); + bytes +} + +/// Days from 0001-01-01 (counted as day 1, the "days from CE" of the +/// proleptic Gregorian calendar) to 1970-01-01. +const EPOCH_DAYS_FROM_CE: i32 = 719_163; +const NANOS_PER_SECOND: i128 = 1_000_000_000; + +/// The orderable bytes of an `f64`: negatives flip every bit, positives +/// the sign bit, so the bytes sort as the numbers do. Expects a value +/// [`canonical_f64`] has already folded. +/// +/// The bytes are written straight into the protected vector that is +/// returned (see [`fixed`]). +fn orderable_f64(value: f64) -> Protected> { + let bits = value.to_bits(); + let sign_extension = ((bits as i64) >> 63) as u64; + fixed(|b| *b = (bits ^ (sign_extension | (1u64 << 63))).to_be_bytes()) +} + +/// `f64::from(f32)` in integer operations only. A hardware conversion can +/// take a slow path on subnormal inputs, which would leak timing; this keeps +/// the float path free of floating-point arithmetic. +fn widen_f32(value: f32) -> f64 { + let bits = value.to_bits(); + let sign = u64::from(bits >> 31) << 63; + let exponent = (bits >> 23) & 0xff; + let mantissa = u64::from(bits & 0x7f_ffff); + let zero_exponent = 0u64.wrapping_sub((exponent == 0) as u64); + let max_exponent = 0u64.wrapping_sub((exponent == 0xff) as u64); + let nonzero = 0u64.wrapping_sub((mantissa != 0) as u64); + // Normal, infinite and NaN: rebias the exponent (127 to 1023, or all + // ones stays all ones) and left-align the mantissa. + let rebiased = ((u64::from(exponent) + 896) & !max_exponent) | (0x7ff & max_exponent); + let normal = (rebiased << 52) | (mantissa << 29); + // Subnormal: the highest set bit becomes the implicit leading one. + let top = highest_set_bit(mantissa); + let subnormal = ((top + 874) << 52) | ((mantissa << (52 - top)) & ((1 << 52) - 1)); + f64::from_bits(sign | (normal & !zero_exponent) | (subnormal & zero_exponent & nonzero)) +} + +/// Index of the highest set bit of a subnormal f32 mantissa. `| 1` keeps the +/// result in range for a zero mantissa, which `widen_f32` masks out. +/// +/// Kept out of `widen_f32` so the `.cargo/mutants.toml` exclusion of that +/// function's equivalent `|`-to-`^` mutants cannot reach this `|`, whose +/// operands overlap and whose mutant a test does catch. +fn highest_set_bit(mantissa: u64) -> u64 { + u64::from(63 - (mantissa | 1).leading_zeros()) +} + +/// Folds every NaN to one quiet NaN and `-0.0` to `0.0`, in integer +/// operations only. +fn canonical_f64(value: f64) -> f64 { + let bits = value.to_bits(); + let magnitude = bits & 0x7fff_ffff_ffff_ffff; + let nan = 0u64.wrapping_sub((magnitude > 0x7ff0_0000_0000_0000) as u64); + let nonzero = 0u64.wrapping_sub((magnitude != 0) as u64); + f64::from_bits((bits & !nan).wrapping_add(0x7ff8_0000_0000_0000 & nan) & nonzero) +} + +#[cfg(test)] +#[path = "scalar_tests.rs"] +mod tests; diff --git a/packages/vitaminc-normalize/src/scalar_tests.rs b/packages/vitaminc-normalize/src/scalar_tests.rs new file mode 100644 index 000000000..07b156c6f --- /dev/null +++ b/packages/vitaminc-normalize/src/scalar_tests.rs @@ -0,0 +1,607 @@ +use super::*; +use orderable_bytes::OrderableBytes; +use quickcheck_macros::quickcheck; +use vitaminc_aead::UnknownLogical; + +fn term(ty: Option, v: Physical<'_>) -> Vec { + normalize(ty, v) + .expect("valid test value") + .bytes + .risky_ref() + .clone() +} + +fn int(ty: Option, i: Int) -> Vec { + term(ty, Physical::Int(i)) +} + +fn integer_bytes(sign: u8, word: u128) -> Vec { + let mut expected = vec![sign]; + expected.extend_from_slice(&word.to_be_bytes()); + expected +} + +#[test] +fn integers_share_one_domain_whatever_their_width() { + let five = [ + Int::I8(5), + Int::U8(5), + Int::I16(5), + Int::U16(5), + Int::I32(5), + Int::U32(5), + Int::I64(5), + Int::U64(5), + Int::I128(5), + Int::U128(5), + ]; + for value in five { + let n = normalize(None, Physical::Int(value)).expect("int"); + assert_eq!(n.domain, domain::INTEGER); + assert_eq!(n.bytes.risky_ref(), &integer_bytes(1, 5)); + } + for value in [ + Int::I8(-7), + Int::I16(-7), + Int::I32(-7), + Int::I64(-7), + Int::I128(-7), + ] { + assert_eq!(int(None, value), integer_bytes(0, -7i128 as u128)); + } + assert_eq!(int(None, Int::I128(i128::MIN)), integer_bytes(0, 1 << 127)); + assert_eq!(int(None, Int::I128(-1)), integer_bytes(0, u128::MAX)); + assert_eq!(int(None, Int::I128(0)), integer_bytes(1, 0)); + assert_eq!(int(None, Int::U128(u128::MAX)), integer_bytes(1, u128::MAX)); + let ascending = [ + Int::I128(i128::MIN), + Int::I64(i64::MIN), + Int::I8(-1), + Int::U8(0), + Int::I8(i8::MAX), + Int::U64(u64::MAX), + Int::I128(i128::MAX), + Int::U128(u128::MAX), + ]; + for pair in ascending.windows(2) { + assert!(int(None, pair[0]) < int(None, pair[1])); + } +} + +#[quickcheck] +fn signed_and_unsigned_integers_agree_when_equal(value: u64) -> bool { + int(None, Int::U64(value)) == int(None, Int::I128(value.into())) + && int(None, Int::U128(value.into())) == int(None, Int::I128(value.into())) +} + +#[quickcheck] +fn integer_order_agrees_with_numeric_order(a: i64, b: u64) -> bool { + let (wide_a, wide_b) = (i128::from(a), i128::from(b)); + int(None, Int::I64(a)).cmp(&int(None, Int::U64(b))) == wide_a.cmp(&wide_b) + && int(None, Int::I128(wide_a * wide_b)).cmp(&int(None, Int::I64(a))) + == (wide_a * wide_b).cmp(&wide_a) +} + +#[test] +fn the_opt_in_table_names_every_domain_and_nothing_else() { + let one = Physical::Int(Int::I32(1)); + assert_eq!(domain_of(None, &one), Some(domain::INTEGER)); + assert_eq!( + domain_of(None, &Physical::Float(Float::F32(1.0))), + Some(domain::FLOAT) + ); + assert_eq!(domain_of(None, &Physical::Text("a")), Some(domain::TEXT)); + assert_eq!(domain_of(None, &Physical::Bytes(&[1])), Some(domain::BYTES)); + assert_eq!(domain_of(Some(Logical::Date), &one), Some(domain::DATE)); + assert_eq!( + domain_of(Some(Logical::Timestamp(TimeUnit::Millis)), &one), + Some(domain::TIMESTAMP) + ); + assert_eq!( + domain_of(Some(Logical::Decimal { scale: 2 }), &one), + Some(domain::DECIMAL) + ); + assert_eq!( + domain_of(Some(Logical::Uuid), &Physical::Bytes(&[0; 16])), + Some(domain::UUID) + ); + assert_eq!(domain_of(None, &Physical::Null), Some(domain::NULL)); + assert_eq!(domain_of(None, &Physical::Bool(true)), None); + assert_eq!(domain_of(Some(Logical::Undefined), &Physical::Null), None); + let unknown = Logical::from_wire(200, 1).expect("unknown"); + assert!(matches!(unknown, Logical::Unknown(UnknownLogical { .. }))); + assert_eq!(domain_of(Some(unknown), &one), None); + assert_eq!(domain::ALL.len(), 9); + for label in domain::ALL { + assert!(label.starts_with("vitaminc/prf/value/"), "{label}"); + } +} + +#[test] +fn a_scalar_with_no_domain_is_refused_with_no_domain() { + let unknown = Logical::from_wire(200, 1).expect("unknown"); + for (ty, v) in [ + (None, Physical::Bool(false)), + (Some(Logical::Undefined), Physical::Null), + (Some(unknown), Physical::Int(Int::I32(1))), + (Some(unknown), Physical::Text("x")), + ] { + assert_eq!( + normalize(ty, v).expect_err("no term"), + NormalizeError::NoDomain + ); + } + for error in [ + NormalizeError::NoDomain, + NormalizeError::Invalid, + NormalizeError::UnassignedCodePoint, + NormalizeError::Reserved, + ] { + assert!(!error.to_string().is_empty()); + } +} + +#[test] +fn a_value_that_does_not_fit_its_logical_type_is_invalid() { + for (ty, v) in [ + (Logical::Date, Physical::Text("2024-01-01")), + (Logical::Date, Physical::Int(Int::I64(i64::MAX))), + ( + Logical::Timestamp(TimeUnit::Nanos), + Physical::Int(Int::I128(i128::MAX)), + ), + (Logical::Decimal { scale: 29 }, Physical::Int(Int::I32(1))), + ( + Logical::Decimal { scale: 1 }, + Physical::Int(Int::I128(1 << 100)), + ), + (Logical::Uuid, Physical::Bytes(&[0; 15])), + (Logical::Uuid, Physical::Int(Int::I32(1))), + ] { + assert_eq!( + normalize(Some(ty), v).expect_err("invalid"), + NormalizeError::Invalid + ); + } + // `undefined` over anything but a null is a value that does not fit + // its type, not one with nothing to index. + assert_eq!( + normalize(Some(Logical::Undefined), Physical::Int(Int::I32(1))).expect_err("invalid"), + NormalizeError::Invalid + ); + // The encoders say the same without going through `admits`, one day + // past the wire's range on either side included. + assert!(date(Int::I64(i64::MAX)).is_none()); + assert!(date(Int::I32(MAX_DATE_DAYS + 1)).is_none()); + assert!(date(Int::I32(MIN_DATE_DAYS - 1)).is_none()); + assert!(date(Int::I32(MAX_DATE_DAYS)).is_some()); + assert!(date(Int::I32(MIN_DATE_DAYS)).is_some()); + for days in [MAX_DATE_DAYS + 1, MIN_DATE_DAYS - 1] { + assert_eq!( + normalize(Some(Logical::Date), Physical::Int(Int::I32(days))).expect_err("invalid"), + NormalizeError::Invalid + ); + } + assert!(timestamp(TimeUnit::Nanos, Int::I128(i128::MAX)).is_none()); + assert!(decimal(29, Int::I32(1)).is_none()); + assert!(decimal(1, Int::U128(u128::MAX)).is_none()); + assert!(uuid(&[0; 15]).is_none()); +} + +#[test] +fn a_logical_value_never_shares_a_term_with_its_physical_value() { + let days = Int::I32(19_000); + assert_ne!(int(Some(Logical::Date), days), int(None, days)); + let count = Int::I64(1_700_000_000_000); + assert_ne!( + int(Some(Logical::Timestamp(TimeUnit::Millis)), count), + int(None, count) + ); + let mantissa = Int::I128(150); + assert_ne!( + int(Some(Logical::Decimal { scale: 2 }), mantissa), + int(None, mantissa) + ); + // A uuid is its sixteen bytes, so the domain alone keeps it apart from + // the same bytes written as bytes. + let id = [5u8; 16]; + assert_eq!(uuid(&id).expect("uuid").risky_ref(), bytes(&id).risky_ref()); + assert_ne!( + normalize(Some(Logical::Uuid), Physical::Bytes(&id)) + .expect("uuid") + .domain, + normalize(None, Physical::Bytes(&id)).expect("bytes").domain + ); +} + +#[test] +fn dates_are_orderable_days_from_the_common_era() { + // 0001-01-01 is day 1 from CE; 1970-01-01 is day 719163. + assert_eq!( + int(Some(Logical::Date), Int::I32(1 - EPOCH_DAYS_FROM_CE)), + [0x80, 0x00, 0x00, 0x01] + ); + assert_eq!( + int(Some(Logical::Date), Int::I32(0)), + ((EPOCH_DAYS_FROM_CE as u32) ^ (1 << 31)).to_be_bytes() + ); + assert!(int(Some(Logical::Date), Int::I32(-1)) < int(Some(Logical::Date), Int::I32(0))); + assert!(int(Some(Logical::Date), Int::I32(0)) < int(Some(Logical::Date), Int::I32(1))); +} + +#[test] +fn timestamps_in_any_unit_truncate_to_microseconds() { + let nanos = Int::I128(1_700_000_000_123_456_789); + let micros = Int::I64(1_700_000_000_123_456); + let millis = Int::I64(1_700_000_000_123); + let seconds = Int::I64(1_700_000_000); + let by = |unit, count| int(Some(Logical::Timestamp(unit)), count); + assert_eq!(by(TimeUnit::Nanos, nanos), by(TimeUnit::Micros, micros)); + assert_eq!( + by(TimeUnit::Millis, millis), + by(TimeUnit::Micros, Int::I64(1_700_000_000_123_000)) + ); + assert_eq!( + by(TimeUnit::Seconds, seconds), + by(TimeUnit::Nanos, Int::I128(1_700_000_000_000_000_000)) + ); + let mut expected = ((1_700_000_000u64) ^ (1 << 63)).to_be_bytes().to_vec(); + expected.extend_from_slice(&123_456_000u32.to_be_bytes()); + assert_eq!(by(TimeUnit::Nanos, nanos), expected); + // Before the epoch the seconds floor and the fraction stays positive. + let before = by(TimeUnit::Nanos, Int::I128(-1_000_000_000 + 123_456_789)); + let mut expected = ((-1i64 as u64) ^ (1 << 63)).to_be_bytes().to_vec(); + expected.extend_from_slice(&123_456_000u32.to_be_bytes()); + assert_eq!(before, expected); + assert!(before < by(TimeUnit::Seconds, Int::I64(0))); +} + +#[test] +fn decimals_normalize_scale_and_signed_zero() { + let by = |scale, mantissa| int(Some(Logical::Decimal { scale }), Int::I128(mantissa)); + assert_eq!(by(0, 1), by(1, 10)); + assert_eq!(by(0, 1), by(2, 100)); + assert_eq!(by(2, 150), by(1, 15)); + assert_eq!(by(2, 0), by(0, 0)); + assert_eq!(by(0, -0), by(0, 0)); + assert!(by(0, -1) < by(0, 0)); + assert!(by(0, 0) < by(0, 1)); + assert!(by(2, 150) < by(0, 2)); +} + +#[test] +fn nfc_expansion_fills_an_exactly_sized_buffer() { + // U+0344 is two UTF-8 bytes; its NFC form U+0308 U+0301 is four. + let normalized = text("\u{344}").expect("valid test value"); + assert_eq!(normalized.risky_ref(), "\u{308}\u{301}".as_bytes()); + assert_eq!(normalized.risky_ref().capacity(), 4); +} + +#[test] +fn unicode_version_and_equivalence_are_frozen() { + // Normalization stability makes newer NFC tables safe for text that is + // assigned in Unicode 16; the assignment table is the exact pin. + assert!(unicode_normalization::UNICODE_VERSION >= (16, 0, 0)); + assert_eq!(unicode_general_category::UNICODE_VERSION, (16, 0, 0)); + assert_eq!(term(None, Physical::Text("e\u{301}")), "é".as_bytes()); + assert_ne!( + term(None, Physical::Text("É")), + term(None, Physical::Text("é")) + ); + assert_ne!( + term(None, Physical::Text("e")), + term(None, Physical::Text("é")) + ); + for s in ["\u{378}", "\u{10ffff}", "\u{1faea}"] { + assert_eq!( + normalize(None, Physical::Text(s)).expect_err("unsupported input"), + NormalizeError::UnassignedCodePoint + ); + } + assert_eq!(text("a\0").expect("valid test value").risky_ref(), b"a\0"); +} + +#[quickcheck] +fn nfc_is_idempotent(s: String) -> bool { + match text(&s) { + Ok(first) => { + let first = String::from_utf8(first.risky_ref().clone()).expect("utf-8"); + text(&first).expect("valid test value").risky_ref() == first.as_bytes() + } + Err(_) => s + .chars() + .any(|c| get_general_category(c) == GeneralCategory::Unassigned), + } +} + +fn f32_term(v: f32) -> Vec { + term(None, Physical::Float(Float::F32(v))) +} + +fn f64_term(v: f64) -> Vec { + term(None, Physical::Float(Float::F64(v))) +} + +#[test] +fn floats_have_postgres_zero_and_nan_ordering() { + assert_eq!(f64_term(-0.0), f64_term(0.0)); + assert_eq!(f32_term(-0.0), f64_term(0.0)); + for bits in [0x7fc0_0000, 0xff80_0001, 0xffff_ffff, 0x7f80_0001] { + assert_eq!( + f32_term(f32::from_bits(bits)), + [0xff, 0xf8, 0, 0, 0, 0, 0, 0] + ); + } + for bits in [0x7ff8_0000_0000_0000, 0xfff0_0000_0000_0001, u64::MAX] { + assert_eq!( + f64_term(f64::from_bits(bits)), + [0xff, 0xf8, 0, 0, 0, 0, 0, 0] + ); + } + assert_eq!(f32_term(1.5), [0xbf, 0xf8, 0, 0, 0, 0, 0, 0]); + assert_eq!( + f32_term(-1.5), + [0x40, 0x07, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff] + ); + assert_eq!(f32_term(f32::INFINITY), [0xff, 0xf0, 0, 0, 0, 0, 0, 0]); + assert_eq!( + f32_term(f32::NEG_INFINITY), + [0, 0x0f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff] + ); + let ascending = [f64::NEG_INFINITY, -1.0, 0.0, 1.0, f64::INFINITY, f64::NAN]; + for pair in ascending.windows(2) { + assert!(f64_term(pair[0]) < f64_term(pair[1])); + } +} + +#[quickcheck] +fn f64_order_agrees_with_numeric_order(a: f64, b: f64) -> bool { + a.is_nan() + || b.is_nan() + || f64_term(a).cmp(&f64_term(b)) == a.partial_cmp(&b).expect("valid test value") +} + +#[test] +fn float_widths_share_one_domain_for_equal_numbers() { + for value in [ + 0.0f32, + 1.5, + -0.25, + 16_777_216.0, + f32::MAX, + f32::MIN_POSITIVE, + ] { + assert_eq!(f32_term(value), f64_term(value.into())); + } + // 0.1 is a different number in each width, so the terms differ. + assert_ne!(f32_term(0.1), f64_term(0.1)); +} + +fn widen_matches_hardware(bits: u32) -> bool { + let value = f32::from_bits(bits); + let (ours, hardware) = (widen_f32(value), f64::from(value)); + // NaN payload bits are folded later; only NaN-ness must agree for them. + if value.is_nan() { + ours.is_nan() && ours.is_sign_negative() == hardware.is_sign_negative() + } else { + ours.to_bits() == hardware.to_bits() + } +} + +#[test] +fn widening_matches_hardware_at_every_exponent_and_subnormal_bit() { + for sign in [0, 1u32 << 31] { + for exponent in 0..=0xffu32 { + for mantissa in [0, 1, 0x40_0000, 0x7f_ffff, 0x2a_aaaa] { + let bits = sign | (exponent << 23) | mantissa; + assert!(widen_matches_hardware(bits), "{bits:#010x}"); + } + } + for shift in 0..23 { + let bits = sign | 1 << shift; + assert!(widen_matches_hardware(bits), "{bits:#010x}"); + assert!( + widen_matches_hardware(bits | ((1 << shift) - 1)), + "{bits:#010x}" + ); + } + } +} + +#[quickcheck] +fn widening_matches_hardware_conversion(bits: u32) -> bool { + widen_matches_hardware(bits) +} + +/// Every f32 bit pattern; slow in debug builds, so run on demand with +/// `cargo test --release -p vitaminc-normalize -- --ignored`. +#[test] +#[ignore] +fn widening_matches_hardware_for_every_f32() { + assert!((0..=u32::MAX).all(widen_matches_hardware)); +} + +#[quickcheck] +fn f64_canonicalisation_is_idempotent(bits: u64) -> bool { + let value = canonical_f64(f64::from_bits(bits)); + canonical_f64(value).to_bits() == value.to_bits() +} + +/// Whether `bytes` holds exactly `expected`. The encoding is compared +/// through a borrow, so no copy of it is made outside its `Protected`, and +/// there is nothing left unwiped. Only the answer, which is not secret, +/// is taken out. +fn holds(bytes: &Protected>, expected: &[u8]) -> bool { + bytes.risky_ref().as_slice() == expected +} + +mod given_any_canonical_f64 { + use super::*; + + #[quickcheck] + fn returns_the_bytes_orderable_bytes_gives(bits: u64) -> bool { + let value = canonical_f64(f64::from_bits(bits)); + holds(&orderable_f64(value), &value.to_orderable_bytes()) + } +} + +#[test] +fn timestamps_one_past_the_wire_range_are_invalid() { + use vitaminc_aead::plaintext::kinds::{MAX_TIMESTAMP_NANOS, MIN_TIMESTAMP_NANOS}; + let ns = Logical::Timestamp(TimeUnit::Nanos); + assert!(timestamp(TimeUnit::Nanos, Int::I128(MAX_TIMESTAMP_NANOS)).is_some()); + assert!(timestamp(TimeUnit::Nanos, Int::I128(MIN_TIMESTAMP_NANOS)).is_some()); + for nanos in [MAX_TIMESTAMP_NANOS + 1, MIN_TIMESTAMP_NANOS - 1] { + assert!(timestamp(TimeUnit::Nanos, Int::I128(nanos)).is_none()); + assert_eq!( + normalize(Some(ns), Physical::Int(Int::I128(nanos))).expect_err("invalid"), + NormalizeError::Invalid + ); + } +} + +/// Whether `bytes` holds exactly `len` bytes in a buffer with room for +/// exactly `len`, checked inside the protected value with `zip_ref` so +/// the encoding never leaves its wrapper. Only the answer, which is not +/// secret, is taken out. +fn fills_exactly(bytes: &Protected>, len: usize) -> bool { + Protected::new(len) + .zip_ref(bytes, |len, bytes: &Vec| { + bytes.len() == len && bytes.capacity() == len + }) + .risky_unwrap() +} + +/// A `Vec` that grows frees its old buffer without wiping it, and spare +/// capacity is a sign the buffer was not made at its final size. So every +/// fixed-width encoder must return a buffer whose length is its capacity. +mod given_a_fixed_width_encoder { + use super::*; + + #[test] + fn returns_a_buffer_with_no_spare_capacity() { + for value in [Int::I8(-1), Int::U128(u128::MAX), Int::I128(i128::MIN)] { + assert!(fills_exactly(&integer(value), 17), "integer {value:?}"); + } + for value in [Float::F32(-1.5), Float::F64(f64::MAX), Float::F64(f64::NAN)] { + assert!(fills_exactly(&float(value), 8), "float {value:?}"); + } + for days in [Int::I32(-1), Int::I32(0), Int::I32(20_000)] { + let bytes = date(days).expect("in range"); + assert!(fills_exactly(&bytes, 4), "date {days:?}"); + } + for count in [Int::I64(-1), Int::I64(1_700_000_000_123)] { + let bytes = timestamp(TimeUnit::Millis, count).expect("in range"); + assert!(fills_exactly(&bytes, 12), "timestamp {count:?}"); + } + for (scale, mantissa) in [(0, Int::I64(0)), (2, Int::I64(-12_345)), (28, Int::I128(1))] { + let bytes = decimal(scale, mantissa).expect("in range"); + assert!( + fills_exactly(&bytes, 14), + "decimal {mantissa:?} at scale {scale}" + ); + } + } +} + +#[test] +fn debug_output_does_not_show_the_normalized_bytes() { + let n = normalize(None, Physical::Text("secret")).expect("text"); + let v = format!("{n:?}"); + assert!(v.contains(domain::TEXT), "{v}"); + assert!(v.contains("***"), "{v}"); + // "secret" as a `Vec` would print as [115, 101, 99, ...]. + assert!(!v.contains("secret") && !v.contains("115, 101, 99"), "{v}"); +} + +/// The widths an `i16` fits, each holding `n`. +fn every_width(n: i16) -> Vec { + let mut widths = vec![ + Int::I16(n), + Int::I32(n.into()), + Int::I64(n.into()), + Int::I128(n.into()), + ]; + if let Ok(v) = i8::try_from(n) { + widths.push(Int::I8(v)); + } + if let Ok(v) = u16::try_from(n) { + widths.extend([ + Int::U16(v), + Int::U32(v.into()), + Int::U64(v.into()), + Int::U128(v.into()), + ]); + } + if let Ok(v) = u8::try_from(n) { + widths.push(Int::U8(v)); + } + widths +} + +/// A logical term is over the number, not the width that carried it, as +/// the plain integer term is. +#[quickcheck] +fn a_logical_term_is_the_same_at_every_integer_width(n: i16) -> bool { + [ + Logical::Date, + Logical::Timestamp(TimeUnit::Seconds), + Logical::Decimal { scale: 2 }, + ] + .into_iter() + .all(|ty| { + let widths = every_width(n); + let first = int(Some(ty), widths[0]); + widths.iter().all(|&w| int(Some(ty), w) == first) + }) +} + +/// The 96-bit check is the only one between a direct caller and the +/// encoder, which would otherwise drop a mantissa's top bits and give it +/// the term of another value. +#[test] +fn decimal_refuses_a_mantissa_outside_96_bits_by_itself() { + let limit = 1i128 << 96; + assert!( + decimal(0, Int::I128(limit - 1)).is_some(), + "the largest mantissa" + ); + assert!( + decimal(0, Int::I128(1 - limit)).is_some(), + "the smallest mantissa" + ); + assert!( + decimal(0, Int::I128(limit)).is_none(), + "one past the largest" + ); + assert!( + decimal(0, Int::I128(-limit)).is_none(), + "one past the smallest" + ); + assert!( + decimal(5, Int::I128((1i128 << 104) + 10i128.pow(28))).is_none(), + "above 104 bits this would take the term of 10^23" + ); + assert!(decimal(0, Int::I128(i128::MAX)).is_none()); + assert!(decimal(0, Int::I128(i128::MIN)).is_none()); +} + +/// A null is one byte under a domain of its own, so every null in a space +/// ties with every other and with nothing else. +#[test] +fn a_null_is_one_zero_byte_under_the_null_domain() { + let null = normalize(None, Physical::Null).expect("a null has a term"); + assert_eq!(null.domain, domain::NULL, "a null has its own domain"); + assert_eq!( + null.domain, "vitaminc/prf/value/null/v1", + "the null label is frozen" + ); + assert_eq!(null.bytes.risky_ref(), &[0x00], "a null is the byte 0x00"); + assert_eq!(super::null().risky_ref(), &[0x00], "the encoder agrees"); + // No other domain's encoding is one zero byte under the null label. + let zero = normalize(None, Physical::Bytes(&[0x00])).expect("bytes"); + assert_ne!( + zero.domain, null.domain, + "the byte 0x00 as bytes is not a null" + ); +} diff --git a/packages/vitaminc-normalize/src/terms.rs b/packages/vitaminc-normalize/src/terms.rs new file mode 100644 index 000000000..42bed495e --- /dev/null +++ b/packages/vitaminc-normalize/src/terms.rs @@ -0,0 +1,815 @@ +//! Equality terms as a sink, and encryption that produces them in the +//! same walk. +//! +//! [`Terms`] is a [`Sink`] that produces one [`Term`] per scalar that has +//! an equality domain. It runs beside encryption as `Tee(EncryptSink, +//! Terms)`, so a caller holds every term before any cipher is called and, +//! with an async cipher, before the first await. [`terms`] runs it alone, +//! and then it refuses what encryption would refuse. +//! +//! The sink does the walking and the [`Normalize`] it is given does the +//! encoding, so an index of another kind (an order index, whose bytes +//! differ from an equality term's) collects its terms through the same +//! sink with a normalizer of its own, through [`Terms::by`] and +//! [`terms_by`]. + +use core::future::Future; +use core::marker::PhantomData; + +use vitaminc_aead::plaintext::{Error, Path, Step}; +use vitaminc_aead::seal::{seal_all, seal_all_async, AsyncCipher, Cipher}; +use vitaminc_aead::shape::{self, Locate, MapRules, SeqRules, Settle}; +use vitaminc_aead::{ + Encrypt, EncryptError, EncryptRef, EncryptSink, FixedType, IntoAad, Logical, MapSink, Node, + Pending, Physical, Refusal, SeqSink, Sink, SourceError, Tee, +}; + +use vitaminc_protected::OpaqueDebug; + +use crate::scalar::{normalize, NormalizeError, Normalized}; + +/// How [`Terms`] turns one scalar into a term. +/// +/// [`Equality`] is the normalizer this crate is about. An index of another +/// kind supplies its own, with a term type of its own (an order index +/// seals its term so only a scheme can read it) and the same outcome +/// contract: a scalar whose kind has no term under this index (a boolean, +/// or a null where the index gives nulls none) returns +/// [`NormalizeError::NoDomain`], and [`Terms`] skips it +/// when it has no logical type; a scalar whose logical type has no term +/// returns the same error and stops the walk; any other error stops the +/// walk too. +/// +/// A normalizer is copied into every child sink of a walk, so it is +/// `Copy`: it carries settings, such as the type an index declares, but +/// no state that a walk changes. +pub trait Normalize: Copy { + /// What one scalar becomes. + type Term; + + /// The kind of index the terms are for, as a refusal names it: + /// `"equality"` for [`Equality`], so a scalar it cannot normalize is + /// reported as having no equality term. + const INDEX: &'static str; + + /// The term for one scalar, or why it has none. + fn normalize( + &self, + ty: Option, + value: Physical<'_>, + ) -> Result; +} + +/// The equality normalizer: [`normalize`]. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct Equality; + +impl Normalize for Equality { + type Term = Normalized; + + const INDEX: &'static str = "equality"; + + fn normalize( + &self, + ty: Option, + value: Physical<'_>, + ) -> Result { + normalize(ty, value) + } +} + +/// One term: where the scalar sits in the value, and what the normalizer +/// made of it. An equality term, a [`Normalized`], unless [`Terms::by`] +/// was given another normalizer. +/// +/// `Debug` shows the path's shape, with its map keys masked as [`Step`] +/// masks them, and masks the term. +#[derive(OpaqueDebug)] +pub struct Term { + /// The path from the root, empty for a scalar at the root. + #[non_sensitive] + pub path: Path, + /// The term itself: for equality, the frozen domain label and the + /// normalized bytes. + pub normalized: T, +} + +/// A scalar [`Terms`] refused: why, and where in the value. +/// +/// This is the type to downcast a refusal to. Its +/// [`source`](core::error::Error::source) is the [`NormalizeError`], so a +/// reporter that walks the error chain reaches the reason too. +/// +/// `Display` shows only the reason, because the path can hold map keys and +/// map keys can be user data. `Debug` shows the reason and the path's +/// shape, with every key masked. Read the path with +/// [`path`](TermError::path). +#[derive(Clone, OpaqueDebug, thiserror::Error)] +#[error("no {index} term: {error}")] +pub struct TermError { + #[non_sensitive] + index: &'static str, + #[non_sensitive] + path: Path, + #[non_sensitive] + #[source] + error: NormalizeError, +} + +impl TermError { + /// The kind of index the scalar has no term for: the normalizer's + /// [`Normalize::INDEX`]. + pub fn index(&self) -> &'static str { + self.index + } + + /// Where the refused scalar sits, from the root. + pub fn path(&self) -> &Path { + &self.path + } + + /// Why the scalar has no term. + pub fn error(&self) -> NormalizeError { + self.error + } +} + +/// What [`terms`] fails with: what [`Terms`] refuses, or the source's own +/// failure. +/// +/// A source reports through [`Error::source`] whichever sink it feeds, so +/// every failure arrives as a [`SourceError`]. [`term`](TermsError::term) +/// recovers a [`TermError`] from it, the same downcast a caller makes on +/// [`EncryptError::Source`] when `Terms` runs beside encryption, and +/// [`refusal`](TermsError::refusal) a value refused for its shape, which +/// encryption reports as [`EncryptError::Shape`]. +/// [`source_error`](TermsError::source_error) is the error as it arrived. +#[derive(Debug, thiserror::Error)] +#[error(transparent)] +pub struct TermsError(SourceError); + +impl TermsError { + /// The scalar [`Terms`] refused, or `None` if the source failed on its + /// own or the value was refused for its shape. + pub fn term(&self) -> Option<&TermError> { + self.0.inner().downcast_ref() + } + + /// The value refused for its shape, as encryption would refuse it, or + /// `None` if it was refused for another reason. + pub fn refusal(&self) -> Option<&Refusal> { + self.0.inner().downcast_ref() + } + + /// The failure as the walk reported it: what [`Terms`] refused, or the + /// source's own error. + pub fn source_error(&self) -> &SourceError { + &self.0 + } +} + +impl Error for TermsError { + fn source(error: SourceError) -> Self { + Self(error) + } +} + +/// A sink that collects one [`Term`] per scalar with an equality domain, +/// in walk order. +/// +/// Generic over its error type so it adopts its [`Tee`] partner's. To +/// collect terms without encrypting, call [`terms`], whose error type is +/// [`TermsError`]. Generic too over the [`Normalize`] that encodes each +/// scalar, [`Equality`] unless [`by`](Terms::by) is given another, so an +/// index of another kind collects its terms through this same walk. +/// +/// Under [`Equality`] every null has a term, typed or plain, at the +/// null's path and under [`domain::NULL`](crate::domain::NULL), so an +/// absent value is indexed like any other. A layer that must keep a SQL +/// `NULL` for some column drops that term; its domain says it is a null. +/// +/// A scalar whose *kind* has no domain (a boolean, an `undefined`, or a +/// null under a normalizer that gives nulls none) produces no term and +/// does not stop the walk: an unindexable value is an ordinary thing to +/// find in a document, and the caller has the paths to see which fields +/// were indexed. A scalar whose *logical +/// type* has no domain ([`Logical::Unknown`], or a type this crate does +/// not know) stops the walk instead: it came from a newer client and +/// means something, and encrypting it with no term and no error would +/// leave an index silently incomplete. +/// +/// Passthrough subtrees travel in the clear and get no terms. +/// +/// # Only what can be encrypted +/// +/// A `Terms` refuses every value [`EncryptSink`] refuses, for the same +/// [`Unencryptable`](vitaminc_aead::Unencryptable) reason and at the same path, so an index never holds +/// terms for a value that cannot be stored. It keeps the +/// [`shape`] rules through the code `EncryptSink` +/// keeps them with: nothing deeper than the transport's depth limit, every +/// scalar valid for its logical type, every passthrough subtree framable, +/// no map key given twice, no child sink dropped without a value, and +/// something sealed in every container with children. The last rule is +/// about sealing, and this walk seals nothing, but a value that breaks it +/// cannot be encrypted, so it is refused here too. A passthrough is framed +/// as encryption frames it, to check that it can be, and the frame is +/// dropped. +/// +/// So [`terms`] accepts a value exactly when [`encrypt_with_terms`] does +/// with a cipher that does not fail, and refuses it for the same reason at +/// the same path. [`plan_with_terms`], and the encrypting functions built +/// on it, pair `EncryptSink` with a `Terms` that leaves the shape rules to +/// it, so they are kept once. +/// +/// # Errors +/// +/// The walk stops with `E::source(SourceError::new(error))`, where `error` +/// is one of: +/// +/// - a [`Refusal`]: the value breaks a shape rule, as above. A scalar not +/// valid for its logical type is refused this way, as +/// [`Unencryptable::InvalidValue`](vitaminc_aead::Unencryptable::InvalidValue), before it is normalized. Through +/// [`terms`] it is [`TermsError::refusal`]. Beside `EncryptSink`, which +/// refuses it first, it is [`EncryptError::Shape`]. +/// - a [`TermError`] holding the scalar's path and the +/// [`NormalizeError`]: the scalar's logical type has no domain +/// (`NoDomain`), or its text holds a code point unassigned in Unicode 16 +/// (`UnassignedCodePoint`). Beside [`EncryptSink`] that arrives as +/// [`EncryptError::Source`], and +/// `source.inner().downcast_ref::()` recovers it. Alone, +/// through [`terms`], it is [`TermsError::term`]. Either way the +/// [`NormalizeError`] is on the `source()` chain. +/// +/// # Cost +/// +/// A path costs nothing until a term is pushed or a refusal is built. Each +/// child sink holds a link to its container's place and its own index, or +/// the position of its key in one buffer of the keys on the path being +/// walked, which the whole walk shares and reuses. So the walk allocates +/// that buffer, as long as the keys on the longest path, and otherwise +/// only what each pushed term needs. +/// +/// The shape rules cost what they cost encryption: a map keeps one copy +/// of each of its keys until it ends, which is what checking for a repeat +/// exactly takes, and a passthrough is framed. Beside `EncryptSink`, +/// through [`plan_with_terms`], none of that is paid twice. A caller that +/// tees `Terms::new` beside `EncryptSink` itself has both keep the rules. +pub struct Terms<'t, E, N: Normalize = Equality> { + out: &'t mut Vec>, + keys: Keys<'t>, + at: Place<'t>, + /// `None` beside an [`EncryptSink`] that keeps the rules itself. + rules: Option>, + by: N, + _error: PhantomData, +} + +/// The shape rules one node keeps: how deep it sits, and its hold on its +/// container's rules, which it settles when it ends. The root has no +/// container. +struct NodeRules<'t> { + depth: usize, + settle: Option>, +} + +impl NodeRules<'_> { + /// The node put a sealed node: a scalar, or a container. + fn sealed(self) { + if let Some(settle) = self.settle { + settle.sealed(); + } + } +} + +/// A container's shape rules, `R`, with the rules of the node it is. +struct Held<'t, R> { + node: NodeRules<'t>, + rules: R, +} + +/// The map keys on the path being walked, end to end. The root owns the +/// buffer and every sink below it borrows it. A container truncates it +/// back to where its own keys begin before each child, so it holds only +/// the keys of the current path. +enum Keys<'t> { + Own(String), + Lent(&'t mut String), +} + +impl Keys<'_> { + fn get(&mut self) -> &mut String { + match self { + Keys::Own(keys) => keys, + Keys::Lent(keys) => keys, + } + } + + fn as_str(&self) -> &str { + match self { + Keys::Own(keys) => keys, + Keys::Lent(keys) => keys, + } + } +} + +/// Where a node sits: a link to its container's place and its own step. +/// A key is named by its position in [`Keys`]. +#[derive(Clone, Copy)] +enum Place<'t> { + Root, + Element { + parent: &'t Place<'t>, + index: usize, + }, + Entry { + parent: &'t Place<'t>, + key: (usize, usize), + }, +} + +impl Place<'_> { + /// Append the steps from the root to this node, reading keys from + /// `keys`. + fn locate(&self, keys: &str, steps: &mut Vec) { + match *self { + Place::Root => {} + Place::Element { parent, index } => { + parent.locate(keys, steps); + steps.push(Step::Index(index)); + } + Place::Entry { + parent, + key: (start, end), + } => { + parent.locate(keys, steps); + steps.extend(keys.get(start..end).map(|key| Step::Key(key.to_owned()))); + } + } + } + + /// The path from the root to this node. + fn path(&self, keys: &str) -> Path { + let mut steps = Vec::new(); + self.locate(keys, &mut steps); + Path::new(steps) + } +} + +/// A place with the keys it names: what the shape rules locate a refusal +/// with. +struct At<'a> { + place: &'a Place<'a>, + keys: &'a str, +} + +impl Locate for At<'_> { + fn locate(&self, steps: &mut Vec) { + self.place.locate(self.keys, steps); + } +} + +/// A shape refusal, reported the only way a sink generic over its error +/// can report anything. +fn refused(refusal: Refusal) -> E { + E::source(SourceError::new(refusal)) +} + +impl<'t, E> Terms<'t, E> { + /// A sink that appends equality terms to `out` and keeps the shape + /// rules itself. + pub fn new(out: &'t mut Vec) -> Self { + Self::by(Equality, out) + } + + /// A sink that appends to `out` and leaves the shape rules to the + /// [`EncryptSink`] it is teed beside, which refuses first. + fn beside_encryption(out: &'t mut Vec) -> Self { + Self { + rules: None, + ..Self::new(out) + } + } +} + +impl<'t, E, N: Normalize> Terms<'t, E, N> { + /// A sink that appends the terms `by` makes to `out` and keeps the + /// shape rules itself. + /// + /// The normalizer is copied into every child sink, which is why + /// [`Normalize`] requires `Copy`. + pub fn by(by: N, out: &'t mut Vec>) -> Self { + Self { + out, + keys: Keys::Own(String::new()), + at: Place::Root, + rules: Some(NodeRules { + depth: 0, + settle: None, + }), + by, + _error: PhantomData, + } + } + + fn at(&self) -> At<'_> { + At { + place: &self.at, + keys: self.keys.as_str(), + } + } +} + +impl<'t, E: Error, N: Normalize> Sink for Terms<'t, E, N> { + type Ok = (); + type Error = E; + type Seq = TermsSeq<'t, E, N>; + type Map = TermsMap<'t, E, N>; + + fn scalar(self, ty: Option, value: Physical<'_>) -> Result<(), E> { + if let Some(rules) = &self.rules { + shape::scalar(rules.depth, ty, &value, &self.at()).map_err(refused)?; + } + match self.by.normalize(ty, value) { + Ok(normalized) => { + let path = self.at.path(self.keys.as_str()); + self.out.push(Term { path, normalized }); + } + // No domain for the kind: nothing to index, carry on. No domain + // for a logical type: refuse, see the type's docs. + Err(NormalizeError::NoDomain) if matches!(ty, None | Some(Logical::Undefined)) => {} + Err(error) => { + return Err(E::source(SourceError::new(TermError { + index: N::INDEX, + path: self.at.path(self.keys.as_str()), + error, + }))) + } + } + if let Some(rules) = self.rules { + rules.sealed(); + } + Ok(()) + } + + /// Indexed as a plain null. Equality has no width, so the type adds + /// nothing: under [`Equality`] a typed null is the same term as a + /// plain one. + fn typed_null(self, _: FixedType) -> Result<(), E> { + self.scalar(None, Physical::Null) + } + + fn seq(self, _: Option) -> Result { + let rules = match self.rules { + Some(node) => { + shape::container( + node.depth, + &At { + place: &self.at, + keys: self.keys.as_str(), + }, + ) + .map_err(refused)?; + Some(Held { + node, + rules: SeqRules::new(), + }) + } + None => None, + }; + Ok(TermsSeq { + mark: self.keys.as_str().len(), + out: self.out, + keys: self.keys, + at: self.at, + next: 0, + rules, + by: self.by, + _error: PhantomData, + }) + } + + fn map(self, _: Option) -> Result { + let rules = match self.rules { + Some(node) => { + shape::container( + node.depth, + &At { + place: &self.at, + keys: self.keys.as_str(), + }, + ) + .map_err(refused)?; + Some(Held { + node, + rules: MapRules::new(), + }) + } + None => None, + }; + Ok(TermsMap { + mark: self.keys.as_str().len(), + out: self.out, + keys: self.keys, + at: self.at, + rules, + by: self.by, + _error: PhantomData, + }) + } + + /// No terms. Keeping the shape rules, the subtree is framed, as + /// encryption frames it, and the frame dropped. + fn passthrough(self, value: &P) -> Result<(), E> { + if let Some(rules) = self.rules { + let at = At { + place: &self.at, + keys: self.keys.as_str(), + }; + shape::frame_passthrough(value.lend(), rules.depth, &at, refused)?; + if let Some(settle) = rules.settle { + settle.passthrough(); + } + } + Ok(()) + } +} + +/// The sequence side of [`Terms`]: each element's path is the sequence's +/// plus its index. +pub struct TermsSeq<'t, E, N: Normalize = Equality> { + out: &'t mut Vec>, + keys: Keys<'t>, + /// Where this sequence's own keys would begin: the length of `keys` + /// at its start. + mark: usize, + at: Place<'t>, + next: usize, + rules: Option>, + by: N, + _error: PhantomData, +} + +impl SeqSink for TermsSeq<'_, E, N> { + type Ok = (); + type Error = E; + type Element<'s> + = Terms<'s, E, N> + where + Self: 's; + + fn element(&mut self) -> Result, E> { + let TermsSeq { + out, + keys, + mark, + at, + next, + rules, + by, + .. + } = self; + let keys = keys.get(); + let rules = match rules { + Some(held) => Some(NodeRules { + depth: held.node.depth + 1, + settle: Some( + held.rules + .element(&At { place: at, keys }) + .map_err(refused)?, + ), + }), + None => None, + }; + keys.truncate(*mark); + let index = *next; + *next += 1; + Ok(Terms { + out, + keys: Keys::Lent(keys), + at: Place::Element { parent: at, index }, + rules, + by: *by, + _error: PhantomData, + }) + } + + fn end(self) -> Result<(), E> { + if let Some(held) = self.rules { + let at = At { + place: &self.at, + keys: self.keys.as_str(), + }; + held.rules.end(&at).map_err(refused)?; + held.node.sealed(); + } + Ok(()) + } +} + +/// The map side of [`Terms`]: each entry's path is the map's plus its +/// key. +pub struct TermsMap<'t, E, N: Normalize = Equality> { + out: &'t mut Vec>, + keys: Keys<'t>, + /// Where this map's keys begin in `keys`: its length at the map's + /// start. Each entry's key replaces the last one there. + mark: usize, + at: Place<'t>, + rules: Option>, + by: N, + _error: PhantomData, +} + +impl MapSink for TermsMap<'_, E, N> { + type Ok = (); + type Error = E; + type Entry<'s> + = Terms<'s, E, N> + where + Self: 's; + + fn entry(&mut self, key: &str) -> Result, E> { + let TermsMap { + out, + keys, + mark, + at, + rules, + by, + .. + } = self; + let keys = keys.get(); + let rules = match rules { + Some(held) => Some(NodeRules { + depth: held.node.depth + 1, + settle: Some( + held.rules + .entry(key, &At { place: at, keys }) + .map_err(refused)?, + ), + }), + None => None, + }; + keys.truncate(*mark); + keys.push_str(key); + let key = (*mark, keys.len()); + Ok(Terms { + out, + keys: Keys::Lent(keys), + at: Place::Entry { parent: at, key }, + rules, + by: *by, + _error: PhantomData, + }) + } + + fn end(self) -> Result<(), E> { + if let Some(held) = self.rules { + let at = At { + place: &self.at, + keys: self.keys.as_str(), + }; + held.rules.end(&at).map_err(refused)?; + held.node.sealed(); + } + Ok(()) + } +} + +/// Every equality term of `value`, in walk order, without encrypting it. +/// +/// It refuses every value encryption refuses, for the same reason at the +/// same path (see [`Terms`]), so it never returns terms for a value that +/// cannot be stored. +/// +/// # Examples +/// +/// ``` +/// use std::collections::BTreeMap; +/// use vitaminc_normalize::{domain, terms, NormalizeError, Step}; +/// +/// let mut user = BTreeMap::new(); +/// user.insert("name", "Ada"); +/// let found = terms(&user)?; +/// assert_eq!(found[0].path.steps(), [Step::Key("name".into())]); +/// assert_eq!(found[0].normalized.domain, domain::TEXT); +/// +/// // U+0378 is unassigned in Unicode 16, so the name has no term. +/// user.insert("name", "\u{378}"); +/// let refused = terms(&user).unwrap_err(); +/// let term = refused.term().expect("refused by Terms"); +/// assert_eq!(term.error(), NormalizeError::UnassignedCodePoint); +/// assert_eq!(term.path().steps(), [Step::Key("name".into())]); +/// // The message names neither the field nor its value. +/// assert_eq!( +/// refused.to_string(), +/// "no equality term: text contains a code point unassigned in Unicode 16" +/// ); +/// +/// // A uuid of three bytes cannot be encrypted, so it has no term either: +/// // `terms` refuses it as encryption does. +/// use vitaminc_aead::{Logical, Physical, Raw, Unencryptable}; +/// let id = Raw(Some(Logical::Uuid), Physical::Bytes(&[0; 3])); +/// let refused = terms(id).unwrap_err(); +/// let refusal = refused.refusal().expect("refused for its shape"); +/// assert_eq!(refusal.reason(), Unencryptable::InvalidValue); +/// # Ok::<(), vitaminc_normalize::TermsError>(()) +/// ``` +/// +/// # Errors +/// +/// [`TermsError`]: what [`Terms`] refuses, a value encryption would refuse +/// included, or the source's own failure. +pub fn terms(value: P) -> Result, TermsError> { + terms_by(Equality, value) +} + +/// Every term of `value` under the normalizer `by`, in walk order, without +/// encrypting it: [`terms`] for an index of another kind. +/// +/// It refuses what [`terms`] refuses for the value's shape, and what `by` +/// refuses for a scalar, the way [`Terms`] describes. +/// +/// # Errors +/// +/// [`TermsError`]: what [`Terms`] refuses, a value encryption would refuse +/// included, or the source's own failure. +pub fn terms_by(by: N, value: P) -> Result>, TermsError> +where + N: Normalize, + P: Encrypt, +{ + let mut out = Vec::new(); + value.visit(Terms::by(by, &mut out))?; + Ok(out) +} + +/// A ciphertext tree and the terms of the value it was sealed from, in +/// walk order. +pub type WithTerms = (Node, Vec); + +/// Walk `value` into the encrypting sink and the terms sink at once, +/// without sealing: the planned tree of pending leaves, and every term. +/// +/// # Errors +/// +/// Everything [`EncryptSink`] refuses, plus what [`Terms`] refuses, which +/// arrives as [`EncryptError::Source`] carrying a [`TermError`]. +pub fn plan_with_terms<'a, P, E, A>(value: P, aad: A) -> Result, EncryptError> +where + P: Encrypt, + A: IntoAad<'a>, +{ + let mut terms = Vec::new(); + let (planned, ()) = value.visit(Tee( + EncryptSink::root(aad), + Terms::beside_encryption(&mut terms), + ))?; + Ok((planned, terms)) +} + +/// Encrypt `value` and produce its equality terms in the same walk. +/// +/// # Errors +/// +/// As [`plan_with_terms`], then [`EncryptError::Cipher`] if the cipher +/// refuses a leaf. +pub fn encrypt_with_terms<'a, P, C, A>( + value: P, + cipher: &C, + aad: A, +) -> Result, EncryptError> +where + P: Encrypt, + C: Cipher, + A: IntoAad<'a>, +{ + let (planned, terms) = plan_with_terms(value, aad)?; + Ok((seal_all(cipher, planned)?, terms)) +} + +/// Encrypt `value` through an async cipher and produce its equality terms +/// in the same walk. The walk, and so every term, is complete before the +/// future is returned, so the future holds only the planned leaves and is +/// `Send` even when the source is not. +/// +/// # Errors +/// +/// As [`encrypt_with_terms`]. A refusal during the walk is held in the +/// future and returned on its first poll. +pub fn encrypt_with_terms_async<'a, 'c, P, C, A>( + value: P, + cipher: &'c C, + aad: A, +) -> impl Future, EncryptError>> + Send + 'c +where + P: Encrypt, + C: AsyncCipher, + A: IntoAad<'a>, +{ + let planned = plan_with_terms(value, aad); + async move { + let (planned, terms) = planned?; + Ok((seal_all_async(cipher, planned).await?, terms)) + } +} diff --git a/packages/vitaminc-normalize/tasks.toml b/packages/vitaminc-normalize/tasks.toml new file mode 100644 index 000000000..c150c12b0 --- /dev/null +++ b/packages/vitaminc-normalize/tasks.toml @@ -0,0 +1,14 @@ +# Tasks for vitaminc-normalize, imported from cipherstash/vitaminc. Included +# from the root mise.toml. + +# Rustdoc with warnings as errors. The root `doc` task runs this task. +# It builds the public docs, then the docs of private items too. Only the +# public build warns when a public doc links to a private item. Only the +# private build checks the links in private docs. +["doc:vitaminc-normalize"] +description = "Build docs for vitaminc-normalize with all features, public then private items (warnings are errors)" +env = { RUSTDOCFLAGS = "-D warnings" } +run = [ + "cargo doc -p vitaminc-normalize --no-deps --all-features", + "cargo doc -p vitaminc-normalize --no-deps --all-features --document-private-items", +] diff --git a/packages/vitaminc-normalize/tests/agreement.rs b/packages/vitaminc-normalize/tests/agreement.rs new file mode 100644 index 000000000..d3ac4ea28 --- /dev/null +++ b/packages/vitaminc-normalize/tests/agreement.rs @@ -0,0 +1,393 @@ +//! `terms` and `encrypt_with_terms` agree on every value: each accepts +//! what the other accepts, with the same terms, and refuses what the other +//! refuses, for the same reason at the same path. One case per rule +//! encryption keeps, and per refusal of `Terms`'s own. + +use std::collections::BTreeMap; + +use vitaminc_aead::frame::MAX_DEPTH; +use vitaminc_aead::plaintext::render; +use vitaminc_aead::seal::Cipher; +use vitaminc_aead::{ + Context, Encrypt, EncryptError, EncryptRef, Logical, MapSink, Physical, Raw, SeqSink, Sink, + SourceError, Unencryptable, +}; +use vitaminc_normalize::{encrypt_with_terms, terms, NormalizeError, Term, TermError}; +use vitaminc_protected::{Controlled, Protected}; + +/// Seals in the clear: these tests are about the walk, not the cipher. +struct Clear; + +impl Cipher for Clear { + type Leaf = Vec; + type Error = &'static str; + + fn seal( + &self, + plaintext: Protected>, + _: &Context<'_>, + ) -> Result, &'static str> { + Ok(plaintext.risky_unwrap()) + } + + fn open(&self, leaf: Vec, _: &Context<'_>) -> Result>, &'static str> { + Ok(Protected::new(leaf)) + } +} + +/// How a walk ended, with every path written out. +#[derive(Debug, PartialEq)] +enum Outcome { + Terms(Vec), + Shape(Unencryptable, String), + Term(NormalizeError, String), + Source(String), +} + +use Outcome::{Shape, Source, Term as NoTerm, Terms}; + +fn paths(found: &[Term]) -> Outcome { + Terms(found.iter().map(|t| render(&t.path)).collect()) +} + +fn sourced(source: &SourceError) -> Outcome { + match source.inner().downcast_ref::() { + Some(term) => NoTerm(term.error(), render(term.path())), + None => Source(source.to_string()), + } +} + +fn alone(value: P) -> Outcome { + match terms(value) { + Ok(found) => paths(&found), + Err(err) => match err.refusal() { + Some(refusal) => Shape(refusal.reason(), render(refusal.path())), + None => sourced(err.source_error()), + }, + } +} + +fn encrypting(value: P) -> Outcome { + match encrypt_with_terms(value, &Clear, "ctx") { + Ok((_, found)) => paths(&found), + Err(EncryptError::Shape(refusal)) => Shape(refusal.reason(), render(refusal.path())), + Err(EncryptError::Source(source)) => sourced(&source), + Err(other) => panic!("{other:?}"), + } +} + +/// `value()` ends the same way both walks, and that way is `expected`. +#[track_caller] +fn agree(value: impl Fn() -> P, expected: Outcome) { + assert_eq!(encrypting(value()), expected, "encrypt_with_terms"); + assert_eq!(alone(value()), expected, "terms"); +} + +fn shape(reason: Unencryptable, at: &str) -> Outcome { + Shape(reason, at.to_owned()) +} + +/// A document whose `users` entry is a sequence of two values, the second +/// of them `bad`, beside a well-formed `id`, so every refusal below the +/// root has a path with a key and an index in it. +#[derive(Clone)] +struct Users

(P); + +impl Encrypt for Users

{ + fn visit(self, sink: S) -> Result { + let mut map = sink.map(Some(2))?; + 1u32.visit(map.entry("id")?)?; + let mut users = map.entry("users")?.seq(Some(2))?; + "ada".visit(users.element()?)?; + self.0.visit(users.element()?)?; + users.end()?; + map.end() + } +} + +/// A map that gives `k` twice. +#[derive(Clone)] +struct Dup; + +impl Encrypt for Dup { + fn visit(self, sink: S) -> Result { + let mut map = sink.map(None)?; + "one".visit(map.entry("k")?)?; + "two".visit(map.entry("k")?)?; + map.end() + } +} + +/// A container with one passthrough in it and nothing sealed. +#[derive(Clone)] +struct OnlyPass { + map: bool, +} + +impl Encrypt for OnlyPass { + fn visit(self, sink: S) -> Result { + if self.map { + let mut map = sink.map(Some(1))?; + map.entry("note")?.passthrough(&"public")?; + map.end() + } else { + let mut seq = sink.seq(Some(1))?; + seq.element()?.passthrough(&"public")?; + seq.end() + } + } +} + +/// A container whose source takes a child sink and drops it unused. +#[derive(Clone)] +struct DropsAChild { + map: bool, +} + +impl Encrypt for DropsAChild { + fn visit(self, sink: S) -> Result { + if self.map { + let mut map = sink.map(None)?; + let _ = map.entry("a")?; + "b".visit(map.entry("b")?)?; + map.end() + } else { + let mut seq = sink.seq(None)?; + "a".visit(seq.element()?)?; + let _ = seq.element()?; + seq.end() + } + } +} + +/// A passthrough that opens a container and never ends it. +#[derive(Clone)] +struct Unclosed; + +impl Encrypt for Unclosed { + fn visit(self, sink: S) -> Result { + let mut outer = sink.seq(None)?; + let mut inner = outer.element()?.seq(None)?; + 1u32.visit(inner.element()?)?; + drop(inner); + outer.end() + } +} + +/// `inner` as a passthrough, beside a sealed sibling. +struct Passes

(P); + +impl Encrypt for Passes

{ + fn visit(self, sink: S) -> Result { + let mut seq = sink.seq(Some(2))?; + "sealed".visit(seq.element()?)?; + seq.element()?.passthrough(&self.0)?; + seq.end() + } +} + +/// A source whose getter throws. +#[derive(Clone)] +struct Throws; + +impl Encrypt for Throws { + fn visit(self, _: S) -> Result { + Err(::source( + SourceError::msg("getter threw"), + )) + } +} + +#[derive(Clone, Copy)] +enum Kind { + Seq, + Map, + Pass, + Scalar, +} + +/// `n` levels of one kind of nesting around an innermost value at depth +/// `n`: an empty sequence, or for `Scalar`, a string inside sequences. +#[derive(Clone, Copy)] +struct Nest(Kind, usize); + +impl Encrypt for Nest { + fn visit(self, sink: S) -> Result { + let Nest(kind, n) = self; + if n == 0 { + return match kind { + Kind::Scalar => "deep".visit(sink), + _ => sink.seq(Some(0))?.end(), + }; + } + let inner = Nest(kind, n - 1); + match kind { + Kind::Seq | Kind::Scalar => { + let mut seq = sink.seq(Some(1))?; + inner.visit(seq.element()?)?; + seq.end() + } + Kind::Map => { + let mut map = sink.map(Some(1))?; + inner.visit(map.entry("k")?)?; + map.end() + } + Kind::Pass => sink.passthrough(&inner), + } + } +} + +/// A passthrough is lent, so a source a test passes through walks by +/// reference too, as the value it is. +macro_rules! lent_as_owned { + ($($ty:ident => $value:expr),+ $(,)?) => {$( + impl Encrypt for &$ty { + fn visit(self, sink: S) -> Result { + let owned: $ty = $value(self); + owned.visit(sink) + } + } + )+}; +} +lent_as_owned!( + Dup => |_| Dup, + Unclosed => |_| Unclosed, + Throws => |_| Throws, + Nest => |nest: &Nest| *nest, +); + +#[test] +fn both_accept_a_well_formed_value_with_the_same_terms() { + let doc = || { + let mut doc = BTreeMap::new(); + doc.insert("ages", vec![Some(36u32), None]); + doc.insert("empty", vec![]); + doc + }; + // The absent age has a term as the present one does. + agree(doc, Terms(vec![".ages[0]".into(), ".ages[1]".into()])); + // A passthrough beside a sealed sibling, and nesting right up to the + // limit, are fine. + agree(|| Passes("public"), Terms(vec!["[0]".into()])); + agree( + || Nest(Kind::Scalar, MAX_DEPTH), + Terms(vec!["[0]".repeat(MAX_DEPTH)]), + ); + agree(|| Nest(Kind::Map, MAX_DEPTH), Terms(Vec::new())); +} + +#[test] +fn both_refuse_a_duplicate_key_at_the_repeated_entry() { + agree( + || Users(Dup), + shape(Unencryptable::DuplicateKey, ".users[1].k"), + ); + agree(|| Dup, shape(Unencryptable::DuplicateKey, ".k")); +} + +#[test] +fn both_refuse_a_container_with_nothing_sealed() { + agree( + || Users(OnlyPass { map: false }), + shape(Unencryptable::SequenceHasNothingSealed, ".users[1]"), + ); + agree( + || Users(OnlyPass { map: true }), + shape(Unencryptable::MapHasNothingSealed, ".users[1]"), + ); + agree( + || OnlyPass { map: false }, + shape(Unencryptable::SequenceHasNothingSealed, ""), + ); +} + +#[test] +fn both_refuse_a_dropped_child_sink() { + for map in [false, true] { + agree( + || Users(DropsAChild { map }), + shape(Unencryptable::DroppedChild, ".users[1]"), + ); + } +} + +#[test] +fn both_refuse_a_value_invalid_for_its_logical_type() { + let invalid = || Raw(Some(Logical::Uuid), Physical::Bytes(&[0; 3])); + agree( + || Users(invalid()), + shape(Unencryptable::InvalidValue, ".users[1]"), + ); + // `undefined` over an int has no term either, but is refused all the + // same: it cannot be encrypted. + agree( + || { + Raw( + Some(Logical::Undefined), + Physical::Int(vitaminc_aead::Int::I8(1)), + ) + }, + shape(Unencryptable::InvalidValue, ""), + ); +} + +#[test] +fn both_refuse_a_passthrough_that_does_not_frame_at_the_passthrough() { + agree( + || Passes(Unclosed), + shape(Unencryptable::UnframablePassthrough, "[1]"), + ); + agree( + || Passes(Dup), + shape(Unencryptable::UnframablePassthrough, "[1]"), + ); + // A source error inside the passthrough is the source's, both ways. + agree(|| Passes(Throws), Source("getter threw".into())); +} + +#[test] +fn both_refuse_a_value_nested_too_deep_at_the_same_node() { + for (kind, step) in [(Kind::Seq, "[0]"), (Kind::Map, ".k"), (Kind::Scalar, "[0]")] { + agree( + || Nest(kind, MAX_DEPTH + 1), + shape(Unencryptable::TooDeep, &step.repeat(MAX_DEPTH + 1)), + ); + } + // A passthrough too deep, or with too much inside it, is refused as a + // whole at its own place. + agree( + || Nest(Kind::Pass, MAX_DEPTH + 1), + shape(Unencryptable::TooDeep, ""), + ); + agree( + || Passes(Nest(Kind::Seq, MAX_DEPTH - 1)), + shape(Unencryptable::TooDeep, "[1]"), + ); + agree( + || Users(Nest(Kind::Seq, MAX_DEPTH - 1)), + shape( + Unencryptable::TooDeep, + &format!(".users[1]{}", "[0]".repeat(MAX_DEPTH - 1)), + ), + ); +} + +#[test] +fn both_refuse_what_terms_refuses_with_the_same_term_error() { + agree( + || Users("\u{378}"), + NoTerm(NormalizeError::UnassignedCodePoint, ".users[1]".into()), + ); + let newer = || { + Users(Raw( + Some(Logical::from_wire(200, 0).expect("unknown")), + Physical::Bytes(b"x"), + )) + }; + agree(newer, NoTerm(NormalizeError::NoDomain, ".users[1]".into())); +} + +#[test] +fn both_pass_a_source_failure_through() { + agree(|| Users(Throws), Source("getter threw".into())); +} diff --git a/packages/vitaminc-normalize/tests/allocations.rs b/packages/vitaminc-normalize/tests/allocations.rs new file mode 100644 index 000000000..3f90434cc --- /dev/null +++ b/packages/vitaminc-normalize/tests/allocations.rs @@ -0,0 +1,68 @@ +//! What collecting terms beside encryption allocates, counted by a global +//! allocator. In its own test binary, so no other test allocates while one +//! is counting. + +use std::alloc::{GlobalAlloc, Layout, System}; +use std::collections::BTreeMap; +use std::sync::atomic::{AtomicUsize, Ordering}; + +use vitaminc_aead::plan; +use vitaminc_normalize::plan_with_terms; + +struct Counting; + +static ALLOCATIONS: AtomicUsize = AtomicUsize::new(0); + +// SAFETY: every call forwards to `System` unchanged; the counter is the +// only addition. +unsafe impl GlobalAlloc for Counting { + unsafe fn alloc(&self, layout: Layout) -> *mut u8 { + ALLOCATIONS.fetch_add(1, Ordering::SeqCst); + // SAFETY: the caller's contract is `System`'s. + unsafe { System.alloc(layout) } + } + + unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { + // SAFETY: the caller's contract is `System`'s. + unsafe { System.dealloc(ptr, layout) } + } + + unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 { + ALLOCATIONS.fetch_add(1, Ordering::SeqCst); + // SAFETY: the caller's contract is `System`'s. + unsafe { System.realloc(ptr, layout, new_size) } + } +} + +#[global_allocator] +static GLOBAL: Counting = Counting; + +fn allocations(f: impl FnOnce()) -> usize { + let before = ALLOCATIONS.load(Ordering::SeqCst); + f(); + ALLOCATIONS.load(Ordering::SeqCst) - before +} + +/// Beside encryption, a walk that pushes no term allocates one buffer for +/// the keys on its path and nothing for any container or entry, however +/// many there are. +#[test] +fn a_walk_with_no_terms_allocates_only_the_key_buffer() { + let mut inner = BTreeMap::new(); + for key in ["a", "b", "c", "d"] { + // Booleans, because they have no equality term. A null has one. + inner.insert(key, vec![true, false]); + } + let mut doc = BTreeMap::new(); + for key in ["p", "q", "r"] { + doc.insert(key, vec![inner.clone(), inner.clone()]); + } + let encrypting = allocations(|| { + plan::<_, (), _>(doc.clone(), "ctx").expect("plans"); + }); + let with_terms = allocations(|| { + let (_, terms) = plan_with_terms::<_, (), _>(doc.clone(), "ctx").expect("plans"); + assert!(terms.is_empty()); + }); + assert_eq!(with_terms, encrypting + 1); +} diff --git a/packages/vitaminc-normalize/tests/known_answers.rs b/packages/vitaminc-normalize/tests/known_answers.rs new file mode 100644 index 000000000..75495cfb9 --- /dev/null +++ b/packages/vitaminc-normalize/tests/known_answers.rs @@ -0,0 +1,1523 @@ +//! Known answers for every term: the bytes and the domain label each scalar +//! normalizes to, pinned as literals. These are the terms the `canonical` +//! encoders of `vitaminc-aead-value` produced before ADR 0001, captured +//! from them when that crate held them, so an index written then still +//! matches one written now. A change here is a change to a frozen domain. +//! +//! The second half is the terms sink beside encryption. + +use core::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::collections::BTreeMap; + +use futures_executor::block_on; +use vitaminc_aead::plaintext::kinds::jiff as conv; +use vitaminc_aead::plaintext::render; +use vitaminc_aead::seal::{AsyncCipher, Cipher}; +use vitaminc_aead::{ + Context, Encrypt, EncryptError, Float, Int, Logical, Physical, Refusal, SeqSink, Sink, + SourceError, TimeUnit, Unencryptable, +}; +use vitaminc_normalize::{ + domain, encrypt_with_terms, encrypt_with_terms_async, normalize, plan_with_terms, terms, + NormalizeError, Path, Term, TermError, +}; +use vitaminc_protected::{Controlled, Protected}; + +fn hex(bytes: &[u8]) -> String { + bytes.iter().map(|b| format!("{b:02x}")).collect() +} + +#[track_caller] +fn pin(ty: Option, v: Physical<'_>, domain: &str, bytes: &str) { + let term = normalize(ty, v).expect("normalizes"); + assert_eq!(term.domain, domain, "{ty:?} {v:?}"); + assert_eq!(hex(term.bytes.risky_ref()), bytes, "{ty:?} {v:?}"); +} + +#[test] +fn every_integer_width_normalizes_to_its_pinned_term() { + pin( + None, + Physical::Int(Int::I8(0)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000000000000000000000", + ); + pin( + None, + Physical::Int(Int::U8(0)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000000000000000000000", + ); + pin( + None, + Physical::Int(Int::I16(0)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000000000000000000000", + ); + pin( + None, + Physical::Int(Int::U16(0)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000000000000000000000", + ); + pin( + None, + Physical::Int(Int::I32(0)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000000000000000000000", + ); + pin( + None, + Physical::Int(Int::U32(0)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000000000000000000000", + ); + pin( + None, + Physical::Int(Int::I64(0)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000000000000000000000", + ); + pin( + None, + Physical::Int(Int::U64(0)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000000000000000000000", + ); + pin( + None, + Physical::Int(Int::I128(0)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000000000000000000000", + ); + pin( + None, + Physical::Int(Int::U128(0)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000000000000000000000", + ); + pin( + None, + Physical::Int(Int::I8(1)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000000000000000000001", + ); + pin( + None, + Physical::Int(Int::U8(1)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000000000000000000001", + ); + pin( + None, + Physical::Int(Int::I16(1)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000000000000000000001", + ); + pin( + None, + Physical::Int(Int::U16(1)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000000000000000000001", + ); + pin( + None, + Physical::Int(Int::I32(1)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000000000000000000001", + ); + pin( + None, + Physical::Int(Int::U32(1)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000000000000000000001", + ); + pin( + None, + Physical::Int(Int::I64(1)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000000000000000000001", + ); + pin( + None, + Physical::Int(Int::U64(1)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000000000000000000001", + ); + pin( + None, + Physical::Int(Int::I128(1)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000000000000000000001", + ); + pin( + None, + Physical::Int(Int::U128(1)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000000000000000000001", + ); + pin( + None, + Physical::Int(Int::I8(5)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000000000000000000005", + ); + pin( + None, + Physical::Int(Int::U8(5)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000000000000000000005", + ); + pin( + None, + Physical::Int(Int::I16(5)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000000000000000000005", + ); + pin( + None, + Physical::Int(Int::U16(5)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000000000000000000005", + ); + pin( + None, + Physical::Int(Int::I32(5)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000000000000000000005", + ); + pin( + None, + Physical::Int(Int::U32(5)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000000000000000000005", + ); + pin( + None, + Physical::Int(Int::I64(5)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000000000000000000005", + ); + pin( + None, + Physical::Int(Int::U64(5)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000000000000000000005", + ); + pin( + None, + Physical::Int(Int::I128(5)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000000000000000000005", + ); + pin( + None, + Physical::Int(Int::U128(5)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000000000000000000005", + ); + pin( + None, + Physical::Int(Int::I8(-7)), + "vitaminc/prf/value/integer-orderable/v1", + "00fffffffffffffffffffffffffffffff9", + ); + pin( + None, + Physical::Int(Int::I16(-7)), + "vitaminc/prf/value/integer-orderable/v1", + "00fffffffffffffffffffffffffffffff9", + ); + pin( + None, + Physical::Int(Int::I32(-7)), + "vitaminc/prf/value/integer-orderable/v1", + "00fffffffffffffffffffffffffffffff9", + ); + pin( + None, + Physical::Int(Int::I64(-7)), + "vitaminc/prf/value/integer-orderable/v1", + "00fffffffffffffffffffffffffffffff9", + ); + pin( + None, + Physical::Int(Int::I128(-7)), + "vitaminc/prf/value/integer-orderable/v1", + "00fffffffffffffffffffffffffffffff9", + ); + pin( + None, + Physical::Int(Int::I8(127)), + "vitaminc/prf/value/integer-orderable/v1", + "010000000000000000000000000000007f", + ); + pin( + None, + Physical::Int(Int::U8(127)), + "vitaminc/prf/value/integer-orderable/v1", + "010000000000000000000000000000007f", + ); + pin( + None, + Physical::Int(Int::I16(127)), + "vitaminc/prf/value/integer-orderable/v1", + "010000000000000000000000000000007f", + ); + pin( + None, + Physical::Int(Int::U16(127)), + "vitaminc/prf/value/integer-orderable/v1", + "010000000000000000000000000000007f", + ); + pin( + None, + Physical::Int(Int::I32(127)), + "vitaminc/prf/value/integer-orderable/v1", + "010000000000000000000000000000007f", + ); + pin( + None, + Physical::Int(Int::U32(127)), + "vitaminc/prf/value/integer-orderable/v1", + "010000000000000000000000000000007f", + ); + pin( + None, + Physical::Int(Int::I64(127)), + "vitaminc/prf/value/integer-orderable/v1", + "010000000000000000000000000000007f", + ); + pin( + None, + Physical::Int(Int::U64(127)), + "vitaminc/prf/value/integer-orderable/v1", + "010000000000000000000000000000007f", + ); + pin( + None, + Physical::Int(Int::I128(127)), + "vitaminc/prf/value/integer-orderable/v1", + "010000000000000000000000000000007f", + ); + pin( + None, + Physical::Int(Int::U128(127)), + "vitaminc/prf/value/integer-orderable/v1", + "010000000000000000000000000000007f", + ); + pin( + None, + Physical::Int(Int::I8(-128)), + "vitaminc/prf/value/integer-orderable/v1", + "00ffffffffffffffffffffffffffffff80", + ); + pin( + None, + Physical::Int(Int::I16(-128)), + "vitaminc/prf/value/integer-orderable/v1", + "00ffffffffffffffffffffffffffffff80", + ); + pin( + None, + Physical::Int(Int::I32(-128)), + "vitaminc/prf/value/integer-orderable/v1", + "00ffffffffffffffffffffffffffffff80", + ); + pin( + None, + Physical::Int(Int::I64(-128)), + "vitaminc/prf/value/integer-orderable/v1", + "00ffffffffffffffffffffffffffffff80", + ); + pin( + None, + Physical::Int(Int::I128(-128)), + "vitaminc/prf/value/integer-orderable/v1", + "00ffffffffffffffffffffffffffffff80", + ); + pin( + None, + Physical::Int(Int::U8(255)), + "vitaminc/prf/value/integer-orderable/v1", + "01000000000000000000000000000000ff", + ); + pin( + None, + Physical::Int(Int::I16(255)), + "vitaminc/prf/value/integer-orderable/v1", + "01000000000000000000000000000000ff", + ); + pin( + None, + Physical::Int(Int::U16(255)), + "vitaminc/prf/value/integer-orderable/v1", + "01000000000000000000000000000000ff", + ); + pin( + None, + Physical::Int(Int::I32(255)), + "vitaminc/prf/value/integer-orderable/v1", + "01000000000000000000000000000000ff", + ); + pin( + None, + Physical::Int(Int::U32(255)), + "vitaminc/prf/value/integer-orderable/v1", + "01000000000000000000000000000000ff", + ); + pin( + None, + Physical::Int(Int::I64(255)), + "vitaminc/prf/value/integer-orderable/v1", + "01000000000000000000000000000000ff", + ); + pin( + None, + Physical::Int(Int::U64(255)), + "vitaminc/prf/value/integer-orderable/v1", + "01000000000000000000000000000000ff", + ); + pin( + None, + Physical::Int(Int::I128(255)), + "vitaminc/prf/value/integer-orderable/v1", + "01000000000000000000000000000000ff", + ); + pin( + None, + Physical::Int(Int::U128(255)), + "vitaminc/prf/value/integer-orderable/v1", + "01000000000000000000000000000000ff", + ); + pin( + None, + Physical::Int(Int::U16(65535)), + "vitaminc/prf/value/integer-orderable/v1", + "010000000000000000000000000000ffff", + ); + pin( + None, + Physical::Int(Int::I32(65535)), + "vitaminc/prf/value/integer-orderable/v1", + "010000000000000000000000000000ffff", + ); + pin( + None, + Physical::Int(Int::U32(65535)), + "vitaminc/prf/value/integer-orderable/v1", + "010000000000000000000000000000ffff", + ); + pin( + None, + Physical::Int(Int::I64(65535)), + "vitaminc/prf/value/integer-orderable/v1", + "010000000000000000000000000000ffff", + ); + pin( + None, + Physical::Int(Int::U64(65535)), + "vitaminc/prf/value/integer-orderable/v1", + "010000000000000000000000000000ffff", + ); + pin( + None, + Physical::Int(Int::I128(65535)), + "vitaminc/prf/value/integer-orderable/v1", + "010000000000000000000000000000ffff", + ); + pin( + None, + Physical::Int(Int::U128(65535)), + "vitaminc/prf/value/integer-orderable/v1", + "010000000000000000000000000000ffff", + ); + pin( + None, + Physical::Int(Int::I16(-32768)), + "vitaminc/prf/value/integer-orderable/v1", + "00ffffffffffffffffffffffffffff8000", + ); + pin( + None, + Physical::Int(Int::I32(-32768)), + "vitaminc/prf/value/integer-orderable/v1", + "00ffffffffffffffffffffffffffff8000", + ); + pin( + None, + Physical::Int(Int::I64(-32768)), + "vitaminc/prf/value/integer-orderable/v1", + "00ffffffffffffffffffffffffffff8000", + ); + pin( + None, + Physical::Int(Int::I128(-32768)), + "vitaminc/prf/value/integer-orderable/v1", + "00ffffffffffffffffffffffffffff8000", + ); + pin( + None, + Physical::Int(Int::I128(-170141183460469231731687303715884105728)), + "vitaminc/prf/value/integer-orderable/v1", + "0080000000000000000000000000000000", + ); + pin( + None, + Physical::Int(Int::I128(170141183460469231731687303715884105727)), + "vitaminc/prf/value/integer-orderable/v1", + "017fffffffffffffffffffffffffffffff", + ); + pin( + None, + Physical::Int(Int::I16(32767)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000000000000000007fff", + ); + pin( + None, + Physical::Int(Int::I32(-2147483648)), + "vitaminc/prf/value/integer-orderable/v1", + "00ffffffffffffffffffffffff80000000", + ); + pin( + None, + Physical::Int(Int::I32(2147483647)), + "vitaminc/prf/value/integer-orderable/v1", + "010000000000000000000000007fffffff", + ); + pin( + None, + Physical::Int(Int::I64(-9223372036854775808)), + "vitaminc/prf/value/integer-orderable/v1", + "00ffffffffffffffff8000000000000000", + ); + pin( + None, + Physical::Int(Int::I64(9223372036854775807)), + "vitaminc/prf/value/integer-orderable/v1", + "0100000000000000007fffffffffffffff", + ); + pin( + None, + Physical::Int(Int::U32(4294967295)), + "vitaminc/prf/value/integer-orderable/v1", + "01000000000000000000000000ffffffff", + ); + pin( + None, + Physical::Int(Int::U64(18446744073709551615)), + "vitaminc/prf/value/integer-orderable/v1", + "010000000000000000ffffffffffffffff", + ); + pin( + None, + Physical::Int(Int::U128(340282366920938463463374607431768211455)), + "vitaminc/prf/value/integer-orderable/v1", + "01ffffffffffffffffffffffffffffffff", + ); +} + +#[test] +fn both_float_widths_normalize_to_their_pinned_terms() { + pin( + None, + Physical::Float(Float::F32(f32::from_bits(0x0))), + "vitaminc/prf/value/float-orderable/v1", + "8000000000000000", + ); + pin( + None, + Physical::Float(Float::F32(f32::from_bits(0x80000000))), + "vitaminc/prf/value/float-orderable/v1", + "8000000000000000", + ); + pin( + None, + Physical::Float(Float::F32(f32::from_bits(0x3fc00000))), + "vitaminc/prf/value/float-orderable/v1", + "bff8000000000000", + ); + pin( + None, + Physical::Float(Float::F32(f32::from_bits(0xbfc00000))), + "vitaminc/prf/value/float-orderable/v1", + "4007ffffffffffff", + ); + pin( + None, + Physical::Float(Float::F32(f32::from_bits(0x3dcccccd))), + "vitaminc/prf/value/float-orderable/v1", + "bfb99999a0000000", + ); + pin( + None, + Physical::Float(Float::F32(f32::from_bits(0x7f7fffff))), + "vitaminc/prf/value/float-orderable/v1", + "c7efffffe0000000", + ); + pin( + None, + Physical::Float(Float::F32(f32::from_bits(0x800000))), + "vitaminc/prf/value/float-orderable/v1", + "b810000000000000", + ); + pin( + None, + Physical::Float(Float::F32(f32::from_bits(0x7f800000))), + "vitaminc/prf/value/float-orderable/v1", + "fff0000000000000", + ); + pin( + None, + Physical::Float(Float::F32(f32::from_bits(0xff800000))), + "vitaminc/prf/value/float-orderable/v1", + "000fffffffffffff", + ); + pin( + None, + Physical::Float(Float::F32(f32::from_bits(0x7fc00000))), + "vitaminc/prf/value/float-orderable/v1", + "fff8000000000000", + ); + pin( + None, + Physical::Float(Float::F32(f32::from_bits(0xff800001))), + "vitaminc/prf/value/float-orderable/v1", + "fff8000000000000", + ); + pin( + None, + Physical::Float(Float::F32(f32::from_bits(0x1))), + "vitaminc/prf/value/float-orderable/v1", + "b6a0000000000000", + ); + pin( + None, + Physical::Float(Float::F64(f64::from_bits(0x0))), + "vitaminc/prf/value/float-orderable/v1", + "8000000000000000", + ); + pin( + None, + Physical::Float(Float::F64(f64::from_bits(0x8000000000000000))), + "vitaminc/prf/value/float-orderable/v1", + "8000000000000000", + ); + pin( + None, + Physical::Float(Float::F64(f64::from_bits(0x3ff8000000000000))), + "vitaminc/prf/value/float-orderable/v1", + "bff8000000000000", + ); + pin( + None, + Physical::Float(Float::F64(f64::from_bits(0x3fb999999999999a))), + "vitaminc/prf/value/float-orderable/v1", + "bfb999999999999a", + ); + pin( + None, + Physical::Float(Float::F64(f64::from_bits(0x7fefffffffffffff))), + "vitaminc/prf/value/float-orderable/v1", + "ffefffffffffffff", + ); + pin( + None, + Physical::Float(Float::F64(f64::from_bits(0x10000000000000))), + "vitaminc/prf/value/float-orderable/v1", + "8010000000000000", + ); + pin( + None, + Physical::Float(Float::F64(f64::from_bits(0x7ff0000000000000))), + "vitaminc/prf/value/float-orderable/v1", + "fff0000000000000", + ); + pin( + None, + Physical::Float(Float::F64(f64::from_bits(0xfff0000000000000))), + "vitaminc/prf/value/float-orderable/v1", + "000fffffffffffff", + ); + pin( + None, + Physical::Float(Float::F64(f64::from_bits(0x7ff8000000000000))), + "vitaminc/prf/value/float-orderable/v1", + "fff8000000000000", + ); + pin( + None, + Physical::Float(Float::F64(f64::from_bits(0xfff0000000000001))), + "vitaminc/prf/value/float-orderable/v1", + "fff8000000000000", + ); +} + +#[test] +fn text_and_bytes_normalize_to_their_pinned_terms() { + pin( + None, + Physical::Text(""), + "vitaminc/prf/value/text-nfc/unicode-16/v1", + "", + ); + pin( + None, + Physical::Text("Ada"), + "vitaminc/prf/value/text-nfc/unicode-16/v1", + "416461", + ); + pin( + None, + Physical::Text("e\u{301}"), + "vitaminc/prf/value/text-nfc/unicode-16/v1", + "c3a9", + ); + pin( + None, + Physical::Text("\u{344}"), + "vitaminc/prf/value/text-nfc/unicode-16/v1", + "cc88cc81", + ); + pin( + None, + Physical::Text("a\0b"), + "vitaminc/prf/value/text-nfc/unicode-16/v1", + "610062", + ); + pin( + None, + Physical::Text("日本語"), + "vitaminc/prf/value/text-nfc/unicode-16/v1", + "e697a5e69cace8aa9e", + ); + pin( + None, + Physical::Bytes(&[]), + "vitaminc/prf/value/bytes/v1", + "", + ); + pin( + None, + Physical::Bytes(&[0x00]), + "vitaminc/prf/value/bytes/v1", + "00", + ); + pin( + None, + Physical::Bytes(&[0x01, 0x02, 0x03]), + "vitaminc/prf/value/bytes/v1", + "010203", + ); + pin( + None, + Physical::Bytes(&[ + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + ]), + "vitaminc/prf/value/bytes/v1", + "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", + ); + assert_eq!( + normalize(None, Physical::Text("\u{378}")).expect_err("unassigned"), + NormalizeError::UnassignedCodePoint + ); +} + +#[test] +fn dates_normalize_to_their_pinned_terms() { + // The wire's minimum (jiff's Date::MIN, -9999-01-01), 0001-01-01, + // 1969-12-31, 1970-01-01, 2024-02-29, the wire's maximum (jiff's + // Date::MAX, 9999-12-31). + pin( + Some(Logical::Date), + Physical::Int(Int::I32(-4371587)), + "vitaminc/prf/value/date-orderable/v1", + "7fc844b8", + ); + pin( + Some(Logical::Date), + Physical::Int(Int::I32(-719162)), + "vitaminc/prf/value/date-orderable/v1", + "80000001", + ); + pin( + Some(Logical::Date), + Physical::Int(Int::I32(-1)), + "vitaminc/prf/value/date-orderable/v1", + "800af93a", + ); + pin( + Some(Logical::Date), + Physical::Int(Int::I32(0)), + "vitaminc/prf/value/date-orderable/v1", + "800af93b", + ); + pin( + Some(Logical::Date), + Physical::Int(Int::I32(19782)), + "vitaminc/prf/value/date-orderable/v1", + "800b4681", + ); + pin( + Some(Logical::Date), + Physical::Int(Int::I32(2932896)), + "vitaminc/prf/value/date-orderable/v1", + "8037b9db", + ); +} + +#[test] +fn timestamps_in_every_unit_normalize_to_their_pinned_terms() { + // Five instants as nanoseconds, each then truncated to micros, millis + // and seconds (a coarser unit matches the term of the instant at that + // precision), then the wire's minimum and maximum (jiff's + // Timestamp::MIN and Timestamp::MAX). + pin( + Some(Logical::Timestamp(TimeUnit::Nanos)), + Physical::Int(Int::I128(0)), + "vitaminc/prf/value/timestamp-micros-orderable/v1", + "800000000000000000000000", + ); + pin( + Some(Logical::Timestamp(TimeUnit::Micros)), + Physical::Int(Int::I64(0)), + "vitaminc/prf/value/timestamp-micros-orderable/v1", + "800000000000000000000000", + ); + pin( + Some(Logical::Timestamp(TimeUnit::Millis)), + Physical::Int(Int::I64(0)), + "vitaminc/prf/value/timestamp-micros-orderable/v1", + "800000000000000000000000", + ); + pin( + Some(Logical::Timestamp(TimeUnit::Seconds)), + Physical::Int(Int::I64(0)), + "vitaminc/prf/value/timestamp-micros-orderable/v1", + "800000000000000000000000", + ); + pin( + Some(Logical::Timestamp(TimeUnit::Nanos)), + Physical::Int(Int::I128(-876543211)), + "vitaminc/prf/value/timestamp-micros-orderable/v1", + "7fffffffffffffff075bca00", + ); + pin( + Some(Logical::Timestamp(TimeUnit::Micros)), + Physical::Int(Int::I64(-876544)), + "vitaminc/prf/value/timestamp-micros-orderable/v1", + "7fffffffffffffff075bca00", + ); + pin( + Some(Logical::Timestamp(TimeUnit::Millis)), + Physical::Int(Int::I64(-877)), + "vitaminc/prf/value/timestamp-micros-orderable/v1", + "7fffffffffffffff0754d4c0", + ); + pin( + Some(Logical::Timestamp(TimeUnit::Seconds)), + Physical::Int(Int::I64(-1)), + "vitaminc/prf/value/timestamp-micros-orderable/v1", + "7fffffffffffffff00000000", + ); + pin( + Some(Logical::Timestamp(TimeUnit::Nanos)), + Physical::Int(Int::I128(59999999999)), + "vitaminc/prf/value/timestamp-micros-orderable/v1", + "800000000000003b3b9ac618", + ); + pin( + Some(Logical::Timestamp(TimeUnit::Micros)), + Physical::Int(Int::I64(59999999)), + "vitaminc/prf/value/timestamp-micros-orderable/v1", + "800000000000003b3b9ac618", + ); + pin( + Some(Logical::Timestamp(TimeUnit::Millis)), + Physical::Int(Int::I64(59999)), + "vitaminc/prf/value/timestamp-micros-orderable/v1", + "800000000000003b3b8b87c0", + ); + pin( + Some(Logical::Timestamp(TimeUnit::Seconds)), + Physical::Int(Int::I64(59)), + "vitaminc/prf/value/timestamp-micros-orderable/v1", + "800000000000003b00000000", + ); + pin( + Some(Logical::Timestamp(TimeUnit::Nanos)), + Physical::Int(Int::I128(1700000000123456789)), + "vitaminc/prf/value/timestamp-micros-orderable/v1", + "800000006553f100075bca00", + ); + pin( + Some(Logical::Timestamp(TimeUnit::Micros)), + Physical::Int(Int::I64(1700000000123456)), + "vitaminc/prf/value/timestamp-micros-orderable/v1", + "800000006553f100075bca00", + ); + pin( + Some(Logical::Timestamp(TimeUnit::Millis)), + Physical::Int(Int::I64(1700000000123)), + "vitaminc/prf/value/timestamp-micros-orderable/v1", + "800000006553f1000754d4c0", + ); + pin( + Some(Logical::Timestamp(TimeUnit::Seconds)), + Physical::Int(Int::I64(1700000000)), + "vitaminc/prf/value/timestamp-micros-orderable/v1", + "800000006553f10000000000", + ); + pin( + Some(Logical::Timestamp(TimeUnit::Nanos)), + Physical::Int(Int::I128(-61999999999999995000)), + "vitaminc/prf/value/timestamp-micros-orderable/v1", + "7ffffff19083140000001388", + ); + pin( + Some(Logical::Timestamp(TimeUnit::Micros)), + Physical::Int(Int::I64(-61999999999999995)), + "vitaminc/prf/value/timestamp-micros-orderable/v1", + "7ffffff19083140000001388", + ); + pin( + Some(Logical::Timestamp(TimeUnit::Millis)), + Physical::Int(Int::I64(-62000000000000)), + "vitaminc/prf/value/timestamp-micros-orderable/v1", + "7ffffff19083140000000000", + ); + pin( + Some(Logical::Timestamp(TimeUnit::Seconds)), + Physical::Int(Int::I64(-62000000000)), + "vitaminc/prf/value/timestamp-micros-orderable/v1", + "7ffffff19083140000000000", + ); + pin( + Some(Logical::Timestamp(TimeUnit::Nanos)), + Physical::Int(Int::I128(-377705023201000000000)), + "vitaminc/prf/value/timestamp-micros-orderable/v1", + "7fffffa80f06b91f00000000", + ); + pin( + Some(Logical::Timestamp(TimeUnit::Nanos)), + Physical::Int(Int::I128(253402207200999999999)), + "vitaminc/prf/value/timestamp-micros-orderable/v1", + "8000003afff2d3e03b9ac618", + ); +} + +#[test] +fn decimals_normalize_to_their_pinned_terms() { + // 0 + pin( + Some(Logical::Decimal { scale: 0 }), + Physical::Int(Int::I128(0)), + "vitaminc/prf/value/decimal-orderable/v1", + "8000000000000000000000000000", + ); + // 0.0 + pin( + Some(Logical::Decimal { scale: 1 }), + Physical::Int(Int::I128(0)), + "vitaminc/prf/value/decimal-orderable/v1", + "8000000000000000000000000000", + ); + // -0.00 + pin( + Some(Logical::Decimal { scale: 2 }), + Physical::Int(Int::I128(0)), + "vitaminc/prf/value/decimal-orderable/v1", + "8000000000000000000000000000", + ); + // 1 + pin( + Some(Logical::Decimal { scale: 0 }), + Physical::Int(Int::I128(1)), + "vitaminc/prf/value/decimal-orderable/v1", + "c000204fce5e3e25026110000000", + ); + // 1.0 + pin( + Some(Logical::Decimal { scale: 1 }), + Physical::Int(Int::I128(10)), + "vitaminc/prf/value/decimal-orderable/v1", + "c000204fce5e3e25026110000000", + ); + // 1.50 + pin( + Some(Logical::Decimal { scale: 2 }), + Physical::Int(Int::I128(150)), + "vitaminc/prf/value/decimal-orderable/v1", + "c0003077b58d5d37839198000000", + ); + // 1.5 + pin( + Some(Logical::Decimal { scale: 1 }), + Physical::Int(Int::I128(15)), + "vitaminc/prf/value/decimal-orderable/v1", + "c0003077b58d5d37839198000000", + ); + // -1.5 + pin( + Some(Logical::Decimal { scale: 1 }), + Physical::Int(Int::I128(-15)), + "vitaminc/prf/value/decimal-orderable/v1", + "3fffcf884a72a2c87c6e67ffffff", + ); + // 0.001 + pin( + Some(Logical::Decimal { scale: 3 }), + Physical::Int(Int::I128(1)), + "vitaminc/prf/value/decimal-orderable/v1", + "bd00204fce5e3e25026110000000", + ); + // 123456789.987654321 + pin( + Some(Logical::Decimal { scale: 9 }), + Physical::Int(Int::I128(123456789987654321)), + "vitaminc/prf/value/decimal-orderable/v1", + "c80027e41b37904205f388c66800", + ); + // 79228162514264337593543950335 + pin( + Some(Logical::Decimal { scale: 0 }), + Physical::Int(Int::I128(79228162514264337593543950335)), + "vitaminc/prf/value/decimal-orderable/v1", + "dc00ffffffffffffffffffffffff", + ); + // -79228162514264337593543950335 + pin( + Some(Logical::Decimal { scale: 0 }), + Physical::Int(Int::I128(-79228162514264337593543950335)), + "vitaminc/prf/value/decimal-orderable/v1", + "23ff000000000000000000000000", + ); + // 0.0000000000000000000000000001 + pin( + Some(Logical::Decimal { scale: 28 }), + Physical::Int(Int::I128(1)), + "vitaminc/prf/value/decimal-orderable/v1", + "a400204fce5e3e25026110000000", + ); +} + +/// Every null is one term, typed or plain, under a domain of its own: +/// the walk sends a typed null as a plain one, so a `None` of any fixed +/// width is the same pinned byte. +#[test] +fn a_null_is_one_pinned_byte_under_the_null_domain_whatever_its_type() { + pin(None, Physical::Null, "vitaminc/prf/value/null/v1", "00"); + let typed = |found: Vec| { + assert_eq!(found.len(), 1, "a typed null has one term"); + assert_eq!(found[0].normalized.domain, domain::NULL); + hex(found[0].normalized.bytes.risky_ref()) + }; + assert_eq!(typed(terms(None::).expect("walks")), "00"); + assert_eq!(typed(terms(None::).expect("walks")), "00"); + assert_eq!(typed(terms(None::).expect("walks")), "00"); + assert_eq!(typed(terms(None::).expect("walks")), "00"); +} + +#[test] +fn a_uuid_has_a_domain_of_its_own() { + let id = uuid::Uuid::from_bytes([ + 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, + 0xf0, + ]); + let n = normalize(Some(Logical::Uuid), Physical::Bytes(id.as_bytes())).expect("uuid"); + assert_eq!(n.domain, "vitaminc/prf/value/uuid/v1"); + assert_eq!(hex(n.bytes.risky_ref()), "123456789abcdef0123456789abcdef0"); + let plain = normalize(None, Physical::Bytes(id.as_bytes())).expect("bytes"); + assert_eq!(hex(plain.bytes.risky_ref()), hex(n.bytes.risky_ref())); + assert_ne!(plain.domain, n.domain); + // The uuid source carries its logical type, so the two never meet. + let mut terms = Vec::new(); + let (_, ()) = id + .visit(vitaminc_aead::Tee( + vitaminc_aead::EncryptSink::<()>::root(()), + vitaminc_normalize::Terms::new(&mut terms), + )) + .expect("walks"); + assert_eq!(terms[0].normalized.domain, domain::UUID); +} + +#[test] +fn a_date_never_matches_its_day_count_and_widths_agree() { + let date = jiff::civil::Date::constant(2024, 2, 29); + let days = conv::date_days(date); + let as_date = normalize(Some(Logical::Date), Physical::Int(Int::I32(days))).expect("date"); + let as_int = normalize(None, Physical::Int(Int::I32(days))).expect("int"); + assert_ne!(as_date.domain, as_int.domain); + assert_ne!(as_date.bytes.risky_ref(), as_int.bytes.risky_ref()); + let narrow = normalize(None, Physical::Int(Int::I8(34))).expect("i8"); + let wide = normalize(None, Physical::Int(Int::U64(34))).expect("u64"); + assert_eq!(narrow.domain, wide.domain); + assert_eq!(narrow.bytes.risky_ref(), wide.bytes.risky_ref()); +} + +// The terms sink beside encryption. + +#[derive(Debug, Clone, PartialEq, Eq)] +struct Leaf { + aad: Vec, + plaintext: Vec, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +struct Refused; + +/// Seals in the clear and counts calls, so a test can see when the cipher +/// first runs. +#[derive(Default)] +struct Counting { + calls: AtomicUsize, +} + +impl Cipher for Counting { + type Leaf = Leaf; + type Error = Refused; + + fn seal(&self, plaintext: Protected>, aad: &Context<'_>) -> Result { + self.calls.fetch_add(1, Ordering::SeqCst); + Ok(Leaf { + aad: aad.as_bytes().to_vec(), + plaintext: plaintext.risky_unwrap(), + }) + } + + fn open(&self, leaf: Leaf, aad: &Context<'_>) -> Result>, Refused> { + if leaf.aad != aad.as_bytes() { + return Err(Refused); + } + Ok(Protected::new(leaf.plaintext)) + } +} + +fn user() -> BTreeMap<&'static str, Vec>> { + let mut m = BTreeMap::new(); + m.insert("ages", vec![Some(36), None, Some(41)]); + m.insert("empty", vec![]); + m +} + +fn paths(terms: &[Term]) -> Vec { + terms.iter().map(|t| render(&t.path)).collect() +} + +/// What `Terms` refused inside an encryption error, and where. +fn term_error(err: &EncryptError) -> Option<(NormalizeError, String)> { + match err { + EncryptError::Source(source) => source + .inner() + .downcast_ref::() + .map(|t| (t.error(), render(t.path()))), + _ => None, + } +} + +fn refused(error: NormalizeError, at: &str) -> Option<(NormalizeError, String)> { + Some((error, at.to_owned())) +} + +#[test] +fn plan_with_terms_has_every_term_without_a_cipher() { + let (planned, terms) = plan_with_terms::<_, Refused, _>(user(), "ctx").expect("plans"); + assert_eq!(paths(&terms), [".ages[0]", ".ages[1]", ".ages[2]"]); + assert_eq!(terms[0].normalized.domain, domain::INTEGER); + assert_eq!( + terms[1].normalized.domain, + domain::NULL, + "the absent age has the null term" + ); + assert_eq!( + terms[2].normalized.bytes.risky_ref(), + normalize(None, Physical::Int(Int::U32(41))) + .expect("int") + .bytes + .risky_ref() + ); + // The plan is the same one `encrypt` would seal. + let sealed = vitaminc_aead::seal::seal_all(&Counting::default(), planned).expect("seals"); + assert!(matches!(sealed, vitaminc_aead::CipherText::Map(_))); +} + +#[test] +fn encrypt_with_terms_seals_the_same_leaves_and_returns_the_terms() { + let cipher = Counting::default(); + let (sealed, terms) = encrypt_with_terms(user(), &cipher, "ctx").expect("encrypts"); + assert_eq!(terms.len(), 3, "the absent age has a term too"); + // Three elements, one empty marker. + assert_eq!(cipher.calls.load(Ordering::SeqCst), 4); + let back: BTreeMap>> = + vitaminc_aead::decrypt(&cipher, sealed, "ctx").expect("decrypts"); + assert_eq!(back["ages"], [Some(36), None, Some(41)]); +} + +#[test] +fn scalars_without_a_domain_and_passthroughs_get_no_term_and_a_null_gets_one() { + struct Doc; + impl Encrypt for Doc { + fn visit(self, sink: S) -> Result { + use vitaminc_aead::MapSink; + let mut map = sink.map(Some(5))?; + true.visit(map.entry("active")?)?; + None::.visit(map.entry("missing")?)?; + map.entry("tenant")?.passthrough(&"acme")?; + vitaminc_aead::Raw(Some(Logical::Undefined), Physical::Null) + .visit(map.entry("undefined")?)?; + "Ada".visit(map.entry("name")?)?; + map.end() + } + } + let (_, terms) = plan_with_terms::<_, Refused, _>(Doc, "ctx").expect("plans"); + assert_eq!( + paths(&terms), + [".missing", ".name"], + "a boolean, a passthrough and an undefined get no term; a null does" + ); + assert_eq!(terms[0].normalized.domain, domain::NULL); + assert_eq!(terms[1].normalized.domain, domain::TEXT); +} + +/// A logical type this build does not know means something to the client +/// that sent it, so it is refused rather than encrypted with no term. +#[test] +fn an_unknown_logical_type_stops_the_walk() { + let newer = vitaminc_aead::Raw( + Some(Logical::from_wire(200, 0).expect("unknown")), + Physical::Int(Int::I32(1)), + ); + let err = plan_with_terms::<_, Refused, _>(vec![newer], "ctx") + .err() + .expect("refused"); + assert_eq!(term_error(&err), refused(NormalizeError::NoDomain, "[0]")); +} + +/// Nested paths are the container's path plus the step, at every depth. +#[test] +fn paths_follow_the_nesting() { + let mut inner = BTreeMap::new(); + inner.insert("k", vec![vec![1u8, 2]]); + let mut outer = BTreeMap::new(); + outer.insert("m", vec![inner]); + let (_, terms) = plan_with_terms::<_, Refused, _>(outer, "ctx").expect("plans"); + assert_eq!(paths(&terms), [".m[0].k[0]"]); + assert_eq!(terms[0].normalized.domain, domain::BYTES); +} + +/// Every container on a path shares one buffer of keys, and each starts +/// over where its own keys begin, so a path names only its own keys +/// however many siblings went before it. +#[test] +fn sibling_paths_name_only_their_own_keys() { + let mut first = BTreeMap::new(); + first.insert("x", vec!["1", "2"]); + first.insert("yy", vec!["3"]); + let mut second = BTreeMap::new(); + second.insert("zzz", vec!["4"]); + let mut doc = BTreeMap::new(); + doc.insert("a", vec![first.clone(), second]); + doc.insert("bb", vec![first]); + for found in [ + plan_with_terms::<_, Refused, _>(doc.clone(), "ctx") + .expect("plans") + .1, + terms(doc).expect("walks"), + ] { + assert_eq!( + paths(&found), + [ + ".a[0].x[0]", + ".a[0].x[1]", + ".a[0].yy[0]", + ".a[1].zzz[0]", + ".bb[0].x[0]", + ".bb[0].x[1]", + ".bb[0].yy[0]", + ] + ); + } +} + +#[test] +fn an_unassigned_code_point_stops_the_walk_with_the_normalize_error() { + let err = plan_with_terms::<_, Refused, _>("\u{378}", "ctx") + .err() + .expect("refused"); + assert_eq!( + term_error(&err), + refused(NormalizeError::UnassignedCodePoint, "") + ); +} + +/// The refusal names the field, nested at any depth, through an accessor +/// only: neither the message nor `Debug` shows a key. +#[test] +fn a_refusal_names_the_field_only_on_request() { + let mut inner = BTreeMap::new(); + inner.insert("ada@example.com", vec!["ok", "\u{378}"]); + let mut outer = BTreeMap::new(); + outer.insert("emails", vec![inner]); + let err = plan_with_terms::<_, Refused, _>(outer, "ctx") + .err() + .expect("refused"); + assert_eq!( + term_error(&err), + refused( + NormalizeError::UnassignedCodePoint, + ".emails[0].ada@example.com[1]" + ) + ); + let EncryptError::Source(source) = &err else { + panic!("{err:?}") + }; + let term = source + .inner() + .downcast_ref::() + .expect("a term error"); + assert_eq!( + term.to_string(), + "no equality term: text contains a code point unassigned in Unicode 16" + ); + for shown in [format!("{term:?}"), format!("{err:?}")] { + assert!(!shown.contains("ada"), "{shown}"); + assert!(!shown.contains("emails"), "{shown}"); + } + // The walk's error shows `SourceError(..)` in place of the inner + // error, so the reason and the position are read from the term error. + let shown = format!("{term:?}"); + assert!(shown.contains("UnassignedCodePoint"), "{shown}"); + assert!(shown.contains("Index(1)"), "{shown}"); +} + +/// Every error in a chain, from `err` down through each `source()`. +fn chain<'e>( + err: &'e (dyn core::error::Error + 'static), +) -> Vec<&'e (dyn core::error::Error + 'static)> { + core::iter::successors(Some(err), |e| e.source()).collect() +} + +/// A reporter that walks `source()` reaches the `NormalizeError` behind a +/// refusal, whether it arrived through encryption or through `terms`. +#[test] +fn the_normalize_error_is_on_the_source_chain() { + let reason = |err: &(dyn core::error::Error + 'static)| { + chain(err) + .into_iter() + .find_map(|e| e.downcast_ref::().copied()) + }; + let encrypting = plan_with_terms::<_, &str, _>(vec!["\u{378}"], "ctx") + .err() + .expect("refused"); + assert_eq!( + reason(&encrypting), + Some(NormalizeError::UnassignedCodePoint) + ); + let alone = terms(vec!["\u{378}"]).expect_err("refused"); + assert_eq!(reason(&alone), Some(NormalizeError::UnassignedCodePoint)); + // The chain ends at the reason, which says why and nothing more. + let last = chain(&alone).pop().expect("a chain"); + assert!(last.source().is_none()); + assert_eq!( + last.to_string(), + "text contains a code point unassigned in Unicode 16" + ); + // `TermError` itself names its reason as its source. + let term = alone.term().expect("refused by Terms"); + let source = core::error::Error::source(term).expect("a source"); + assert_eq!( + source.downcast_ref::(), + Some(&NormalizeError::UnassignedCodePoint) + ); +} + +#[test] +fn terms_collects_every_term_without_encrypting() { + let found = terms(user()).expect("walks"); + assert_eq!(paths(&found), [".ages[0]", ".ages[1]", ".ages[2]"]); + assert_eq!(found[1].normalized.domain, domain::NULL); + assert_eq!(found[2].normalized.domain, domain::INTEGER); + // A borrowed value walks too, and a scalar at the root has no steps. + let name = String::from("Ada"); + let found = terms(&name).expect("walks"); + assert_eq!(paths(&found), [""]); + assert!(terms(Vec::::new()).expect("walks").is_empty()); +} + +#[test] +fn terms_says_which_field_it_refused() { + let mut doc = BTreeMap::new(); + doc.insert("x", "\u{378}"); + let err = terms(doc).expect_err("refused"); + let term = err.term().expect("refused by Terms"); + assert!(err.refusal().is_none()); + assert_eq!(term.error(), NormalizeError::UnassignedCodePoint); + assert_eq!(render(term.path()), ".x"); + assert_eq!( + err.to_string(), + "no equality term: text contains a code point unassigned in Unicode 16" + ); + + // A value invalid for its logical type cannot be encrypted, so it is + // refused for its shape, as encryption refuses it, before it is + // normalized. + let invalid = vitaminc_aead::Raw(Some(Logical::Undefined), Physical::Int(Int::I32(1))); + let mut doc = BTreeMap::new(); + doc.insert("x", invalid); + let err = terms(doc).expect_err("refused"); + assert!(err.term().is_none()); + let refusal = err.refusal().expect("refused for its shape"); + assert_eq!(refusal.reason(), Unencryptable::InvalidValue); + assert_eq!(render(refusal.path()), ".x"); + assert_eq!(err.to_string(), "value is not valid for its logical type"); +} + +#[test] +fn terms_passes_a_source_failure_through() { + struct Throws; + impl Encrypt for Throws { + fn visit(self, sink: S) -> Result { + let mut seq = sink.seq(None)?; + 1u32.visit(seq.element()?)?; + Err(::source( + SourceError::msg("getter threw"), + )) + } + } + let err = terms(Throws).expect_err("refused"); + assert!(err.term().is_none()); + assert_eq!(err.to_string(), "getter threw"); + assert_eq!(err.source_error().to_string(), "getter threw"); +} + +/// Seals through an await, and checks that the source's walk had finished +/// before the first one. +struct Remote { + walked: &'static AtomicBool, +} + +impl AsyncCipher for Remote { + type Leaf = Leaf; + type Error = Refused; + + async fn seal( + &self, + plaintext: Protected>, + aad: Context<'static>, + ) -> Result { + assert!( + self.walked.load(Ordering::SeqCst), + "sealed before the walk ended" + ); + Counting::default().seal(plaintext, &aad) + } + + async fn open(&self, leaf: Leaf, aad: Context<'static>) -> Result>, Refused> { + Counting::default().open(leaf, &aad) + } +} + +#[test] +fn encrypt_with_terms_async_has_every_term_before_its_first_await() { + static WALKED: AtomicBool = AtomicBool::new(false); + struct Source; + impl Encrypt for Source { + fn visit(self, sink: S) -> Result { + let out = vec![1u32, 2].visit(sink); + WALKED.store(true, Ordering::SeqCst); + out + } + } + let remote = Remote { walked: &WALKED }; + let future = encrypt_with_terms_async(Source, &remote, "ctx"); + // The walk ran, and the terms exist, before the future is polled. + assert!(WALKED.load(Ordering::SeqCst)); + fn assert_send(t: T) -> T { + t + } + let (sealed, terms) = block_on(assert_send(future)).expect("encrypts"); + assert_eq!(paths(&terms), ["[0]", "[1]"]); + let back: Vec = + block_on(vitaminc_aead::decrypt_async(&remote, sealed, "ctx")).expect("decrypts"); + assert_eq!(back, [1, 2]); +} + +/// A cipher that must never be reached. +struct Never; + +impl AsyncCipher for Never { + type Leaf = Leaf; + type Error = Refused; + + async fn seal(&self, _: Protected>, _: Context<'static>) -> Result { + panic!("sealed after the walk was refused") + } + + async fn open(&self, _: Leaf, _: Context<'static>) -> Result>, Refused> { + Err(Refused) + } +} + +fn is_unassigned(err: &EncryptError) -> bool { + term_error(err) == refused(NormalizeError::UnassignedCodePoint, "[1]") +} + +/// The walk ends before any leaf is sealed, so a value `Terms` refuses +/// reaches no cipher, even when its first element was fine; the async +/// future holds the refusal and returns it on its first poll. +#[test] +fn a_refused_walk_never_reaches_the_cipher() { + let doc = || vec!["ok", "\u{378}"]; + let cipher = Counting::default(); + let err = encrypt_with_terms(doc(), &cipher, "ctx").expect_err("refused"); + assert!(is_unassigned(&err), "{err:?}"); + assert_eq!(cipher.calls.load(Ordering::SeqCst), 0); + let err = block_on(encrypt_with_terms_async(doc(), &Never, "ctx")).expect_err("refused"); + assert!(is_unassigned(&err), "{err:?}"); +} + +/// `Terms` is public and works without `EncryptSink` in front of it, and +/// then refuses a value invalid for its logical type itself, as +/// encryption would. The refusal arrives through its partner's error type +/// as a source error. +#[test] +fn terms_alone_refuses_a_value_invalid_for_its_logical_type() { + use vitaminc_aead::Raw; + use vitaminc_normalize::Terms; + + // A scalar at the root has an empty path. + let mut out = Vec::new(); + let sink: Terms<'_, EncryptError> = Terms::new(&mut out); + "Ada".visit(sink).expect("walks"); + assert_eq!(paths(&out), [""]); + + let mut out = Vec::new(); + let sink: Terms<'_, EncryptError> = Terms::new(&mut out); + let err = Raw(Some(Logical::Undefined), Physical::Int(Int::I32(1))) + .visit(sink) + .expect_err("refused"); + let EncryptError::Source(source) = &err else { + panic!("{err:?}") + }; + let refusal = source + .inner() + .downcast_ref::() + .expect("refused for its shape"); + assert_eq!(refusal.reason(), Unencryptable::InvalidValue); + assert_eq!(refusal.path(), &Path::default()); + assert!(out.is_empty()); +} + +/// `EncryptSink` runs first in the `Tee`, so a value invalid for its +/// logical type is a shape error from encryption, not a normalize error. +#[test] +fn an_invalid_logical_value_is_refused_by_the_encrypt_sink_first() { + let invalid = vitaminc_aead::Raw(Some(Logical::Date), Physical::Text("2024-01-01")); + let err = plan_with_terms::<_, Refused, _>(invalid, "ctx") + .err() + .expect("refused"); + assert!(matches!(err, EncryptError::Shape(_)), "{err:?}"); +} diff --git a/packages/vitaminc-normalize/tests/normalizer.rs b/packages/vitaminc-normalize/tests/normalizer.rs new file mode 100644 index 000000000..f76583f29 --- /dev/null +++ b/packages/vitaminc-normalize/tests/normalizer.rs @@ -0,0 +1,134 @@ +//! `Terms` under a normalizer of the caller's own: the walk is the same, +//! the terms are the normalizer's, and the skip-or-stop rule for a scalar +//! with no term is applied to what the normalizer returns. + +use std::collections::BTreeMap; + +use vitaminc_aead::plaintext::render; +use vitaminc_aead::{Encrypt, Int, Logical, Physical, Raw, Tee}; +use vitaminc_normalize::{ + domain, terms, terms_by, Equality, Normalize, NormalizeError, Normalized, Terms, TermsError, +}; +use vitaminc_protected::{Controlled, Protected}; + +/// Every int is one byte under a domain of its own; nothing else has a +/// term. +#[derive(Clone, Copy)] +struct LowByte; + +impl Normalize for LowByte { + type Term = Normalized; + + const INDEX: &'static str = "low byte"; + + fn normalize( + &self, + ty: Option, + value: Physical<'_>, + ) -> Result { + match (ty, value) { + (None, Physical::Int(i)) => Ok(Normalized { + domain: "test/low-byte/v1", + bytes: Protected::new(vec![i.to_i128().unwrap_or(0) as u8]), + }), + _ => Err(NormalizeError::NoDomain), + } + } +} + +fn doc() -> BTreeMap<&'static str, Raw<'static>> { + let mut doc = BTreeMap::new(); + doc.insert("a", Raw(None, Physical::Int(Int::I32(0x1_02)))); + doc.insert("b", Raw(None, Physical::Text("text"))); + doc.insert("c", Raw(None, Physical::Null)); + doc +} + +#[test] +fn the_terms_are_the_normalizers_and_the_walk_is_the_same() { + let found = terms_by(LowByte, doc()).expect("terms"); + assert_eq!(found.len(), 1, "text and null have no term under LowByte"); + assert_eq!(render(&found[0].path), ".a"); + assert_eq!(found[0].normalized.domain, "test/low-byte/v1"); + assert_eq!(found[0].normalized.bytes.risky_ref(), &[0x02]); + // `terms` is `terms_by(Equality, ..)`. + let equality = terms(doc()).expect("terms"); + let by_name = terms_by(Equality, doc()).expect("terms"); + assert_eq!(equality.len(), 3, "under equality the null has a term too"); + assert_eq!(equality.len(), by_name.len()); + assert_eq!( + equality[1].normalized.bytes.risky_ref(), + by_name[1].normalized.bytes.risky_ref() + ); +} + +#[test] +fn a_logical_type_the_normalizer_refuses_stops_the_walk() { + let mut doc = BTreeMap::new(); + doc.insert("d", Raw(Some(Logical::Date), Physical::Int(Int::I32(1)))); + let err = terms_by(LowByte, doc).expect_err("refused"); + let term = err.term().expect("refused by the normalizer"); + assert_eq!(term.error(), NormalizeError::NoDomain); + assert_eq!(render(term.path()), ".d"); + // The refusal names the normalizer's index, not equality. + assert_eq!(term.index(), "low byte"); + assert_eq!( + err.to_string(), + "no low byte term: no domain for this kind of value" + ); +} + +#[test] +fn two_normalizers_share_one_walk() { + let (mut equality, mut low) = (Vec::new(), Vec::new()); + doc() + .visit(Tee( + Terms::::new(&mut equality), + Terms::by(LowByte, &mut low), + )) + .expect("walk"); + assert_eq!( + equality.iter().map(|t| render(&t.path)).collect::>(), + [".a", ".b", ".c"] + ); + assert_eq!( + low.iter().map(|t| render(&t.path)).collect::>(), + [".a"] + ); +} + +/// A fixed-width `None` reaches the sink as a typed null. Under equality +/// it is indexed as a plain null, so the absent field has a term at its +/// own path under the null domain, and the walk carries on. A normalizer +/// that gives nulls no term still skips it. +#[test] +fn a_fixed_width_none_has_the_null_term_at_its_path_and_does_not_stop_the_walk() { + let mut doc = BTreeMap::new(); + doc.insert("gone", None::); + doc.insert("here", Some(5i32)); + let found = terms(doc).expect("a typed null does not stop the walk"); + assert_eq!( + found.iter().map(|t| render(&t.path)).collect::>(), + [".gone", ".here"], + "the absent field has a term as the present one does" + ); + assert_eq!( + found[0].normalized.domain, + domain::NULL, + "the absent field's term is under the null domain" + ); + assert_eq!( + found[0].normalized.bytes.risky_ref(), + &[0x00], + "the absent field's term is the null's one byte" + ); + let plain = terms(BTreeMap::from([("gone", Raw(None, Physical::Null))])).expect("terms"); + assert_eq!( + plain[0].normalized.bytes.risky_ref(), + found[0].normalized.bytes.risky_ref(), + "a typed null and a plain null are one term" + ); + let by_name = terms_by(LowByte, BTreeMap::from([("gone", None::)])) + .expect("a typed null does not stop a normalizer of the caller's own"); + assert!(by_name.is_empty(), "a typed null has no term under LowByte"); +} diff --git a/release-plz.toml b/release-plz.toml index 7f28ee209..e230abb8a 100644 --- a/release-plz.toml +++ b/release-plz.toml @@ -103,3 +103,12 @@ publish = false name = "vitaminc-aead-derive" release = false publish = false + +# vitaminc-normalize moved here from cipherstash/vitaminc after the AEAD +# crates. crates.io's 0.10.0 was published from vitaminc. It is listed here +# so that release-plz neither bumps nor publishes it. It stays listed until +# it is published from here under the same name. +[[package]] +name = "vitaminc-normalize" +release = false +publish = false diff --git a/scripts/__tests__/crates-ci.test.mjs b/scripts/__tests__/crates-ci.test.mjs index 52d243f1c..d6743660b 100644 --- a/scripts/__tests__/crates-ci.test.mjs +++ b/scripts/__tests__/crates-ci.test.mjs @@ -238,7 +238,7 @@ const CI_EXEMPT_TASKS = new Map([ ]) describe('the scan sees every task mise sees', () => { - it('reads the nine crate task files from the root mise.toml', () => { + it('reads the ten crate task files from the root mise.toml', () => { expect(INCLUDES.sort()).toEqual( [ 'packages/stack-auth/tasks.toml', @@ -250,6 +250,7 @@ describe('the scan sees every task mise sees', () => { 'packages/vitaminc-aead/tasks.toml', 'packages/recipher-frame/tasks.toml', 'packages/vitaminc-aead-derive/tasks.toml', + 'packages/vitaminc-normalize/tasks.toml', ].sort(), ) }) @@ -303,6 +304,7 @@ describe('the scan sees every task mise sees', () => { 'doc:vitaminc-aead', 'doc:vitaminc-aead-derive', 'doc:recipher-frame', + 'doc:vitaminc-normalize', ].sort(), ) }) diff --git a/supply-chain/vitaminc-aead/README.md b/supply-chain/vitaminc-aead/README.md index 39f8778e5..c15823469 100644 --- a/supply-chain/vitaminc-aead/README.md +++ b/supply-chain/vitaminc-aead/README.md @@ -1,12 +1,12 @@ # Supply-chain checks for the vitaminc-aead crates This directory holds the `cargo deny` config and the `cargo vet` store for -`vitaminc-aead`, `recipher-frame` and `vitaminc-aead-derive`, and their -dependency graph **only**. Nothing here checks the rest of the root +`vitaminc-aead`, `recipher-frame`, `vitaminc-aead-derive` and +`vitaminc-normalize`, and their dependency graph **only**. Nothing here checks the rest of the root workspace; that is #1842. CI runs both in `.github/workflows/supply-chain-vitaminc-aead.yml`, on pull -requests that change the three crates, `Cargo.lock`, `Cargo.toml` or this +requests that change the four crates, `Cargo.lock`, `Cargo.toml` or this directory. `cargo deny` also runs nightly, for advisories published against versions already in the lockfile. @@ -16,13 +16,13 @@ versions already in the lockfile. started as `cipherstash/vitaminc`'s, with its audits and imported registries. The policies name every root workspace member, because cargo vet checks policies against the whole workspace before it applies the - filter; naming one does not vet it. The three crates' policies set + filter; naming one does not vet it. The four crates' policies set `criteria = "safe-to-deploy"`: they are not roots of the workspace graph (stack-encrypt depends on them), and once the filter drops their dependents nothing else would require more than `safe-to-run` of their runtime dependencies. - `filter-graph`: the `--filter-graph` expression that drops every other - root workspace member, so the graph vetted is the three crates and their + root workspace member, so the graph vetted is the four crates and their dependencies. ## Commands diff --git a/supply-chain/vitaminc-aead/audits.toml b/supply-chain/vitaminc-aead/audits.toml index 95873dfb3..4cbf3956b 100644 --- a/supply-chain/vitaminc-aead/audits.toml +++ b/supply-chain/vitaminc-aead/audits.toml @@ -286,3 +286,10 @@ trusted-publisher = "github:rust-lang/cc-rs" start = "2025-09-01" end = "2027-12-04" notes = "cc runs the C compiler for build scripts. Here aws-lc-sys uses it, directly and through cmake, to compile the AWS-LC C library. Versions up to 1.2.34 were published by the crates.io user rust-lang-owner. Later versions, 1.2.55 among them, are published by the crates.io trusted publisher of the rust-lang/cc-rs repository. 1.2.55 is the version in the graph." + +[[trusted.orderable-bytes]] +criteria = "safe-to-run" +trusted-publisher = "github:cipherstash/ore.rs" +start = "2026-05-05" +end = "2027-12-05" +notes = "orderable-bytes is a CipherStash crate, published from the cipherstash/ore.rs repository by crates.io trusted publishing. vitaminc-normalize uses it only in tests, to check its decimal encoding against it byte for byte." diff --git a/supply-chain/vitaminc-aead/config.toml b/supply-chain/vitaminc-aead/config.toml index dcbe74624..2bb13c58a 100644 --- a/supply-chain/vitaminc-aead/config.toml +++ b/supply-chain/vitaminc-aead/config.toml @@ -56,6 +56,10 @@ dependency-criteria = { zeroize = ["safe-to-deploy", "crypto-reviewed"] } [policy."vitaminc-aead:0.5.1"] criteria = "safe-to-deploy" +[policy."vitaminc-normalize:0.10.0"] +audit-as-crates-io = false +criteria = "safe-to-deploy" + [[exemptions.aead]] version = "0.5.2" criteria = ["safe-to-deploy", "crypto-reviewed"] @@ -484,10 +488,6 @@ criteria = "safe-to-run" version = "0.10.0" criteria = "safe-to-deploy" -[[exemptions.vitaminc-normalize]] -version = "0.10.0" -criteria = "safe-to-run" - [[exemptions.vitaminc-prf]] version = "0.10.0" criteria = "safe-to-run" diff --git a/supply-chain/vitaminc-aead/deny.toml b/supply-chain/vitaminc-aead/deny.toml index b9619acde..947ae93aa 100644 --- a/supply-chain/vitaminc-aead/deny.toml +++ b/supply-chain/vitaminc-aead/deny.toml @@ -116,6 +116,10 @@ allow-build-scripts = [ "target-tuple", "thiserror", "typenum", + # unicode-general-category: a dependency of vitaminc-normalize. The build + # script reads the Unicode table compiled into the crate and writes a + # lookup table to OUT_DIR. It reads only OUT_DIR, and starts no process. + "unicode-general-category", "vitaminc-protected", "wasm-bindgen", "wasm-bindgen-shared", diff --git a/supply-chain/vitaminc-aead/filter-graph b/supply-chain/vitaminc-aead/filter-graph index 6b8e9b3ac..620431ba0 100644 --- a/supply-chain/vitaminc-aead/filter-graph +++ b/supply-chain/vitaminc-aead/filter-graph @@ -1 +1 @@ -exclude(all(is_workspace_member(true),not(any(name(vitaminc-aead),name(recipher-frame),name(vitaminc-aead-derive))))) +exclude(all(is_workspace_member(true),not(any(name(vitaminc-aead),name(recipher-frame),name(vitaminc-aead-derive),name(vitaminc-normalize))))) diff --git a/supply-chain/vitaminc-aead/imports.lock b/supply-chain/vitaminc-aead/imports.lock index c38cd07bc..05a6dfa25 100644 --- a/supply-chain/vitaminc-aead/imports.lock +++ b/supply-chain/vitaminc-aead/imports.lock @@ -20,6 +20,11 @@ version = "1.2.55" when = "2026-01-30" trusted-publisher = "github:rust-lang/cc-rs" +[[publisher.orderable-bytes]] +version = "0.2.1" +when = "2026-10-19" +trusted-publisher = "github:cipherstash/ore.rs" + [[publisher.unicode-normalization]] version = "0.1.25" when = "2025-10-30"