diff --git a/.cargo/mutants.toml b/.cargo/mutants.toml index 107f70367..ac4c85ebe 100644 --- a/.cargo/mutants.toml +++ b/.cargo/mutants.toml @@ -30,20 +30,27 @@ additional_cargo_args = ["--all-features"] test_tool = "nextest" additional_cargo_test_args = ["-E", "not binary(ui) & not test(stress_tests)"] -# Skip the derive crate: its logic runs inside `#[proc_macro_derive]` entry -# points at compile time, not in the instrumented test binary, so every -# mutant there survives spuriously. Its behaviour is pinned by stack-encrypt's -# `tests/derive.rs` and the trybuild UI suite instead. +# Skip the record derives of stack-encrypt-derive (`EncryptTarget`, +# `DecryptSource`, `predicate!`): their logic runs inside the +# `#[proc_macro_derive]` entry points at compile time, not in the +# instrumented test binary, so every mutant there survives spuriously. Their +# behaviour is pinned by stack-encrypt's `tests/derive.rs` and the trybuild UI +# suite instead. # -# vitaminc-aead-derive is mutated: only its `#[proc_macro_derive]` shims in -# lib.rs run at compile time, and the expansion they delegate to is in -# modules its unit tests call directly. +# Its `Encrypt` and `Decrypt` derives, in `src/value/`, are mutated: only +# their `#[proc_macro_derive]` shims in lib.rs run at compile time, and the +# expansion they delegate to is in modules its unit tests call directly. # # recipher-frame's Kani harnesses build only under `cfg(kani)`, so no # test binary contains them. kani.yml checks them. exclude_globs = [ - "packages/stack-encrypt-derive/**", - "packages/vitaminc-aead-derive/src/lib.rs", + "packages/stack-encrypt-derive/src/lib.rs", + "packages/stack-encrypt-derive/src/attrs.rs", + "packages/stack-encrypt-derive/src/json_paths.rs", + "packages/stack-encrypt-derive/src/owned_decrypt.rs", + "packages/stack-encrypt-derive/src/owned_encrypt.rs", + "packages/stack-encrypt-derive/src/predicate.rs", + "packages/stack-encrypt-derive/src/shape.rs", "packages/recipher-frame/src/storage/proofs.rs", ] diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 621d001a2..92a017333 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -27,5 +27,4 @@ # conformance corpus their tests read. Not published from here yet. /packages/vitaminc-aead/ @cipherstash/developers /packages/recipher-frame/ @cipherstash/developers -/packages/vitaminc-aead-derive/ @cipherstash/developers /conformance/vitaminc-aead/ @cipherstash/developers diff --git a/.github/workflows/bench-eql.yml b/.github/workflows/bench-eql.yml index 6422ddb9a..75be71a3d 100644 --- a/.github/workflows/bench-eql.yml +++ b/.github/workflows/bench-eql.yml @@ -70,7 +70,6 @@ on: - "packages/stack-encrypt-jsonpath/**" - "packages/vitaminc-aead/**" - "packages/recipher-frame/**" - - "packages/vitaminc-aead-derive/**" - "packages/stack-kms/**" - "packages/stack-auth/**" - "packages/stack-profile/**" diff --git a/.github/workflows/fuzz.yml b/.github/workflows/fuzz.yml index 2b02d041e..78877aecd 100644 --- a/.github/workflows/fuzz.yml +++ b/.github/workflows/fuzz.yml @@ -31,7 +31,7 @@ on: - packages/stack-encrypt/** - packages/vitaminc-aead/** - packages/recipher-frame/** - - packages/vitaminc-aead-derive/** + - packages/stack-encrypt-derive/** - Cargo.toml - Cargo.lock - mise.toml diff --git a/.github/workflows/mutants.yml b/.github/workflows/mutants.yml index 5c161ebd6..f9b3a2083 100644 --- a/.github/workflows/mutants.yml +++ b/.github/workflows/mutants.yml @@ -5,9 +5,10 @@ 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), stack-encrypt-derive (its `Encrypt` and `Decrypt` +# derives; .cargo/mutants.toml leaves out the record derives), and +# vitaminc-aead and recipher-frame (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 @@ -37,9 +38,9 @@ on: - packages/stack-auth/** - packages/stack-encrypt/** - packages/stack-encrypt-jsonpath/** + - packages/stack-encrypt-derive/** - packages/vitaminc-aead/** - packages/recipher-frame/** - - packages/vitaminc-aead-derive/** - 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","stack-encrypt-derive","vitaminc-aead","recipher-frame"]') }} 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 stack-encrypt-derive -p vitaminc-aead -p recipher-frame) 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, stack-encrypt-derive, vitaminc-aead, recipher-frame)" 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..d3ca3ff36 100644 --- a/.github/workflows/supply-chain-vitaminc-aead.yml +++ b/.github/workflows/supply-chain-vitaminc-aead.yml @@ -1,8 +1,9 @@ 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 three crates and their dependency graph +# ONLY: vitaminc-aead, recipher-frame, and stack-encrypt-derive. The derive +# is here because it writes every derived `Encrypt` and `Decrypt` impl. 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, @@ -21,7 +22,7 @@ on: paths: - packages/vitaminc-aead/** - packages/recipher-frame/** - - packages/vitaminc-aead-derive/** + - packages/stack-encrypt-derive/** - supply-chain/vitaminc-aead/** - Cargo.toml - Cargo.lock @@ -73,16 +74,25 @@ jobs: # `--manifest-path` on a workspace member checks that package's graph, # not the workspace's. `--locked` refuses to touch Cargo.lock, so the - # graph checked is the one the pull request ships. + # graph checked is the one the pull request ships. The derive's + # dev-dependencies reach the rest of the workspace. So the derive's + # check leaves out dev-dependencies (`--exclude-dev`). The tests of the + # other two crates use the derive, so their checks leave the derive + # out. See deny.toml. - name: cargo deny check, one crate at a time run: | status=0 - for crate in vitaminc-aead recipher-frame vitaminc-aead-derive; do + check() { + local crate=$1 + shift echo "::group::$crate" - cargo deny --locked --config supply-chain/vitaminc-aead/deny.toml \ + cargo deny --locked "$@" --config supply-chain/vitaminc-aead/deny.toml \ --manifest-path "packages/$crate/Cargo.toml" check || status=1 echo "::endgroup::" - done + } + check vitaminc-aead --exclude stack-encrypt-derive + check recipher-frame --exclude stack-encrypt-derive + check stack-encrypt-derive --exclude-dev exit "$status" vet: @@ -106,7 +116,8 @@ 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 three crates, stack-encrypt-jsonpath (the derive's + # path grammar), 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 69ee76f0f..79cb01aa5 100644 --- a/.github/workflows/test-eql.yml +++ b/.github/workflows/test-eql.yml @@ -116,7 +116,6 @@ on: - "packages/stack-encrypt-jsonpath/**" - "packages/vitaminc-aead/**" - "packages/recipher-frame/**" - - "packages/vitaminc-aead-derive/**" - "packages/stack-kms/**" - "packages/stack-auth/**" - "packages/stack-profile/**" @@ -221,7 +220,6 @@ jobs: - "packages/stack-encrypt-jsonpath/**" - "packages/vitaminc-aead/**" - "packages/recipher-frame/**" - - "packages/vitaminc-aead-derive/**" - "packages/stack-kms/**" - "packages/stack-auth/**" - "packages/stack-profile/**" @@ -540,18 +538,9 @@ jobs: postgres-version: ${{ fromJSON(needs.setup.outputs.pg-versions) }} services: encryption-postgres: - image: postgres:${{ matrix.postgres-version }} - # Docker Hub refuses pulls without a login after too many from one - # address, and RunsOn machines reach that limit. One expression, not - # `username:` and `password:` keys: GitHub rejects an empty value for - # either key ("Unexpected value ''"), which fails the job on a fork's - # pull request. With either secret empty this gives `{}`, and the - # runner then pulls without a login. - credentials: >- - ${{ secrets.DOCKER_HUB_USERNAME != '' && secrets.DOCKER_HUB_PASSWORD != '' - && fromJSON(format('{{"username":{0},"password":{1}}}', - toJSON(secrets.DOCKER_HUB_USERNAME), toJSON(secrets.DOCKER_HUB_PASSWORD))) - || fromJSON('{}') }} + # Docker's public mirror avoids Hub's anonymous pull limit when + # Docker Hub secrets are unavailable (#2016). + image: public.ecr.aws/docker/library/postgres:${{ matrix.postgres-version }} env: POSTGRES_PASSWORD: postgres # Container port only: Docker picks the host port, and the test step diff --git a/.github/workflows/tests-crates.yml b/.github/workflows/tests-crates.yml index b31cbae84..be1444c77 100644 --- a/.github/workflows/tests-crates.yml +++ b/.github/workflows/tests-crates.yml @@ -24,11 +24,11 @@ on: - conformance/stack-encrypt/** - conformance/vitaminc-aead/** - packages/stack-encrypt-derive/** + - packages/stack-encrypt-downstream/** - packages/stack-encrypt-jsonpath/** - packages/stack-guest-abi/** - packages/vitaminc-aead/** - packages/recipher-frame/** - - packages/vitaminc-aead-derive/** - languages/typescript/packages/auth/** - languages/typescript/packages/profile/** - languages/typescript/packages/stack-auth-wasm/** @@ -54,11 +54,11 @@ on: - conformance/stack-encrypt/** - conformance/vitaminc-aead/** - packages/stack-encrypt-derive/** + - packages/stack-encrypt-downstream/** - packages/stack-encrypt-jsonpath/** - packages/stack-guest-abi/** - packages/vitaminc-aead/** - packages/recipher-frame/** - - packages/vitaminc-aead-derive/** - 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 f03d30b25..508783c57 100644 --- a/.github/workflows/tests-golang.yml +++ b/.github/workflows/tests-golang.yml @@ -45,7 +45,6 @@ on: - packages/stack-guest-abi/** - packages/vitaminc-aead/** - packages/recipher-frame/** - - packages/vitaminc-aead-derive/** # The eql guest build links eql-bindings. - packages/eql/crates/eql-bindings/** - packages/eql/crates/eql-domains/** @@ -93,7 +92,6 @@ on: - packages/stack-guest-abi/** - packages/vitaminc-aead/** - packages/recipher-frame/** - - packages/vitaminc-aead-derive/** # The eql guest build links eql-bindings. - packages/eql/crates/eql-bindings/** - packages/eql/crates/eql-domains/** @@ -483,18 +481,9 @@ jobs: timeout-minutes: 30 services: postgres: - image: postgres:17 - # Docker Hub refuses pulls without a login after too many from one - # address, and RunsOn machines reach that limit. One expression, not - # `username:` and `password:` keys: GitHub rejects an empty value for - # either key ("Unexpected value ''"), which fails the job on a fork's - # pull request. With either secret empty this gives `{}`, and the - # runner then pulls without a login. - credentials: >- - ${{ secrets.DOCKER_HUB_USERNAME != '' && secrets.DOCKER_HUB_PASSWORD != '' - && fromJSON(format('{{"username":{0},"password":{1}}}', - toJSON(secrets.DOCKER_HUB_USERNAME), toJSON(secrets.DOCKER_HUB_PASSWORD))) - || fromJSON('{}') }} + # Docker's public mirror avoids Hub's anonymous pull limit when + # Docker Hub secrets are unavailable (#2016). + image: public.ecr.aws/docker/library/postgres:17 env: POSTGRES_PASSWORD: postgres # Container port only: Docker picks the host port, and the test step diff --git a/.github/workflows/tests-recipher-js.yml b/.github/workflows/tests-recipher-js.yml index ef5f62a4f..6c6d86d0d 100644 --- a/.github/workflows/tests-recipher-js.yml +++ b/.github/workflows/tests-recipher-js.yml @@ -28,7 +28,6 @@ on: - packages/stack-encrypt-jsonpath/** - packages/vitaminc-aead/** - packages/recipher-frame/** - - packages/vitaminc-aead-derive/** - Cargo.toml - mise.toml - pnpm-lock.yaml @@ -47,7 +46,6 @@ on: - packages/stack-encrypt-jsonpath/** - packages/vitaminc-aead/** - packages/recipher-frame/** - - packages/vitaminc-aead-derive/** - Cargo.toml - mise.toml - pnpm-lock.yaml diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 564723c70..60389432b 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -113,7 +113,7 @@ jobs: - '!packages/stack-guest-abi/**' - '!packages/vitaminc-aead/**' - '!packages/recipher-frame/**' - - '!packages/vitaminc-aead-derive/**' + - '!packages/stack-encrypt-downstream/**' - '!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. @@ -745,14 +745,15 @@ jobs: # key's column, so the upgrade example's dependency preflight sees a # different catalogue there. No postgres-eql image exists for 18; the # upgrade suite installs EQL v2.2.1 and v3 itself, so the official image - # (pinned by digest) is enough. + # (pinned by digest) is enough. Use Docker's public mirror so missing + # Docker Hub secrets cannot cause an anonymous pull limit failure. - name: Start PostgreSQL 18 id: db18 if: ${{ !cancelled() && steps.ffi-binding.outcome == 'success' && steps.auth-binding.outcome == 'success' }} run: | docker run -d --name pg18-upgrade -e POSTGRES_PASSWORD=password \ -p 127.0.0.1::5432 \ - postgres:18@sha256:e3d24f6906d0760bf4da0dae872415391ededefad23fd471c47dc53b0ddf3c42 + public.ecr.aws/docker/library/postgres:18@sha256:e3d24f6906d0760bf4da0dae872415391ededefad23fd471c47dc53b0ddf3c42 # Probe over TCP: the init-time server listens on the socket only. for _ in $(seq 1 60); do docker exec pg18-upgrade pg_isready -h 127.0.0.1 -U postgres -q && break diff --git a/.github/workflows/udeps.yml b/.github/workflows/udeps.yml index 3123e765a..ac9ff6458 100644 --- a/.github/workflows/udeps.yml +++ b/.github/workflows/udeps.yml @@ -16,11 +16,11 @@ on: - packages/stack-kms/** - packages/stack-encrypt/** - packages/stack-encrypt-derive/** + - packages/stack-encrypt-downstream/** - packages/stack-encrypt-jsonpath/** - packages/stack-guest-abi/** - packages/vitaminc-aead/** - packages/recipher-frame/** - - packages/vitaminc-aead-derive/** - languages/typescript/packages/auth/** - languages/typescript/packages/profile/** - languages/typescript/packages/stack-auth-wasm/** @@ -39,11 +39,11 @@ on: - packages/stack-kms/** - packages/stack-encrypt/** - packages/stack-encrypt-derive/** + - packages/stack-encrypt-downstream/** - packages/stack-encrypt-jsonpath/** - packages/stack-guest-abi/** - packages/vitaminc-aead/** - packages/recipher-frame/** - - packages/vitaminc-aead-derive/** - languages/typescript/packages/auth/** - languages/typescript/packages/profile/** - languages/typescript/packages/stack-auth-wasm/** diff --git a/AGENTS.md b/AGENTS.md index d695507f1..b441b8277 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -90,8 +90,8 @@ 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/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/stack-auth`, `packages/stack-profile`, `packages/stack-kms`, `packages/stack-encrypt`, `packages/stack-encrypt-derive`, `packages/stack-encrypt-jsonpath`, `packages/stack-guest-abi`, `packages/stack-encrypt-downstream`: The Rust crates imported from `cipherstash/cipherstash-suite` with their history, and two 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`). `stack-encrypt-derive` contains every derive that `stack-encrypt` re-exports. The record derives are `EncryptTarget` and `DecryptSource`, with `#[stash(...)]` attributes. The value derives are `Encrypt` and `Decrypt`, with `#[aead(...)]` attributes, in `src/value/`. Those files keep their MIT licence, in `src/value/LICENSE-MIT`. The code that the value derives write names every item through `stack_encrypt::__derive`, a hidden re-export of `vitaminc_aead::__derive`. So a crate that depends on `stack-encrypt` alone can derive both traits. `packages/stack-encrypt-downstream` (`publish = false`) is such a crate. It derives `Encrypt` and `Decrypt`, and writes one pair of impls by hand. Its `tests/manifest.rs` fails if its manifest names a dependency other than `stack-encrypt`, or names a vitaminc crate. They are the members of the **root Cargo workspace**, with the two AEAD crates and the three node binding crates below. See "Working on the Rust crates". +- `packages/vitaminc-aead`, `packages/recipher-frame`: 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, and the transport frame and storage profile (`recipher-frame`, whose storage corpus is `testdata/storage-v1.json`). The third crate imported with them, `vitaminc-aead-derive`, is gone. Its code is now the value derives of `stack-encrypt-derive`. `vitaminc-aead` has no derives of its own. Its tests use Stack Encrypt's derives, with `#[aead(crate = "::vitaminc_aead")]`. `vitaminc-aead` keeps its crates.io name, because vitaminc crates that stay on crates.io depend on it. The frame crate was `vitaminc-aead-frame`. It is now `recipher-frame`, since only crates here depend on it. Both keep the MIT licence, and both are members of the root workspace. Both are `publish = false`, with `release = false` in `release-plz.toml`. crates.io's 0.10.0 was published from vitaminc. They publish from here only before the next `stack-encrypt` release. Every Cargo workspace that resolves `vitaminc-aead` has a `[patch.crates-io]` table pointing at these copies (see "Working on the Rust crates"). Their tests read the cross-language value conformance corpus, `conformance/vitaminc-aead/value-conformance.json`. vitaminc's checks on them run here. They are 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 and that of `stack-encrypt-derive` 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". - `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` and `Ciphertext` 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). 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/`) holds only `Result`, `RecipherError`, the loader (`src/binding.ts`, which hands the addon the `Ok`, `Err` and `RecipherError` classes) and stand-in classes for a build that did not load. A method called without its object throws a `TypeError` (#1801); 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) and the policy packages `encrypt/policy` and `encrypt/policy/protosource`; 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). 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), a final version dispatched from anywhere but `main`, and a final version while `languages/golang/go.mod` pins a `github.com/cipherstash/vitaminc/…` module at a pseudo-version (vitaminc's Go bindings have no tags, and a TEMPORARY pin on an unreleased commit must be gone before the module is tagged); a pre-release may come from a branch and may carry such a pin. 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. `./...` 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. @@ -747,9 +747,8 @@ term. `cts-common` and `zerokms-protocol` take caret 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 other vitaminc crates come from crates.io at 0.10, and four of +vitaminc's AEAD crates (`vitaminc-aead`, `recipher-frame`) live here, in +`packages/`, and are not published from here yet. The other vitaminc crates come from crates.io at 0.10, and four of them depend on `vitaminc-aead`: `vitaminc-normalize`, `vitaminc-prf`, `vitaminc-ore` and `vitaminc-encrypt`, with the `vitaminc` umbrella crate, `clww-ore` and `ore-rs` above them. So every Cargo workspace that resolves @@ -768,8 +767,8 @@ published from here. 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), +- **Three Cargo workspaces, not one.** The root workspace (the eight stack-* + crates, the two 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 @@ -817,7 +816,7 @@ which the plan schedules before the next `stack-encrypt` release. bundle built from the tree — `mise run go:test:postgres` locally, which also runs the Rust and Go EQL/JSON conformance lane and so needs `psql` and the `MISE_ENV=test` cargo tools — and the live tests), `crap-crates.yml`, - `mutants.yml`, `fuzz.yml`, `miri.yml`, `udeps.yml`, and for the three + `mutants.yml`, `fuzz.yml`, `miri.yml`, `udeps.yml`, and for the two AEAD crates `kani.yml`, `supply-chain-vitaminc-aead.yml` and `storage-corpus.yml`. `scripts/__tests__/crates-ci.test.mjs` fails when a mise task in the root @@ -878,7 +877,7 @@ 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 +Miri and the sanitizers do not run on the AEAD crates. Both `#![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. @@ -903,7 +902,7 @@ 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 +stack-encrypt-derive's value derives, vitaminc-aead, recipher-frame) 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 diff --git a/Cargo.lock b/Cargo.lock index 283ca69ad..02fd75467 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3689,6 +3689,16 @@ dependencies = [ "zeroize", ] +[[package]] +name = "stack-encrypt-downstream" +version = "0.0.0" +dependencies = [ + "stack-encrypt", + "tokio", + "toml 1.1.8+spec-1.1.0", + "trybuild", +] + [[package]] name = "stack-encrypt-jsonpath" version = "0.3.0" @@ -4539,7 +4549,7 @@ checksum = "62cacd4dae485e98cfe5407e919187a8468dd933ea4234be5115b7d13a30f3c6" dependencies = [ "bytes", "serde", - "vitaminc-aead-derive 0.5.1", + "vitaminc-aead-derive", "vitaminc-context 0.5.1", "vitaminc-protected 0.5.1", "vitaminc-random 0.5.1", @@ -4559,10 +4569,10 @@ dependencies = [ "rust_decimal", "serde", "serde_json", + "stack-encrypt-derive", "thiserror 2.0.18", "trybuild", "uuid", - "vitaminc-aead-derive 0.10.0", "vitaminc-context 0.10.0", "vitaminc-prf", "vitaminc-protected 0.10.0", @@ -4581,18 +4591,6 @@ dependencies = [ "syn 3.0.9", ] -[[package]] -name = "vitaminc-aead-derive" -version = "0.10.0" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.9", - "vitaminc 0.10.0", - "vitaminc-aead 0.10.0", - "zeroize", -] - [[package]] name = "vitaminc-context" version = "0.5.1" diff --git a/Cargo.toml b/Cargo.toml index eb443de30..7cdb1e06d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -2,7 +2,7 @@ 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 two AEAD crates moved from cipherstash/vitaminc. # 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 @@ -13,16 +13,18 @@ members = [ "packages/stack-kms", "packages/stack-encrypt", "packages/stack-encrypt-derive", + # A crate that depends on stack-encrypt alone, as an application does. + "packages/stack-encrypt-downstream", "packages/stack-encrypt-jsonpath", "packages/stack-guest-abi", - # The AEAD crates moved from cipherstash/vitaminc. vitaminc-aead and - # vitaminc-aead-derive keep their crates.io names, and are not published - # from here yet; see the patch table at the end. recipher-frame was - # vitaminc-aead-frame: only crates in this repository depend on it, so it - # could take a name of its own. + # The AEAD crates moved from cipherstash/vitaminc. vitaminc-aead keeps + # its crates.io name. It is not published from here yet: see the patch + # table at the end. recipher-frame was vitaminc-aead-frame. Only crates in + # this repository depend on it, so it could take a name of its own. + # The vitaminc-aead crate has no derives of its own. The `Encrypt` and + # `Decrypt` derives of stack-encrypt-derive implement its traits. "packages/vitaminc-aead", "packages/recipher-frame", - "packages/vitaminc-aead-derive", "languages/typescript/packages/auth", "languages/typescript/packages/profile", "languages/typescript/packages/stack-auth-wasm", @@ -173,8 +175,8 @@ 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 +# vitaminc-aead moved here from cipherstash/vitaminc and is 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 @@ -185,4 +187,3 @@ vitaminc-protected = "0.10.0" # resolves these crates carries the same table. [patch.crates-io] vitaminc-aead = { path = "./packages/vitaminc-aead" } -vitaminc-aead-derive = { path = "./packages/vitaminc-aead-derive" } diff --git a/SECURITY.md b/SECURITY.md index b037162ea..13ebab20d 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -41,18 +41,20 @@ by `.github/workflows/release-golang.yml` as `languages/golang/vX.Y.Z` and `languages/golang/encrypt/encrypttest/vX.Y.Z` tags. All of these are in scope for security reports on the same terms as the npm packages above. -It also carries the source of three Rust crates moved from -`cipherstash/vitaminc`: **`vitaminc-aead`**, **`recipher-frame`** and -**`vitaminc-aead-derive`** (`packages/vitaminc-aead`, -`packages/recipher-frame`, `packages/vitaminc-aead-derive`). They define -the value types Stack Encrypt seals, how each is encoded, and how a value is -sealed. Their crates.io releases up to 0.10.0 were published from +It also contains the source of two Rust crates moved from +`cipherstash/vitaminc`: **`vitaminc-aead`** and **`recipher-frame`** +(`packages/vitaminc-aead`, `packages/recipher-frame`). They define the value +types Stack Encrypt seals, how each is encoded, and how a value is sealed. +Their crates.io releases up to 0.10.0 were published from `cipherstash/vitaminc`, the frame crate's under its old name `vitaminc-aead-frame`, and they are not published from this repository yet. Every build that uses `vitaminc-aead` 0.10 uses the copies here; the 0.5.1 -and 0.2.0-pre that some builds still reach come from crates.io. The three +and 0.2.0-pre that some builds still reach come from crates.io. The two crates are licensed under MIT, and are in scope for security reports on the -same terms as the npm packages above. +same terms as the npm packages above. A third crate moved with them, +`vitaminc-aead-derive`, is no longer in this repository: its derives are +now `stack-encrypt-derive`'s `Encrypt` and `Decrypt`. Its crates.io +releases up to 0.10.0 were published from `cipherstash/vitaminc`. The `encrypttest` module ships test builds of the engine whose keys derive from a published seed. Those keys are not secret by @@ -66,6 +68,12 @@ includes the optional `stack-encrypt` feature of the MIT-licensed `eql-bindings` crate, which depends on `stack-encrypt` and so is usable only under the same terms. +The `stack-encrypt-downstream` Rust crate +(`packages/stack-encrypt-downstream`) is an unpublished test crate. It +depends on `stack-encrypt` alone, as an application does, and its tests +check that such a crate can derive and implement `Encrypt` and `Decrypt`. +It adds no published package or production service. + The `eql-encryption-tests` Rust crate (`packages/eql/tests/encryption`) is an unpublished test harness for these bindings. It uses real encryption with a fake key source, executes the Rustdoc text encryption example, and provides diff --git a/languages/golang/auth/guest/Cargo.lock b/languages/golang/auth/guest/Cargo.lock index a3cee53c5..2d165e3ce 100644 --- a/languages/golang/auth/guest/Cargo.lock +++ b/languages/golang/auth/guest/Cargo.lock @@ -2290,7 +2290,7 @@ checksum = "62cacd4dae485e98cfe5407e919187a8468dd933ea4234be5115b7d13a30f3c6" dependencies = [ "bytes", "serde", - "vitaminc-aead-derive 0.5.1", + "vitaminc-aead-derive", "vitaminc-context 0.5.1", "vitaminc-protected 0.5.1", "vitaminc-random 0.5.1", @@ -2305,7 +2305,6 @@ dependencies = [ "futures-util", "serde", "thiserror 2.0.20", - "vitaminc-aead-derive 0.10.0", "vitaminc-context 0.10.0", "vitaminc-protected 0.10.0", "vitaminc-random 0.10.0", @@ -2323,15 +2322,6 @@ dependencies = [ "syn 3.0.6", ] -[[package]] -name = "vitaminc-aead-derive" -version = "0.10.0" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.6", -] - [[package]] name = "vitaminc-context" version = "0.5.1" diff --git a/languages/golang/auth/guest/Cargo.toml b/languages/golang/auth/guest/Cargo.toml index d22ee9d4c..434707c6d 100644 --- a/languages/golang/auth/guest/Cargo.toml +++ b/languages/golang/auth/guest/Cargo.toml @@ -64,9 +64,8 @@ opt-level = "s" 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 lives in this repository and is not published from +# here yet. Build against the copy, 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" } diff --git a/languages/golang/encrypt/guest/Cargo.lock b/languages/golang/encrypt/guest/Cargo.lock index 2c958fc08..d80d12836 100644 --- a/languages/golang/encrypt/guest/Cargo.lock +++ b/languages/golang/encrypt/guest/Cargo.lock @@ -2854,7 +2854,7 @@ checksum = "62cacd4dae485e98cfe5407e919187a8468dd933ea4234be5115b7d13a30f3c6" dependencies = [ "bytes", "serde", - "vitaminc-aead-derive 0.5.1", + "vitaminc-aead-derive", "vitaminc-context 0.5.1", "vitaminc-protected 0.5.1", "vitaminc-random 0.5.1", @@ -2871,7 +2871,6 @@ dependencies = [ "rust_decimal", "serde", "thiserror 2.0.20", - "vitaminc-aead-derive 0.10.0", "vitaminc-context 0.10.0", "vitaminc-protected 0.10.0", "vitaminc-random 0.10.0", @@ -2889,15 +2888,6 @@ dependencies = [ "syn 3.0.4", ] -[[package]] -name = "vitaminc-aead-derive" -version = "0.10.0" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.4", -] - [[package]] name = "vitaminc-context" version = "0.5.1" diff --git a/languages/golang/encrypt/guest/Cargo.toml b/languages/golang/encrypt/guest/Cargo.toml index c501fb6c6..d3fbbce4b 100644 --- a/languages/golang/encrypt/guest/Cargo.toml +++ b/languages/golang/encrypt/guest/Cargo.toml @@ -98,9 +98,8 @@ 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 lives in this repository and is not published from +# here yet. Build against the copy, 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" } diff --git a/languages/typescript/packages/recipher-js/Cargo.lock b/languages/typescript/packages/recipher-js/Cargo.lock index c368c643d..7dd16b181 100644 --- a/languages/typescript/packages/recipher-js/Cargo.lock +++ b/languages/typescript/packages/recipher-js/Cargo.lock @@ -3769,7 +3769,7 @@ checksum = "62cacd4dae485e98cfe5407e919187a8468dd933ea4234be5115b7d13a30f3c6" dependencies = [ "bytes", "serde", - "vitaminc-aead-derive 0.5.1", + "vitaminc-aead-derive", "vitaminc-context 0.5.1", "vitaminc-protected 0.5.1", "vitaminc-random 0.5.1", @@ -3786,7 +3786,6 @@ dependencies = [ "rust_decimal", "serde", "thiserror 2.0.21", - "vitaminc-aead-derive 0.10.0", "vitaminc-context 0.10.0", "vitaminc-protected 0.10.0", "vitaminc-random 0.10.0", @@ -3804,15 +3803,6 @@ dependencies = [ "syn 3.0.10", ] -[[package]] -name = "vitaminc-aead-derive" -version = "0.10.0" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.10", -] - [[package]] name = "vitaminc-context" version = "0.5.1" diff --git a/languages/typescript/packages/recipher-js/Cargo.toml b/languages/typescript/packages/recipher-js/Cargo.toml index 85f4883f8..39f99ec5c 100644 --- a/languages/typescript/packages/recipher-js/Cargo.toml +++ b/languages/typescript/packages/recipher-js/Cargo.toml @@ -21,9 +21,8 @@ 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 lives in this repository and is not published from +# here yet. Build against the copy, 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" } diff --git a/languages/typescript/packages/recipher-js/value-napi/tests/addon/Cargo.lock b/languages/typescript/packages/recipher-js/value-napi/tests/addon/Cargo.lock index 86d29fe77..5d7a552dc 100644 --- a/languages/typescript/packages/recipher-js/value-napi/tests/addon/Cargo.lock +++ b/languages/typescript/packages/recipher-js/value-napi/tests/addon/Cargo.lock @@ -1128,22 +1128,12 @@ dependencies = [ "rust_decimal", "serde", "thiserror", - "vitaminc-aead-derive", "vitaminc-context", "vitaminc-protected", "vitaminc-random", "zeroize", ] -[[package]] -name = "vitaminc-aead-derive" -version = "0.10.0" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.10", -] - [[package]] name = "vitaminc-context" version = "0.10.0" diff --git a/languages/typescript/packages/recipher-js/value-napi/tests/addon/Cargo.toml b/languages/typescript/packages/recipher-js/value-napi/tests/addon/Cargo.toml index 0e71e685b..b84680732 100644 --- a/languages/typescript/packages/recipher-js/value-napi/tests/addon/Cargo.toml +++ b/languages/typescript/packages/recipher-js/value-napi/tests/addon/Cargo.toml @@ -20,9 +20,8 @@ vitaminc-protected = "0.10.0" [build-dependencies] napi-build = "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 lives in this repository and is not published from +# here yet. Build against the copy, 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" } diff --git a/mise.toml b/mise.toml index 9cecb8933..dfcd353de 100644 --- a/mise.toml +++ b/mise.toml @@ -1,5 +1,5 @@ # 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 +# workspace in Cargo.toml (the stack-* crates, the two AEAD crates 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) @@ -12,11 +12,11 @@ includes = [ "packages/stack-kms/tasks.toml", "packages/stack-profile/tasks.toml", "packages/stack-encrypt/tasks.toml", + "packages/stack-encrypt-derive/tasks.toml", "packages/stack-encrypt-jsonpath/tasks.toml", "packages/stack-guest-abi/tasks.toml", "packages/vitaminc-aead/tasks.toml", "packages/recipher-frame/tasks.toml", - "packages/vitaminc-aead-derive/tasks.toml", ] [tools] diff --git a/packages/eql/Cargo.lock b/packages/eql/Cargo.lock index 53fef182a..3e196ecaa 100644 --- a/packages/eql/Cargo.lock +++ b/packages/eql/Cargo.lock @@ -5077,7 +5077,7 @@ checksum = "62cacd4dae485e98cfe5407e919187a8468dd933ea4234be5115b7d13a30f3c6" dependencies = [ "bytes", "serde", - "vitaminc-aead-derive 0.5.1", + "vitaminc-aead-derive", "vitaminc-context 0.5.1", "vitaminc-protected 0.5.1", "vitaminc-random 0.5.1", @@ -5094,7 +5094,6 @@ dependencies = [ "rust_decimal", "serde", "thiserror 2.0.20", - "vitaminc-aead-derive 0.10.0", "vitaminc-context 0.10.0", "vitaminc-protected 0.10.0", "vitaminc-random 0.10.0", @@ -5112,15 +5111,6 @@ dependencies = [ "syn 3.0.3", ] -[[package]] -name = "vitaminc-aead-derive" -version = "0.10.0" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.3", -] - [[package]] name = "vitaminc-context" version = "0.5.1" diff --git a/packages/eql/Cargo.toml b/packages/eql/Cargo.toml index 72314769c..3162f3e95 100644 --- a/packages/eql/Cargo.toml +++ b/packages/eql/Cargo.toml @@ -36,9 +36,8 @@ 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 lives in this repository and is not published from +# here yet. Build against the copy, 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" } diff --git a/packages/eql/tests/docker-compose.yml b/packages/eql/tests/docker-compose.yml index 7089551a2..a1b23eaef 100644 --- a/packages/eql/tests/docker-compose.yml +++ b/packages/eql/tests/docker-compose.yml @@ -1,7 +1,8 @@ services: postgres: &postgres container_name: postgres - image: postgres:17 + # Docker's public mirror avoids Hub's anonymous pull limit in CI (#2016). + image: public.ecr.aws/docker/library/postgres:17 # max_locks_per_transaction is NOT a per-transaction cap — it sizes the # CLUSTER-WIDE shared lock table as max_locks_per_transaction * # max_connections. The shipped uninstaller drops both eql_v3 schemas with @@ -44,24 +45,24 @@ services: postgres-17: <<: *postgres - image: postgres:17 + image: public.ecr.aws/docker/library/postgres:17 container_name: postgres-17 #volumes: # uncomment if you need to inspect the container contents #- ./pg/data-17:/var/lib/postgresql/data postgres-16: <<: *postgres - image: postgres:16 + image: public.ecr.aws/docker/library/postgres:16 container_name: postgres-16 postgres-15: <<: *postgres - image: postgres:15 + image: public.ecr.aws/docker/library/postgres:15 container_name: postgres-15 postgres-14: <<: *postgres - image: postgres:14 + image: public.ecr.aws/docker/library/postgres:14 container_name: postgres-14 networks: 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..f1c08f9fb 100644 --- a/packages/eql/tests/timing/ore_block_v2/ctgen/Cargo.lock +++ b/packages/eql/tests/timing/ore_block_v2/ctgen/Cargo.lock @@ -749,22 +749,12 @@ dependencies = [ "futures-util", "serde", "thiserror 2.0.21", - "vitaminc-aead-derive", "vitaminc-context", "vitaminc-protected", "vitaminc-random", "zeroize", ] -[[package]] -name = "vitaminc-aead-derive" -version = "0.10.0" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.9", -] - [[package]] name = "vitaminc-context" version = "0.10.0" 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..e8ada27fb 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,8 @@ 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 lives in this repository and is not published from +# here yet. Build against the copy, 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" } diff --git a/packages/stack-auth/fuzz/Cargo.lock b/packages/stack-auth/fuzz/Cargo.lock index c445c934d..d059845f1 100644 --- a/packages/stack-auth/fuzz/Cargo.lock +++ b/packages/stack-auth/fuzz/Cargo.lock @@ -3203,7 +3203,7 @@ checksum = "62cacd4dae485e98cfe5407e919187a8468dd933ea4234be5115b7d13a30f3c6" dependencies = [ "bytes", "serde", - "vitaminc-aead-derive 0.5.1", + "vitaminc-aead-derive", "vitaminc-context 0.5.1", "vitaminc-protected 0.5.1", "vitaminc-random 0.5.1", @@ -3218,7 +3218,6 @@ dependencies = [ "futures-util", "serde", "thiserror 2.0.18", - "vitaminc-aead-derive 0.10.0", "vitaminc-context 0.10.0", "vitaminc-protected 0.10.0", "vitaminc-random 0.10.0", @@ -3236,15 +3235,6 @@ dependencies = [ "syn 3.0.3", ] -[[package]] -name = "vitaminc-aead-derive" -version = "0.10.0" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.3", -] - [[package]] name = "vitaminc-context" version = "0.5.1" diff --git a/packages/stack-auth/fuzz/Cargo.toml b/packages/stack-auth/fuzz/Cargo.toml index b36843b72..ad0da06c8 100644 --- a/packages/stack-auth/fuzz/Cargo.toml +++ b/packages/stack-auth/fuzz/Cargo.toml @@ -39,9 +39,8 @@ 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 lives in this repository and is not published from +# here yet. Build against the copy, 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" } diff --git a/packages/vitaminc-aead-derive/docs/attributes.md b/packages/stack-encrypt-derive/docs/value-attributes.md similarity index 61% rename from packages/vitaminc-aead-derive/docs/attributes.md rename to packages/stack-encrypt-derive/docs/value-attributes.md index 5c29bc878..d01ae9fe1 100644 --- a/packages/vitaminc-aead-derive/docs/attributes.md +++ b/packages/stack-encrypt-derive/docs/value-attributes.md @@ -6,7 +6,7 @@ option is one the author believes is in effect. | Attribute | Applies to | Effect | |---|---|---| -| `crate = "path"` | container | Name the path to `vitaminc_aead` in the generated code | +| `crate = "path"` | container | Name the path to `stack_encrypt` in the generated code | | `recursive` | container | Mark a mutually recursive type, whose depth the derive cannot work out | | `rename = "name"` | field | Store the field under `name` instead of its own name | | `passthrough` | field | Store the field **in the clear**, unencrypted and unauthenticated | @@ -17,30 +17,45 @@ Enum variants take no attributes. ## `#[aead(crate = "...")]` -Points the generated code at a re-export of `vitaminc_aead`, for callers who -depend on it through an umbrella crate rather than directly: +Names the path to `stack_encrypt` in the generated code. Use it in a crate +that reaches `stack_encrypt` through a re-export of another crate: ```rust -use vitaminc::aead::{Decrypt, Encrypt}; +mod platform { + // A crate of your own that re-exports Stack Encrypt. + pub use stack_encrypt; +} + +use platform::stack_encrypt::{Decrypt, Encrypt}; #[derive(Encrypt, Decrypt)] -#[aead(crate = "::vitaminc::aead")] +#[aead(crate = "crate::platform::stack_encrypt")] struct User { name: String, } -# fn round_trip(value: T) -> T { -# use vitaminc::protected::Controlled; -# use vitaminc_aead::Encrypt; -# let bytes = vitaminc_aead::to_frame(value).unwrap(); -# let frame = vitaminc_aead::Frame::parse(bytes.risky_ref()).unwrap(); -# frame.visit(T::sink()).unwrap() +# fn round_trip(value: T) -> T { +# round_trip_as(value) +# } +# fn round_trip_as(value: T) -> U { +# tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { +# let cipher = stack_encrypt::StackCipher::builder() +# .kms(stack_encrypt::kms::FakeDataKeySource::new()) +# .init() +# .await +# .unwrap(); +# let keyset = cipher.default_keyset(); +# let stored = keyset.encrypt_tree(value, ("docs", "example")).await.unwrap(); +# keyset.decrypt_tree(stored, ("docs", "example")).await.unwrap() +# }) # } +# fn main() { # let user = round_trip(User { name: "Ada".into() }); # assert_eq!(user.name, "Ada"); +# } ``` -Every path the expansion emits is redirected, so the deriving crate needs no -direct dependency on `vitaminc_aead` at all. +Every path the generated code writes starts at that path, so the deriving +crate needs no direct dependency on `stack_encrypt`. ## `#[aead(recursive)]` @@ -49,17 +64,22 @@ fails to compile a type deeper than `MAX_DEPTH`, whose fully populated values the encrypting sink would always refuse: ```text -error[E0080]: evaluation panicked: `TooDeep` nests deeper than `MAX_DEPTH` levels, so - the encrypting sink would refuse its fully populated values +error[E0080]: evaluation panicked: `TooDeep` nests deeper than + `stack_encrypt::plaintext::depth::MAX_DEPTH` levels. Stack Encrypt refuses + to encrypt a value nested that deeply, so it would refuse every full value + of this type ``` +The path in the message starts at the `crate` path, when the type names +one. + A recursive type has no fixed depth: a tree can be as deep as its data. For a type that names itself in a field, directly or as `Self`, the derive sees this and leaves the check to the walk, which refuses a value that is too deep when it is encrypted: ```rust -use vitaminc_aead::{Decrypt, Encrypt}; +use stack_encrypt::{Decrypt, Encrypt}; #[derive(Encrypt, Decrypt)] struct Tree { @@ -68,13 +88,19 @@ struct Tree { } # assert_eq!(Tree::DEPTH, None); # let tree = Tree { label: "root".into(), children: vec![Tree { label: "child".into(), children: vec![] }] }; -# let bytes = vitaminc_aead::to_frame(tree).unwrap(); -# use vitaminc::protected::Controlled; -# assert!(vitaminc_aead::Frame::parse(bytes.risky_ref()).is_ok()); +# tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { +# let cipher = stack_encrypt::StackCipher::builder() +# .kms(stack_encrypt::kms::FakeDataKeySource::new()) +# .init() +# .await +# .unwrap(); +# let keyset = cipher.default_keyset(); +# assert!(keyset.encrypt_tree(tree, ("docs", "tree")).await.is_ok()); +# }); ``` -This example checks recursive encoding. Decoding this `Tree` with -`Frame::visit(Tree::sink())` currently hits a compiler recursion limit. +This example checks that a recursive `Tree` encrypts. Decrypting this +`Tree` hits a compiler recursion limit. The derive looks for the type's bare name. A field that names the type through a path, such as `crate::models::Tree`, is read as another type with the @@ -85,7 +111,7 @@ derive, and fails to compile with `error[E0391]: cycle detected when simplifying each type's `DEPTH`. Mark every type in the cycle `recursive`: ```rust -use vitaminc_aead::{Decrypt, Encrypt}; +use stack_encrypt::{Decrypt, Encrypt}; #[derive(Encrypt, Decrypt)] #[aead(recursive)] @@ -98,12 +124,20 @@ struct Even { struct Odd { next: Vec, } -# fn round_trip(value: T) -> T { -# use vitaminc::protected::Controlled; -# use vitaminc_aead::Encrypt; -# let bytes = vitaminc_aead::to_frame(value).unwrap(); -# let frame = vitaminc_aead::Frame::parse(bytes.risky_ref()).unwrap(); -# frame.visit(T::sink()).unwrap() +# fn round_trip(value: T) -> T { +# round_trip_as(value) +# } +# fn round_trip_as(value: T) -> U { +# tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { +# let cipher = stack_encrypt::StackCipher::builder() +# .kms(stack_encrypt::kms::FakeDataKeySource::new()) +# .init() +# .await +# .unwrap(); +# let keyset = cipher.default_keyset(); +# let stored = keyset.encrypt_tree(value, ("docs", "example")).await.unwrap(); +# keyset.decrypt_tree(stored, ("docs", "example")).await.unwrap() +# }) # } # let even = round_trip(Even { next: vec![Odd { next: vec![] }] }); # assert_eq!(even.next.len(), 1); @@ -122,7 +156,7 @@ concrete type, under `cargo build` rather than `cargo check`. Changes the map key a field is stored under: ```rust -use vitaminc_aead::{Decrypt, Encrypt}; +use stack_encrypt::{Decrypt, Encrypt}; #[derive(Encrypt, Decrypt)] struct User { @@ -130,18 +164,26 @@ struct User { name: String, } // ciphertext: Map { "n": … } -# fn round_trip(value: T) -> T { -# use vitaminc::protected::Controlled; -# use vitaminc_aead::Encrypt; -# let bytes = vitaminc_aead::to_frame(value).unwrap(); -# let frame = vitaminc_aead::Frame::parse(bytes.risky_ref()).unwrap(); -# frame.visit(T::sink()).unwrap() +# fn round_trip(value: T) -> T { +# round_trip_as(value) +# } +# fn round_trip_as(value: T) -> U { +# tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { +# let cipher = stack_encrypt::StackCipher::builder() +# .kms(stack_encrypt::kms::FakeDataKeySource::new()) +# .init() +# .await +# .unwrap(); +# let keyset = cipher.default_keyset(); +# let stored = keyset.encrypt_tree(value, ("docs", "example")).await.unwrap(); +# keyset.decrypt_tree(stored, ("docs", "example")).await.unwrap() +# }) # } # let user = round_trip(User { name: "Ada".into() }); # assert_eq!(user.name, "Ada"); -# let plan = vitaminc_aead::plan::<_, std::convert::Infallible, _>(user, ()).unwrap(); -# let vitaminc_aead::CipherText::Map(entries) = plan else { panic!("expected a map") }; -# assert_eq!(entries[0].0, "n"); +# // The stored map has the key `n`, so it decrypts into a map with that key. +# let renamed: std::collections::HashMap = round_trip_as(User { name: "Ada".into() }); +# assert_eq!(renamed.get("n").map(String::as_str), Some("Ada")); ``` Field names are part of the ciphertext contract — each key is bound into the @@ -160,7 +202,7 @@ Stores a field as a cleartext map entry, so it can be an ordinary database column that other queries select, filter, and update without holding the key: ```rust -use vitaminc_aead::{Decrypt, Encrypt}; +use stack_encrypt::{Decrypt, Encrypt}; #[derive(Encrypt, Decrypt)] struct Row { @@ -168,12 +210,20 @@ struct Row { tenant: String, // a plain column ssn: String, // encrypted } -# fn round_trip(value: T) -> T { -# use vitaminc::protected::Controlled; -# use vitaminc_aead::Encrypt; -# let bytes = vitaminc_aead::to_frame(value).unwrap(); -# let frame = vitaminc_aead::Frame::parse(bytes.risky_ref()).unwrap(); -# frame.visit(T::sink()).unwrap() +# fn round_trip(value: T) -> T { +# round_trip_as(value) +# } +# fn round_trip_as(value: T) -> U { +# tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { +# let cipher = stack_encrypt::StackCipher::builder() +# .kms(stack_encrypt::kms::FakeDataKeySource::new()) +# .init() +# .await +# .unwrap(); +# let keyset = cipher.default_keyset(); +# let stored = keyset.encrypt_tree(value, ("docs", "example")).await.unwrap(); +# keyset.decrypt_tree(stored, ("docs", "example")).await.unwrap() +# }) # } # let row = round_trip(Row { tenant: "acme".into(), ssn: "example-only".into() }); # assert_eq!(row.tenant, "acme"); @@ -232,7 +282,7 @@ somewhere else, such as an ordinary column alongside the ciphertext, or a value derived from the others: ```rust -use vitaminc_aead::{Decrypt, Encrypt}; +use stack_encrypt::{Decrypt, Encrypt}; #[derive(Encrypt, Decrypt)] struct User { @@ -240,12 +290,20 @@ struct User { id: u64, // not in the ciphertext at all password: String, // encrypted } -# fn round_trip(value: T) -> T { -# use vitaminc::protected::Controlled; -# use vitaminc_aead::Encrypt; -# let bytes = vitaminc_aead::to_frame(value).unwrap(); -# let frame = vitaminc_aead::Frame::parse(bytes.risky_ref()).unwrap(); -# frame.visit(T::sink()).unwrap() +# fn round_trip(value: T) -> T { +# round_trip_as(value) +# } +# fn round_trip_as(value: T) -> U { +# tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { +# let cipher = stack_encrypt::StackCipher::builder() +# .kms(stack_encrypt::kms::FakeDataKeySource::new()) +# .init() +# .await +# .unwrap(); +# let keyset = cipher.default_keyset(); +# let stored = keyset.encrypt_tree(value, ("docs", "example")).await.unwrap(); +# keyset.decrypt_tree(stored, ("docs", "example")).await.unwrap() +# }) # } # let user = round_trip(User { id: 42, password: "example-only".into() }); # assert_eq!(user.id, 0); @@ -272,17 +330,25 @@ swaps the field for its default with `core::mem::take` instead, and the empty value left behind is dropped, and wiped, with `self`: ```rust -use vitaminc_aead::{Decrypt, Encrypt}; +use stack_encrypt::{Decrypt, Encrypt}; use zeroize::ZeroizeOnDrop; #[derive(Encrypt, Decrypt, ZeroizeOnDrop)] struct SecretToken(#[aead(take)] String); -# fn round_trip(value: T) -> T { -# use vitaminc::protected::Controlled; -# use vitaminc_aead::Encrypt; -# let bytes = vitaminc_aead::to_frame(value).unwrap(); -# let frame = vitaminc_aead::Frame::parse(bytes.risky_ref()).unwrap(); -# frame.visit(T::sink()).unwrap() +# fn round_trip(value: T) -> T { +# round_trip_as(value) +# } +# fn round_trip_as(value: T) -> U { +# tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { +# let cipher = stack_encrypt::StackCipher::builder() +# .kms(stack_encrypt::kms::FakeDataKeySource::new()) +# .init() +# .await +# .unwrap(); +# let keyset = cipher.default_keyset(); +# let stored = keyset.encrypt_tree(value, ("docs", "example")).await.unwrap(); +# keyset.decrypt_tree(stored, ("docs", "example")).await.unwrap() +# }) # } # let token = round_trip(SecretToken("example-only".into())); # assert_eq!(token.0, "example-only"); diff --git a/packages/stack-encrypt-derive/docs/value-derives.md b/packages/stack-encrypt-derive/docs/value-derives.md new file mode 100644 index 000000000..8116b3bc9 --- /dev/null +++ b/packages/stack-encrypt-derive/docs/value-derives.md @@ -0,0 +1,121 @@ +# Encrypting a type of your own + +`#[derive(Encrypt)]` describes a value of your type to Stack Encrypt. +`#[derive(Decrypt)]` builds the value back. Import both from +`stack_encrypt`. Your crate needs no other dependency for them: + +```rust +use stack_encrypt::{Decrypt, Encrypt, StackCipher}; + +#[derive(Encrypt, Decrypt)] +struct User { + name: String, + age: u32, +} +# tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { +// With no `.kms(..)`, the cipher uses ZeroKMS. It reads credentials from +// the environment, or from the profile that `npx stash auth login` writes. +let cipher = StackCipher::builder() +# .kms(stack_encrypt::kms::FakeDataKeySource::new()) + .init() + .await?; +let keyset = cipher.default_keyset(); +let user = User { name: "Ada".into(), age: 37 }; +let stored = keyset.encrypt_tree(user, ("users", "profile")).await?; +let user: User = keyset.decrypt_tree(stored, ("users", "profile")).await?; +assert_eq!(user.name, "Ada"); +assert_eq!(user.age, 37); +# Ok::<(), Box>(()) +# }).unwrap(); +``` + +`#[derive(Encrypt)]` walks a struct into a sink as a map, with one entry +per field. `#[derive(Decrypt)]` generates the map sink that builds the +struct back. The sink hands each entry to the sink of the field's own type. + +## The shape of the ciphertext + +A struct is encrypted as a **map**, keyed by field name. A map binds each +entry's key into the associated data that its value is sealed against. +So nobody can rename or swap the fields of a stored ciphertext without +decryption failing. A sequence would not do this. The associated data of a +sequence element has no position in it, so two fields of the same type +could be swapped. + +The map shape has these consequences: + +- Field **names are part of the ciphertext**. Renaming a field breaks the + data already stored under the old name. Use `#[aead(rename = "...")]` to + keep the old name. +- A derived struct's ciphertext is the same as the ciphertext of the + equivalent `HashMap`, and of a map that another language's SDK + wrote. +- A tuple struct of two or more fields uses each field's index as its key: + `"0"`, `"1"`, and so on. Each field is bound to its key, as in a struct + with named fields. +- A **newtype** is a struct with exactly one unnamed field, such as + `struct Email(String)`. A newtype is *transparent*: it encrypts and + decrypts exactly as its inner type. It adds nothing to the ciphertext. + serde treats a newtype in the same way. So does `Protected`. + A newtype is also a `Scalar`, one leaf, when its inner type is one. So + `Email(String)` is a `Scalar`, and `keyset.encrypt` takes it. + `Tags(Vec)` is not a `Scalar`. +- A unit struct, or a struct with no fields, encrypts to the authenticated + marker of an empty map. + +The entries of a stored map are not authenticated in any order. So the +derived `Decrypt` reads each key first, and matches it to a field. +Decryption is strict: it refuses an unknown key, a key that appears twice, +and a missing field. + +## Enums + +A **fieldless** enum is one `u32` leaf that contains the variant's +discriminant. The discriminant is an explicit `= n`, or one more than the +previous variant's, as Rust assigns them. The leaf is sealed and +authenticated like any other. Every variant's leaf has the same length, so +the length of the ciphertext does not show the variant. + +Decryption refuses an integer that is not the discriminant of a variant. +Give each variant an explicit `= n` before you store anything. Otherwise, +reordering the variants changes their discriminants. Variants take no +`#[aead(...)]` attributes. A fieldless enum is a `Scalar`, by value and by +reference, because it is one leaf. + +`#[derive(Zeroize)]` from the zeroize crate does not wipe a fieldless enum: +its `zeroize` does nothing. So a caller that wipes the value after it +encrypts it leaves the variant in memory. To have the variant wiped, give +the enum a `#[default]` variant and implement `zeroize::DefaultIsZeroes` +for it. Its `zeroize` then overwrites the value with the default variant. + +```rust +use stack_encrypt::Encrypt; +use zeroize::Zeroize; + +#[derive(Encrypt, Clone, Copy, Default, Debug, PartialEq)] +enum Status { + #[default] + Active, + Suspended = 7, +} + +impl zeroize::DefaultIsZeroes for Status {} + +let mut status = Status::Suspended; +status.zeroize(); +assert_eq!(status, Status::Active, "zeroize writes the default variant"); +``` + +An enum with fields cannot be derived. There is no agreed layout for the +fields of a variant. Model the choice as a struct instead, with a +fieldless enum for the variant and an `Option` field for each variant's +data. + +## Writing the impls by hand + +A type can implement `Encrypt` and `Decrypt` by hand, with no other +dependency than `stack_encrypt`. The items a hand-written impl names are in +`stack_encrypt::plaintext`: the sink traits, the `depth` constants, and +the types of a scalar. A type that encrypts as one value also implements +`stack_encrypt::Scalar` for its borrow. The docs of +`stack_encrypt::OpaqueEncode` show a complete example. diff --git a/packages/stack-encrypt-derive/src/lib.rs b/packages/stack-encrypt-derive/src/lib.rs index 75811172e..d5c36ccfb 100644 --- a/packages/stack-encrypt-derive/src/lib.rs +++ b/packages/stack-encrypt-derive/src/lib.rs @@ -1,4 +1,15 @@ -//! Derive the declarations of encrypted records. +//! Derive the declarations of encrypted records, and the description of a +//! plaintext value. +//! +//! Stack Encrypt re-exports every macro here, so depend on `stack-encrypt` +//! and import them from `stack_encrypt`. The macros come in two families: +//! +//! - `#[derive(Encrypt)]` and `#[derive(Decrypt)]` describe a plaintext +//! value of your own type, read `#[aead(...)]` attributes, and are +//! documented on each macro. See [`Encrypt`](macro@Encrypt). +//! - `#[derive(EncryptTarget)]` and `#[derive(DecryptSource)]` declare a +//! stored record, read `#[stash(...)]` attributes, and are documented +//! below. //! //! Derive `EncryptTarget

` and `DecryptSource

` on the struct that holds //! the encrypted form of a plaintext `P`. Then: @@ -329,6 +340,36 @@ mod owned_decrypt; mod owned_encrypt; mod predicate; mod shape; +mod value; + +/// Derive `Encrypt` for a struct or a fieldless enum: how a value of the type +/// is walked into a sink. A struct walks as a map keyed by field name. A +/// fieldless enum walks as one integer leaf, its discriminant. Pair it with +/// [`Decrypt`](macro@Decrypt) to read the value back. +/// +/// The derive also implements `Scalar` for a type that encrypts as one leaf: +/// a newtype over a `Scalar`, and a fieldless enum. +#[doc = include_str!("../docs/value-derives.md")] +#[doc = include_str!("../docs/value-attributes.md")] +#[proc_macro_derive(Encrypt, attributes(aead))] +pub fn derive_encrypt(input: TokenStream) -> TokenStream { + let input = parse_macro_input!(input as DeriveInput); + value::encrypt::derive(input) + .unwrap_or_else(syn::Error::into_compile_error) + .into() +} + +/// Derive `Decrypt` for a struct or a fieldless enum: the sink that builds +/// the type back from what [`Encrypt`](macro@Encrypt) walked. The wire shape +/// and the attributes are the same as for `Encrypt`. The docs of +/// [`Encrypt`](macro@Encrypt) describe them. +#[proc_macro_derive(Decrypt, attributes(aead))] +pub fn derive_decrypt(input: TokenStream) -> TokenStream { + let input = parse_macro_input!(input as DeriveInput); + value::decrypt::derive(input) + .unwrap_or_else(syn::Error::into_compile_error) + .into() +} /// Derive the owned `EncryptTarget` declaration for a record struct. See /// the [crate documentation](crate) for what the derive emits. The attributes diff --git a/packages/vitaminc-aead-derive/LICENSE b/packages/stack-encrypt-derive/src/value/LICENSE-MIT similarity index 100% rename from packages/vitaminc-aead-derive/LICENSE rename to packages/stack-encrypt-derive/src/value/LICENSE-MIT diff --git a/packages/vitaminc-aead-derive/src/attrs.rs b/packages/stack-encrypt-derive/src/value/attrs.rs similarity index 84% rename from packages/vitaminc-aead-derive/src/attrs.rs rename to packages/stack-encrypt-derive/src/value/attrs.rs index d8345ca26..bcf3c9daa 100644 --- a/packages/vitaminc-aead-derive/src/attrs.rs +++ b/packages/stack-encrypt-derive/src/value/attrs.rs @@ -1,13 +1,17 @@ -//! Parsing of the `#[aead(...)]` container and field attributes. +//! Parsing of the `#[aead(...)]` container and field attributes of +//! `#[derive(Encrypt)]` and `#[derive(Decrypt)]`. use syn::{Attribute, Path, Result}; /// Container-level options, from `#[aead(...)]` on the struct itself. pub(crate) struct ContainerAttrs { - /// Path to the `vitaminc_aead` crate in the generated code. Defaults to - /// `::vitaminc_aead`; overridden by `#[aead(crate = "...")]` so the macros - /// work through a re-export such as `::vitaminc::aead`. - pub(crate) krate: Path, + /// The module the generated code names every item through: + /// `::__derive`. `` is `::stack_encrypt` unless + /// `#[aead(crate = "...")]` names another path to it, such as a + /// re-export. Every path the expansion writes starts here, so the + /// deriving crate needs no dependency other than the one `` + /// names. + pub(crate) aead: Path, /// The type is recursive, from `#[aead(recursive)]`: its depth depends on /// the value, so it is checked by the walk rather than at compile time. /// Needed only for mutual recursion; a type that names itself in a field @@ -37,10 +41,9 @@ impl ContainerAttrs { })?; } - Ok(Self { - krate: krate.unwrap_or_else(|| syn::parse_quote!(::vitaminc_aead)), - recursive, - }) + let mut aead = krate.unwrap_or_else(|| syn::parse_quote!(::stack_encrypt)); + aead.segments.push(syn::parse_quote!(__derive)); + Ok(Self { aead, recursive }) } } diff --git a/packages/vitaminc-aead-derive/src/typed_decrypt.rs b/packages/stack-encrypt-derive/src/value/decrypt.rs similarity index 75% rename from packages/vitaminc-aead-derive/src/typed_decrypt.rs rename to packages/stack-encrypt-derive/src/value/decrypt.rs index 8220dcba4..f55fad4b2 100644 --- a/packages/vitaminc-aead-derive/src/typed_decrypt.rs +++ b/packages/stack-encrypt-derive/src/value/decrypt.rs @@ -16,14 +16,14 @@ use quote::{format_ident, quote, quote_spanned}; use syn::spanned::Spanned; use syn::{parse_quote, DeriveInput, Result}; -use crate::{ +use super::{ attrs::ContainerAttrs, shape::{FieldInfo, Shape, VariantInfo}, }; pub(crate) fn derive(input: DeriveInput) -> Result { let attrs = ContainerAttrs::parse(&input.attrs)?; - let krate = &attrs.krate; + let aead = &attrs.aead; let shape = Shape::parse(&input)?; let name = &input.ident; let vis = &input.vis; @@ -32,7 +32,7 @@ pub(crate) fn derive(input: DeriveInput) -> Result { // of type `Vec` picks up `Vec: Decrypt` from the blanket impl. let mut generics = input.generics.clone(); for param in generics.type_params_mut() { - param.bounds.push(parse_quote!(#krate::typed::Decrypt)); + param.bounds.push(parse_quote!(#aead::Decrypt)); } let (impl_generics, ty_generics, where_clause) = generics.split_for_impl(); // The generated items are declared with the struct's own generics, and @@ -44,7 +44,7 @@ pub(crate) fn derive(input: DeriveInput) -> Result { let marker = quote!(::core::marker::PhantomData #name #ty_generics>); let expanded = match &shape { - Shape::Enum(variants) => enum_target(krate, &input, variants), + Shape::Enum(variants) => enum_target(aead, &input, variants), Shape::Newtype(field) => { let inner = &field.ty; let wrap = format_ident!("__{name}DecryptWrap"); @@ -53,9 +53,9 @@ pub(crate) fn derive(input: DeriveInput) -> Result { #vis struct #wrap #decl_generics (#marker) #decl_where; #[automatically_derived] - impl #impl_generics #krate::typed::Rewrap<#inner> for #wrap #ty_generics #where_clause { + impl #impl_generics #aead::Rewrap<#inner> for #wrap #ty_generics #where_clause { type Output = #name #ty_generics; - fn rewrap(__value: #inner) -> ::core::result::Result { + fn rewrap(__value: #inner) -> ::core::result::Result { ::core::result::Result::Ok(#name(__value)) } } @@ -63,29 +63,29 @@ pub(crate) fn derive(input: DeriveInput) -> Result { // Transparent, mirroring the `Encrypt` side: the inner // type's sink, with its result rewrapped. #[automatically_derived] - impl #impl_generics #krate::typed::Decrypt for #name #ty_generics #where_clause { - type Sink = #krate::typed::Wrapped< - <#inner as #krate::typed::Decrypt>::Sink, + impl #impl_generics #aead::Decrypt for #name #ty_generics #where_clause { + type Sink = #aead::Wrapped< + <#inner as #aead::Decrypt>::Sink, #wrap #ty_generics, >; - fn reads_null(__ty: #krate::FixedType) -> bool { - <#inner as #krate::typed::Decrypt>::reads_null(__ty) + fn reads_null(__ty: #aead::FixedType) -> bool { + <#inner as #aead::Decrypt>::reads_null(__ty) } fn sink() -> Self::Sink { - #krate::typed::Wrapped::new(<#inner as #krate::typed::Decrypt>::sink()) + #aead::Wrapped::new(<#inner as #aead::Decrypt>::sink()) } } } } - Shape::Map(fields) => map_target(krate, &input, fields, &marker), - Shape::Empty => map_target(krate, &input, &[], &marker), + Shape::Map(fields) => map_target(aead, &input, fields, &marker), + Shape::Empty => map_target(aead, &input, &[], &marker), }; Ok(expanded) } fn map_target( - krate: &syn::Path, + aead: &syn::Path, input: &DeriveInput, fields: &[FieldInfo], marker: &TokenStream, @@ -95,7 +95,7 @@ fn map_target( let expected = name.to_string(); let mut generics = input.generics.clone(); for param in generics.type_params_mut() { - param.bounds.push(parse_quote!(#krate::typed::Decrypt)); + param.bounds.push(parse_quote!(#aead::Decrypt)); } let (impl_generics, ty_generics, where_clause) = generics.split_for_impl(); let (decl_generics, _, decl_where) = input.generics.split_for_impl(); @@ -120,21 +120,21 @@ fn map_target( let field_sink = |field: &FieldInfo| { let ty = &field.ty; if field.passthrough { - quote!(#krate::typed::Clear<#ty, #krate::typed::Slot<'__s, #ty>>) + quote!(#aead::Clear<#ty, #aead::Slot<'__s, #ty>>) } else { - quote!(#krate::typed::Forward<#ty, #krate::typed::Slot<'__s, #ty>>) + quote!(#aead::Forward<#ty, #aead::Slot<'__s, #ty>>) } }; let entry_ty = stored.iter().rev().fold(None, |tail, field| { let head = field_sink(field); Some(match tail { None => head, - Some(tail) => quote!(#krate::typed::Either<#head, #tail>), + Some(tail) => quote!(#aead::Either<#head, #tail>), }) }); // An empty struct hands out no entry sink at all; the type still has to // be named. - let entry_ty = entry_ty.unwrap_or_else(|| quote!(#krate::typed::Nothing)); + let entry_ty = entry_ty.unwrap_or_else(|| quote!(#aead::Nothing)); let arms = stored.iter().enumerate().map(|(index, field)| { let key = &field.key; @@ -144,14 +144,14 @@ fn map_target( // Nothing here is verified — no tag covers a passthrough entry // and nothing binds its key — so what comes back is untrusted // input, exactly as the column it came from is. - quote!(#krate::typed::Clear::new(#krate::typed::Slot(&mut self.#local))) + quote!(#aead::Clear::new(#aead::Slot(&mut self.#local))) } else { // Spanned to the field's type, so "`Foo` does not implement // `Decrypt`" points at the field rather than at the derive. - let sink = quote_spanned!(ty.span()=> <#ty as #krate::typed::Decrypt>::sink()); - quote!(#krate::typed::Forward( + let sink = quote_spanned!(ty.span()=> <#ty as #aead::Decrypt>::sink()); + quote!(#aead::Forward( #sink, - #krate::typed::Slot(&mut self.#local), + #aead::Slot(&mut self.#local), )) }; let last = index + 1 == stored.len(); @@ -159,9 +159,9 @@ fn map_target( if last { build } else { - quote!(#krate::typed::Either::Left(#build)) + quote!(#aead::Either::Left(#build)) }, - |inner, _| quote!(#krate::typed::Either::Right(#inner)), + |inner, _| quote!(#aead::Either::Right(#inner)), ); // The walk refuses a repeated key before any leaf is opened; this // catches a source that does not, rather than let last-wins @@ -169,7 +169,7 @@ fn map_target( quote! { #key => { if self.#local.is_some() { - return ::core::result::Result::Err(#krate::DecodeError::duplicate_key(__key)); + return ::core::result::Result::Err(#aead::DecodeError::duplicate_key(__key)); } ::core::result::Result::Ok(#wrapped) } @@ -185,7 +185,7 @@ fn map_target( } else { // A missing field is a refusal, not a default: an absent entry // is an unauthenticated one. - quote!(#member: self.#local.ok_or(#krate::DecodeError::MissingField(#key))?,) + quote!(#member: self.#local.ok_or(#aead::DecodeError::MissingField(#key))?,) } }); @@ -200,32 +200,32 @@ fn map_target( } #[automatically_derived] - impl #impl_generics #krate::Sink for #sink #ty_generics #where_clause { + impl #impl_generics #aead::Sink for #sink #ty_generics #where_clause { type Ok = #name #ty_generics; - type Error = #krate::DecodeError; - type Seq = #krate::typed::Never<#name #ty_generics>; + type Error = #aead::DecodeError; + type Seq = #aead::Never<#name #ty_generics>; type Map = #map #ty_generics; fn scalar( self, - _: ::core::option::Option<#krate::Logical>, - _: #krate::Physical<'_>, + _: ::core::option::Option<#aead::Logical>, + _: #aead::Physical<'_>, ) -> ::core::result::Result { - ::core::result::Result::Err(#krate::DecodeError::Expected(#expected)) + ::core::result::Result::Err(#aead::DecodeError::Expected(#expected)) } fn typed_null( self, - _: #krate::FixedType, + _: #aead::FixedType, ) -> ::core::result::Result { - ::core::result::Result::Err(#krate::DecodeError::Expected(#expected)) + ::core::result::Result::Err(#aead::DecodeError::Expected(#expected)) } fn seq( self, _: ::core::option::Option, ) -> ::core::result::Result { - ::core::result::Result::Err(#krate::DecodeError::Expected(#expected)) + ::core::result::Result::Err(#aead::DecodeError::Expected(#expected)) } fn map( @@ -242,17 +242,17 @@ fn map_target( // for a sealed struct. fn passthrough<__P>(self, _: &__P) -> ::core::result::Result where - __P: ?::core::marker::Sized + #krate::EncryptRef, + __P: ?::core::marker::Sized + #aead::EncryptRef, { - ::core::result::Result::Err(#krate::DecodeError::Expected(#expected)) + ::core::result::Result::Err(#aead::DecodeError::Expected(#expected)) } } #[automatically_derived] #[allow(clippy::type_complexity)] - impl #impl_generics #krate::MapSink for #map #ty_generics #where_clause { + impl #impl_generics #aead::MapSink for #map #ty_generics #where_clause { type Ok = #name #ty_generics; - type Error = #krate::DecodeError; + type Error = #aead::DecodeError; type Entry<'__s> = #entry_ty where @@ -269,7 +269,7 @@ fn map_target( #(#arms)* // Unknown keys are refused rather than skipped: a // skipped value is one nobody checked. - _ => ::core::result::Result::Err(#krate::DecodeError::unknown_key(__key)), + _ => ::core::result::Result::Err(#aead::DecodeError::unknown_key(__key)), } } @@ -279,7 +279,7 @@ fn map_target( } #[automatically_derived] - impl #impl_generics #krate::typed::Decrypt for #name #ty_generics #where_clause { + impl #impl_generics #aead::Decrypt for #name #ty_generics #where_clause { type Sink = #sink #ty_generics; fn sink() -> Self::Sink { #sink(::core::marker::PhantomData) @@ -293,7 +293,7 @@ fn map_target( /// a value that is no variant's included, is refused by the enum's name. /// Going through `FromScalar` gives the enum its `Decrypt` through the /// blanket impl. -fn enum_target(krate: &syn::Path, input: &DeriveInput, variants: &[VariantInfo]) -> TokenStream { +fn enum_target(aead: &syn::Path, input: &DeriveInput, variants: &[VariantInfo]) -> TokenStream { let name = &input.ident; let expected = name.to_string(); let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl(); @@ -306,19 +306,19 @@ fn enum_target(krate: &syn::Path, input: &DeriveInput, variants: &[VariantInfo]) }); quote! { #[automatically_derived] - impl #impl_generics #krate::FromScalar for #name #ty_generics #where_clause { + impl #impl_generics #aead::FromScalar for #name #ty_generics #where_clause { const EXPECTED: &'static str = #expected; // Its own `None`, even with no variant at zero to read. - const FIXED: ::core::option::Option<#krate::FixedType> = - #krate::FixedType::plain(#krate::Width::U32); + const FIXED: ::core::option::Option<#aead::FixedType> = + #aead::FixedType::plain(#aead::Width::U32); fn from_scalar( - __ty: ::core::option::Option<#krate::Logical>, - __value: #krate::Physical<'_>, + __ty: ::core::option::Option<#aead::Logical>, + __value: #aead::Physical<'_>, ) -> ::core::option::Option { match (__ty, __value) { - (::core::option::Option::None, #krate::Physical::Int(__int)) => { - match #krate::Int::to_u128(__int) { + (::core::option::Option::None, #aead::Physical::Int(__int)) => { + match #aead::Int::to_u128(__int) { #(#arms)* _ => ::core::option::Option::None, } @@ -333,7 +333,7 @@ fn enum_target(krate: &syn::Path, input: &DeriveInput, variants: &[VariantInfo]) #[cfg(test)] mod tests { use super::*; - use crate::test_support::{assert_contains, assert_lacks}; + use crate::value::test_support::{assert_contains, assert_lacks}; fn expand(input: DeriveInput) -> String { derive(input).expect("expansion should succeed").to_string() @@ -356,30 +356,30 @@ mod tests { assert_contains(&out, quote!("age" =>)); assert_contains( &out, - quote!(::vitaminc_aead::typed::Either::Left( - ::vitaminc_aead::typed::Forward( - ::sink(), - ::vitaminc_aead::typed::Slot(&mut self.__field_0), + quote!(::stack_encrypt::__derive::Either::Left( + ::stack_encrypt::__derive::Forward( + ::sink(), + ::stack_encrypt::__derive::Slot(&mut self.__field_0), ) )), ); // The last field is the chain's tail. assert_contains( &out, - quote!(::vitaminc_aead::typed::Either::Right( - ::vitaminc_aead::typed::Forward( - ::sink(), - ::vitaminc_aead::typed::Slot(&mut self.__field_1), + quote!(::stack_encrypt::__derive::Either::Right( + ::stack_encrypt::__derive::Forward( + ::sink(), + ::stack_encrypt::__derive::Slot(&mut self.__field_1), ) )), ); assert_contains( &out, - quote!(type Entry<'__s> = ::vitaminc_aead::typed::Either<), + quote!(type Entry<'__s> = ::stack_encrypt::__derive::Either<), ); assert_contains( &out, - quote!(::vitaminc_aead::typed::Forward>,), + quote!(::stack_encrypt::__derive::Forward>,), ); } @@ -397,7 +397,7 @@ mod tests { &out, quote!(name: self .__field_0 - .ok_or(::vitaminc_aead::DecodeError::MissingField("name"))?), + .ok_or(::stack_encrypt::__derive::DecodeError::MissingField("name"))?), ); } @@ -414,7 +414,7 @@ mod tests { assert_contains(&out, quote!(if self.__field_0.is_some())); assert_contains( &out, - quote!(::vitaminc_aead::DecodeError::duplicate_key(__key)), + quote!(::stack_encrypt::__derive::DecodeError::duplicate_key(__key)), ); } @@ -430,7 +430,7 @@ mod tests { assert_contains( &out, - quote!(::vitaminc_aead::DecodeError::unknown_key(__key)), + quote!(::stack_encrypt::__derive::DecodeError::unknown_key(__key)), ); } @@ -448,15 +448,15 @@ mod tests { assert_contains( &out, - quote!(::vitaminc_aead::typed::Clear::new( - ::vitaminc_aead::typed::Slot(&mut self.__field_0) + quote!(::stack_encrypt::__derive::Clear::new( + ::stack_encrypt::__derive::Slot(&mut self.__field_0) )), ); assert_contains( &out, - quote!(::vitaminc_aead::typed::Forward( - ::sink(), - ::vitaminc_aead::typed::Slot(&mut self.__field_1), + quote!(::stack_encrypt::__derive::Forward( + ::sink(), + ::stack_encrypt::__derive::Slot(&mut self.__field_1), )), ); } @@ -488,8 +488,8 @@ mod tests { assert_contains(&out, quote!(struct __WrapperDecryptWrap)); assert_contains( &out, - quote!(type Sink = ::vitaminc_aead::typed::Wrapped< - ::Sink, + quote!(type Sink = ::stack_encrypt::__derive::Wrapped< + ::Sink, __WrapperDecryptWrap, >), ); @@ -507,11 +507,11 @@ mod tests { assert_contains( &out, - quote!(type Entry<'__s> = ::vitaminc_aead::typed::Nothing), + quote!(type Entry<'__s> = ::stack_encrypt::__derive::Nothing), ); assert_contains( &out, - quote!(::vitaminc_aead::DecodeError::unknown_key(__key)), + quote!(::stack_encrypt::__derive::DecodeError::unknown_key(__key)), ); assert_contains(&out, quote!(::core::result::Result::Ok(Marker {}))); } @@ -527,9 +527,12 @@ mod tests { } }); - assert_contains(&out, quote!(::vitaminc_aead::FromScalar for Status)); + assert_contains( + &out, + quote!(::stack_encrypt::__derive::FromScalar for Status), + ); assert_contains(&out, quote!(const EXPECTED: &'static str = "Status")); - assert_contains(&out, quote!(::vitaminc_aead::Int::to_u128(__int))); + assert_contains(&out, quote!(::stack_encrypt::__derive::Int::to_u128(__int))); assert_contains( &out, quote!(::core::option::Option::Some(0u128) => ::core::option::Option::Some(Status::Active)), @@ -538,7 +541,7 @@ mod tests { &out, quote!(::core::option::Option::Some(7u128) => ::core::option::Option::Some(Status::Suspended)), ); - assert_lacks(&out, quote!(typed::Decrypt for Status)); + assert_lacks(&out, quote!(__derive::Decrypt for Status)); } /// Every type parameter must itself be a target, and the generated @@ -555,7 +558,7 @@ mod tests { assert_contains( &out, - quote!(impl<'a, T: ::vitaminc_aead::typed::Decrypt, const N: usize>), + quote!(impl<'a, T: ::stack_encrypt::__derive::Decrypt, const N: usize>), ); assert_contains(&out, quote!(fn() -> Holder<'a, T, N>)); assert_contains( @@ -581,15 +584,15 @@ mod tests { #[test] fn crate_attribute_redirects_every_path() { let out = expand(parse_quote! { - #[aead(crate = "::vitaminc::aead")] + #[aead(crate = "::app::encryption")] struct User { name: String, } }); - assert_contains(&out, quote!(::vitaminc::aead::typed::Decrypt for User)); + assert_contains(&out, quote!(::app::encryption::__derive::Decrypt for User)); assert!( - !out.contains("vitaminc_aead"), + !out.contains(":: stack_encrypt ::"), "expansion still references the default crate path:\n{out}" ); } diff --git a/packages/vitaminc-aead-derive/src/encrypt.rs b/packages/stack-encrypt-derive/src/value/encrypt.rs similarity index 74% rename from packages/vitaminc-aead-derive/src/encrypt.rs rename to packages/stack-encrypt-derive/src/value/encrypt.rs index 6ace5eea3..d1a254c1a 100644 --- a/packages/vitaminc-aead-derive/src/encrypt.rs +++ b/packages/stack-encrypt-derive/src/value/encrypt.rs @@ -17,14 +17,14 @@ use proc_macro2::TokenStream; use quote::quote; use syn::{parse_quote, DeriveInput, Result}; -use crate::{ +use super::{ attrs::ContainerAttrs, shape::{FieldInfo, Shape, VariantInfo}, }; pub(crate) fn derive(input: DeriveInput) -> Result { let attrs = ContainerAttrs::parse(&input.attrs)?; - let krate = &attrs.krate; + let aead = &attrs.aead; let shape = Shape::parse(&input)?; let name = &input.ident; // Whether the type has a fixed depth. A type that contains itself has @@ -36,7 +36,7 @@ pub(crate) fn derive(input: DeriveInput) -> Result { matches!(shape, Shape::Enum(_)) || !(attrs.recursive || names_itself(name, &shape)); // Bound every type parameter, serde-style: a field of type `Vec` then - // picks up `Vec: Encrypt` from the blanket impl in `vitaminc_aead`. + // picks up `Vec: Encrypt` from the blanket impl in the AEAD crate. // A passthrough field is lent to the sink, never moved, so a parameter // it names is bounded on `EncryptRef`; one named only there is not // bounded on `Encrypt` at all. @@ -44,10 +44,10 @@ pub(crate) fn derive(input: DeriveInput) -> Result { for param in generics.type_params_mut() { let usage = Usage::of(¶m.ident, &shape); if usage.walked || !usage.lent { - param.bounds.push(parse_quote!(#krate::Encrypt)); + param.bounds.push(parse_quote!(#aead::Encrypt)); } if usage.lent { - param.bounds.push(parse_quote!(#krate::EncryptRef)); + param.bounds.push(parse_quote!(#aead::EncryptRef)); } } let (impl_generics, ty_generics, where_clause) = generics.split_for_impl(); @@ -64,7 +64,7 @@ pub(crate) fn derive(input: DeriveInput) -> Result { .type_params() .map(|param| { let ident = ¶m.ident; - parse_quote!(#ident: #krate::EncryptRef) + parse_quote!(#ident: #aead::EncryptRef) }) .collect(); ref_generics @@ -84,11 +84,11 @@ pub(crate) fn derive(input: DeriveInput) -> Result { }; let (body, ref_body) = match &shape { - Shape::Newtype(field) => (newtype_body(krate, field), newtype_ref_body(krate, field)), - Shape::Map(fields) => (map_body(krate, fields), map_ref_body(krate, fields)), - Shape::Empty => (empty_body(krate), empty_body(krate)), + Shape::Newtype(field) => (newtype_body(aead, field), newtype_ref_body(aead, field)), + Shape::Map(fields) => (map_body(aead, fields), map_ref_body(aead, fields)), + Shape::Empty => (empty_body(aead), empty_body(aead)), Shape::Enum(variants) => { - let body = enum_body(krate, name, variants); + let body = enum_body(aead, name, variants); (body.clone(), body) } }; @@ -98,19 +98,19 @@ pub(crate) fn derive(input: DeriveInput) -> Result { by_ref: ref_depth, item_check, visit_check, - } = depth(krate, &input, &shape, fixed_depth); - let (fixed, ref_fixed) = fixed(krate, &shape, fixed_depth); - let scalar = scalar(krate, &input, &shape, fixed_depth, &generics, &ref_generics); + } = depth(aead, &input, &shape, fixed_depth); + let (fixed, ref_fixed) = fixed(aead, &shape, fixed_depth); + let scalar = scalar(aead, &input, &shape, fixed_depth, &generics, &ref_generics); Ok(quote! { #[automatically_derived] - impl #impl_generics #krate::Encrypt for #name #ty_generics #where_clause { + impl #impl_generics #aead::Encrypt for #name #ty_generics #where_clause { #depth #fixed fn visit<__S>(#receiver, __sink: __S) -> ::core::result::Result<__S::Ok, __S::Error> where - __S: #krate::Sink, + __S: #aead::Sink, { #visit_check #body @@ -118,13 +118,13 @@ pub(crate) fn derive(input: DeriveInput) -> Result { } #[automatically_derived] - impl #ref_impl_generics #krate::Encrypt for &'__r #name #ty_generics #ref_where_clause { + impl #ref_impl_generics #aead::Encrypt for &'__r #name #ty_generics #ref_where_clause { #ref_depth #ref_fixed fn visit<__S>(self, __sink: __S) -> ::core::result::Result<__S::Ok, __S::Error> where - __S: #krate::Sink, + __S: #aead::Sink, { #visit_check #ref_body @@ -153,7 +153,7 @@ pub(crate) fn derive(input: DeriveInput) -> Result { /// impl's bound is inside a `for<'__s>` binder. The compiler then checks /// each bound only where code asks for the `Scalar` impl. fn scalar( - krate: &syn::Path, + aead: &syn::Path, input: &DeriveInput, shape: &Shape, fixed_depth: bool, @@ -168,12 +168,12 @@ fn scalar( owned .make_where_clause() .predicates - .push(parse_quote!(for<'__s> #ty: #krate::Scalar)); + .push(parse_quote!(for<'__s> #ty: #aead::Scalar)); let mut by_ref = ref_generics.clone(); by_ref .make_where_clause() .predicates - .push(parse_quote!(&'__r #ty: #krate::Scalar)); + .push(parse_quote!(&'__r #ty: #aead::Scalar)); (owned, by_ref) } Shape::Enum(_) => (generics.clone(), ref_generics.clone()), @@ -183,10 +183,10 @@ fn scalar( let (ref_impl_generics, _, ref_where_clause) = by_ref.split_for_impl(); quote! { #[automatically_derived] - impl #impl_generics #krate::Scalar for #name #ty_generics #where_clause {} + impl #impl_generics #aead::Scalar for #name #ty_generics #where_clause {} #[automatically_derived] - impl #ref_impl_generics #krate::Scalar for &'__r #name #ty_generics #ref_where_clause {} + impl #ref_impl_generics #aead::Scalar for &'__r #name #ty_generics #ref_where_clause {} } } @@ -205,11 +205,26 @@ struct Depth { visit_check: TokenStream, } +/// The path to `MAX_DEPTH` for the too-deep message, as text. The text +/// starts at the crate path that the expansion names every item through, so +/// it follows `#[aead(crate = "...")]`. `aead` is that crate path followed +/// by `__derive`. +fn max_depth_path(aead: &syn::Path) -> String { + let krate = aead + .segments + .iter() + .take(aead.segments.len().saturating_sub(1)) + .map(|segment| segment.ident.to_string()) + .collect::>() + .join("::"); + format!("{krate}::plaintext::depth::MAX_DEPTH") +} + /// Work out the type's depth from its fields' depths, the way the encrypting /// sink counts nesting. A recursive type has no fixed depth, and naming its /// own `DEPTH` would be a cycle, so it keeps the default `None` and the /// walk checks each value instead. -fn depth(krate: &syn::Path, input: &DeriveInput, shape: &Shape, fixed_depth: bool) -> Depth { +fn depth(aead: &syn::Path, input: &DeriveInput, shape: &Shape, fixed_depth: bool) -> Depth { let name = &input.ident; if !fixed_depth { return Depth { @@ -220,13 +235,13 @@ fn depth(krate: &syn::Path, input: &DeriveInput, shape: &Shape, fixed_depth: boo }; } - let depth = quote!(#krate::plaintext::depth); + let depth = quote!(#aead::depth); let expr = |by_ref: bool| -> TokenStream { let of = |ty: &syn::Type, by_ref: bool| { if by_ref { - quote!(<#ty as #krate::EncryptRef>::REF_DEPTH) + quote!(<#ty as #aead::EncryptRef>::REF_DEPTH) } else { - quote!(<#ty as #krate::Encrypt>::DEPTH) + quote!(<#ty as #aead::Encrypt>::DEPTH) } }; match shape { @@ -257,12 +272,13 @@ fn depth(krate: &syn::Path, input: &DeriveInput, shape: &Shape, fixed_depth: boo let owned = expr(false); let by_ref = expr(true); + let limit = max_depth_path(aead); let message = format!( - "`{name}` nests deeper than `MAX_DEPTH` levels, so the encrypting sink would refuse \ - its fully populated values" + "`{name}` nests deeper than `{limit}` levels. Stack Encrypt refuses to encrypt a value \ + nested that deeply, so it would refuse every full value of this type" ); let check = |ty: TokenStream| { - quote!(::core::assert!(#depth::within_limit(<#ty as #krate::Encrypt>::DEPTH), #message)) + quote!(::core::assert!(#depth::within_limit(<#ty as #aead::Encrypt>::DEPTH), #message)) }; // A type with no type or const parameters is checked where it is // defined, so `cargo check` sees the error. Each lifetime becomes @@ -302,18 +318,18 @@ fn depth(krate: &syn::Path, input: &DeriveInput, shape: &Shape, fixed_depth: boo /// value and by reference, as `DEPTH` does). A fieldless enum is always a /// `u32` leaf. A struct is a map, which has none, and a recursive newtype /// keeps the default rather than name its own constant in a cycle. -fn fixed(krate: &syn::Path, shape: &Shape, fixed_depth: bool) -> (TokenStream, TokenStream) { - let decl = |value: TokenStream| quote!(const FIXED: ::core::option::Option<#krate::FixedType> = #value;); +fn fixed(aead: &syn::Path, shape: &Shape, fixed_depth: bool) -> (TokenStream, TokenStream) { + let decl = |value: TokenStream| quote!(const FIXED: ::core::option::Option<#aead::FixedType> = #value;); match shape { Shape::Newtype(field) if fixed_depth => { let ty = &field.ty; ( - decl(quote!(<#ty as #krate::Encrypt>::FIXED)), - decl(quote!(<#ty as #krate::EncryptRef>::REF_FIXED)), + decl(quote!(<#ty as #aead::Encrypt>::FIXED)), + decl(quote!(<#ty as #aead::EncryptRef>::REF_FIXED)), ) } Shape::Enum(_) => { - let u32 = decl(quote!(#krate::FixedType::plain(#krate::Width::U32))); + let u32 = decl(quote!(#aead::FixedType::plain(#aead::Width::U32))); (u32.clone(), u32) } Shape::Newtype(_) | Shape::Map(_) | Shape::Empty => { @@ -415,17 +431,17 @@ fn value(field: &FieldInfo) -> TokenStream { /// A newtype adds nothing to the ciphertext — it describes itself exactly /// as its inner value, so wrapping a type is not a wire-breaking change. -fn newtype_body(krate: &syn::Path, field: &FieldInfo) -> TokenStream { +fn newtype_body(aead: &syn::Path, field: &FieldInfo) -> TokenStream { let value = value(field); quote! { - #krate::Encrypt::visit(#value, __sink) + #aead::Encrypt::visit(#value, __sink) } } -fn newtype_ref_body(krate: &syn::Path, field: &FieldInfo) -> TokenStream { +fn newtype_ref_body(aead: &syn::Path, field: &FieldInfo) -> TokenStream { let member = &field.member; quote! { - #krate::EncryptRef::visit_ref(&self.#member, __sink) + #aead::EncryptRef::visit_ref(&self.#member, __sink) } } @@ -433,7 +449,7 @@ fn newtype_ref_body(krate: &syn::Path, field: &FieldInfo) -> TokenStream { /// arrives; if the sink refuses at any point, the fields not yet moved are /// discarded through their own walk first, which wipes each owned leaf, /// rather than dropped bare with `self`. -fn map_body(krate: &syn::Path, fields: &[FieldInfo]) -> TokenStream { +fn map_body(aead: &syn::Path, fields: &[FieldInfo]) -> TokenStream { let stored: Vec<&FieldInfo> = fields.iter().filter(|field| field.stored()).collect(); let len = stored.len(); // The fields from `from` on, discarded. A passthrough field is @@ -445,7 +461,7 @@ fn map_body(krate: &syn::Path, fields: &[FieldInfo]) -> TokenStream { .filter(|field| !field.passthrough) .map(|field| { let value = value(field); - quote!(#krate::plaintext::__private::discard_one(#value);) + quote!(#aead::discard_one(#value);) }); quote!(#(#rest)*) }; @@ -462,13 +478,13 @@ fn map_body(krate: &syn::Path, fields: &[FieldInfo]) -> TokenStream { // the encrypted ones. It is lent in place, so it needs neither a // move nor `take`, even on a type that implements `Drop`. let member = &field.member; - quote!(#krate::Sink::passthrough(__entry, &self.#member)) + quote!(#aead::Sink::passthrough(__entry, &self.#member)) } else { let value = value(field); - quote!(#krate::Encrypt::visit(#value, __entry)) + quote!(#aead::Encrypt::visit(#value, __entry)) }; quote! { - let __entry = match #krate::MapSink::entry(&mut __map, #key) { + let __entry = match #aead::MapSink::entry(&mut __map, #key) { ::core::result::Result::Ok(__entry) => __entry, ::core::result::Result::Err(__err) => { #on_entry_failure @@ -486,7 +502,7 @@ fn map_body(krate: &syn::Path, fields: &[FieldInfo]) -> TokenStream { // The encrypting sink binds each field's key into the AAD its value // is sealed against (`Context::for_map_entry`), so a stored field // cannot be renamed or moved to another key undetected. - let mut __map = match #krate::Sink::map(__sink, ::core::option::Option::Some(#len)) { + let mut __map = match #aead::Sink::map(__sink, ::core::option::Option::Some(#len)) { ::core::result::Result::Ok(__map) => __map, ::core::result::Result::Err(__err) => { #open @@ -494,12 +510,12 @@ fn map_body(krate: &syn::Path, fields: &[FieldInfo]) -> TokenStream { } }; #(#entries)* - #krate::MapSink::end(__map) + #aead::MapSink::end(__map) } } /// The by-reference walk: nothing is moved, so nothing needs discarding. -fn map_ref_body(krate: &syn::Path, fields: &[FieldInfo]) -> TokenStream { +fn map_ref_body(aead: &syn::Path, fields: &[FieldInfo]) -> TokenStream { let stored: Vec<&FieldInfo> = fields.iter().filter(|field| field.stored()).collect(); let len = stored.len(); let entries = stored.iter().map(|field| { @@ -507,27 +523,27 @@ fn map_ref_body(krate: &syn::Path, fields: &[FieldInfo]) -> TokenStream { let member = &field.member; if field.passthrough { quote! { - #krate::Sink::passthrough(#krate::MapSink::entry(&mut __map, #key)?, &self.#member)?; + #aead::Sink::passthrough(#aead::MapSink::entry(&mut __map, #key)?, &self.#member)?; } } else { quote! { - #krate::EncryptRef::visit_ref(&self.#member, #krate::MapSink::entry(&mut __map, #key)?)?; + #aead::EncryptRef::visit_ref(&self.#member, #aead::MapSink::entry(&mut __map, #key)?)?; } } }); quote! { - let mut __map = #krate::Sink::map(__sink, ::core::option::Option::Some(#len))?; + let mut __map = #aead::Sink::map(__sink, ::core::option::Option::Some(#len))?; #(#entries)* - #krate::MapSink::end(__map) + #aead::MapSink::end(__map) } } /// No fields: an empty map, which the encrypting sink seals as the /// authenticated empty-map marker, so even a field-less struct binds its /// AAD. -fn empty_body(krate: &syn::Path) -> TokenStream { +fn empty_body(aead: &syn::Path) -> TokenStream { quote! { - #krate::MapSink::end(#krate::Sink::map(__sink, ::core::option::Option::Some(0))?) + #aead::MapSink::end(#aead::Sink::map(__sink, ::core::option::Option::Some(0))?) } } @@ -535,15 +551,15 @@ fn empty_body(krate: &syn::Path) -> TokenStream { /// `u32`. Fixed width, so every variant seals to a leaf of the same length /// and the ciphertext's size gives nothing away. It is sealed and /// authenticated like any other leaf. -fn enum_body(krate: &syn::Path, name: &syn::Ident, variants: &[VariantInfo]) -> TokenStream { +fn enum_body(aead: &syn::Path, name: &syn::Ident, variants: &[VariantInfo]) -> TokenStream { let arms = variants.iter().map(|variant| { let ident = &variant.ident; let discriminant = variant.discriminant; quote! { - #name::#ident => #krate::Sink::scalar( + #name::#ident => #aead::Sink::scalar( __sink, ::core::option::Option::None, - #krate::Physical::Int(#krate::Int::U32(#discriminant)), + #aead::Physical::Int(#aead::Int::U32(#discriminant)), ), } }); @@ -557,7 +573,7 @@ fn enum_body(krate: &syn::Path, name: &syn::Ident, variants: &[VariantInfo]) -> #[cfg(test)] mod tests { use super::*; - use crate::test_support::{assert_contains, assert_lacks}; + use crate::value::test_support::{assert_contains, assert_lacks}; fn expand(input: DeriveInput) -> String { derive(input).expect("expansion should succeed").to_string() @@ -577,28 +593,32 @@ mod tests { assert_contains( &out, - quote!(::vitaminc_aead::Sink::map( + quote!(::stack_encrypt::__derive::Sink::map( __sink, ::core::option::Option::Some(2usize) )), ); assert_contains( &out, - quote!(::vitaminc_aead::MapSink::entry(&mut __map, "name")), + quote!(::stack_encrypt::__derive::MapSink::entry( + &mut __map, "name" + )), ); assert_contains( &out, - quote!(::vitaminc_aead::Encrypt::visit(self.name, __entry)), + quote!(::stack_encrypt::__derive::Encrypt::visit( + self.name, __entry + )), ); assert_contains( &out, - quote!(::vitaminc_aead::MapSink::entry(&mut __map, "age")), + quote!(::stack_encrypt::__derive::MapSink::entry(&mut __map, "age")), ); assert_contains( &out, - quote!(::vitaminc_aead::Encrypt::visit(self.age, __entry)), + quote!(::stack_encrypt::__derive::Encrypt::visit(self.age, __entry)), ); - assert_contains(&out, quote!(::vitaminc_aead::MapSink::end(__map))); + assert_contains(&out, quote!(::stack_encrypt::__derive::MapSink::end(__map))); } /// When the sink refuses part way, the fields not yet walked are @@ -614,7 +634,7 @@ mod tests { } }); - let discard = |field: TokenStream| quote!(::vitaminc_aead::plaintext::__private::discard_one(#field);); + let discard = |field: TokenStream| quote!(::stack_encrypt::__derive::discard_one(#field);); let name = discard(quote!(self.name)); let age = discard(quote!(self.age)); // Map refused: both. Entry for `name` refused: both. `name` refused: @@ -624,7 +644,7 @@ mod tests { assert_contains( &out, quote!(if let ::core::result::Result::Err(__err) = - ::vitaminc_aead::Encrypt::visit(self.age, __entry) + ::stack_encrypt::__derive::Encrypt::visit(self.age, __entry) { return ::core::result::Result::Err(__err); }), @@ -645,19 +665,19 @@ mod tests { assert_contains( &out, - quote!(impl<'__r> ::vitaminc_aead::Encrypt for &'__r Row), + quote!(impl<'__r> ::stack_encrypt::__derive::Encrypt for &'__r Row), ); assert_contains( &out, - quote!(::vitaminc_aead::EncryptRef::visit_ref( + quote!(::stack_encrypt::__derive::EncryptRef::visit_ref( &self.name, - ::vitaminc_aead::MapSink::entry(&mut __map, "name")? + ::stack_encrypt::__derive::MapSink::entry(&mut __map, "name")? )), ); assert_contains( &out, - quote!(::vitaminc_aead::Sink::passthrough( - ::vitaminc_aead::MapSink::entry(&mut __map, "tenant")?, + quote!(::stack_encrypt::__derive::Sink::passthrough( + ::stack_encrypt::__derive::MapSink::entry(&mut __map, "tenant")?, &self.tenant )), ); @@ -666,7 +686,9 @@ mod tests { )); assert_contains( &out, - quote!(::vitaminc_aead::EncryptRef::visit_ref(&self.0, __sink)), + quote!(::stack_encrypt::__derive::EncryptRef::visit_ref( + &self.0, __sink + )), ); } @@ -683,7 +705,7 @@ mod tests { assert_contains( &out, - quote!(::vitaminc_aead::MapSink::entry(&mut __map, "yrs")), + quote!(::stack_encrypt::__derive::MapSink::entry(&mut __map, "yrs")), ); assert_lacks(&out, quote!("age")); } @@ -696,11 +718,11 @@ mod tests { assert_contains( &out, - quote!(::vitaminc_aead::MapSink::entry(&mut __map, "0")), + quote!(::stack_encrypt::__derive::MapSink::entry(&mut __map, "0")), ); assert_contains( &out, - quote!(::vitaminc_aead::MapSink::entry(&mut __map, "1")), + quote!(::stack_encrypt::__derive::MapSink::entry(&mut __map, "1")), ); } @@ -718,11 +740,14 @@ mod tests { assert_contains( &out, - quote!(::vitaminc_aead::Sink::passthrough(__entry, &self.tenant)), + quote!(::stack_encrypt::__derive::Sink::passthrough( + __entry, + &self.tenant + )), ); assert_contains( &out, - quote!(::vitaminc_aead::Encrypt::visit(self.ssn, __entry)), + quote!(::stack_encrypt::__derive::Encrypt::visit(self.ssn, __entry)), ); } @@ -740,7 +765,10 @@ mod tests { assert_contains( &out, - quote!(::vitaminc_aead::Sink::passthrough(__entry, &self.tenant)), + quote!(::stack_encrypt::__derive::Sink::passthrough( + __entry, + &self.tenant + )), ); assert_lacks(&out, quote!(::core::mem::take)); assert_lacks(&out, quote!(mut self)); @@ -763,7 +791,7 @@ mod tests { assert_lacks(&out, quote!(self.id)); assert_contains( &out, - quote!(::vitaminc_aead::Sink::map( + quote!(::stack_encrypt::__derive::Sink::map( __sink, ::core::option::Option::Some(1usize) )), @@ -785,16 +813,16 @@ mod tests { assert_contains(&out, quote!(mut self, __sink: __S)); assert_contains( &out, - quote!(::vitaminc_aead::Encrypt::visit( + quote!(::stack_encrypt::__derive::Encrypt::visit( ::core::mem::take(&mut self.token), __entry )), ); assert_contains( &out, - quote!(::vitaminc_aead::plaintext::__private::discard_one( - ::core::mem::take(&mut self.token) - )), + quote!(::stack_encrypt::__derive::discard_one(::core::mem::take( + &mut self.token + ))), ); } @@ -818,16 +846,16 @@ mod tests { assert_contains( &out, - quote!(::vitaminc_aead::Encrypt::visit(self.0, __sink)), + quote!(::stack_encrypt::__derive::Encrypt::visit(self.0, __sink)), ); - assert_lacks(&out, quote!(::vitaminc_aead::Sink::map)); + assert_lacks(&out, quote!(::stack_encrypt::__derive::Sink::map)); let out = expand(parse_quote!( struct Token(#[aead(take)] String); )); assert_contains( &out, - quote!(::vitaminc_aead::Encrypt::visit( + quote!(::stack_encrypt::__derive::Encrypt::visit( ::core::mem::take(&mut self.0), __sink )), @@ -844,12 +872,11 @@ mod tests { assert_contains( &out, - quote!(::vitaminc_aead::MapSink::end(::vitaminc_aead::Sink::map( - __sink, - ::core::option::Option::Some(0) - )?)), + quote!(::stack_encrypt::__derive::MapSink::end( + ::stack_encrypt::__derive::Sink::map(__sink, ::core::option::Option::Some(0))? + )), ); - assert_lacks(&out, quote!(::vitaminc_aead::MapSink::entry)); + assert_lacks(&out, quote!(::stack_encrypt::__derive::MapSink::entry)); } /// A fieldless enum is one fixed-width int leaf holding the @@ -865,19 +892,19 @@ mod tests { assert_contains( &out, - quote!(Status::Active => ::vitaminc_aead::Sink::scalar( + quote!(Status::Active => ::stack_encrypt::__derive::Sink::scalar( __sink, ::core::option::Option::None, - ::vitaminc_aead::Physical::Int(::vitaminc_aead::Int::U32(0u32)), + ::stack_encrypt::__derive::Physical::Int(::stack_encrypt::__derive::Int::U32(0u32)), )), ); assert_contains( &out, - quote!(::vitaminc_aead::Physical::Int(::vitaminc_aead::Int::U32( - 7u32 - ))), + quote!(::stack_encrypt::__derive::Physical::Int( + ::stack_encrypt::__derive::Int::U32(7u32) + )), ); - assert_lacks(&out, quote!(::vitaminc_aead::Physical::Text)); + assert_lacks(&out, quote!(::stack_encrypt::__derive::Physical::Text)); } /// What an absent value of the type is sealed as: a newtype's inner @@ -885,21 +912,22 @@ mod tests { /// enum; nothing for a struct, which is a map. #[test] fn fixed_follows_the_shape() { + let aead = quote!(::stack_encrypt::__derive); let out = expand(parse_quote!( struct Age(u32); )); assert_contains( &out, quote!( - const FIXED: ::core::option::Option<::vitaminc_aead::FixedType> = - ::FIXED; + const FIXED: ::core::option::Option<::stack_encrypt::__derive::FixedType> = + ::FIXED; ), ); assert_contains( &out, quote!( - const FIXED: ::core::option::Option<::vitaminc_aead::FixedType> = - ::REF_FIXED; + const FIXED: ::core::option::Option<::stack_encrypt::__derive::FixedType> = + ::REF_FIXED; ), ); @@ -911,8 +939,8 @@ mod tests { assert_contains( &out, quote!( - const FIXED: ::core::option::Option<::vitaminc_aead::FixedType> = - ::vitaminc_aead::FixedType::plain(::vitaminc_aead::Width::U32); + const FIXED: ::core::option::Option<#aead::FixedType> = + #aead::FixedType::plain(#aead::Width::U32); ), ); @@ -955,10 +983,13 @@ mod tests { } }); - assert_contains(&out, quote!(impl<'a, T: ::vitaminc_aead::Encrypt>)); + assert_contains( + &out, + quote!(impl<'a, T: ::stack_encrypt::__derive::Encrypt>), + ); assert_contains(&out, quote!(for Holder<'a, T>)); assert_contains(&out, quote!(impl<'__r, 'a, T>)); - assert_contains(&out, quote!(T: ::vitaminc_aead::EncryptRef)); + assert_contains(&out, quote!(T: ::stack_encrypt::__derive::EncryptRef)); assert_lacks(&out, quote!('a: '__r)); assert_contains(&out, quote!(for &'__r Holder<'a, T>)); } @@ -984,11 +1015,11 @@ mod tests { assert_contains( &out, quote!(impl< - P: ::vitaminc_aead::EncryptRef, - B: ::vitaminc_aead::Encrypt + ::vitaminc_aead::EncryptRef, - W: ::vitaminc_aead::Encrypt, - S: ::vitaminc_aead::Encrypt - > ::vitaminc_aead::Encrypt for Row), + P: ::stack_encrypt::__derive::EncryptRef, + B: ::stack_encrypt::__derive::Encrypt + ::stack_encrypt::__derive::EncryptRef, + W: ::stack_encrypt::__derive::Encrypt, + S: ::stack_encrypt::__derive::Encrypt + > ::stack_encrypt::__derive::Encrypt for Row), ); } @@ -1006,13 +1037,11 @@ mod tests { assert_lacks( &out, - quote!(::vitaminc_aead::plaintext::__private::discard_one( - self.tenant - )), + quote!(::stack_encrypt::__derive::discard_one(self.tenant)), ); assert_contains( &out, - quote!(::vitaminc_aead::plaintext::__private::discard_one(self.ssn)), + quote!(::stack_encrypt::__derive::discard_one(self.ssn)), ); } @@ -1021,20 +1050,17 @@ mod tests { #[test] fn crate_attribute_redirects_every_path() { let out = expand(parse_quote! { - #[aead(crate = "::vitaminc::aead")] + #[aead(crate = "::app::encryption")] struct User { name: String, } }); - assert_contains(&out, quote!(::vitaminc::aead::Encrypt for User)); - assert_contains(&out, quote!(::vitaminc::aead::MapSink::entry)); - assert_contains( - &out, - quote!(::vitaminc::aead::plaintext::__private::discard_one), - ); + assert_contains(&out, quote!(::app::encryption::__derive::Encrypt for User)); + assert_contains(&out, quote!(::app::encryption::__derive::MapSink::entry)); + assert_contains(&out, quote!(::app::encryption::__derive::discard_one)); assert!( - !out.contains("vitaminc_aead"), + !out.contains(":: stack_encrypt ::"), "expansion still references the default crate path:\n{out}" ); } @@ -1054,28 +1080,28 @@ mod tests { } }); - let depth = quote!(::vitaminc_aead::plaintext::depth); + let depth = quote!(::stack_encrypt::__derive::depth); assert_contains( &out, quote!(const DEPTH: ::core::option::Option = #depth::container( #depth::max( - #depth::max(#depth::SCALAR, ::DEPTH), - #depth::passthrough( as ::vitaminc_aead::EncryptRef>::REF_DEPTH) + #depth::max(#depth::SCALAR, ::DEPTH), + #depth::passthrough( as ::stack_encrypt::__derive::EncryptRef>::REF_DEPTH) ) );), ); assert_contains( &out, - quote!(::REF_DEPTH), + quote!(::REF_DEPTH), ); assert_lacks(&out, quote!(Vec>)); assert_contains( &out, - quote!(#depth::within_limit(::DEPTH)), + quote!(#depth::within_limit(::DEPTH)), ); assert_contains( &out, - quote!(#depth::within_limit(<&'static User as ::vitaminc_aead::Encrypt>::DEPTH)), + quote!(#depth::within_limit(<&'static User as ::stack_encrypt::__derive::Encrypt>::DEPTH)), ); assert!( out.contains("const _ : () = { :: core :: assert !"), @@ -1093,15 +1119,55 @@ mod tests { }); assert_contains( &out, - quote!(#depth::within_limit( as ::vitaminc_aead::Encrypt>::DEPTH)), + quote!(#depth::within_limit( as ::stack_encrypt::__derive::Encrypt>::DEPTH)), ); assert_contains( &out, - quote!(#depth::within_limit(<&'static Row<'static, 'static> as ::vitaminc_aead::Encrypt>::DEPTH)), + quote!(#depth::within_limit(<&'static Row<'static, 'static> as ::stack_encrypt::__derive::Encrypt>::DEPTH)), ); assert!(!out.contains("const {"), "{out}"); } + /// The too-deep message names `MAX_DEPTH` through the crate path the + /// expansion uses, so the path in the message resolves in the deriving + /// crate. + #[test] + fn the_too_deep_message_follows_the_crate_path() { + let message = |krate: &str| { + format!( + "`User` nests deeper than `{krate}::plaintext::depth::MAX_DEPTH` levels. Stack \ + Encrypt refuses to encrypt a value nested that deeply, so it would refuse every \ + full value of this type" + ) + }; + let quoted = |text: String| quote!(#text).to_string(); + + let out = expand(parse_quote! { + struct User { + name: String, + } + }); + assert!( + out.contains("ed(message("stack_encrypt"))), + "the default message does not name `stack_encrypt`'s `MAX_DEPTH`:\n{out}" + ); + + let out = expand(parse_quote! { + #[aead(crate = "::vitaminc_aead")] + struct User { + name: String, + } + }); + assert!( + out.contains("ed(message("vitaminc_aead"))), + "the message does not follow `crate = \"::vitaminc_aead\"`:\n{out}" + ); + assert!( + !out.contains("stack_encrypt"), + "the message still names the default crate path:\n{out}" + ); + } + /// A generic type's depth is known only at a concrete type, so it is /// checked inside `visit`, where it is monomorphized. #[test] @@ -1115,8 +1181,8 @@ mod tests { assert!(out.contains("const {"), "{out}"); assert_contains( &out, - quote!(::vitaminc_aead::plaintext::depth::within_limit( - ::DEPTH + quote!(::stack_encrypt::__derive::depth::within_limit( + ::DEPTH )), ); assert_lacks(&out, quote!(const _: ())); @@ -1175,7 +1241,7 @@ mod tests { }); assert_contains( &out, - quote!(::DEPTH), + quote!(::DEPTH), ); assert_contains(&out, quote!(within_limit)); @@ -1206,13 +1272,16 @@ mod tests { )); assert_contains( &out, - quote!(impl ::vitaminc_aead::Scalar for Email - where for<'__s> String: ::vitaminc_aead::Scalar {}), + quote!(impl ::stack_encrypt::__derive::Scalar for Email + where for<'__s> String: ::stack_encrypt::__derive::Scalar {}), ); assert_contains( &out, quote!( - impl<'__r> ::vitaminc_aead::Scalar for &'__r Email where &'__r String: ::vitaminc_aead::Scalar {} + impl<'__r> ::stack_encrypt::__derive::Scalar for &'__r Email where + &'__r String: ::stack_encrypt::__derive::Scalar + { + } ), ); @@ -1221,13 +1290,16 @@ mod tests { )); assert_contains( &out, - quote!(impl ::vitaminc_aead::Scalar for Tags - where for<'__s> Vec: ::vitaminc_aead::Scalar {}), + quote!(impl ::stack_encrypt::__derive::Scalar for Tags + where for<'__s> Vec: ::stack_encrypt::__derive::Scalar {}), ); assert_contains( &out, quote!( - impl<'__r> ::vitaminc_aead::Scalar for &'__r Tags where &'__r Vec: ::vitaminc_aead::Scalar {} + impl<'__r> ::stack_encrypt::__derive::Scalar for &'__r Tags where + &'__r Vec: ::stack_encrypt::__derive::Scalar + { + } ), ); } @@ -1243,8 +1315,8 @@ mod tests { assert_contains( &out, quote!( - impl ::vitaminc_aead::Scalar for Wrapper where - for<'__s> T: ::vitaminc_aead::Scalar + impl ::stack_encrypt::__derive::Scalar for Wrapper where + for<'__s> T: ::stack_encrypt::__derive::Scalar { } ), @@ -1252,10 +1324,10 @@ mod tests { assert_contains( &out, quote!( - impl<'__r, T> ::vitaminc_aead::Scalar for &'__r Wrapper + impl<'__r, T> ::stack_encrypt::__derive::Scalar for &'__r Wrapper where - T: ::vitaminc_aead::EncryptRef, - &'__r T: ::vitaminc_aead::Scalar + T: ::stack_encrypt::__derive::EncryptRef, + &'__r T: ::stack_encrypt::__derive::Scalar { } ), @@ -1271,11 +1343,14 @@ mod tests { Active, } }); - assert_contains(&out, quote!(impl ::vitaminc_aead::Scalar for Status {})); + assert_contains( + &out, + quote!(impl ::stack_encrypt::__derive::Scalar for Status {}), + ); assert_contains( &out, quote!( - impl<'__r> ::vitaminc_aead::Scalar for &'__r Status {} + impl<'__r> ::stack_encrypt::__derive::Scalar for &'__r Status {} ), ); } @@ -1283,8 +1358,12 @@ mod tests { /// A fieldless enum cannot contain itself, so `recursive` changes /// nothing. The enum still declares a scalar depth and a `u32` fixed /// type, and it is still a `Scalar`. + // rustfmt would add a trailing comma inside `plain(..)`, which changes + // the tokens the fragment is compared as. + #[rustfmt::skip] #[test] fn a_recursive_fieldless_enum_is_still_one_leaf() { + let aead = quote!(::stack_encrypt::__derive); let out = expand(parse_quote! { #[aead(recursive)] enum Status { @@ -1295,21 +1374,24 @@ mod tests { &out, quote!( const DEPTH: ::core::option::Option = - ::vitaminc_aead::plaintext::depth::SCALAR; + ::stack_encrypt::__derive::depth::SCALAR; ), ); assert_contains( &out, quote!( - const FIXED: ::core::option::Option<::vitaminc_aead::FixedType> = - ::vitaminc_aead::FixedType::plain(::vitaminc_aead::Width::U32); + const FIXED: ::core::option::Option<#aead::FixedType> = + #aead::FixedType::plain(#aead::Width::U32); ), ); - assert_contains(&out, quote!(impl ::vitaminc_aead::Scalar for Status {})); + assert_contains( + &out, + quote!(impl ::stack_encrypt::__derive::Scalar for Status {}), + ); assert_contains( &out, quote!( - impl<'__r> ::vitaminc_aead::Scalar for &'__r Status {} + impl<'__r> ::stack_encrypt::__derive::Scalar for &'__r Status {} ), ); } @@ -1338,7 +1420,7 @@ mod tests { struct Even(Option>); ), ] { - assert_lacks(&expand(input), quote!(::vitaminc_aead::Scalar)); + assert_lacks(&expand(input), quote!(::stack_encrypt::__derive::Scalar)); } } @@ -1347,12 +1429,12 @@ mod tests { #[test] fn the_marker_follows_the_crate_attribute() { let out = expand(parse_quote! { - #[aead(crate = "::vitaminc::aead")] + #[aead(crate = "::app::encryption")] struct Email(String); }); - assert_contains(&out, quote!(::vitaminc::aead::Scalar for Email)); + assert_contains(&out, quote!(::app::encryption::__derive::Scalar for Email)); assert!( - !out.contains("vitaminc_aead"), + !out.contains(":: stack_encrypt ::"), "expansion still references the default crate path:\n{out}" ); } diff --git a/packages/stack-encrypt-derive/src/value/mod.rs b/packages/stack-encrypt-derive/src/value/mod.rs new file mode 100644 index 000000000..b485f8a19 --- /dev/null +++ b/packages/stack-encrypt-derive/src/value/mod.rs @@ -0,0 +1,23 @@ +//! `#[derive(Encrypt)]` and `#[derive(Decrypt)]`: how a plaintext value is +//! walked into a sink, and the sink that builds it back. +//! +//! The record derives in the rest of this crate describe a stored record +//! and read `#[stash(...)]` attributes. These two describe a plaintext +//! value and read `#[aead(...)]` attributes. Keeping the two names apart +//! means that one type can derive from both families, and neither family +//! refuses the other's attributes. +//! +//! The generated code names every item through `::__derive`. That +//! module of `stack_encrypt` is hidden, and contains exactly the items that +//! the expansion uses. `` is `::stack_encrypt` unless +//! `#[aead(crate = "...")]` names another path to it. + +// The files of this module are under the MIT licence in `LICENSE-MIT` +// beside them. + +pub(crate) mod attrs; +pub(crate) mod decrypt; +pub(crate) mod encrypt; +pub(crate) mod shape; +#[cfg(test)] +mod test_support; diff --git a/packages/vitaminc-aead-derive/src/shape.rs b/packages/stack-encrypt-derive/src/value/shape.rs similarity index 99% rename from packages/vitaminc-aead-derive/src/shape.rs rename to packages/stack-encrypt-derive/src/value/shape.rs index 373679896..23045c7cc 100644 --- a/packages/vitaminc-aead-derive/src/shape.rs +++ b/packages/stack-encrypt-derive/src/value/shape.rs @@ -5,7 +5,7 @@ use std::collections::HashMap; use proc_macro2::Span; use syn::{Data, DeriveInput, Fields, Ident, Member, Result, Type}; -use crate::attrs::FieldAttrs; +use super::attrs::FieldAttrs; /// One field of a struct. #[cfg_attr(test, derive(Debug))] diff --git a/packages/vitaminc-aead-derive/src/test_support.rs b/packages/stack-encrypt-derive/src/value/test_support.rs similarity index 100% rename from packages/vitaminc-aead-derive/src/test_support.rs rename to packages/stack-encrypt-derive/src/value/test_support.rs diff --git a/packages/stack-encrypt-derive/tasks.toml b/packages/stack-encrypt-derive/tasks.toml new file mode 100644 index 000000000..1ebec0b98 --- /dev/null +++ b/packages/stack-encrypt-derive/tasks.toml @@ -0,0 +1,14 @@ +# Tasks for stack-encrypt-derive, the derives that stack-encrypt re-exports. +# Included from the root mise.toml. + +# Rustdoc with warnings as errors. The root `doc` task runs this task. +# It builds the public docs first, 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:stack-encrypt-derive"] +description = "Build docs for stack-encrypt-derive with all features, public then private items (warnings are errors)" +env = { RUSTDOCFLAGS = "-D warnings" } +run = [ + "cargo doc -p stack-encrypt-derive --no-deps --all-features", + "cargo doc -p stack-encrypt-derive --no-deps --all-features --document-private-items", +] diff --git a/packages/stack-encrypt-downstream/Cargo.toml b/packages/stack-encrypt-downstream/Cargo.toml new file mode 100644 index 000000000..3f7676334 --- /dev/null +++ b/packages/stack-encrypt-downstream/Cargo.toml @@ -0,0 +1,32 @@ +[package] +name = "stack-encrypt-downstream" +description = "A crate that depends on stack-encrypt alone, as an application does: it derives and hand-writes Encrypt and Decrypt" +version = "0.0.0" +edition.workspace = true +authors.workspace = true +repository.workspace = true +homepage.workspace = true +license-file = "../stack-encrypt/LICENSE" +# A test of how another crate uses stack-encrypt, never a release of its own. +publish = false + +# stack-encrypt is the only dependency. `tests/manifest.rs` fails if a +# dependency table other than `[dev-dependencies]` lists another crate. That +# includes `[build-dependencies]` and the tables under `[target.]`. The +# test also fails if any table here names one of the AEAD crates that +# stack-encrypt is built on. +[dependencies] +stack-encrypt = { path = "../stack-encrypt" } + +[dev-dependencies] +# The in-memory key source the tests encrypt with. +stack-encrypt = { path = "../stack-encrypt", features = ["test-support"] } +tokio = { workspace = true, features = ["rt", "macros"] } +# The compile-fail tests in `tests/ui`. They pin the errors that a user of +# stack-encrypt reads when a derive is refused. This crate has no +# `[features]`, so the errors are the same under every feature set +# (`tests/ui.rs` says why). +trybuild = "1" +# `tests/manifest.rs` parses this manifest, so that it reads every form of +# dependency table. +toml = "1" diff --git a/packages/stack-encrypt-downstream/src/lib.rs b/packages/stack-encrypt-downstream/src/lib.rs new file mode 100644 index 000000000..49df6d957 --- /dev/null +++ b/packages/stack-encrypt-downstream/src/lib.rs @@ -0,0 +1,134 @@ +// Security lints +#![deny(unsafe_code)] +#![warn(clippy::unwrap_used)] +#![warn(clippy::expect_used)] +#![warn(clippy::panic)] +// Prevent mem::forget from bypassing ZeroizeOnDrop +#![warn(clippy::mem_forget)] +// Prevent accidental data leaks via output +#![warn(clippy::print_stdout)] +#![warn(clippy::print_stderr)] +#![warn(clippy::dbg_macro)] +// Code quality +#![warn(unreachable_pub)] +#![warn(unused_results)] +#![warn(clippy::todo)] +#![warn(clippy::unimplemented)] +// Relax in tests +#![cfg_attr(test, allow(clippy::unwrap_used))] +#![cfg_attr(test, allow(clippy::expect_used))] +#![cfg_attr(test, allow(clippy::panic))] +#![cfg_attr(test, allow(unused_results))] +//! Types of an application that depends on `stack-encrypt` and nothing +//! else. +//! +//! Each type derives `Encrypt` and `Decrypt` from `stack_encrypt`, except +//! [`Price`], whose impls are written by hand with the items in +//! `stack_encrypt::plaintext`. The crate's tests encrypt and decrypt each of +//! them. If a derive or a hand-written impl needed any other crate, this +//! crate would not compile. +//! +//! `keyset.encrypt` asks for `Zeroize`, so that it can wipe the value. An +//! application usually derives `Zeroize` with the zeroize crate. These types +//! implement it by hand, through `stack_encrypt`'s re-export of the trait, +//! so that the crate's only dependency stays `stack-encrypt`. + +use stack_encrypt::plaintext::{depth, FixedType, Logical, Physical, Sink}; +use stack_encrypt::target::Zeroize; +use stack_encrypt::{Decrypt, Encrypt, EncryptRef, FromScalar, Scalar}; + +/// A newtype over a `String`. It encrypts as its `String`, so it is a +/// `Scalar`, and `keyset.encrypt` takes it. +#[derive(Debug, PartialEq, Encrypt, Decrypt)] +pub struct Email(pub String); + +impl Zeroize for Email { + fn zeroize(&mut self) { + self.0.zeroize(); + } +} + +/// A struct with named fields: it encrypts as a map, one entry per field. +#[derive(Debug, PartialEq, Encrypt, Decrypt)] +pub struct Profile { + pub name: String, + pub age: u32, + pub role: Role, + /// Stored in the clear, beside the encrypted fields. + #[aead(passthrough)] + pub tenant: String, +} + +/// A fieldless enum: it encrypts as one integer, its discriminant. +#[derive(Debug, PartialEq, Encrypt, Decrypt)] +pub enum Role { + Admin = 1, + Member = 2, +} + +impl Zeroize for Role { + fn zeroize(&mut self) { + *self = Role::Member; + } +} + +/// A generic newtype: a `Scalar` when its inner type is one. +#[derive(Debug, PartialEq, Encrypt, Decrypt)] +pub struct Wrapper(pub T); + +impl Zeroize for Wrapper { + fn zeroize(&mut self) { + self.0.zeroize(); + } +} + +/// A generic struct: a map whose `value` entry has the type `T`. +#[derive(Debug, PartialEq, Encrypt, Decrypt)] +pub struct Labelled { + pub label: String, + pub value: T, +} + +/// An amount in cents, with hand-written impls. The derive would store it +/// as a map with one entry, `cents`. These impls store it as its one +/// integer, so `keyset.encrypt` takes it and an `i64` decrypts it. +#[derive(Debug, PartialEq)] +pub struct Price { + pub cents: i64, +} + +impl Zeroize for Price { + fn zeroize(&mut self) { + self.cents.zeroize(); + } +} + +impl Encrypt for Price { + const DEPTH: Option = depth::SCALAR; + const FIXED: Option = ::FIXED; + fn visit(self, sink: S) -> Result { + self.cents.visit(sink) + } +} + +// `keyset.encrypt` reads the value through a borrow, so the borrow encrypts +// too, and is marked `Scalar`. +impl Encrypt for &Price { + const DEPTH: Option = depth::SCALAR; + const FIXED: Option = <&i64 as Encrypt>::FIXED; + fn visit(self, sink: S) -> Result { + self.cents.visit_ref(sink) + } +} + +impl Scalar for Price {} +impl Scalar for &Price {} + +// `FromScalar` gives `Price` its `Decrypt`. +impl FromScalar for Price { + const EXPECTED: &'static str = "a price in cents"; + const FIXED: Option = ::FIXED; + fn from_scalar(ty: Option, value: Physical<'_>) -> Option { + i64::from_scalar(ty, value).map(|cents| Price { cents }) + } +} diff --git a/packages/stack-encrypt-downstream/tests/derives.rs b/packages/stack-encrypt-downstream/tests/derives.rs new file mode 100644 index 000000000..cd3176fb7 --- /dev/null +++ b/packages/stack-encrypt-downstream/tests/derives.rs @@ -0,0 +1,172 @@ +//! Each type of this crate goes through the cipher and comes back. The types +//! derive `Encrypt` and `Decrypt` from `stack_encrypt`, or implement them by +//! hand, in a crate whose only dependency is `stack-encrypt`. + +use stack_encrypt::kms::FakeDataKeySource; +use stack_encrypt::{Ciphertext, KeysetCipher, StackCipher}; +use stack_encrypt_downstream::{Email, Labelled, Price, Profile, Role, Wrapper}; + +/// Runs `test` with a keyset over the in-memory key source. +fn with_keyset(test: F) +where + F: AsyncFnOnce(&KeysetCipher<'_, FakeDataKeySource>), +{ + tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .expect("a runtime builds") + .block_on(async { + let cipher = StackCipher::builder() + .kms(FakeDataKeySource::new()) + .init() + .await + .expect("a cipher over the in-memory key source starts"); + let keyset = cipher.default_keyset(); + test(&keyset).await; + }); +} + +#[test] +fn a_derived_newtype_encrypts_as_one_ciphertext() { + with_keyset(async |keyset| { + let stored: Ciphertext = keyset + .encrypt(Email("ada@example.com".into())) + .await + .expect("a derived newtype over a String is one value"); + let as_string: String = keyset + .decrypt(stored.clone()) + .await + .expect("the newtype's ciphertext is its String's"); + assert_eq!( + as_string, "ada@example.com", + "a newtype encrypts exactly as its inner value" + ); + let email: Email = keyset + .decrypt(stored) + .await + .expect("the derived Decrypt builds the newtype"); + assert_eq!( + email, + Email("ada@example.com".into()), + "the newtype comes back as it went in" + ); + }); +} + +#[test] +fn a_derived_struct_and_enum_encrypt_as_a_tree() { + with_keyset(async |keyset| { + let profile = Profile { + name: "Ada".into(), + age: 37, + role: Role::Admin, + tenant: "acme".into(), + }; + let stored = keyset + .encrypt_tree(profile, ("users", "profile")) + .await + .expect("a derived struct encrypts as a tree"); + let back: Profile = keyset + .decrypt_tree(stored, ("users", "profile")) + .await + .expect("the derived Decrypt builds the struct"); + assert_eq!( + back, + Profile { + name: "Ada".into(), + age: 37, + role: Role::Admin, + tenant: "acme".into(), + }, + "every field, the enum, and the passthrough field come back" + ); + }); +} + +#[test] +fn a_derived_enum_encrypts_as_one_ciphertext() { + with_keyset(async |keyset| { + let stored = keyset + .encrypt(Role::Member) + .await + .expect("a fieldless enum is one value"); + let role: Role = keyset + .decrypt(stored) + .await + .expect("the derived Decrypt reads the discriminant"); + assert_eq!(role, Role::Member, "the variant comes back"); + }); +} + +#[test] +fn derived_generic_types_encrypt_at_a_concrete_type() { + with_keyset(async |keyset| { + let stored = keyset + .encrypt(Wrapper(42i64)) + .await + .expect("a generic newtype over an i64 is one value"); + let wrapped: Wrapper = keyset + .decrypt(stored) + .await + .expect("the generic newtype comes back"); + assert_eq!(wrapped, Wrapper(42), "the inner value comes back"); + + let labelled = Labelled { + label: "visits".into(), + value: 7u32, + }; + let stored = keyset + .encrypt_tree(labelled, ("users", "visits")) + .await + .expect("a generic struct encrypts as a tree"); + let back: Labelled = keyset + .decrypt_tree(stored, ("users", "visits")) + .await + .expect("the generic struct comes back"); + assert_eq!( + back, + Labelled { + label: "visits".into(), + value: 7, + }, + "both fields of the generic struct come back" + ); + }); +} + +#[test] +fn a_hand_written_impl_encrypts_as_one_ciphertext() { + with_keyset(async |keyset| { + let stored = keyset + .encrypt(Price { cents: 1999 }) + .await + .expect("a hand-written Scalar type is one value"); + let cents: i64 = keyset + .decrypt(stored.clone()) + .await + .expect("the hand-written impl stores one integer"); + assert_eq!(cents, 1999, "the integer is the price in cents"); + let price: Price = keyset + .decrypt(stored) + .await + .expect("FromScalar builds the price"); + assert_eq!(price, Price { cents: 1999 }, "the price comes back"); + }); +} + +#[test] +fn the_paths_that_derive_errors_name_resolve() { + // A refused derive or `Scalar` impl names these paths, so a user who + // depends on stack-encrypt alone must be able to write them. + assert_eq!( + stack_encrypt::plaintext::depth::SCALAR, + Some(0), + "a scalar has nothing below it" + ); + assert!( + stack_encrypt::plaintext::depth::within_limit(Some( + stack_encrypt::plaintext::depth::MAX_DEPTH + )), + "a value exactly `MAX_DEPTH` deep can be encrypted" + ); +} diff --git a/packages/stack-encrypt-downstream/tests/manifest.rs b/packages/stack-encrypt-downstream/tests/manifest.rs new file mode 100644 index 000000000..b51451f0b --- /dev/null +++ b/packages/stack-encrypt-downstream/tests/manifest.rs @@ -0,0 +1,355 @@ +//! This crate proves that a crate which depends on `stack-encrypt` alone can +//! derive and implement `Encrypt` and `Decrypt`. The proof holds only while +//! the manifest keeps that shape, so these tests read it. +//! +//! Rust resolves a path such as `::vitaminc_aead` only when the crate being +//! compiled names that crate as a dependency of its own. So a manifest that +//! names no vitaminc crate means that nothing here, the derived code +//! included, can reach one except through `stack_encrypt`. +//! +//! Cargo reads dependencies from more than one table: `[dependencies]`, +//! `[build-dependencies]`, and `[dev-dependencies]`, each also under +//! `[target.]`. A dependency can be a sub-table of its own, such as +//! `[dependencies.serde]`. The manifest is parsed as TOML, so every one of +//! those forms is read. + +use toml::{Table, Value}; + +const MANIFEST: &str = include_str!("../Cargo.toml"); + +/// The only crate that a table other than a dev-dependency table can list. +const ONLY_DEPENDENCY: &str = "stack-encrypt"; + +/// The three kinds of dependency table that Cargo reads. +const KINDS: [&str; 3] = ["dependencies", "build-dependencies", "dev-dependencies"]; + +/// One entry of a dependency table. +struct Dependency { + /// Where the entry is, such as `target.'cfg(unix)'.dependencies.serde`. + place: String, + /// The table's kind, one of [`KINDS`]. + kind: &'static str, + /// The name the entry is listed under. + name: String, + /// The crate the entry resolves to: its `package` key, if it has one, + /// or else its name. + package: String, +} + +/// Every entry of every dependency table in `manifest`: the top-level tables +/// and those under each `[target.]`. +fn dependencies(manifest: &str) -> Vec { + let manifest: Table = manifest.parse().expect("the manifest is not valid TOML"); + let mut found = Vec::new(); + collect(&manifest, "", &mut found); + if let Some(Value::Table(targets)) = manifest.get("target") { + for (cfg, target) in targets { + if let Value::Table(target) = target { + collect(target, &format!("target.'{cfg}'."), &mut found); + } + } + } + found +} + +/// The entries of the dependency tables directly under `table`. +fn collect(table: &Table, prefix: &str, found: &mut Vec) { + for kind in KINDS { + let Some(Value::Table(entries)) = table.get(kind) else { + continue; + }; + for (name, entry) in entries { + let package = match entry { + Value::Table(entry) => entry.get("package").and_then(Value::as_str), + _ => None, + }; + found.push(Dependency { + place: format!("{prefix}{kind}.{name}"), + kind, + name: name.clone(), + package: package.unwrap_or(name).to_owned(), + }); + } + } +} + +/// What makes `manifest` break the rule this crate depends on. Empty when +/// the manifest keeps the rule: +/// +/// - `[dependencies]` lists `stack-encrypt`. +/// - No table but a dev-dependency table lists any other crate. +/// - No table, dev-dependency tables included, names a vitaminc crate. +fn problems(manifest: &str) -> Vec { + let dependencies = dependencies(manifest); + let mut problems = Vec::new(); + let lists_stack_encrypt = dependencies.iter().any(|dependency| { + dependency.place == format!("dependencies.{ONLY_DEPENDENCY}") + && dependency.package == ONLY_DEPENDENCY + }); + if !lists_stack_encrypt { + problems.push(format!( + "`[dependencies]` does not list `{ONLY_DEPENDENCY}`" + )); + } + for dependency in &dependencies { + let Dependency { + place, + kind, + name, + package, + } = dependency; + let only = name == ONLY_DEPENDENCY && package == ONLY_DEPENDENCY; + if *kind != "dev-dependencies" && !only { + problems.push(format!("`{place}` lists `{package}`")); + } + if name.contains("vitaminc") || package.contains("vitaminc") { + problems.push(format!("`{place}` names a vitaminc crate, `{package}`")); + } + } + problems +} + +/// Every key and string value in `manifest` that names a vitaminc crate, +/// with where it is. The scan reads every table, not only the dependency +/// tables, such as a `[patch]` table or a feature list. +fn vitaminc_mentions(manifest: &str) -> Vec { + fn walk(value: &Value, place: &str, found: &mut Vec) { + match value { + Value::String(text) if text.contains("vitaminc") => { + found.push(format!("`{place}` = {text:?}")); + } + Value::Array(items) => { + for item in items { + walk(item, place, found); + } + } + Value::Table(table) => { + for (key, value) in table { + let place = if place.is_empty() { + key.clone() + } else { + format!("{place}.{key}") + }; + if key.contains("vitaminc") { + found.push(format!("`{place}`")); + } + walk(value, &place, found); + } + } + _ => {} + } + } + let manifest: Table = manifest.parse().expect("the manifest is not valid TOML"); + let mut found = Vec::new(); + walk(&Value::Table(manifest), "", &mut found); + found +} + +#[test] +fn the_only_dependency_is_stack_encrypt() { + assert_eq!( + problems(MANIFEST), + Vec::::new(), + "this crate must depend on stack-encrypt and on nothing else, and reach vitaminc only \ + through stack-encrypt, or it no longer shows what a crate with that one dependency \ + can do" + ); +} + +#[test] +fn no_table_names_a_vitaminc_crate() { + let named = vitaminc_mentions(MANIFEST); + assert!( + named.is_empty(), + "this crate must reach vitaminc only through stack-encrypt, but its manifest names \ + it: {named:?}" + ); +} + +#[test] +fn the_crate_has_no_features() { + // trybuild builds `tests/ui` with this crate's features. A feature that + // turned on a stack-encrypt feature could add implementors to the lists + // that rustc prints, and so change the errors recorded there. + let manifest: Table = MANIFEST.parse().expect("the manifest is not valid TOML"); + assert!( + !manifest.contains_key("features"), + "this crate must have no features, or the errors recorded in `tests/ui` can depend on \ + which features are on" + ); +} + +#[test] +fn the_reader_sees_every_dependency_table() { + // A reader that missed a table would pass the test above on a manifest + // it had not read. + let kinds: Vec<&str> = dependencies(MANIFEST) + .iter() + .map(|dependency| dependency.kind) + .collect(); + for kind in ["dependencies", "dev-dependencies"] { + assert!( + kinds.contains(&kind), + "the manifest reader found no entry in a `[{kind}]` table; it found {kinds:?}" + ); + } +} + +/// The checks of `problems` and `vitaminc_mentions`, one manifest form at a +/// time. +mod problems { + use super::{problems, vitaminc_mentions}; + + /// The `[dependencies]` table that every manifest below starts with. + const BASE: &str = "[dependencies]\nstack-encrypt = { path = \"../stack-encrypt\" }\n"; + + #[track_caller] + fn assert_refused(extra: &str, expected: &str) { + let manifest = format!("{BASE}{extra}"); + assert_eq!( + problems(&manifest), + vec![expected.to_owned()], + "the check did not refuse this manifest with exactly the expected problem:\n{manifest}" + ); + } + + #[test] + fn accepts_stack_encrypt_alone() { + assert_eq!( + problems(BASE), + Vec::::new(), + "the check refused a manifest whose only dependency is stack-encrypt" + ); + } + + #[test] + fn accepts_dev_dependencies_that_are_not_vitaminc() { + let manifest = format!( + "{BASE}[dev-dependencies]\n\ + stack-encrypt = {{ path = \"../stack-encrypt\", features = [\"test-support\"] }}\n\ + tokio = {{ workspace = true, features = [\"rt\", \"macros\"] }}\n\ + trybuild = \"1\"\n" + ); + assert_eq!( + problems(&manifest), + Vec::::new(), + "the check refused dev-dependencies that name no vitaminc crate" + ); + } + + #[test] + fn refuses_a_manifest_without_stack_encrypt() { + assert_eq!( + problems("[dependencies]\n"), + vec!["`[dependencies]` does not list `stack-encrypt`".to_owned()], + "the check accepted a manifest that does not depend on stack-encrypt" + ); + } + + #[test] + fn refuses_a_second_entry_in_dependencies() { + assert_refused("serde = \"1\"\n", "`dependencies.serde` lists `serde`"); + } + + #[test] + fn refuses_a_dependency_written_as_a_sub_table() { + assert_refused( + "[dependencies.serde]\nversion = \"1\"\n", + "`dependencies.serde` lists `serde`", + ); + } + + #[test] + fn refuses_a_dependency_under_a_target() { + assert_refused( + "[target.'cfg(unix)'.dependencies]\nlibc = \"0.2\"\n", + "`target.'cfg(unix)'.dependencies.libc` lists `libc`", + ); + } + + #[test] + fn refuses_a_dependency_written_as_a_dotted_key_under_a_target() { + assert_refused( + "[target.'cfg(unix)']\ndependencies.libc = \"0.2\"\n", + "`target.'cfg(unix)'.dependencies.libc` lists `libc`", + ); + } + + #[test] + fn refuses_a_build_dependency() { + assert_refused( + "[build-dependencies]\ncc = \"1\"\n", + "`build-dependencies.cc` lists `cc`", + ); + } + + #[test] + fn refuses_a_build_dependency_under_a_target() { + assert_refused( + "[target.'cfg(unix)'.build-dependencies]\ncc = \"1\"\n", + "`target.'cfg(unix)'.build-dependencies.cc` lists `cc`", + ); + } + + #[test] + fn refuses_a_vitaminc_dev_dependency() { + assert_refused( + "[dev-dependencies]\nvitaminc-aead = \"0.10\"\n", + "`dev-dependencies.vitaminc-aead` names a vitaminc crate, `vitaminc-aead`", + ); + } + + #[test] + fn refuses_a_vitaminc_dev_dependency_under_a_target() { + assert_refused( + "[target.'cfg(unix)'.dev-dependencies]\nvitaminc-aead = \"0.10\"\n", + "`target.'cfg(unix)'.dev-dependencies.vitaminc-aead` names a vitaminc crate, \ + `vitaminc-aead`", + ); + } + + #[test] + fn refuses_a_vitaminc_crate_under_another_name() { + assert_refused( + "[dev-dependencies]\naead = { package = \"vitaminc-aead\", version = \"0.10\" }\n", + "`dev-dependencies.aead` names a vitaminc crate, `vitaminc-aead`", + ); + } + + #[test] + fn finds_vitaminc_outside_the_dependency_tables() { + let manifest = format!( + "{BASE}[features]\nextra = [\"stack-encrypt/vitaminc-extra\"]\n\ + [patch.crates-io]\nvitaminc-aead = {{ path = \"../vitaminc-aead\" }}\n" + ); + assert_eq!( + vitaminc_mentions(&manifest), + vec![ + "`features.extra` = \"stack-encrypt/vitaminc-extra\"".to_owned(), + "`patch.crates-io.vitaminc-aead`".to_owned(), + "`patch.crates-io.vitaminc-aead.path` = \"../vitaminc-aead\"".to_owned(), + ], + "the scan missed a vitaminc name outside the dependency tables" + ); + assert_eq!( + vitaminc_mentions(BASE), + Vec::::new(), + "the scan found a vitaminc name in a manifest that has none" + ); + } + + #[test] + fn refuses_another_crate_listed_as_stack_encrypt() { + let manifest = + "[dependencies]\nstack-encrypt = { package = \"vitaminc-aead\", version = \"0.10\" }\n"; + assert_eq!( + problems(manifest), + vec![ + "`[dependencies]` does not list `stack-encrypt`".to_owned(), + "`dependencies.stack-encrypt` lists `vitaminc-aead`".to_owned(), + "`dependencies.stack-encrypt` names a vitaminc crate, `vitaminc-aead`".to_owned(), + ], + "the check accepted another crate renamed to stack-encrypt" + ); + } +} diff --git a/packages/stack-encrypt-downstream/tests/ui.rs b/packages/stack-encrypt-downstream/tests/ui.rs new file mode 100644 index 000000000..7ecfb9ee5 --- /dev/null +++ b/packages/stack-encrypt-downstream/tests/ui.rs @@ -0,0 +1,22 @@ +//! What a user of `stack-encrypt` reads when a derive is refused. The +//! errors name `stack_encrypt` paths, since this crate has no other +//! dependency. +//! +//! rustc lists a trait's other implementors in its help, and a +//! stack-encrypt feature such as `dynamic` adds implementors. The recorded +//! errors are still the same under every feature set. trybuild builds the +//! cases as a separate project, from this crate's dev-dependencies and +//! features. This crate has no features, and +//! `tests/manifest.rs` checks that it has none. So a workspace build with +//! `--all-features`, as CI runs, does not change that project. +//! +//! Re-record with `TRYBUILD=overwrite cargo test -p +//! stack-encrypt-downstream --test ui` after an intended change. + +// trybuild launches rustc. Miri cannot run rustc. +#[cfg(not(miri))] +#[test] +fn ui() { + let tests = trybuild::TestCases::new(); + tests.compile_fail("tests/ui/*.rs"); +} diff --git a/packages/stack-encrypt-downstream/tests/ui/field_type_not_encryptable.rs b/packages/stack-encrypt-downstream/tests/ui/field_type_not_encryptable.rs new file mode 100644 index 000000000..139a84027 --- /dev/null +++ b/packages/stack-encrypt-downstream/tests/ui/field_type_not_encryptable.rs @@ -0,0 +1,13 @@ +//! A field whose type implements neither `Encrypt` nor `Decrypt`. Each +//! error names the trait by its `stack_encrypt` path. +use stack_encrypt::{Decrypt, Encrypt}; + +struct Opaque; + +#[derive(Encrypt, Decrypt)] +struct Record { + name: String, + secret: Opaque, +} + +fn main() {} diff --git a/packages/stack-encrypt-downstream/tests/ui/field_type_not_encryptable.stderr b/packages/stack-encrypt-downstream/tests/ui/field_type_not_encryptable.stderr new file mode 100644 index 000000000..beb923e43 --- /dev/null +++ b/packages/stack-encrypt-downstream/tests/ui/field_type_not_encryptable.stderr @@ -0,0 +1,214 @@ +error[E0277]: the trait bound `Opaque: FromScalar` is not satisfied + --> tests/ui/field_type_not_encryptable.rs:7:19 + | +7 | #[derive(Encrypt, Decrypt)] + | ^^^^^^^ unsatisfied trait bound + | +help: the trait `FromScalar` is not implemented for `Opaque` + --> tests/ui/field_type_not_encryptable.rs:5:1 + | +5 | struct Opaque; + | ^^^^^^^^^^^^^ + = help: the following other types implement trait `FromScalar`: + JsonPlaintext + Vec + [u8; N] + bool + f32 + f64 + i128 + i16 + and $N others + = note: required for `Opaque` to implement `Decrypt` + = note: required for `Forward>` to implement `stack_encrypt::plaintext::Sink` + = note: 1 redundant requirement hidden + = note: required for `Either>, Forward>>` to implement `stack_encrypt::plaintext::Sink` +note: required by a bound in `stack_encrypt::plaintext::MapSink::Entry` + --> $WORKSPACE/packages/vitaminc-aead/src/plaintext/mod.rs + | + | type Entry<'s>: Sink + | ^^^^^^^^^^^^^^^^^^^ required by this bound in `MapSink::Entry` + = note: this error originates in the derive macro `Decrypt` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0277]: the trait bound `Opaque: FromScalar` is not satisfied + --> tests/ui/field_type_not_encryptable.rs:7:19 + | +7 | #[derive(Encrypt, Decrypt)] + | ^^^^^^^ unsatisfied trait bound + | +help: the trait `FromScalar` is not implemented for `Opaque` + --> tests/ui/field_type_not_encryptable.rs:5:1 + | +5 | struct Opaque; + | ^^^^^^^^^^^^^ + = help: the following other types implement trait `FromScalar`: + JsonPlaintext + Vec + [u8; N] + bool + f32 + f64 + i128 + i16 + and $N others + = note: required for `Opaque` to implement `Decrypt` +note: required by a bound in `Forward` + --> $WORKSPACE/packages/vitaminc-aead/src/typed.rs + | + | pub struct Forward(pub T::Sink, pub O); + | ^^^^^^^ required by this bound in `Forward` + = note: this error originates in the derive macro `Decrypt` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0277]: the trait bound `Opaque: Encrypt` is not satisfied + --> tests/ui/field_type_not_encryptable.rs:10:13 + | +10 | secret: Opaque, + | ^^^^^^ unsatisfied trait bound + | +help: the trait `Encrypt` is not implemented for `Opaque` + --> tests/ui/field_type_not_encryptable.rs:5:1 + | + 5 | struct Opaque; + | ^^^^^^^^^^^^^ +note: there are multiple different versions of crate `vitaminc_aead` in the dependency graph + --> $WORKSPACE/packages/vitaminc-aead/src/plaintext/mod.rs + | + | pub trait Encrypt { + | ^^^^^^^^^^^^^^^^^ this is the expected trait + | + ::: $CARGO/vitaminc-aead-$VERSION/src/encrypt/mod.rs + | + | pub trait Encrypt { + | ----------------- this is the trait that was imported + = help: you can use `cargo tree` to explore your dependency tree + = help: the following other types implement trait `Encrypt`: + &&T + &'__r Record + &BTreeMap + &HashMap + &JsonPlaintext + &Option + &PassthroughFrame + &Protected + and $N others + +error[E0277]: the trait bound `Opaque: Encrypt` is not satisfied + --> tests/ui/field_type_not_encryptable.rs:7:10 + | +7 | #[derive(Encrypt, Decrypt)] + | ^^^^^^^ unsatisfied trait bound + | +help: the trait `Encrypt` is not implemented for `Opaque` + --> tests/ui/field_type_not_encryptable.rs:5:1 + | +5 | struct Opaque; + | ^^^^^^^^^^^^^ +note: there are multiple different versions of crate `vitaminc_aead` in the dependency graph + --> $WORKSPACE/packages/vitaminc-aead/src/plaintext/mod.rs + | + | pub trait Encrypt { + | ^^^^^^^^^^^^^^^^^ this is the expected trait + | + ::: $CARGO/vitaminc-aead-$VERSION/src/encrypt/mod.rs + | + | pub trait Encrypt { + | ----------------- this is the trait that was imported + = help: you can use `cargo tree` to explore your dependency tree + = help: the following other types implement trait `Encrypt`: + &&T + &'__r Record + &BTreeMap + &HashMap + &JsonPlaintext + &Option + &PassthroughFrame + &Protected + and $N others +note: required by a bound in `discard_one` + --> $WORKSPACE/packages/vitaminc-aead/src/plaintext/sources.rs + | + | pub fn discard_one(value: P) { + | ^^^^^^^ required by this bound in `discard_one` + = note: this error originates in the derive macro `Encrypt` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0277]: the trait bound `for<'a> &'a Opaque: Encrypt` is not satisfied + --> tests/ui/field_type_not_encryptable.rs:10:13 + | +10 | secret: Opaque, + | ^^^^^^ the trait `for<'a> Encrypt` is not implemented for `&'a Opaque` + | +note: there are multiple different versions of crate `vitaminc_aead` in the dependency graph + --> $WORKSPACE/packages/vitaminc-aead/src/plaintext/mod.rs + | + | pub trait Encrypt { + | ^^^^^^^^^^^^^^^^^ this is the expected trait + | + ::: $CARGO/vitaminc-aead-$VERSION/src/encrypt/mod.rs + | + | pub trait Encrypt { + | ----------------- this is the found trait + = help: you can use `cargo tree` to explore your dependency tree + = help: the following other types implement trait `Encrypt`: + &&T + &'__r Record + &BTreeMap + &HashMap + &JsonPlaintext + &Option + &PassthroughFrame + &Protected + and $N others + = note: required for `Opaque` to implement `EncryptRef` + +error[E0277]: the trait bound `for<'a> &'a Opaque: Encrypt` is not satisfied + --> tests/ui/field_type_not_encryptable.rs:7:10 + | +7 | #[derive(Encrypt, Decrypt)] + | ^^^^^^^ the trait `for<'a> Encrypt` is not implemented for `&'a Opaque` + | +note: there are multiple different versions of crate `vitaminc_aead` in the dependency graph + --> $WORKSPACE/packages/vitaminc-aead/src/plaintext/mod.rs + | + | pub trait Encrypt { + | ^^^^^^^^^^^^^^^^^ this is the expected trait + | + ::: $CARGO/vitaminc-aead-$VERSION/src/encrypt/mod.rs + | + | pub trait Encrypt { + | ----------------- this is the found trait + = help: you can use `cargo tree` to explore your dependency tree + = help: the following other types implement trait `Encrypt`: + &&T + &'__r Record + &BTreeMap + &HashMap + &JsonPlaintext + &Option + &PassthroughFrame + &Protected + and $N others + = note: required for `Opaque` to implement `EncryptRef` + = note: this error originates in the derive macro `Encrypt` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0277]: the trait bound `Opaque: FromScalar` is not satisfied + --> tests/ui/field_type_not_encryptable.rs:10:13 + | +10 | secret: Opaque, + | ^^^^^^ unsatisfied trait bound + | +help: the trait `FromScalar` is not implemented for `Opaque` + --> tests/ui/field_type_not_encryptable.rs:5:1 + | + 5 | struct Opaque; + | ^^^^^^^^^^^^^ + = help: the following other types implement trait `FromScalar`: + JsonPlaintext + Vec + [u8; N] + bool + f32 + f64 + i128 + i16 + and $N others + = note: required for `Opaque` to implement `Decrypt` diff --git a/packages/stack-encrypt-downstream/tests/ui/too_deep.rs b/packages/stack-encrypt-downstream/tests/ui/too_deep.rs new file mode 100644 index 000000000..ca5ae5ba6 --- /dev/null +++ b/packages/stack-encrypt-downstream/tests/ui/too_deep.rs @@ -0,0 +1,19 @@ +//! A type that nests deeper than any value Stack Encrypt encrypts. The +//! error names the limit by its `stack_encrypt` path. +#![recursion_limit = "512"] +use stack_encrypt::Encrypt; + +type V2 = Vec>; +type V4 = V2>; +type V8 = V4>; +type V16 = V8>; +type V32 = V16>; +type V64 = V32>; +type V128 = V64>; + +#[derive(Encrypt)] +struct TooDeep { + deep: V128, +} + +fn main() {} diff --git a/packages/stack-encrypt-downstream/tests/ui/too_deep.stderr b/packages/stack-encrypt-downstream/tests/ui/too_deep.stderr new file mode 100644 index 000000000..e3cf6960a --- /dev/null +++ b/packages/stack-encrypt-downstream/tests/ui/too_deep.stderr @@ -0,0 +1,5 @@ +error[E0080]: evaluation panicked: `TooDeep` nests deeper than `stack_encrypt::plaintext::depth::MAX_DEPTH` levels. Stack Encrypt refuses to encrypt a value nested that deeply, so it would refuse every full value of this type + --> tests/ui/too_deep.rs:14:10 + | +14 | #[derive(Encrypt)] + | ^^^^^^^ evaluation of `_` failed here diff --git a/packages/stack-encrypt/CHANGELOG.md b/packages/stack-encrypt/CHANGELOG.md index b9839b813..90bca8f81 100644 --- a/packages/stack-encrypt/CHANGELOG.md +++ b/packages/stack-encrypt/CHANGELOG.md @@ -9,6 +9,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +- **Write `Encrypt` and `Decrypt` by hand with no dependency other than + `stack-encrypt`** (#2013). The new `plaintext` module contains the items + that the body of a hand-written impl names: + - the sink traits `Sink`, `SeqSink`, and `MapSink`; + - the `depth` constants, with `depth::MAX_DEPTH`; + - the types of a scalar, such as `Physical`, `Logical`, and `FixedType`. + + Two traits are re-exported at the crate root. `Scalar` marks a type that + encrypts as one value. `FromScalar` builds a type from one scalar. The + docs of `plaintext` show a complete example. + - **Encrypt and decrypt one value whose type is known only at run time** (#2009). `dynamic::value` has two functions for a value in a frame. The two functions are the run-time counterparts of the typed `keyset.encrypt` @@ -1488,8 +1499,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 stack-kms CHANGELOG. - **A `Scalar` impl you wrote for a derived newtype or a fieldless enum no - longer compiles** (#2012). `#[derive(Encrypt)]` now implements Vitamin - C's `Scalar` marker for these types. So an `impl Scalar for &Email {}` of + longer compiles** (#2012). `#[derive(Encrypt)]` now implements the + `Scalar` marker for these types. So an `impl Scalar for &Email {}` of your own conflicts with it. The compiler reports `E0119`, conflicting implementations. The compiler reports it even when the inner type is not a `Scalar`. What to do depends on the inner type. @@ -1507,7 +1518,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 `keyset.encrypt` now checks, when the program is built, that the borrow of the type encrypts as one value. So the `Encrypt` impl that you wrote for the borrow must contain `const DEPTH: Option = depth::SCALAR;`. - `depth` is `vitaminc_aead::plaintext::depth`. + `depth` is `stack_encrypt::plaintext::depth`. - An impl that leaves `DEPTH` at its default `None` compiled before. Now `cargo build` fails with `E0080`, and the message names the line to add. `cargo check` does not run this check. @@ -1990,13 +2001,40 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed +- **`#[derive(Encrypt)]` and `#[derive(Decrypt)]` compile in a crate that + depends only on `stack-encrypt`** (#2013). The derives are now Stack + Encrypt's own, in `stack-encrypt-derive`, and `stack_encrypt::Encrypt` and + `stack_encrypt::Decrypt` re-export them. Before this change, they were + vitaminc-aead's derives. Their code named the crate `vitaminc_aead`, so a + crate that used them had to depend on `vitaminc-aead` too. + - The code that the derives write names every item through + `stack_encrypt`. `vitaminc-aead` has no derives of its own any more. + - The attributes are the same: `#[aead(rename = "...")]`, + `#[aead(passthrough)]`, `#[aead(skip)]`, `#[aead(take)]`, and + `#[aead(recursive)]`. The wire shape is the same, so every stored value + still decrypts. + - `#[aead(crate = "...")]` now names the path to `stack_encrypt`, such as + a re-export of it. A path to `vitaminc_aead` works only with the + `vitaminc-aead` source in the `cipherstash/stack` repository. That + source is not on crates.io yet. The code that the derives write names + `vitaminc_aead::__derive`, and crates.io's `vitaminc-aead` 0.10.0 has + no such module. + - To migrate, import the derives from `stack_encrypt` instead of + `vitaminc_aead`, and remove `vitaminc-aead` from your `Cargo.toml` if + nothing else uses it. + - The compile error for a type that nests too deeply now names the limit + by its path, `stack_encrypt::plaintext::depth::MAX_DEPTH`. With + `#[aead(crate = "...")]`, the path starts at the named crate path. The + error for a hand-written `Scalar` impl names + `stack_encrypt::plaintext::depth::SCALAR`. A refused trait bound now + names `FromScalar` by its `stack_encrypt` path. + - **`keyset.encrypt` encrypts a newtype that derives `Encrypt` over one value** (#2012). A newtype is a struct with exactly one unnamed field. `struct Email(String)` with `#[derive(Encrypt, Zeroize)]` now encrypts with `keyset.encrypt(Email(..))`. You no longer write - `impl Scalar for &Email {}` by hand. Your crate still needs - `vitaminc-aead` as a dependency to use the derive, because the derived - code names `vitaminc_aead` (#2013). + `impl Scalar for &Email {}` by hand. Your crate needs no dependency + other than `stack-encrypt` to use the derive (#2013). - The newtype encrypts exactly as its inner value does. The leaf has the same plaintext and the same length. So `keyset.decrypt::` opens what `Email` encrypted. diff --git a/packages/stack-encrypt/examples/mixed_user.rs b/packages/stack-encrypt/examples/mixed_user.rs index 0fe0118d3..025c1642b 100644 --- a/packages/stack-encrypt/examples/mixed_user.rs +++ b/packages/stack-encrypt/examples/mixed_user.rs @@ -17,7 +17,7 @@ //! Passthrough values travel in the clear and are **not authenticated** — //! use them for non-sensitive routing/display data only. //! -//! This is the *cipher-directed* layer — vitaminc's `Encrypt` / `Decrypt` +//! This is the *cipher-directed* layer — the `Encrypt` / `Decrypt` //! derives, sealed through the keyset directly — one level below //! `#[derive(EncryptTarget)]`, which the //! `encrypted_record` example uses. Reach for this layer when a value needs @@ -37,8 +37,7 @@ //! `CS_WORKSPACE_CRN` and `CS_CLIENT_ID` / `CS_CLIENT_KEY` instead (see the //! `zerokms_auth` example for the lookup order). -use stack_encrypt::{CipherText, Label, StackCipher, StackCipherText}; -use vitaminc_aead::{Decrypt, Encrypt}; +use stack_encrypt::{CipherText, Decrypt, Encrypt, Label, StackCipher, StackCipherText}; // --- The record type --------------------------------------------------------- diff --git a/packages/stack-encrypt/fuzz/Cargo.lock b/packages/stack-encrypt/fuzz/Cargo.lock index 923524166..07de8f36d 100644 --- a/packages/stack-encrypt/fuzz/Cargo.lock +++ b/packages/stack-encrypt/fuzz/Cargo.lock @@ -2742,7 +2742,7 @@ checksum = "62cacd4dae485e98cfe5407e919187a8468dd933ea4234be5115b7d13a30f3c6" dependencies = [ "bytes", "serde", - "vitaminc-aead-derive 0.5.1", + "vitaminc-aead-derive", "vitaminc-context 0.5.1", "vitaminc-protected 0.5.1", "vitaminc-random 0.5.1", @@ -2759,7 +2759,6 @@ dependencies = [ "rust_decimal", "serde", "thiserror 2.0.18", - "vitaminc-aead-derive 0.10.0", "vitaminc-context 0.10.0", "vitaminc-protected 0.10.0", "vitaminc-random 0.10.0", @@ -2777,15 +2776,6 @@ dependencies = [ "syn 3.0.3", ] -[[package]] -name = "vitaminc-aead-derive" -version = "0.10.0" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.3", -] - [[package]] name = "vitaminc-context" version = "0.5.1" diff --git a/packages/stack-encrypt/fuzz/Cargo.toml b/packages/stack-encrypt/fuzz/Cargo.toml index e91082049..a4b1a4be1 100644 --- a/packages/stack-encrypt/fuzz/Cargo.toml +++ b/packages/stack-encrypt/fuzz/Cargo.toml @@ -83,9 +83,8 @@ 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 lives in this repository and is not published from +# here yet. Build against the copy, 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" } diff --git a/packages/stack-encrypt/src/lib.rs b/packages/stack-encrypt/src/lib.rs index 077268c39..2ec6fffb0 100644 --- a/packages/stack-encrypt/src/lib.rs +++ b/packages/stack-encrypt/src/lib.rs @@ -31,9 +31,12 @@ //! has its own ZeroKMS data key and independently auditable retrieval. //! //! Structural encryption, searchable targets and derives use the existing -//! plan/target engine. Its [`StackCipherText`] nodes and Vitamin C +//! plan/target engine. Its [`StackCipherText`] nodes and the //! [`Encrypt`]/[`Decrypt`] visitors remain available through the low-level -//! API while the owned Rust interface is extended beyond scalars. +//! API while the owned Rust interface is extended beyond scalars. Derive +//! `Encrypt` and `Decrypt` for a type of your own with +//! `#[derive(stack_encrypt::Encrypt, stack_encrypt::Decrypt)]`, or write +//! them by hand with the items in [`plaintext`]. //! //! # Quick start //! @@ -741,6 +744,7 @@ pub mod field_reference; pub mod json; pub mod keyset; pub mod op; +pub mod plaintext; pub mod plan; pub mod refusal; pub mod sem; @@ -782,16 +786,28 @@ pub use target::{ Match, Ope, Ore, OreBlock, Pending, PendingFuture, Request, Responses, TermSet, }; -// Re-export the vitaminc AEAD surface callers need to drive the cipher, so they -// don't have to depend on `vitaminc-aead` directly for the common path: a -// value describes itself once (`Encrypt`) and names the sink that reads it -// back (`Decrypt`). A context type of your own implements `IntoContext` once; -// `IntoAad` and `IntoPrfContext` are vitaminc's blankets over it, so both -// derivations see the same bytes. +// The data model of a plaintext, so that a caller needs no dependency on +// `vitaminc-aead`. A value describes itself once (`Encrypt`). It names the +// sink that reads it back (`Decrypt`). +// +// `Scalar` marks a type that encrypts as one value. `FromScalar` builds a +// type from one scalar. The items that the body of a hand-written impl names +// are in `plaintext`. +// +// A context type of your own implements `IntoContext` once; `IntoAad` and +// `IntoPrfContext` are vitaminc's blankets over it, so both derivations see +// the same bytes. pub use vitaminc_aead::{ CipherText, Context, ContextPiece, ContextTag, DecodeError, Decrypt, Encrypt, EncryptRef, - IntoAad, IntoContext, Node, PassthroughFrame, ScalarTarget, Unspecified, + FromScalar, IntoAad, IntoContext, Node, PassthroughFrame, Scalar, ScalarTarget, Unspecified, }; +// The derives of the two traits above. Each name is both the trait and its +// derive, as serde's `Serialize` is. +pub use stack_encrypt_derive::{Decrypt, Encrypt}; +// The code that `#[derive(Encrypt)]` and `#[derive(Decrypt)]` write names +// each item through `::stack_encrypt::__derive`. Not an API. +#[doc(hidden)] +pub use vitaminc_aead::__derive; /// A type with an order target of its own: what an order index /// ([`Ore`], [`Ope`], [`OreBlock`]), an order term ([`sem::OreTerm`], /// [`sem::OpeTerm`], [`sem::OreBlockTerm`]) and the ordering operators diff --git a/packages/stack-encrypt/src/plaintext.rs b/packages/stack-encrypt/src/plaintext.rs new file mode 100644 index 000000000..fd9c8bfff --- /dev/null +++ b/packages/stack-encrypt/src/plaintext.rs @@ -0,0 +1,99 @@ +//! The items that a hand-written [`Encrypt`](trait@crate::Encrypt) or +//! [`Decrypt`](trait@crate::Decrypt) impl names. +//! +//! Most types derive both traits, with +//! `#[derive(stack_encrypt::Encrypt, stack_encrypt::Decrypt)]`. Write the +//! impls by hand when the derive does not describe the value as you want. +//! For example, a struct with a named field derives as a map, and you want +//! it stored as the one value it holds. +//! +//! A hand-written `Encrypt` impl describes the value to a [`Sink`]: one +//! scalar with [`Sink::scalar`], or a container with [`Sink::seq`] or +//! [`Sink::map`]. Its `DEPTH` says how deeply a value of the type nests, and +//! [`depth`] has the constants for it. A type that encrypts as one value +//! also implements [`Scalar`](crate::Scalar), so that +//! [`KeysetCipher::encrypt`](crate::KeysetCipher::encrypt) takes it. +//! +//! A type that is built from one scalar implements +//! [`FromScalar`](crate::FromScalar). The type then has `Decrypt` with no +//! other code. +//! +//! ``` +//! use stack_encrypt::plaintext::{depth, FixedType, Logical, Physical, Sink}; +//! use stack_encrypt::{Encrypt, EncryptRef, FromScalar, Scalar, StackCipher}; +//! use zeroize::Zeroize; +//! +//! /// An amount in cents. The derive would store it as a map with one +//! /// entry, `cents`. These impls store it as its one integer instead. +//! #[derive(Zeroize)] +//! struct Price { +//! cents: i64, +//! } +//! +//! impl Encrypt for Price { +//! const DEPTH: Option = depth::SCALAR; +//! const FIXED: Option = ::FIXED; +//! fn visit(self, sink: S) -> Result { +//! self.cents.visit(sink) +//! } +//! } +//! +//! // `keyset.encrypt` reads the value through a borrow, so the borrow +//! // encrypts too, and is marked `Scalar`. +//! impl Encrypt for &Price { +//! const DEPTH: Option = depth::SCALAR; +//! const FIXED: Option = <&i64 as Encrypt>::FIXED; +//! fn visit(self, sink: S) -> Result { +//! self.cents.visit_ref(sink) +//! } +//! } +//! impl Scalar for Price {} +//! impl Scalar for &Price {} +//! +//! // `FromScalar` gives `Price` its `Decrypt`. +//! impl FromScalar for Price { +//! const EXPECTED: &'static str = "a price in cents"; +//! const FIXED: Option = ::FIXED; +//! fn from_scalar(ty: Option, value: Physical<'_>) -> Option { +//! i64::from_scalar(ty, value).map(|cents| Price { cents }) +//! } +//! } +//! +//! # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async { +//! // With no `.kms(..)`, the cipher uses ZeroKMS. It reads credentials from +//! // the environment, or from the profile that `npx stash auth login` writes. +//! let cipher = StackCipher::builder() +//! # .kms(stack_encrypt::kms::FakeDataKeySource::new()) +//! .init() +//! .await?; +//! let keyset = cipher.default_keyset(); +//! let stored = keyset.encrypt(Price { cents: 1999 }).await?; +//! // The stored value is one integer, so it also decrypts as an `i64`. +//! let cents: i64 = keyset.decrypt(stored.clone()).await?; +//! assert_eq!(cents, 1999); +//! let price: Price = keyset.decrypt(stored).await?; +//! assert_eq!(price.cents, 1999); +//! # Ok::<(), Box>(()) +//! # }).unwrap(); +//! ``` + +pub use vitaminc_aead::plaintext::{ + FixedType, Float, Int, Logical, MapSink, Physical, SeqSink, Sink, TimeUnit, Width, +}; + +/// How deeply a type nests, for [`Encrypt::DEPTH`](crate::Encrypt::DEPTH). +/// +/// A depth counts the containers below a value's own root. A scalar is `0`, +/// and a sequence or a map is one more than its deepest child. `None` means +/// that the type alone does not fix the depth, as for a recursive type. The +/// encrypting walk then checks each value instead. +/// +/// The functions are `const fn`s, so that a type's depth is worked out at +/// compile time from its fields' depths. `#[derive(Encrypt)]` uses them, +/// and fails to compile a type that nests too deeply to be encrypted. +pub mod depth { + pub use vitaminc_aead::frame::MAX_DEPTH; + pub use vitaminc_aead::plaintext::depth::{ + container, is_scalar, max, passthrough, within_limit, SCALAR, + }; +} diff --git a/packages/stack-encrypt/src/scalar.rs b/packages/stack-encrypt/src/scalar.rs index 886760b28..19743dde8 100644 --- a/packages/stack-encrypt/src/scalar.rs +++ b/packages/stack-encrypt/src/scalar.rs @@ -50,8 +50,8 @@ pub(crate) mod sealed { /// `OpaqueEncode` is implemented for every owned type `S` that meets two /// conditions: /// -/// - `&S` implements Vitamin C's [`Scalar`] marker, so Vitamin C encrypts it -/// as a single value. +/// - `&S` implements the [`Scalar`] marker, so it encrypts as +/// a single value. /// - `S` implements [`Zeroize`], so it can be wiped. /// /// These built-in types meet both conditions: @@ -70,9 +70,9 @@ pub(crate) mod sealed { /// derive marks the newtype `Scalar` when its inner type is a `Scalar`. /// /// The newtype encrypts exactly as its inner value does. So -/// `keyset.decrypt::` opens what an `Email` encrypted. The derive -/// comes from Vitamin C, so your crate needs `vitaminc-aead` as a -/// dependency to use it. +/// `keyset.decrypt::` opens what an `Email` encrypted. The derive is +/// Stack Encrypt's, so your crate needs no dependency other than +/// `stack-encrypt` to use it. /// /// ``` /// # async fn example() -> Result<(), stack_encrypt::Error> { @@ -131,8 +131,9 @@ pub(crate) mod sealed { /// # let _ = encrypt::; /// ``` /// -/// You can also write the `Encrypt` impl of a type yourself. Such a type is -/// an `OpaqueEncode` type when you implement `Scalar` for its borrow. +/// You can also write the `Encrypt` impl of a type yourself, with the items +/// in [`plaintext`](crate::plaintext). Such a type is an `OpaqueEncode` type +/// when you implement `Scalar` for its borrow. /// /// A `Scalar` impl states that the borrow encrypts as one value. So the /// borrow's `Encrypt` impl must set its [`DEPTH`](crate::Encrypt::DEPTH): @@ -141,7 +142,7 @@ pub(crate) mod sealed { /// const DEPTH: Option = depth::SCALAR; /// ``` /// -/// `depth` is `vitaminc_aead::plaintext::depth`. The default `DEPTH` is +/// `depth` is [`plaintext::depth`](crate::plaintext::depth). The default `DEPTH` is /// `None`. `None` means that the depth depends on the value. `keyset.encrypt` /// checks the `DEPTH` when your program is built. A `Scalar` type whose /// borrow has any other `DEPTH` fails the build. @@ -161,7 +162,7 @@ pub(crate) mod sealed { /// into one `Ciphertext`. A `Vec` of any other `OpaqueEncode` type encrypts /// element by element into a `Vec`, through [`EncryptInto`]. The /// [crate docs on collections](crate#collections) explain how. `u8` is not an `OpaqueEncode` type, -/// because Vitamin C encrypts a `Vec` as one byte string, not as a +/// because a `Vec` encrypts as one byte string, not as a /// collection of bytes. /// /// # Nullable values @@ -364,8 +365,8 @@ impl sealed::OneValue for S where for<'a> &'a S: Scalar {} /// ``` /// use stack_encrypt::kms::FakeDataKeySource; /// use stack_encrypt::{Encrypt, EncryptRef, KeysetCipher}; -/// use vitaminc_aead::plaintext::{depth, Sink}; -/// use vitaminc_aead::Scalar; +/// use stack_encrypt::plaintext::{depth, Sink}; +/// use stack_encrypt::Scalar; /// use zeroize::Zeroize; /// /// // A type whose borrow encrypts as its one `String`. @@ -397,8 +398,8 @@ impl sealed::OneValue for S where for<'a> &'a S: Scalar {} /// ```compile_fail,E0080 /// use stack_encrypt::kms::FakeDataKeySource; /// use stack_encrypt::{Encrypt, EncryptRef, KeysetCipher}; -/// use vitaminc_aead::plaintext::{depth, Sink}; -/// use vitaminc_aead::Scalar; +/// use stack_encrypt::plaintext::{depth, Sink}; +/// use stack_encrypt::Scalar; /// use zeroize::Zeroize; /// /// // A type whose borrow encrypts as its one `String`. @@ -435,9 +436,9 @@ where assert!( vitaminc_aead::plaintext::depth::is_scalar(::REF_DEPTH), "a type marked `Scalar` must encrypt as one value. Set \ - `const DEPTH: Option = depth::SCALAR;` in the `Encrypt` impl that you \ - wrote for its borrow. For a newtype that derives `Encrypt`, set it on the \ - innermost type whose `Encrypt` impl you wrote by hand.", + `const DEPTH: Option = stack_encrypt::plaintext::depth::SCALAR;` in the \ + `Encrypt` impl that you wrote for its borrow. For a newtype that derives \ + `Encrypt`, set it on the innermost type whose `Encrypt` impl you wrote by hand.", ) }; crate::target::core::encrypt_opaque(self.lend(), cipher, context) diff --git a/packages/stack-kms/fuzz/Cargo.lock b/packages/stack-kms/fuzz/Cargo.lock index 389e4a957..ae6dc975c 100644 --- a/packages/stack-kms/fuzz/Cargo.lock +++ b/packages/stack-kms/fuzz/Cargo.lock @@ -2405,7 +2405,7 @@ checksum = "62cacd4dae485e98cfe5407e919187a8468dd933ea4234be5115b7d13a30f3c6" dependencies = [ "bytes", "serde", - "vitaminc-aead-derive 0.5.1", + "vitaminc-aead-derive", "vitaminc-context 0.5.1", "vitaminc-protected 0.5.1", "vitaminc-random 0.5.1", @@ -2420,7 +2420,6 @@ dependencies = [ "futures-util", "serde", "thiserror 2.0.18", - "vitaminc-aead-derive 0.10.0", "vitaminc-context 0.10.0", "vitaminc-protected 0.10.0", "vitaminc-random 0.10.0", @@ -2438,15 +2437,6 @@ dependencies = [ "syn 3.0.3", ] -[[package]] -name = "vitaminc-aead-derive" -version = "0.10.0" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.3", -] - [[package]] name = "vitaminc-context" version = "0.5.1" diff --git a/packages/stack-kms/fuzz/Cargo.toml b/packages/stack-kms/fuzz/Cargo.toml index c876f9c88..6368ad212 100644 --- a/packages/stack-kms/fuzz/Cargo.toml +++ b/packages/stack-kms/fuzz/Cargo.toml @@ -34,9 +34,8 @@ 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 lives in this repository and is not published from +# here yet. Build against the copy, 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" } diff --git a/packages/vitaminc-aead-derive/CHANGELOG.md b/packages/vitaminc-aead-derive/CHANGELOG.md deleted file mode 100644 index c37269877..000000000 --- a/packages/vitaminc-aead-derive/CHANGELOG.md +++ /dev/null @@ -1,104 +0,0 @@ -## [Unreleased] - -### Breaking - -- **Breaking:** `#[derive(Encrypt)]` now implements `Scalar` for a newtype and for a fieldless enum. - A `Scalar` impl you wrote for such a type no longer compiles. - The compiler reports `E0119`, conflicting implementations, even when the inner type is not a `Scalar`. - - For a fieldless enum, or for a newtype whose inner type is a `Scalar`, delete your impl, because the derived impl replaces it. - - When the inner type is not a `Scalar`, but you know that its value is one leaf, stop deriving `Encrypt`. - Write `Encrypt` for the type and for its borrow by hand, with `const DEPTH: Option = depth::SCALAR;`, and keep your `Scalar` impl. - -### Features - -- `#[derive(Encrypt)]` implements `Scalar`, by value and by reference, for a type that encrypts as one leaf. - A newtype is a struct with exactly one unnamed field. - A newtype is a `Scalar` when its inner type is one. - So `struct Email(String)` is a `Scalar`. - A generic `Wrapper` is a `Scalar` when `T` is one. - `struct Tags(Vec)` still derives `Encrypt`, but it is not a `Scalar`. - Neither is `struct Nickname(Option)`. - A fieldless enum is always a `Scalar`, because it is one `u32` leaf. - That is true even when the enum is marked `#[aead(recursive)]`. - Its `DEPTH` is now `depth::SCALAR` in that case too, where it was `None`. - A struct with fields is not a `Scalar`. - A recursive newtype is not a `Scalar` either. - -## [0.10.0] - 2026-11-19 - -### Breaking - -- **Breaking:** `#[aead(passthrough, take)]` is now a compile error. - The derived code lends a passthrough field to the sink, and never moves it out of `self`. - So `take` has no effect on a passthrough field. - Remove `take` from your passthrough fields. - A passthrough field of a type that implements `Drop` no longer needs `Default`. - -### Fixes - -- A generic struct with a `Vec` or `Option` field can now be encrypted inside a container. - In 0.9.1, the derived code failed to compile with error E0275, an overflow in the trait solver. -- A struct with a lifetime parameter can now be encrypted inside a container when the lifetime is shorter than `'static`. -- The type of a passthrough field now needs to implement only `Encrypt` for a reference to it. - In 0.9.1, the type also had to implement `Encrypt` by value, and `Clone`. - -## [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. - -## [0.8.1] - 2026-10-26 - -## [0.8.0] - 2026-10-21 - -### Breaking - -- **Breaking:** A derived type knows its fixed width, so a `None` of a derived newtype over a fixed-width type, or of a fieldless enum, now seals as a typed null padded to a `Some`'s length, and reads back as `None` wherever the inner type's, or a `u32`'s, would. A struct is a map and has no fixed width. No derive input changes, but the sealed bytes do: see `vitaminc-aead` 0.8.0 for what a typed null is, and which readers accept one. - -## [0.7.0] - 2026-10-20 - -## [0.6.1] - 2026-10-18 - -## [0.6.0] - 2026-10-17 - -### Breaking - -- **Breaking:** the crate now declares a minimum supported Rust version of 1.88. 0.5.1 declared none. -- **Breaking:** `#[derive(Encrypt)]` and `#[derive(Decrypt)]` keep their names but generate `vitaminc-aead` 0.6's sink-based traits (ADR 0001), and need `vitaminc-aead` 0.6. `Encrypt` is generated for both `T` and `&T`. Code that called the generated impls directly must move to the 0.6 entry points (`encrypt`, `decrypt`). Types derived with 0.5 produce ciphertext that 0.6 does not open; see `vitaminc-aead`. -- **Breaking:** a `#[aead(passthrough)]` field's type must now implement `Encrypt + Clone` on the way in and `Decrypt` on the way out, instead of `Any + Send + 'static`. Borrowed types such as `&'a str` are now allowed. -- **Breaking:** a field's type must be at least as visible as the struct, because the generated decrypt sink names it in a public type. Otherwise the derive fails with E0446. A type that should stay private can be declared `pub` inside a private module. - -### Features - -- A fieldless enum can be derived. It encrypts as one `u32` leaf holding the variant's discriminant, so every variant has the same ciphertext length. Data-carrying enums are still refused. -- `#[aead(skip)]` leaves a field out and rebuilds it with `Default` on decryption. `#[aead(take)]` moves a field out with `mem::take`, so a `ZeroizeOnDrop` type can derive. -- A derived type nested deeper than `MAX_DEPTH` fails to compile, so it is never refused as too deep at runtime unless it is recursive. Mark mutually recursive types with `#[aead(recursive)]`, or rustc reports a const-evaluation cycle (E0391). - -## [0.5.1] - 2026-10-05 - -## [0.5.0] - 2026-09-20 - -### Breaking - -- **Breaking:** one canonical context encoding shared by AAD and PRF derivations - -## [0.4.0] - 2026-09-12 - -## [0.3.0] - 2026-09-07 - -## [0.2.0] - 2026-09-03 - -First release. - -### Features - -- `#[derive(Encrypt, Decrypt)]` encrypts structs field by field with no hand-written impls. -- `#[aead(passthrough)]` stores chosen fields in the clear — those fields are unencrypted and **not authenticated**. - -### Documentation - -- The `#[aead(...)]` attribute reference is written once and inlined everywhere it applies. diff --git a/packages/vitaminc-aead-derive/Cargo.toml b/packages/vitaminc-aead-derive/Cargo.toml deleted file mode 100644 index 0cfde1e20..000000000 --- a/packages/vitaminc-aead-derive/Cargo.toml +++ /dev/null @@ -1,39 +0,0 @@ -[package] -name = "vitaminc-aead-derive" -description = "Derive macros for vitaminc-aead. Part of the VitaminC cryptographic suite." -documentation = "https://docs.rs/vitaminc-aead-derive" -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 - -[lib] -proc-macro = true - -# The dev-dependencies are used only by the doc tests over -# docs/attributes.md, which cargo-udeps cannot see. -[package.metadata.cargo-udeps.ignore] -development = ["vitaminc", "vitaminc-aead", "zeroize"] - -[dependencies] -proc-macro2 = "1" -quote = "1" -syn = { version = "3", features = ["full", "extra-traits"] } - -[dev-dependencies] -# Compile and run the public attribute examples against their consumer APIs. -# The `vitaminc` umbrella comes from crates.io, and resolves vitaminc-aead -# and this crate through the workspace's `[patch.crates-io]`. -vitaminc-aead = { path = "../vitaminc-aead" } -vitaminc = { version = "0.10.0", default-features = false, features = ["aead"] } -zeroize = { version = "1", features = ["derive"] } diff --git a/packages/vitaminc-aead-derive/src/lib.rs b/packages/vitaminc-aead-derive/src/lib.rs deleted file mode 100644 index cb5fae977..000000000 --- a/packages/vitaminc-aead-derive/src/lib.rs +++ /dev/null @@ -1,155 +0,0 @@ -//! Derive macros for [`vitaminc-aead`](https://docs.rs/vitaminc-aead): -//! [`Encrypt`] and [`Decrypt`]. -//! -//! Both are re-exported from `vitaminc_aead`, so depend on that crate -//! rather than this one: -//! -//! ```rust -//! use vitaminc_aead::{Decrypt, Encrypt}; -//! -//! #[derive(Encrypt, Decrypt)] -//! struct User { -//! name: String, -//! age: u32, -//! } -//! # let user = User { name: "Ada".into(), age: 37 }; -//! # let plan = vitaminc_aead::plan::<_, std::convert::Infallible, _>(user, ()).unwrap(); -//! # assert!(matches!(plan, vitaminc_aead::CipherText::Map(entries) if entries.len() == 2)); -//! ``` -//! -//! `#[derive(Encrypt)]` walks the struct into a sink as a map with one -//! entry per field. `#[derive(Decrypt)]` generates the map sink that builds -//! the struct back, routing each entry to the field's own sink. -//! -//! # Installation and compatibility -//! -//! Install the parent crate with `cargo add vitaminc-aead`. This macro crate -//! has no Cargo feature flags and requires Rust **1.89.0**. The macros run on -//! the compiler host; the parent crate requires `std`. -//! MSRV increases require a minor release; patch releases retain the existing -//! floor. See the [workspace policy](https://github.com/cipherstash/vitaminc#compatibility). -//! -//! License: MIT. -//! -//! # Wire shape -//! -//! A struct is encrypted as a **map**, keyed by field name. This is the -//! deliberate choice over a sequence: the encrypting sink binds each entry's -//! key into the AAD its value is sealed against (`Context::for_map_entry`), -//! so a stored ciphertext cannot have its fields renamed or swapped without -//! decryption failing. Sequence elements carry no such binding — their AAD -//! has no positional component — so two same-typed fields encoded as a -//! sequence would be freely interchangeable. -//! -//! The consequences of the map shape: -//! -//! - Field **names are part of the ciphertext contract**. Renaming a field is -//! a wire-breaking change; use `#[aead(rename = "...")]` to keep an old name. -//! - A derived struct's ciphertext is interchangeable with the equivalent -//! `HashMap` ciphertext, and with a map a host binding wrote. -//! - Tuple structs of two or more fields use the decimal field index as the -//! key (`"0"`, `"1"`, …), so they get the same per-field binding. -//! - A **newtype** struct (exactly one unnamed field) is *transparent*: it -//! encrypts and decrypts exactly as its inner type, adding nothing to the -//! ciphertext. This mirrors serde, and matches how `Protected` behaves. -//! A newtype is also a `Scalar`, one leaf, when its inner type is one. -//! So `Email(String)` is a `Scalar`. `Tags(Vec)` is not. -//! - A unit struct — or a struct with no fields — encrypts to the -//! authenticated empty-map marker. -//! -//! Field values are **not** authenticated in any particular order, so the -//! derived `Decrypt` reads keys first and matches them to fields. Decoding is -//! strict: an unknown key, a duplicate key, or a missing field is rejected. -//! -//! # Enums -//! -//! A **fieldless** enum is one `u32` leaf holding the variant's discriminant: -//! an explicit `= n`, or one more than the previous variant's, as Rust -//! assigns them. The leaf is sealed and authenticated like any other, and it -//! is fixed-width, so the ciphertext's length does not give the variant away -//! either. Decoding is strict: an int that is no variant's discriminant is -//! refused. Pin the discriminants with `= n` before storing anything, since -//! reordering variants otherwise changes them. Variants take no -//! `#[aead(...)]` attributes. -//! A fieldless enum is a `Scalar`, by value and by reference, because it -//! is one leaf. -//! -//! `#[derive(Zeroize)]` from the `zeroize` crate does not wipe a fieldless -//! enum: its `zeroize` does nothing. So a caller that wipes the value after -//! it encrypts it leaves the variant in memory. To have the variant wiped, -//! give the enum a `#[default]` variant and implement -//! `zeroize::DefaultIsZeroes` for it. Its `zeroize` then overwrites the -//! value with the default variant. -//! -//! ```rust -//! use vitaminc_aead::Encrypt; -//! use zeroize::Zeroize; -//! -//! #[derive(Encrypt, Clone, Copy, Default, Debug, PartialEq)] -//! enum Status { -//! #[default] -//! Active, -//! Suspended = 7, -//! } -//! -//! impl zeroize::DefaultIsZeroes for Status {} -//! -//! let mut status = Status::Suspended; -//! status.zeroize(); -//! assert_eq!(status, Status::Active, "zeroize writes the default variant"); -//! ``` -//! -//! Enums with fields are not supported. Their payload has no agreed layout -//! (internally or externally tagged, per-variant AAD), so model the choice -//! explicitly, as a struct with a fieldless discriminant and `Option` -//! fields. -//! -// The derive and parent crates release together. Keep parent API links on the -// version being documented without adding a normal dependency cycle. -#![deny(missing_docs)] -#![doc = concat!( - "\n[`Encrypt`]: https://docs.rs/vitaminc-aead/", env!("CARGO_PKG_VERSION"), - "/vitaminc_aead/trait.Encrypt.html\n", - "[`Decrypt`]: https://docs.rs/vitaminc-aead/", env!("CARGO_PKG_VERSION"), - "/vitaminc_aead/trait.Decrypt.html\n" -)] -#![doc = include_str!("../docs/attributes.md")] -#![deny(unsafe_code)] - -use proc_macro::TokenStream; -use syn::{parse_macro_input, DeriveInput}; - -mod attrs; -mod encrypt; -mod shape; -#[cfg(test)] -mod test_support; -mod typed_decrypt; - -#[doc = concat!("Derive [`Encrypt`](https://docs.rs/vitaminc-aead/", - env!("CARGO_PKG_VERSION"), "/vitaminc_aead/trait.Encrypt.html)")] -/// for a struct or a fieldless enum. See the [crate documentation](crate) for -/// the wire shape this produces; the attributes it accepts are reproduced -/// below. -#[doc = include_str!("../docs/attributes.md")] -#[proc_macro_derive(Encrypt, attributes(aead))] -pub fn derive_encrypt(input: TokenStream) -> TokenStream { - let input = parse_macro_input!(input as DeriveInput); - encrypt::derive(input) - .unwrap_or_else(syn::Error::into_compile_error) - .into() -} - -#[doc = concat!("Derive [`Decrypt`](https://docs.rs/vitaminc-aead/", - env!("CARGO_PKG_VERSION"), "/vitaminc_aead/trait.Decrypt.html)")] -/// for a struct or a fieldless enum: the sink that builds it. See the -/// [crate documentation](crate) for the wire shape this consumes; the -/// attributes it accepts are reproduced below. -#[doc = include_str!("../docs/attributes.md")] -#[proc_macro_derive(Decrypt, attributes(aead))] -pub fn derive_decrypt(input: TokenStream) -> TokenStream { - let input = parse_macro_input!(input as DeriveInput); - typed_decrypt::derive(input) - .unwrap_or_else(syn::Error::into_compile_error) - .into() -} diff --git a/packages/vitaminc-aead-derive/tasks.toml b/packages/vitaminc-aead-derive/tasks.toml deleted file mode 100644 index 015d61210..000000000 --- a/packages/vitaminc-aead-derive/tasks.toml +++ /dev/null @@ -1,14 +0,0 @@ -# Tasks for vitaminc-aead-derive, imported from cipherstash/vitaminc. Included from the -# root mise.toml. - -# Rustdoc with warnings as errors, which the root `doc` task fans out to. -# 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, and only -# the private build checks the links in private docs. -["doc:vitaminc-aead-derive"] -description = "Build docs for vitaminc-aead-derive with all features, public then private items (warnings are errors)" -env = { RUSTDOCFLAGS = "-D warnings" } -run = [ - "cargo doc -p vitaminc-aead-derive --no-deps --all-features", - "cargo doc -p vitaminc-aead-derive --no-deps --all-features --document-private-items", -] diff --git a/packages/vitaminc-aead/CHANGELOG.md b/packages/vitaminc-aead/CHANGELOG.md index 8be06db79..f3dc07080 100644 --- a/packages/vitaminc-aead/CHANGELOG.md +++ b/packages/vitaminc-aead/CHANGELOG.md @@ -22,6 +22,16 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). - For a fieldless enum, or for a newtype whose inner type is a `Scalar`, delete your impl. - When the inner type is not a `Scalar`, but you know that its value is one leaf, stop deriving `Encrypt`. Write `Encrypt` for the type and for its borrow by hand, with `const DEPTH: Option = depth::SCALAR;`, and keep your `Scalar` impl. +- This crate no longer has derives of its own (#2013). + `#[derive(Encrypt)]` and `#[derive(Decrypt)]` are Stack Encrypt's. + `vitaminc_aead::Encrypt` and `vitaminc_aead::Decrypt` are now the traits alone. + Import the derives from `stack_encrypt` instead, as `stack_encrypt::{Decrypt, Encrypt}`. + The attributes and the wire shape are the same. + A crate that cannot depend on `stack-encrypt` can use `stack-encrypt-derive` with `#[aead(crate = "::vitaminc_aead")]` on each derived type, as this crate's own tests do. +- The hidden `plaintext::__private` module is gone. + The items that the derived code names are in the hidden `__derive` module. + `stack_encrypt::__derive` re-exports that module. + Neither module is an API. ### Added diff --git a/packages/vitaminc-aead/Cargo.toml b/packages/vitaminc-aead/Cargo.toml index 83f2d487a..98397c8a7 100644 --- a/packages/vitaminc-aead/Cargo.toml +++ b/packages/vitaminc-aead/Cargo.toml @@ -22,7 +22,6 @@ features = ["jiff", "rust_decimal", "uuid", "hlist"] rustdoc-args = ["--cfg", "docsrs"] [dependencies] -vitaminc-aead-derive = { version = "0.10.0", path = "../vitaminc-aead-derive" } vitaminc-context = "0.10.0" vitaminc-protected = "0.10.0" vitaminc-random = "0.10.0" @@ -84,6 +83,11 @@ vitaminc-prf = "0.10.0" vitaminc-context = { version = "0.10.0", features = ["arbitrary"] } quickcheck = "1.1.0" quickcheck_macros = "1.2.0" +# Stack Encrypt's `#[derive(Encrypt)]` and `#[derive(Decrypt)]`. The tests +# derive both for types of their own. stack-encrypt depends on this crate, +# so the tests cannot depend on stack-encrypt. Each derive in the tests +# names this crate instead, with `#[aead(crate = "::vitaminc_aead")]`. +stack-encrypt-derive = { path = "../stack-encrypt-derive" } # Compile-fail tests for the derive macros' guards — see tests/derive_ui.rs. trybuild = "1.0.118" futures-executor = "0.3.31" diff --git a/packages/vitaminc-aead/README.md b/packages/vitaminc-aead/README.md index b2e785d9d..41972b5df 100644 --- a/packages/vitaminc-aead/README.md +++ b/packages/vitaminc-aead/README.md @@ -313,6 +313,8 @@ gets exactly that path — no hand-written impl is needed to keep key material w ### Deriving `Encrypt` and `Decrypt` +This crate has no derives of its own. Stack Encrypt's `#[derive(Encrypt)]` and `#[derive(Decrypt)]` implement both traits: import them from `stack_encrypt`, and see the `stack-encrypt-derive` docs. The example below points the derive at this crate with `#[aead(crate = "::vitaminc_aead")]`, because `stack-encrypt` depends on this crate. + A struct walks as a map keyed by field name, each value sealed under its key, and decodes strictly: an unknown key, a duplicate key or a missing field is refused. A fieldless enum is one int leaf holding the variant's discriminant. ```rust @@ -331,15 +333,18 @@ A struct walks as a map keyed by field name, each value sealed under its key, an # } # } # let cipher = Clear; -use vitaminc_aead::{decrypt, encrypt, CipherText, Decrypt, Encrypt}; +use stack_encrypt_derive::{Decrypt, Encrypt}; +use vitaminc_aead::{decrypt, encrypt, CipherText}; #[derive(Debug, PartialEq, Encrypt, Decrypt)] +#[aead(crate = "::vitaminc_aead")] enum Role { Admin = 1, Member = 2, } #[derive(Debug, PartialEq, Encrypt, Decrypt)] +#[aead(crate = "::vitaminc_aead")] struct User { #[aead(passthrough)] id: u64, // stored in the clear, readable without the key @@ -360,11 +365,11 @@ assert_eq!(back, User { id: 42, email: "ada@example.com".into(), role: Role::Adm # Ok::<(), Box>(()) ``` -The attributes are documented on the derives: `rename`, `passthrough`, `skip`, `take` (for a type that implements `Drop`, such as one deriving `ZeroizeOnDrop`) and `crate`. A field's type must be at least as visible as the struct, since the generated sink names it. +The docs of Stack Encrypt's derives describe the attributes: `rename`, `passthrough`, `skip`, `take`, and `crate`. `take` is for a type that implements `Drop`, such as one that derives `ZeroizeOnDrop`. A field's type must be at least as visible as the struct, since the generated sink names it. ### Custom types -A hand-written source implements [`Encrypt`] by walking itself into the sink, and a hand-written target implements [`Decrypt`] by naming a sink that builds it. Most types need neither; derive both. A source that is a thin view of something else, such as a frame or a host value, is where the trait is written by hand: +A hand-written source implements [`Encrypt`] by walking itself into the sink, and a hand-written target implements [`Decrypt`] by naming a sink that builds it. Most types need neither: derive both with Stack Encrypt's derives. Write the trait by hand for a source that is a view of another value, such as a frame or a host value: ```rust use vitaminc_aead::{MapSink, Encrypt, SeqSink, Sink}; diff --git a/packages/vitaminc-aead/src/lib.rs b/packages/vitaminc-aead/src/lib.rs index 64e044960..5a93e9f10 100644 --- a/packages/vitaminc-aead/src/lib.rs +++ b/packages/vitaminc-aead/src/lib.rs @@ -62,12 +62,6 @@ pub use plaintext::{ ParseValueKindError, Physical, Raw, Scalar, SealedNull, SeqSink, Sink, SourceError, Tee, TimeUnit, UnknownLogical, UnknownLogicalId, ValueKind, Width, }; -/// Derive [`Encrypt`] for a struct or a fieldless enum. A struct walks as -/// a map keyed by field name; a fieldless enum as an int leaf holding the -/// variant's discriminant. Pair it with [`Decrypt`] to read the value back. -/// Inlined so the `#[aead(...)]` reference renders here. -#[doc(inline)] -pub use vitaminc_aead_derive::Encrypt; // Encryption: the sink, the ciphers and the entry points. #[doc(inline)] pub use encrypt_sink::{encrypt, encrypt_async, plan, EncryptError, EncryptSink}; @@ -113,3 +107,20 @@ pub use context::ContextTag; pub use nonce::{Nonce, NonceGenerator, RandomNonceGenerator}; #[doc(inline)] pub use unspecified::Unspecified; + +/// The items that the code of Stack Encrypt's `#[derive(Encrypt)]` and +/// `#[derive(Decrypt)]` names. Not an API: `stack_encrypt` re-exports this +/// module, and the generated code reaches it as `stack_encrypt::__derive`. +/// The module contains exactly what the generated code uses, so the derives +/// reach nothing else in this crate. +#[doc(hidden)] +pub mod __derive { + pub use crate::plaintext::sources::discard_one; + pub use crate::plaintext::{ + depth, Encrypt, EncryptRef, FixedType, Int, Logical, MapSink, Physical, Scalar, Sink, Width, + }; + pub use crate::typed::{ + Clear, DecodeError, Decrypt, Either, Forward, FromScalar, Never, Nothing, Rewrap, Slot, + Wrapped, + }; +} diff --git a/packages/vitaminc-aead/src/plaintext/depth.rs b/packages/vitaminc-aead/src/plaintext/depth.rs index c8933c6c1..a257ddf2e 100644 --- a/packages/vitaminc-aead/src/plaintext/depth.rs +++ b/packages/vitaminc-aead/src/plaintext/depth.rs @@ -9,13 +9,19 @@ //! These are `const fn`s so a type's depth is worked out at compile time, //! from its fields' depths. //! +//! Stack Encrypt's `#[derive(Encrypt)]` writes a type's depth with these, +//! and fails to compile a type that nests too deeply. The examples below +//! use that derive. `stack-encrypt` depends on this crate, so they point +//! the derive at this crate with `#[aead(crate = "::vitaminc_aead")]`. +//! //! A generic type is checked where it is used at a concrete type, when that //! use is built (`cargo build`, not `cargo check`). `Holder>` nests //! one level deeper than `MAX_DEPTH`, so building a use of it fails: //! //! ```compile_fail,E0080 //! #![recursion_limit = "512"] -//! use vitaminc_aead::{plan, Encrypt}; +//! use stack_encrypt_derive::Encrypt; +//! use vitaminc_aead::plan; //! //! type V2 = Vec>; //! type V4 = V2>; @@ -26,6 +32,7 @@ //! type V128 = V64>; //! //! #[derive(Encrypt)] +//! #[aead(crate = "::vitaminc_aead")] //! struct Holder { //! value: T, //! } @@ -37,7 +44,8 @@ //! //! ``` //! #![recursion_limit = "512"] -//! use vitaminc_aead::{plan, Encrypt}; +//! use stack_encrypt_derive::Encrypt; +//! use vitaminc_aead::plan; //! //! type V2 = Vec>; //! type V4 = V2>; @@ -48,6 +56,7 @@ //! type V127 = V64>>>>>>; //! //! #[derive(Encrypt)] +//! #[aead(crate = "::vitaminc_aead")] //! struct Holder { //! value: T, //! } @@ -60,7 +69,7 @@ //! //! ```compile_fail,E0080 //! #![recursion_limit = "512"] -//! use vitaminc_aead::Encrypt; +//! use stack_encrypt_derive::Encrypt; //! //! type V2 = Vec>; //! type V4 = V2>; @@ -71,6 +80,7 @@ //! type V128 = V64>; //! //! #[derive(Encrypt)] +//! #[aead(crate = "::vitaminc_aead")] //! struct Row<'a> { //! name: &'a str, //! deep: V128, @@ -82,7 +92,7 @@ //! //! ```compile_fail,E0080 //! #![recursion_limit = "512"] -//! use vitaminc_aead::Encrypt; +//! use stack_encrypt_derive::Encrypt; //! //! type V2 = Vec>; //! type V4 = V2>; @@ -96,6 +106,7 @@ //! } //! //! #[derive(Encrypt)] +//! #[aead(crate = "::vitaminc_aead")] //! struct User { //! id: u32, //! inner: legacy::User, @@ -103,7 +114,9 @@ //! # fn main() {} //! ``` -use crate::frame::MAX_DEPTH; +// Also reachable here, so the too-deep message of a type derived with +// `#[aead(crate = "::vitaminc_aead")]` names a path that resolves. +pub use crate::frame::MAX_DEPTH; /// A scalar: nothing below it. pub const SCALAR: Option = Some(0); diff --git a/packages/vitaminc-aead/src/plaintext/mod.rs b/packages/vitaminc-aead/src/plaintext/mod.rs index e61fc69b6..3f5f3161e 100644 --- a/packages/vitaminc-aead/src/plaintext/mod.rs +++ b/packages/vitaminc-aead/src/plaintext/mod.rs @@ -17,14 +17,15 @@ //! [`Logical`] type, rather than a method per kind. See [`kinds`]. //! //! `Sink` is implemented inside vitaminc and its host bindings. Application -//! code implements `Encrypt`, usually by derive. +//! code implements `Encrypt`, usually with Stack Encrypt's derive, +//! `#[derive(stack_encrypt::Encrypt)]`. pub mod depth; #[cfg(test)] mod encrypt_ref_tests; pub mod kinds; mod path; -mod sources; +pub(crate) mod sources; mod tee; mod value_kind; @@ -38,11 +39,6 @@ pub use path::render; pub use path::{Path, Step}; pub use sources::{Bytes, Raw}; -/// What `#[derive(Encrypt)]`'s expansion needs by path. Not an API. -#[doc(hidden)] -pub mod __private { - pub use super::sources::discard_one; -} pub use tee::Tee; pub use value_kind::{ParseValueKindError, SealedNull, ValueKind}; @@ -216,9 +212,9 @@ impl Encrypt for &Lent<'_, T> { /// that bounds on `Scalar` asks for a value that is present, and decides /// for itself how to seal an absent one. /// -/// `#[derive(Encrypt)]` implements `Scalar`, by value and by reference, for -/// a derived type that encrypts as one leaf. So you write no impl for such -/// a type. +/// Stack Encrypt's `#[derive(Encrypt)]` implements `Scalar`, by value and +/// by reference, for a derived type that encrypts as one leaf. So you write +/// no impl for such a type. /// /// - A newtype is a struct with exactly one unnamed field. A newtype is a /// `Scalar` when its inner type is one. So `struct Email(String)` is a @@ -229,9 +225,13 @@ impl Encrypt for &Lent<'_, T> { /// - A struct with fields is a map, so it is never a `Scalar`. /// /// ``` -/// use vitaminc_aead::{Encrypt, Scalar}; +/// use stack_encrypt_derive::Encrypt; +/// use vitaminc_aead::Scalar; /// /// #[derive(Encrypt)] +/// // `stack-encrypt` depends on this crate, so this example points the +/// // derive at this crate instead. +/// #[aead(crate = "::vitaminc_aead")] /// struct Email(String); /// /// fn seals_one_leaf(value: S) -> S { diff --git a/packages/vitaminc-aead/src/typed.rs b/packages/vitaminc-aead/src/typed.rs index 4ac8ae934..0c1612cc2 100644 --- a/packages/vitaminc-aead/src/typed.rs +++ b/packages/vitaminc-aead/src/typed.rs @@ -31,7 +31,7 @@ //! protected target is built inside its wrapper from the start, so a walk //! that fails part way wipes whatever it had already decoded. //! -//! A struct's sink is what `#[derive(Decrypt)]` generates, out of the +//! A struct's sink is what Stack Encrypt's `#[derive(Decrypt)]` generates, out of the //! pieces here: a map sink with one slot per field, whose `entry` hands //! back [`Either`] of the fields' own sinks ([`Forward`] for a sealed //! field, [`Clear`] for a passthrough one). A newtype's sink is its inner @@ -58,13 +58,6 @@ use crate::seal::{AsyncCipher, Cipher, Node}; use crate::walk::{decrypt_into, decrypt_into_async, DecryptError}; use crate::IntoAad; -/// Derive [`Decrypt`] for a struct or a fieldless enum: the sink that builds -/// it. A struct reads a map keyed by field name; a fieldless enum reads an -/// int leaf holding the variant's discriminant. Takes the same -/// `#[aead(...)]` attributes as [`Encrypt`](macro@crate::Encrypt). -#[doc(inline)] -pub use vitaminc_aead_derive::Decrypt; - /// Why a typed target refused what it was given. /// /// Non-exhaustive, so a target can add refusals without a breaking change. @@ -318,6 +311,7 @@ impl Decrypt for T { /// - A newtype or an `Option` of one of those. /// /// ``` +/// use stack_encrypt_derive::Decrypt; /// use vitaminc_aead::{Decrypt, Encrypt, OwnedFrame, ScalarTarget}; /// use vitaminc_protected::Protected; /// @@ -334,6 +328,9 @@ impl Decrypt for T { /// /// // A derived newtype of a scalar is a `ScalarTarget` with no extra code. /// #[derive(Decrypt, Debug, PartialEq)] +/// // `stack-encrypt` depends on this crate, so this example points the +/// // derive at this crate instead. +/// #[aead(crate = "::vitaminc_aead")] /// struct Email(String); /// /// let email = "ada@example.com".visit(opens_one_leaf::())?; @@ -382,9 +379,9 @@ mod sealed { /// crate that defines a type and the sink of that type, where the sink /// does not implement `TakesScalar`. The compiler can prove that the /// blanket impl does not apply to that type. So the compiler accepts a - /// second impl of `ScalarTarget` for the type. The sink that - /// `#[derive(Decrypt)]` generates for a struct with named fields is such - /// a sink. + /// second impl of `ScalarTarget` for the type. The sink that Stack + /// Encrypt's `#[derive(Decrypt)]` generates for a struct with named + /// fields is such a sink. /// /// `SinkTakesScalar` is a supertrait of `ScalarTarget`. Code outside this /// module cannot name `SinkTakesScalar`, so that code cannot implement @@ -416,9 +413,9 @@ mod sealed { /// - [`OwnedFrameSink`](crate::frame::OwnedFrameSink). /// /// These sinks do not implement it, because each needs a container: -/// [`List`], [`Dict`], and the protected list. The sink that -/// `#[derive(Decrypt)]` generates for a struct with named fields does not -/// implement it either. +/// [`List`], [`Dict`], and the protected list. The sink that Stack +/// Encrypt's `#[derive(Decrypt)]` generates for a struct with named fields +/// does not implement it either. /// /// So a target whose sink is in the first list needs no extra code. The sink /// of a derived newtype is [`Wrapped`] over the sink of the inner type. That diff --git a/packages/vitaminc-aead/tests/derive_by_reference.rs b/packages/vitaminc-aead/tests/derive_by_reference.rs index adc7e19cf..785a2ef9b 100644 --- a/packages/vitaminc-aead/tests/derive_by_reference.rs +++ b/packages/vitaminc-aead/tests/derive_by_reference.rs @@ -6,6 +6,9 @@ use std::collections::BTreeMap; +// Stack Encrypt's derives. stack-encrypt depends on this crate, so each +// derive here names this crate with `#[aead(crate = "::vitaminc_aead")]`. +use stack_encrypt_derive::Encrypt; use vitaminc_aead::{to_frame, Encrypt, EncryptRef}; use vitaminc_protected::Controlled; @@ -19,6 +22,7 @@ fn lent(value: &T) -> Vec { } #[derive(Clone, Encrypt)] +#[aead(crate = "::vitaminc_aead")] struct Bag { items: Vec, maybe: Option, @@ -39,11 +43,13 @@ fn a_generic_struct_walks_by_reference_with_its_parameter_in_containers() { } #[derive(Encrypt)] +#[aead(crate = "::vitaminc_aead")] struct Named<'a> { name: &'a str, } #[derive(Encrypt)] +#[aead(crate = "::vitaminc_aead")] struct Roster<'a> { items: Vec>, maybe: Option>, @@ -87,6 +93,7 @@ impl Encrypt for &Label { } #[derive(Encrypt)] +#[aead(crate = "::vitaminc_aead")] struct Labelled { #[aead(passthrough)] label: Label, @@ -94,6 +101,7 @@ struct Labelled { } #[derive(Encrypt)] +#[aead(crate = "::vitaminc_aead")] struct Tagged { #[aead(passthrough)] tag: T, @@ -132,6 +140,7 @@ fn a_passthrough_field_need_only_be_a_source_by_reference() { } #[derive(Encrypt)] +#[aead(crate = "::vitaminc_aead")] struct Borrowing<'a> { name: vitaminc_aead::Lent<'a, String>, } @@ -141,6 +150,7 @@ struct Borrowing<'a> { #[test] fn a_lent_field_walks_as_what_it_lends() { #[derive(Encrypt)] + #[aead(crate = "::vitaminc_aead")] struct Owning { name: String, } diff --git a/packages/vitaminc-aead/tests/derive_depth.rs b/packages/vitaminc-aead/tests/derive_depth.rs index 61e0cde67..ee88eda6d 100644 --- a/packages/vitaminc-aead/tests/derive_depth.rs +++ b/packages/vitaminc-aead/tests/derive_depth.rs @@ -13,6 +13,9 @@ use std::collections::{BTreeMap, HashMap}; +// Stack Encrypt's derives. stack-encrypt depends on this crate, so each +// derive here names this crate with `#[aead(crate = "::vitaminc_aead")]`. +use stack_encrypt_derive::Encrypt; use vitaminc_aead::frame::MAX_DEPTH; use vitaminc_aead::plaintext::depth; use vitaminc_aead::{plan, Encrypt, EncryptError, MapSink, Sink, Unencryptable}; @@ -90,6 +93,7 @@ fn the_walk_agrees_with_depth_at_the_limit_for_sequences() { /// A derived struct is a map: one level for the struct, then its deepest /// field. #[derive(Encrypt)] +#[aead(crate = "::vitaminc_aead")] struct JustFits { shallow: u32, deep: V127, @@ -108,6 +112,7 @@ fn a_derived_struct_is_one_deeper_than_its_deepest_field() { /// A passthrough field's frame starts one level below the passthrough node, /// so it counts one deeper than the same field encrypted. #[derive(Encrypt)] +#[aead(crate = "::vitaminc_aead")] struct PassesThrough { sealed: u32, #[aead(passthrough)] @@ -143,14 +148,17 @@ fn the_walk_agrees_with_depth_at_the_limit_for_passthrough() { /// A newtype is transparent, a fieldless enum is one leaf, and a skipped /// field is not walked, so none of them adds a level. #[derive(Encrypt)] +#[aead(crate = "::vitaminc_aead")] struct Wrapper(Vec); #[derive(Encrypt)] +#[aead(crate = "::vitaminc_aead")] enum Status { Active, } #[derive(Encrypt)] +#[aead(crate = "::vitaminc_aead")] struct Skips { kept: u32, #[aead(skip)] @@ -168,6 +176,7 @@ fn newtypes_enums_and_skipped_fields_add_nothing() { /// A generic type's depth follows its parameter. #[derive(Encrypt)] +#[aead(crate = "::vitaminc_aead")] struct Holder { value: T, } @@ -181,12 +190,14 @@ fn a_generic_type_takes_its_depth_from_its_parameter() { /// A type that names itself has no fixed depth; the derive sees that and /// leaves `DEPTH` as `None` rather than writing a cycle. #[derive(Encrypt)] +#[aead(crate = "::vitaminc_aead")] struct Tree { label: u32, children: Vec, } #[derive(Encrypt)] +#[aead(crate = "::vitaminc_aead")] struct List { head: u32, tail: Option>, @@ -195,12 +206,14 @@ struct List { /// Mutual recursion goes through another type, which the derive cannot see /// into, so both sides say so. #[derive(Encrypt)] +#[aead(crate = "::vitaminc_aead")] #[aead(recursive)] struct Even { next: Vec, } #[derive(Encrypt)] +#[aead(crate = "::vitaminc_aead")] #[aead(recursive)] struct Odd { next: Vec, @@ -209,6 +222,7 @@ struct Odd { /// A recursive type inside an ordinary one makes the outer depth unknown /// too, so the check passes it to the walk. #[derive(Encrypt)] +#[aead(crate = "::vitaminc_aead")] struct Forest { trees: Vec, } diff --git a/packages/vitaminc-aead/tests/derive_sink.rs b/packages/vitaminc-aead/tests/derive_sink.rs index 126fbcf00..3363241dd 100644 --- a/packages/vitaminc-aead/tests/derive_sink.rs +++ b/packages/vitaminc-aead/tests/derive_sink.rs @@ -5,6 +5,9 @@ use std::collections::BTreeMap; +// Stack Encrypt's derives. stack-encrypt depends on this crate, so each +// derive here names this crate with `#[aead(crate = "::vitaminc_aead")]`. +use stack_encrypt_derive::{Decrypt, Encrypt}; use vitaminc_aead::{ decrypt, encrypt, Bytes, Context, DecodeError, Decrypt, DecryptError, Encrypt, EncryptRef, FixedType, Int, IntoAad, Logical, MapSink, Physical, Raw, SeqSink, Sink, SourceError, @@ -170,6 +173,7 @@ fn refusal(r: Result>) -> DecodeError { // The ADR's section 1 example, derived and by hand. #[derive(Encrypt, Decrypt, Debug, PartialEq, Clone, zeroize::Zeroize)] +#[aead(crate = "::vitaminc_aead")] struct User { email: String, age: u32, @@ -237,6 +241,7 @@ fn a_derived_struct_round_trips() { } #[derive(Encrypt, Decrypt, Debug, PartialEq, Clone)] +#[aead(crate = "::vitaminc_aead")] struct Account { owner: User, aliases: Vec, @@ -387,6 +392,7 @@ fn a_repeated_key_is_refused_by_the_sink_itself() { // Passthrough, skip and take. #[derive(Encrypt, Decrypt, Debug, PartialEq, Clone)] +#[aead(crate = "::vitaminc_aead")] struct Row { #[aead(passthrough)] tenant: String, @@ -492,6 +498,7 @@ fn an_entry_under_a_skipped_key_is_refused() { /// out; `take` swaps each for its default instead, and the empty value is /// wiped harmlessly when `self` drops. #[derive(Encrypt, Decrypt, ZeroizeOnDrop, Debug, PartialEq)] +#[aead(crate = "::vitaminc_aead")] struct Secret { #[aead(take)] token: String, @@ -500,6 +507,7 @@ struct Secret { } #[derive(Encrypt, Decrypt, ZeroizeOnDrop, Debug, PartialEq)] +#[aead(crate = "::vitaminc_aead")] struct Token(#[aead(take)] String); #[test] @@ -518,6 +526,7 @@ fn take_lets_a_drop_type_derive() { /// A passthrough field is lent to the sink in place, so a `Drop` type needs /// no `take` on it, and its type needs no `Default`. #[derive(Encrypt, Decrypt, ZeroizeOnDrop, Debug, PartialEq)] +#[aead(crate = "::vitaminc_aead")] struct TenantSecret { #[aead(passthrough)] tenant: NoDefault, @@ -527,6 +536,7 @@ struct TenantSecret { /// A passthrough column type with no `Default`, which `take` would need. #[derive(Encrypt, Decrypt, Debug, PartialEq, zeroize::Zeroize)] +#[aead(crate = "::vitaminc_aead")] struct NoDefault(u32); #[test] @@ -547,18 +557,23 @@ fn a_drop_type_lends_a_passthrough_field_without_take() { // Newtypes, tuple structs, empty structs and enums. #[derive(Encrypt, Decrypt, Debug, PartialEq)] +#[aead(crate = "::vitaminc_aead")] struct Wrapper(Vec); #[derive(Encrypt, Decrypt, Debug, PartialEq)] +#[aead(crate = "::vitaminc_aead")] struct Pair(String, u32); #[derive(Encrypt, Decrypt, Debug, PartialEq)] +#[aead(crate = "::vitaminc_aead")] struct Marker; #[derive(Encrypt, Decrypt, Debug, PartialEq)] +#[aead(crate = "::vitaminc_aead")] struct Braced {} #[derive(Encrypt, Decrypt, Debug, PartialEq, Clone, Copy)] +#[aead(crate = "::vitaminc_aead")] enum Status { Active, Suspended = 7, @@ -669,6 +684,7 @@ fn every_variant_seals_to_the_same_length() { // `Either` chain, for every kind of child. #[derive(Encrypt, Decrypt, Debug, PartialEq, Clone)] +#[aead(crate = "::vitaminc_aead")] struct Mixed { first: u32, second: BTreeMap, @@ -678,6 +694,7 @@ struct Mixed { } #[derive(Encrypt, Decrypt, Debug, PartialEq, Clone)] +#[aead(crate = "::vitaminc_aead")] struct Named(BTreeMap>); #[test] @@ -720,6 +737,7 @@ fn a_newtype_over_a_container_is_transparent_and_refuses_a_passthrough() { // Generics and the crate attribute. #[derive(Encrypt, Decrypt, Debug, PartialEq)] +#[aead(crate = "::vitaminc_aead")] struct Holder { value: T, bytes: [u8; N], @@ -747,7 +765,7 @@ mod umbrella { } } -#[derive(umbrella::aead::Encrypt, umbrella::aead::Decrypt, Debug, PartialEq)] +#[derive(Encrypt, Decrypt, Debug, PartialEq)] #[aead(crate = "crate::umbrella::aead")] struct Renamed { value: u32, @@ -789,6 +807,7 @@ fn the_by_reference_walk_makes_the_same_calls_as_the_by_value_walk() { /// too, and walks the same by reference as by value: a borrowed field is /// then visited as `&&'a str`, `&Option<&'a str>` and so on. #[derive(Encrypt, Clone)] +#[aead(crate = "::vitaminc_aead")] struct NewUser<'a> { email: &'a str, nickname: Option<&'a str>, @@ -849,6 +868,7 @@ impl Encrypt for &Counted { } #[derive(Encrypt, zeroize::Zeroize)] +#[aead(crate = "::vitaminc_aead")] struct Three { a: Counted, b: Counted, @@ -986,6 +1006,7 @@ fn a_struct_inside_protected_stays_wrapped_and_is_wiped_whole() { // straight back into `Protected` on the way out. #[derive(Encrypt, Decrypt)] +#[aead(crate = "::vitaminc_aead")] struct Keyed { key: Protected<[u8; 4]>, label: String, @@ -1008,6 +1029,7 @@ fn protected_fields_stay_wrapped() { // unchanged: the generated sink repeats the struct's generics as written. #[derive(Encrypt, Decrypt, Debug, PartialEq, Clone)] +#[aead(crate = "::vitaminc_aead")] struct Window { start: i64, } @@ -1026,12 +1048,14 @@ fn a_const_generic_of_a_non_usize_type_round_trips() { #[cfg(feature = "jiff")] #[derive(Encrypt, Decrypt, Debug, PartialEq)] +#[aead(crate = "::vitaminc_aead")] struct Stamped { at: vitaminc_aead::Timestamp, } #[cfg(feature = "jiff")] #[derive(Encrypt, Decrypt, Debug, PartialEq, Clone)] +#[aead(crate = "::vitaminc_aead")] struct EventAsJiff { at: jiff::Timestamp, } @@ -1055,6 +1079,7 @@ fn a_timestamp_field_round_trips_and_reads_as_a_jiff_timestamp() { #[cfg(all(feature = "jiff", feature = "rust_decimal", feature = "uuid"))] #[derive(Encrypt, Decrypt, Debug, PartialEq)] +#[aead(crate = "::vitaminc_aead")] struct Wiped { day: vitaminc_aead::Date, price: vitaminc_aead::Decimal, @@ -1064,6 +1089,7 @@ struct Wiped { #[cfg(all(feature = "jiff", feature = "rust_decimal", feature = "uuid"))] #[derive(Encrypt, Decrypt, Debug, PartialEq)] +#[aead(crate = "::vitaminc_aead")] struct Foreign { day: jiff::civil::Date, price: rust_decimal::Decimal, @@ -1103,6 +1129,7 @@ fn wipeable_scalar_fields_round_trip_and_read_as_their_foreign_types() { #[cfg(all(feature = "jiff", feature = "rust_decimal", feature = "uuid"))] #[derive(Encrypt, Decrypt, Debug, PartialEq)] +#[aead(crate = "::vitaminc_aead")] struct MaybeWiped { day: Option, price: Option, @@ -1111,6 +1138,7 @@ struct MaybeWiped { #[cfg(all(feature = "jiff", feature = "rust_decimal", feature = "uuid"))] #[derive(Encrypt, Decrypt, Debug, PartialEq)] +#[aead(crate = "::vitaminc_aead")] struct MaybeForeign { day: Option, price: Option, diff --git a/packages/vitaminc-aead/tests/protected_ref.rs b/packages/vitaminc-aead/tests/protected_ref.rs index 639691857..194fec8a6 100644 --- a/packages/vitaminc-aead/tests/protected_ref.rs +++ b/packages/vitaminc-aead/tests/protected_ref.rs @@ -4,6 +4,9 @@ //! back. Sealing goes through a cipher that keeps the plaintext in the //! clear, so a leaf's length is its plaintext's. +// Stack Encrypt's derives. stack-encrypt depends on this crate, so each +// derive here names this crate with `#[aead(crate = "::vitaminc_aead")]`. +use stack_encrypt_derive::{Decrypt, Encrypt}; use vitaminc_aead::{decrypt, encrypt, tags, CipherText, Context, Decrypt, Encrypt, Node}; use vitaminc_protected::{AsProtectedRef, Controlled, Protected, ProtectedRef}; @@ -124,12 +127,14 @@ fn a_fixed_width_value_behind_a_protected_ref_hides_absence() { } #[derive(Encrypt)] +#[aead(crate = "::vitaminc_aead")] struct Profile<'a> { name: ProtectedRef<'a, String>, born: Option>, } #[derive(Decrypt, Debug, PartialEq)] +#[aead(crate = "::vitaminc_aead")] struct ProfileRead { name: String, born: Option, diff --git a/packages/vitaminc-aead/tests/scalar.rs b/packages/vitaminc-aead/tests/scalar.rs index 8f2a0a128..ed1af123a 100644 --- a/packages/vitaminc-aead/tests/scalar.rs +++ b/packages/vitaminc-aead/tests/scalar.rs @@ -15,6 +15,9 @@ use std::convert::Infallible; +// Stack Encrypt's derives. stack-encrypt depends on this crate, so each +// derive here names this crate with `#[aead(crate = "::vitaminc_aead")]`. +use stack_encrypt_derive::Encrypt; use vitaminc_aead::plaintext::{depth, Bytes, Raw}; use vitaminc_aead::{plan, CipherText, Encrypt, Int, Physical, Scalar}; use vitaminc_protected::{AsProtectedRef, Protected, ProtectedRef}; @@ -114,18 +117,23 @@ fn an_empty_text_or_byte_value_is_still_one_leaf() { /// implements `Scalar` for it too. These types have no `Scalar` impl /// written by hand. #[derive(Encrypt, zeroize::Zeroize)] +#[aead(crate = "::vitaminc_aead")] struct Email(String); #[derive(Encrypt, zeroize::Zeroize)] +#[aead(crate = "::vitaminc_aead")] struct Contact(Email); #[derive(Encrypt)] +#[aead(crate = "::vitaminc_aead")] struct Wrapper(T); #[derive(Encrypt)] +#[aead(crate = "::vitaminc_aead")] struct Name<'a>(&'a str); #[derive(Encrypt)] +#[aead(crate = "::vitaminc_aead")] enum Status { Active, } diff --git a/packages/vitaminc-aead/tests/scalar_target.rs b/packages/vitaminc-aead/tests/scalar_target.rs index b5553a41c..89b91c484 100644 --- a/packages/vitaminc-aead/tests/scalar_target.rs +++ b/packages/vitaminc-aead/tests/scalar_target.rs @@ -14,6 +14,9 @@ //! and a protected sequence. The same tests check that no one can implement //! the trait for such a target directly. +// Stack Encrypt's derives. stack-encrypt depends on this crate, so each +// derive here names this crate with `#[aead(crate = "::vitaminc_aead")]`. +use stack_encrypt_derive::{Decrypt, Encrypt}; use vitaminc_aead::plaintext::Raw; use vitaminc_aead::{ Decrypt, Encrypt, FixedType, FromScalar, Logical, OwnedFrame, Physical, ScalarTarget, @@ -156,6 +159,7 @@ fn a_hand_written_scalar_target_carries_the_marker() { #[test] fn a_derived_newtype_of_a_scalar_target_is_one_as_it_is() { #[derive(Decrypt, Debug, PartialEq)] + #[aead(crate = "::vitaminc_aead")] struct Email(String); assert_eq!( built_by_one_scalar::("ada@example.com"), @@ -164,6 +168,7 @@ fn a_derived_newtype_of_a_scalar_target_is_one_as_it_is() { ); #[derive(Decrypt, Debug, PartialEq)] + #[aead(crate = "::vitaminc_aead")] struct UserId(u64); assert_eq!( built_by_one_scalar::(42u64), @@ -173,6 +178,7 @@ fn a_derived_newtype_of_a_scalar_target_is_one_as_it_is() { // A newtype of a newtype, and a nullable newtype. #[derive(Decrypt, Debug, PartialEq)] + #[aead(crate = "::vitaminc_aead")] struct Primary(Email); assert_eq!( built_by_one_scalar::("ada@example.com"), @@ -186,6 +192,7 @@ fn a_derived_newtype_of_a_scalar_target_is_one_as_it_is() { ); #[derive(Decrypt, Debug, PartialEq)] + #[aead(crate = "::vitaminc_aead")] struct MaybeId(Option); assert_eq!( built_by_one_scalar::(null()), @@ -205,6 +212,7 @@ fn a_protected_newtype_is_a_scalar_target_through_wrap() { use zeroize::Zeroize; #[derive(Decrypt, Zeroize)] + #[aead(crate = "::vitaminc_aead")] struct Email(String); impl DecryptProtected for Email { type ProtectedSink = Wrap<::Sink>; @@ -274,6 +282,7 @@ fn a_hand_written_sink_opts_in_by_its_marker() { #[test] fn a_derived_fieldless_enum_carries_the_marker() { #[derive(Encrypt, Decrypt, Debug, PartialEq, Clone, Copy)] + #[aead(crate = "::vitaminc_aead")] enum Status { Active = 1, Closed = 2, diff --git a/packages/vitaminc-aead/tests/typed_null.rs b/packages/vitaminc-aead/tests/typed_null.rs index 8adc3348a..fe0ee5778 100644 --- a/packages/vitaminc-aead/tests/typed_null.rs +++ b/packages/vitaminc-aead/tests/typed_null.rs @@ -5,6 +5,9 @@ //! leaf's length is its plaintext's; AES-GCM adds the same nonce and tag //! to every leaf. +// Stack Encrypt's derives. stack-encrypt depends on this crate, so each +// derive here names this crate with `#[aead(crate = "::vitaminc_aead")]`. +use stack_encrypt_derive::{Decrypt, Encrypt}; use vitaminc_aead::{ decrypt, decrypt_to_frame, encrypt, tags, to_frame, CipherText, Context, DecodeError, Decrypt, DecryptError, Encrypt, FixedType, Frame, IntoAad, Node, Width, @@ -125,12 +128,14 @@ fn a_decimal_hides_absence_whatever_its_scale() { } #[derive(Encrypt, Decrypt, Debug, PartialEq, Clone, Copy)] +#[aead(crate = "::vitaminc_aead")] enum Status { Active, Suspended = 7, } #[derive(Encrypt, Decrypt, Debug, PartialEq, Clone, Copy)] +#[aead(crate = "::vitaminc_aead")] struct Age(u32); #[test] @@ -156,6 +161,7 @@ fn a_derived_enum_and_newtype_hide_absence() { } #[derive(Encrypt, Decrypt, Debug, PartialEq, Clone)] +#[aead(crate = "::vitaminc_aead")] struct Profile { name: String, born: Option, @@ -226,6 +232,7 @@ fn a_frame_reads_a_typed_null_and_writes_the_plain_null() { } #[derive(Encrypt, Decrypt, Debug, PartialEq, Clone)] +#[aead(crate = "::vitaminc_aead")] struct Row { #[aead(passthrough)] rank: Option, diff --git a/packages/vitaminc-aead/tests/ui/derive/sink_data_enum.rs b/packages/vitaminc-aead/tests/ui/derive/sink_data_enum.rs index bb8c91431..b1f22956b 100644 --- a/packages/vitaminc-aead/tests/ui/derive/sink_data_enum.rs +++ b/packages/vitaminc-aead/tests/ui/derive/sink_data_enum.rs @@ -1,10 +1,13 @@ //! A variant with fields has no agreed payload layout, so the sink derives //! accept only fieldless enums and say so. -use vitaminc_aead::Decrypt; -use vitaminc_aead::Encrypt; +// Stack Encrypt's derives. stack-encrypt depends on this crate, so each +// derive here names this crate with `#[aead(crate = "::vitaminc_aead")]`. +use stack_encrypt_derive::Decrypt; +use stack_encrypt_derive::Encrypt; #[derive(Encrypt, Decrypt)] +#[aead(crate = "::vitaminc_aead")] enum Choice { Text(String), Number(u32), diff --git a/packages/vitaminc-aead/tests/ui/derive/sink_data_enum.stderr b/packages/vitaminc-aead/tests/ui/derive/sink_data_enum.stderr index 76457a773..11f7bdfeb 100644 --- a/packages/vitaminc-aead/tests/ui/derive/sink_data_enum.stderr +++ b/packages/vitaminc-aead/tests/ui/derive/sink_data_enum.stderr @@ -1,5 +1,5 @@ error: only fieldless enums can be derived: a variant with fields has no agreed layout for its payload. Model it as a struct with an enum discriminant and `Option` fields instead. - --> tests/ui/derive/sink_data_enum.rs:9:5 - | -9 | Text(String), - | ^^^^ + --> tests/ui/derive/sink_data_enum.rs:12:5 + | +12 | Text(String), + | ^^^^ diff --git a/packages/vitaminc-aead/tests/ui/derive/sink_discriminant_too_wide.rs b/packages/vitaminc-aead/tests/ui/derive/sink_discriminant_too_wide.rs index e960902d9..f1a147752 100644 --- a/packages/vitaminc-aead/tests/ui/derive/sink_discriminant_too_wide.rs +++ b/packages/vitaminc-aead/tests/ui/derive/sink_discriminant_too_wide.rs @@ -1,9 +1,12 @@ //! The wire holds a `u32`, so a discriminant has to be an unsigned integer //! literal that fits one. -use vitaminc_aead::Encrypt; +// Stack Encrypt's derives. stack-encrypt depends on this crate, so each +// derive here names this crate with `#[aead(crate = "::vitaminc_aead")]`. +use stack_encrypt_derive::Encrypt; #[derive(Encrypt)] +#[aead(crate = "::vitaminc_aead")] enum Status { Active = -1, Suspended, diff --git a/packages/vitaminc-aead/tests/ui/derive/sink_discriminant_too_wide.stderr b/packages/vitaminc-aead/tests/ui/derive/sink_discriminant_too_wide.stderr index e9f0af646..579b1aa90 100644 --- a/packages/vitaminc-aead/tests/ui/derive/sink_discriminant_too_wide.stderr +++ b/packages/vitaminc-aead/tests/ui/derive/sink_discriminant_too_wide.stderr @@ -1,5 +1,5 @@ error: an explicit discriminant must be an unsigned integer literal that fits in 32 bits, since that is the width the variant is sealed at - --> tests/ui/derive/sink_discriminant_too_wide.rs:8:14 - | -8 | Active = -1, - | ^^ + --> tests/ui/derive/sink_discriminant_too_wide.rs:11:14 + | +11 | Active = -1, + | ^^ diff --git a/packages/vitaminc-aead/tests/ui/derive/sink_duplicate_discriminant.rs b/packages/vitaminc-aead/tests/ui/derive/sink_duplicate_discriminant.rs index e260d3eaa..bb4b70812 100644 --- a/packages/vitaminc-aead/tests/ui/derive/sink_duplicate_discriminant.rs +++ b/packages/vitaminc-aead/tests/ui/derive/sink_duplicate_discriminant.rs @@ -1,8 +1,11 @@ //! Two variants with one discriminant would be stored as the same value. -use vitaminc_aead::Decrypt; +// Stack Encrypt's derives. stack-encrypt depends on this crate, so each +// derive here names this crate with `#[aead(crate = "::vitaminc_aead")]`. +use stack_encrypt_derive::Decrypt; #[derive(Decrypt)] +#[aead(crate = "::vitaminc_aead")] enum Status { Active = 1, Suspended = 0, diff --git a/packages/vitaminc-aead/tests/ui/derive/sink_duplicate_discriminant.stderr b/packages/vitaminc-aead/tests/ui/derive/sink_duplicate_discriminant.stderr index 5bb45bb69..35beea481 100644 --- a/packages/vitaminc-aead/tests/ui/derive/sink_duplicate_discriminant.stderr +++ b/packages/vitaminc-aead/tests/ui/derive/sink_duplicate_discriminant.stderr @@ -1,17 +1,17 @@ error: duplicate discriminant `1`: two variants would be stored as the same value - --> tests/ui/derive/sink_duplicate_discriminant.rs:9:5 - | -9 | Closed, - | ^^^^^^ + --> tests/ui/derive/sink_duplicate_discriminant.rs:12:5 + | +12 | Closed, + | ^^^^^^ error[E0081]: discriminant value `1` assigned more than once - --> tests/ui/derive/sink_duplicate_discriminant.rs:6:1 - | -6 | enum Status { - | ^^^^^^^^^^^ -7 | Active = 1, - | - `1` assigned here -8 | Suspended = 0, - | --------- discriminant for `Closed` incremented from this startpoint (`Suspended` + 1 variant later => `Closed` = 1) -9 | Closed, - | ------ `1` assigned here + --> tests/ui/derive/sink_duplicate_discriminant.rs:9:1 + | + 9 | enum Status { + | ^^^^^^^^^^^ +10 | Active = 1, + | - `1` assigned here +11 | Suspended = 0, + | --------- discriminant for `Closed` incremented from this startpoint (`Suspended` + 1 variant later => `Closed` = 1) +12 | Closed, + | ------ `1` assigned here diff --git a/packages/vitaminc-aead/tests/ui/derive/sink_duplicate_map_key.rs b/packages/vitaminc-aead/tests/ui/derive/sink_duplicate_map_key.rs index 30719119c..90781e8f6 100644 --- a/packages/vitaminc-aead/tests/ui/derive/sink_duplicate_map_key.rs +++ b/packages/vitaminc-aead/tests/ui/derive/sink_duplicate_map_key.rs @@ -1,9 +1,12 @@ // Two fields under one key would overwrite each other on encrypt and be // rejected as a duplicate on decrypt — an unreadable ciphertext with no error // until read time. -use vitaminc_aead::{Decrypt, Encrypt}; +// Stack Encrypt's derives. stack-encrypt depends on this crate, so each +// derive here names this crate with `#[aead(crate = "::vitaminc_aead")]`. +use stack_encrypt_derive::{Decrypt, Encrypt}; #[derive(Encrypt, Decrypt)] +#[aead(crate = "::vitaminc_aead")] struct Clash { a: String, #[aead(rename = "a")] diff --git a/packages/vitaminc-aead/tests/ui/derive/sink_duplicate_map_key.stderr b/packages/vitaminc-aead/tests/ui/derive/sink_duplicate_map_key.stderr index 8fb5c4a82..d3a9dd52d 100644 --- a/packages/vitaminc-aead/tests/ui/derive/sink_duplicate_map_key.stderr +++ b/packages/vitaminc-aead/tests/ui/derive/sink_duplicate_map_key.stderr @@ -1,5 +1,5 @@ error: duplicate map key `a`: two fields would be encrypted under the same key - --> tests/ui/derive/sink_duplicate_map_key.rs:7:8 - | -7 | struct Clash { - | ^^^^^ + --> tests/ui/derive/sink_duplicate_map_key.rs:10:8 + | +10 | struct Clash { + | ^^^^^ diff --git a/packages/vitaminc-aead/tests/ui/derive/sink_empty_enum.rs b/packages/vitaminc-aead/tests/ui/derive/sink_empty_enum.rs index 506079c9f..2c8fc8b16 100644 --- a/packages/vitaminc-aead/tests/ui/derive/sink_empty_enum.rs +++ b/packages/vitaminc-aead/tests/ui/derive/sink_empty_enum.rs @@ -1,8 +1,11 @@ //! An enum with no variants has no value to seal. -use vitaminc_aead::Encrypt; +// Stack Encrypt's derives. stack-encrypt depends on this crate, so each +// derive here names this crate with `#[aead(crate = "::vitaminc_aead")]`. +use stack_encrypt_derive::Encrypt; #[derive(Encrypt)] +#[aead(crate = "::vitaminc_aead")] enum Never {} fn main() {} diff --git a/packages/vitaminc-aead/tests/ui/derive/sink_empty_enum.stderr b/packages/vitaminc-aead/tests/ui/derive/sink_empty_enum.stderr index 7edd34f30..f3966722e 100644 --- a/packages/vitaminc-aead/tests/ui/derive/sink_empty_enum.stderr +++ b/packages/vitaminc-aead/tests/ui/derive/sink_empty_enum.stderr @@ -1,5 +1,5 @@ error: cannot be derived for an enum with no variants: there is no value to seal - --> tests/ui/derive/sink_empty_enum.rs:6:6 + --> tests/ui/derive/sink_empty_enum.rs:9:6 | -6 | enum Never {} +9 | enum Never {} | ^^^^^ diff --git a/packages/vitaminc-aead/tests/ui/derive/sink_nothing_sealed.rs b/packages/vitaminc-aead/tests/ui/derive/sink_nothing_sealed.rs index 389f91aa5..77830cb14 100644 --- a/packages/vitaminc-aead/tests/ui/derive/sink_nothing_sealed.rs +++ b/packages/vitaminc-aead/tests/ui/derive/sink_nothing_sealed.rs @@ -1,9 +1,12 @@ //! Every field skipped or passed through would seal nothing, so the //! ciphertext would carry no tag at all. -use vitaminc_aead::Encrypt; +// Stack Encrypt's derives. stack-encrypt depends on this crate, so each +// derive here names this crate with `#[aead(crate = "::vitaminc_aead")]`. +use stack_encrypt_derive::Encrypt; #[derive(Encrypt)] +#[aead(crate = "::vitaminc_aead")] struct Row { #[aead(passthrough)] id: i64, diff --git a/packages/vitaminc-aead/tests/ui/derive/sink_nothing_sealed.stderr b/packages/vitaminc-aead/tests/ui/derive/sink_nothing_sealed.stderr index 83216c9ce..9281b1476 100644 --- a/packages/vitaminc-aead/tests/ui/derive/sink_nothing_sealed.stderr +++ b/packages/vitaminc-aead/tests/ui/derive/sink_nothing_sealed.stderr @@ -1,5 +1,5 @@ error: no field would be encrypted: every field is `#[aead(passthrough)]` or `#[aead(skip)]`, so the ciphertext would carry no tag — neither the associated data nor the entry keys would be authenticated. Encrypt at least one field, or do not derive for this struct at all. - --> tests/ui/derive/sink_nothing_sealed.rs:7:8 - | -7 | struct Row { - | ^^^ + --> tests/ui/derive/sink_nothing_sealed.rs:10:8 + | +10 | struct Row { + | ^^^ diff --git a/packages/vitaminc-aead/tests/ui/derive/sink_passthrough_on_newtype.rs b/packages/vitaminc-aead/tests/ui/derive/sink_passthrough_on_newtype.rs index 633904695..d5444a7d7 100644 --- a/packages/vitaminc-aead/tests/ui/derive/sink_passthrough_on_newtype.rs +++ b/packages/vitaminc-aead/tests/ui/derive/sink_passthrough_on_newtype.rs @@ -1,8 +1,11 @@ // A newtype is transparent — no map is opened — so there is no entry for a // passthrough to occupy. Honouring it would leave the whole value unencrypted. -use vitaminc_aead::{Decrypt, Encrypt}; +// Stack Encrypt's derives. stack-encrypt depends on this crate, so each +// derive here names this crate with `#[aead(crate = "::vitaminc_aead")]`. +use stack_encrypt_derive::{Decrypt, Encrypt}; #[derive(Encrypt, Decrypt)] +#[aead(crate = "::vitaminc_aead")] struct Token(#[aead(passthrough)] String); fn main() {} diff --git a/packages/vitaminc-aead/tests/ui/derive/sink_passthrough_on_newtype.stderr b/packages/vitaminc-aead/tests/ui/derive/sink_passthrough_on_newtype.stderr index 7b77255b5..66bc37fcf 100644 --- a/packages/vitaminc-aead/tests/ui/derive/sink_passthrough_on_newtype.stderr +++ b/packages/vitaminc-aead/tests/ui/derive/sink_passthrough_on_newtype.stderr @@ -1,5 +1,5 @@ error: `#[aead(passthrough)]` is meaningless on a newtype struct: a newtype is transparent, so there is no map entry to store in the clear and nothing would be encrypted at all. Give the struct a named field instead. - --> tests/ui/derive/sink_passthrough_on_newtype.rs:6:8 + --> tests/ui/derive/sink_passthrough_on_newtype.rs:9:8 | -6 | struct Token(#[aead(passthrough)] String); +9 | struct Token(#[aead(passthrough)] String); | ^^^^^ diff --git a/packages/vitaminc-aead/tests/ui/derive/sink_passthrough_with_take.rs b/packages/vitaminc-aead/tests/ui/derive/sink_passthrough_with_take.rs index b202dc251..21cc5cdfa 100644 --- a/packages/vitaminc-aead/tests/ui/derive/sink_passthrough_with_take.rs +++ b/packages/vitaminc-aead/tests/ui/derive/sink_passthrough_with_take.rs @@ -1,8 +1,11 @@ //! A passthrough field is lent to the sink, never taken out of `self`. -use vitaminc_aead::Encrypt; +// Stack Encrypt's derives. stack-encrypt depends on this crate, so each +// derive here names this crate with `#[aead(crate = "::vitaminc_aead")]`. +use stack_encrypt_derive::Encrypt; #[derive(Encrypt)] +#[aead(crate = "::vitaminc_aead")] struct Row { #[aead(passthrough, take)] tenant: String, diff --git a/packages/vitaminc-aead/tests/ui/derive/sink_passthrough_with_take.stderr b/packages/vitaminc-aead/tests/ui/derive/sink_passthrough_with_take.stderr index 4a298f6d6..75946159c 100644 --- a/packages/vitaminc-aead/tests/ui/derive/sink_passthrough_with_take.stderr +++ b/packages/vitaminc-aead/tests/ui/derive/sink_passthrough_with_take.stderr @@ -1,5 +1,5 @@ error: field `tenant` is `#[aead(passthrough)]`, which is lent to the sink and never taken out of `self`: remove `take` - --> tests/ui/derive/sink_passthrough_with_take.rs:6:8 + --> tests/ui/derive/sink_passthrough_with_take.rs:9:8 | -6 | struct Row { +9 | struct Row { | ^^^ diff --git a/packages/vitaminc-aead/tests/ui/derive/sink_private_field_type.rs b/packages/vitaminc-aead/tests/ui/derive/sink_private_field_type.rs index e8a749c44..a0b3cfbf8 100644 --- a/packages/vitaminc-aead/tests/ui/derive/sink_private_field_type.rs +++ b/packages/vitaminc-aead/tests/ui/derive/sink_private_field_type.rs @@ -3,15 +3,19 @@ //! A type that should stay unreachable can be `pub` inside a private module. mod inner { - use vitaminc_aead::Decrypt; - use vitaminc_aead::Encrypt; + // Stack Encrypt's derives. stack-encrypt depends on this crate, so each + // derive here names this crate with `#[aead(crate = "::vitaminc_aead")]`. + use stack_encrypt_derive::Decrypt; + use stack_encrypt_derive::Encrypt; #[derive(Encrypt, Decrypt)] + #[aead(crate = "::vitaminc_aead")] pub(crate) struct Private { a: u32, } #[derive(Encrypt, Decrypt)] + #[aead(crate = "::vitaminc_aead")] pub struct Public { p: Private, } diff --git a/packages/vitaminc-aead/tests/ui/derive/sink_private_field_type.stderr b/packages/vitaminc-aead/tests/ui/derive/sink_private_field_type.stderr index 63df4dee8..9fe5a2f7a 100644 --- a/packages/vitaminc-aead/tests/ui/derive/sink_private_field_type.stderr +++ b/packages/vitaminc-aead/tests/ui/derive/sink_private_field_type.stderr @@ -1,10 +1,10 @@ error[E0446]: crate-private type `Private` in public interface - --> tests/ui/derive/sink_private_field_type.rs:14:23 + --> tests/ui/derive/sink_private_field_type.rs:17:23 | -10 | pub(crate) struct Private { +13 | pub(crate) struct Private { | ------------------------- `Private` declared as crate-private ... -14 | #[derive(Encrypt, Decrypt)] +17 | #[derive(Encrypt, Decrypt)] | ^^^^^^^ can't leak crate-private type | = note: this error originates in the derive macro `Decrypt` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/packages/vitaminc-aead/tests/ui/derive/sink_rename_on_newtype.rs b/packages/vitaminc-aead/tests/ui/derive/sink_rename_on_newtype.rs index 5fdc27970..d9c1419f6 100644 --- a/packages/vitaminc-aead/tests/ui/derive/sink_rename_on_newtype.rs +++ b/packages/vitaminc-aead/tests/ui/derive/sink_rename_on_newtype.rs @@ -1,9 +1,12 @@ //! A newtype is transparent, so its value is not stored under a key and //! there is nothing to rename. -use vitaminc_aead::Encrypt; +// Stack Encrypt's derives. stack-encrypt depends on this crate, so each +// derive here names this crate with `#[aead(crate = "::vitaminc_aead")]`. +use stack_encrypt_derive::Encrypt; #[derive(Encrypt)] +#[aead(crate = "::vitaminc_aead")] struct Token(#[aead(rename = "token")] String); fn main() {} diff --git a/packages/vitaminc-aead/tests/ui/derive/sink_rename_on_newtype.stderr b/packages/vitaminc-aead/tests/ui/derive/sink_rename_on_newtype.stderr index fc4ae9d29..1ad72817e 100644 --- a/packages/vitaminc-aead/tests/ui/derive/sink_rename_on_newtype.stderr +++ b/packages/vitaminc-aead/tests/ui/derive/sink_rename_on_newtype.stderr @@ -1,5 +1,5 @@ error: `#[aead(rename = "...")]` has no effect on a newtype struct: a newtype is transparent, so its value is not stored under a map key at all and there is no key to rename. Give the struct a named field instead. - --> tests/ui/derive/sink_rename_on_newtype.rs:7:8 - | -7 | struct Token(#[aead(rename = "token")] String); - | ^^^^^ + --> tests/ui/derive/sink_rename_on_newtype.rs:10:8 + | +10 | struct Token(#[aead(rename = "token")] String); + | ^^^^^ diff --git a/packages/vitaminc-aead/tests/ui/derive/sink_skip_on_newtype.rs b/packages/vitaminc-aead/tests/ui/derive/sink_skip_on_newtype.rs index f7d86ffb4..61f1bcde8 100644 --- a/packages/vitaminc-aead/tests/ui/derive/sink_skip_on_newtype.rs +++ b/packages/vitaminc-aead/tests/ui/derive/sink_skip_on_newtype.rs @@ -1,8 +1,11 @@ //! A newtype is transparent, so skipping its only field leaves nothing. -use vitaminc_aead::Encrypt; +// Stack Encrypt's derives. stack-encrypt depends on this crate, so each +// derive here names this crate with `#[aead(crate = "::vitaminc_aead")]`. +use stack_encrypt_derive::Encrypt; #[derive(Encrypt)] +#[aead(crate = "::vitaminc_aead")] struct Wrapper(#[aead(skip)] String); fn main() {} diff --git a/packages/vitaminc-aead/tests/ui/derive/sink_skip_on_newtype.stderr b/packages/vitaminc-aead/tests/ui/derive/sink_skip_on_newtype.stderr index 14c24b964..7f39c0289 100644 --- a/packages/vitaminc-aead/tests/ui/derive/sink_skip_on_newtype.stderr +++ b/packages/vitaminc-aead/tests/ui/derive/sink_skip_on_newtype.stderr @@ -1,5 +1,5 @@ error: `#[aead(skip)]` is meaningless on a newtype struct: a newtype is transparent, so skipping its only field would leave nothing to encrypt. Give the struct a named field instead. - --> tests/ui/derive/sink_skip_on_newtype.rs:6:8 + --> tests/ui/derive/sink_skip_on_newtype.rs:9:8 | -6 | struct Wrapper(#[aead(skip)] String); +9 | struct Wrapper(#[aead(skip)] String); | ^^^^^^^ diff --git a/packages/vitaminc-aead/tests/ui/derive/sink_skip_with_passthrough.rs b/packages/vitaminc-aead/tests/ui/derive/sink_skip_with_passthrough.rs index 644918eec..0fcc5173a 100644 --- a/packages/vitaminc-aead/tests/ui/derive/sink_skip_with_passthrough.rs +++ b/packages/vitaminc-aead/tests/ui/derive/sink_skip_with_passthrough.rs @@ -1,8 +1,11 @@ //! A skipped field has no entry to pass through. -use vitaminc_aead::Decrypt; +// Stack Encrypt's derives. stack-encrypt depends on this crate, so each +// derive here names this crate with `#[aead(crate = "::vitaminc_aead")]`. +use stack_encrypt_derive::Decrypt; #[derive(Decrypt)] +#[aead(crate = "::vitaminc_aead")] struct Row { #[aead(skip, passthrough)] id: i64, diff --git a/packages/vitaminc-aead/tests/ui/derive/sink_skip_with_passthrough.stderr b/packages/vitaminc-aead/tests/ui/derive/sink_skip_with_passthrough.stderr index c7a5fdd03..9cccd7098 100644 --- a/packages/vitaminc-aead/tests/ui/derive/sink_skip_with_passthrough.stderr +++ b/packages/vitaminc-aead/tests/ui/derive/sink_skip_with_passthrough.stderr @@ -1,5 +1,5 @@ error: field `id` is `#[aead(skip)]`, so it has no entry to pass through or take: remove the other attribute - --> tests/ui/derive/sink_skip_with_passthrough.rs:6:8 + --> tests/ui/derive/sink_skip_with_passthrough.rs:9:8 | -6 | struct Row { +9 | struct Row { | ^^^ diff --git a/packages/vitaminc-aead/tests/ui/derive/sink_too_deep.rs b/packages/vitaminc-aead/tests/ui/derive/sink_too_deep.rs index c34f76221..fb0d02814 100644 --- a/packages/vitaminc-aead/tests/ui/derive/sink_too_deep.rs +++ b/packages/vitaminc-aead/tests/ui/derive/sink_too_deep.rs @@ -6,7 +6,9 @@ // resolve; without this, its own recursion limit is hit first. #![recursion_limit = "512"] -use vitaminc_aead::Encrypt; +// Stack Encrypt's derives. stack-encrypt depends on this crate, so each +// derive here names this crate with `#[aead(crate = "::vitaminc_aead")]`. +use stack_encrypt_derive::Encrypt; type V2 = Vec>; type V4 = V2>; @@ -17,6 +19,7 @@ type V64 = V32>; type V128 = V64>; #[derive(Encrypt)] +#[aead(crate = "::vitaminc_aead")] struct TooDeep { deep: V128, } diff --git a/packages/vitaminc-aead/tests/ui/derive/sink_too_deep.stderr b/packages/vitaminc-aead/tests/ui/derive/sink_too_deep.stderr index 9d03d4d22..fb0171de1 100644 --- a/packages/vitaminc-aead/tests/ui/derive/sink_too_deep.stderr +++ b/packages/vitaminc-aead/tests/ui/derive/sink_too_deep.stderr @@ -1,5 +1,5 @@ -error[E0080]: evaluation panicked: `TooDeep` nests deeper than `MAX_DEPTH` levels, so the encrypting sink would refuse its fully populated values - --> tests/ui/derive/sink_too_deep.rs:19:10 +error[E0080]: evaluation panicked: `TooDeep` nests deeper than `vitaminc_aead::plaintext::depth::MAX_DEPTH` levels. Stack Encrypt refuses to encrypt a value nested that deeply, so it would refuse every full value of this type + --> tests/ui/derive/sink_too_deep.rs:21:10 | -19 | #[derive(Encrypt)] +21 | #[derive(Encrypt)] | ^^^^^^^ evaluation of `_` failed here diff --git a/packages/vitaminc-aead/tests/ui/derive/sink_unknown_field_attribute.rs b/packages/vitaminc-aead/tests/ui/derive/sink_unknown_field_attribute.rs index 0eb2ddde9..d1f7e9e4f 100644 --- a/packages/vitaminc-aead/tests/ui/derive/sink_unknown_field_attribute.rs +++ b/packages/vitaminc-aead/tests/ui/derive/sink_unknown_field_attribute.rs @@ -1,8 +1,11 @@ // A misspelt attribute is rejected rather than ignored: a silently dropped // option is one the author believes is in effect. -use vitaminc_aead::{Decrypt, Encrypt}; +// Stack Encrypt's derives. stack-encrypt depends on this crate, so each +// derive here names this crate with `#[aead(crate = "::vitaminc_aead")]`. +use stack_encrypt_derive::{Decrypt, Encrypt}; #[derive(Encrypt, Decrypt)] +#[aead(crate = "::vitaminc_aead")] struct Row { #[aead(passthru)] tenant: String, diff --git a/packages/vitaminc-aead/tests/ui/derive/sink_unknown_field_attribute.stderr b/packages/vitaminc-aead/tests/ui/derive/sink_unknown_field_attribute.stderr index dd155a229..eb361a357 100644 --- a/packages/vitaminc-aead/tests/ui/derive/sink_unknown_field_attribute.stderr +++ b/packages/vitaminc-aead/tests/ui/derive/sink_unknown_field_attribute.stderr @@ -1,5 +1,5 @@ error: unsupported field attribute; expected `rename = "..."`, `passthrough`, `skip` or `take` - --> tests/ui/derive/sink_unknown_field_attribute.rs:7:12 - | -7 | #[aead(passthru)] - | ^^^^^^^^ + --> tests/ui/derive/sink_unknown_field_attribute.rs:10:12 + | +10 | #[aead(passthru)] + | ^^^^^^^^ diff --git a/packages/vitaminc-aead/tests/ui/derive/sink_variant_attribute.rs b/packages/vitaminc-aead/tests/ui/derive/sink_variant_attribute.rs index 2ab51ab3c..b30035f64 100644 --- a/packages/vitaminc-aead/tests/ui/derive/sink_variant_attribute.rs +++ b/packages/vitaminc-aead/tests/ui/derive/sink_variant_attribute.rs @@ -1,9 +1,12 @@ //! A variant is stored as its discriminant, so there is nothing for an //! attribute to describe. -use vitaminc_aead::Encrypt; +// Stack Encrypt's derives. stack-encrypt depends on this crate, so each +// derive here names this crate with `#[aead(crate = "::vitaminc_aead")]`. +use stack_encrypt_derive::Encrypt; #[derive(Encrypt)] +#[aead(crate = "::vitaminc_aead")] enum Status { #[aead(rename = "on")] Active, diff --git a/packages/vitaminc-aead/tests/ui/derive/sink_variant_attribute.stderr b/packages/vitaminc-aead/tests/ui/derive/sink_variant_attribute.stderr index 2eaa8cc37..c0e5704f9 100644 --- a/packages/vitaminc-aead/tests/ui/derive/sink_variant_attribute.stderr +++ b/packages/vitaminc-aead/tests/ui/derive/sink_variant_attribute.stderr @@ -1,5 +1,5 @@ error: variants take no `#[aead(...)]` attributes: a variant is stored as its discriminant, so give it an explicit `= n` to pin the value instead - --> tests/ui/derive/sink_variant_attribute.rs:8:5 - | -8 | #[aead(rename = "on")] - | ^^^^^^^^^^^^^^^^^^^^^^ + --> tests/ui/derive/sink_variant_attribute.rs:11:5 + | +11 | #[aead(rename = "on")] + | ^^^^^^^^^^^^^^^^^^^^^^ diff --git a/packages/vitaminc-aead/tests/ui/scalar/derived_newtype_over_a_container.rs b/packages/vitaminc-aead/tests/ui/scalar/derived_newtype_over_a_container.rs index 876c01ac9..854f25f29 100644 --- a/packages/vitaminc-aead/tests/ui/scalar/derived_newtype_over_a_container.rs +++ b/packages/vitaminc-aead/tests/ui/scalar/derived_newtype_over_a_container.rs @@ -3,15 +3,21 @@ //! can be absent. So neither newtype is a `Scalar`, by value or by //! reference. Both still derive `Encrypt`. -use vitaminc_aead::{Encrypt, Scalar}; +// Stack Encrypt's derives. stack-encrypt depends on this crate, so each +// derive here names this crate with `#[aead(crate = "::vitaminc_aead")]`. +use stack_encrypt_derive::Encrypt; +use vitaminc_aead::Scalar; #[derive(Encrypt)] +#[aead(crate = "::vitaminc_aead")] struct Tags(Vec); #[derive(Encrypt)] +#[aead(crate = "::vitaminc_aead")] struct Nickname(Option); #[derive(Encrypt)] +#[aead(crate = "::vitaminc_aead")] struct Wrapper(T); fn seals_one_leaf(_: S) {} diff --git a/packages/vitaminc-aead/tests/ui/scalar/derived_newtype_over_a_container.stderr b/packages/vitaminc-aead/tests/ui/scalar/derived_newtype_over_a_container.stderr index 4cefd5a90..91e32dc60 100644 --- a/packages/vitaminc-aead/tests/ui/scalar/derived_newtype_over_a_container.stderr +++ b/packages/vitaminc-aead/tests/ui/scalar/derived_newtype_over_a_container.stderr @@ -1,7 +1,7 @@ error[E0277]: the trait bound `Vec: vitaminc_aead::Scalar` is not satisfied - --> tests/ui/scalar/derived_newtype_over_a_container.rs:20:20 + --> tests/ui/scalar/derived_newtype_over_a_container.rs:26:20 | -20 | seals_one_leaf(Tags(vec![])); +26 | seals_one_leaf(Tags(vec![])); | -------------- ^^^^^^^^^^^^ the trait `vitaminc_aead::Scalar` is not implemented for `Vec` | | | required by a bound introduced by this call @@ -24,23 +24,24 @@ help: the following other types implement trait `vitaminc_aead::Scalar` | | } | |_- in this macro invocation note: required for `Tags` to implement `vitaminc_aead::Scalar` - --> tests/ui/scalar/derived_newtype_over_a_container.rs:8:10 + --> tests/ui/scalar/derived_newtype_over_a_container.rs:11:10 | - 8 | #[derive(Encrypt)] +11 | #[derive(Encrypt)] | ^^^^^^^ unsatisfied trait bound introduced in this `derive` macro - 9 | struct Tags(Vec); +12 | #[aead(crate = "::vitaminc_aead")] +13 | struct Tags(Vec); | ^^^^ note: required by a bound in `seals_one_leaf` - --> tests/ui/scalar/derived_newtype_over_a_container.rs:17:22 + --> tests/ui/scalar/derived_newtype_over_a_container.rs:23:22 | -17 | fn seals_one_leaf(_: S) {} +23 | fn seals_one_leaf(_: S) {} | ^^^^^^ required by this bound in `seals_one_leaf` = note: this error originates in the macro `scalar` which comes from the expansion of the derive macro `Encrypt` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0277]: the trait bound `&Vec: vitaminc_aead::Scalar` is not satisfied - --> tests/ui/scalar/derived_newtype_over_a_container.rs:21:21 + --> tests/ui/scalar/derived_newtype_over_a_container.rs:27:21 | -21 | seals_one_leaf(&Tags(vec![])); +27 | seals_one_leaf(&Tags(vec![])); | -------------- ^^^^^^^^^^^^ the trait `vitaminc_aead::Scalar` is not implemented for `&Vec` | | | required by a bound introduced by this call @@ -63,21 +64,21 @@ help: the following other types implement trait `vitaminc_aead::Scalar` | | } | |_- in this macro invocation note: required for `&Tags` to implement `vitaminc_aead::Scalar` - --> tests/ui/scalar/derived_newtype_over_a_container.rs:8:10 + --> tests/ui/scalar/derived_newtype_over_a_container.rs:11:10 | - 8 | #[derive(Encrypt)] +11 | #[derive(Encrypt)] | ^^^^^^^ unsatisfied trait bound introduced in this `derive` macro note: required by a bound in `seals_one_leaf` - --> tests/ui/scalar/derived_newtype_over_a_container.rs:17:22 + --> tests/ui/scalar/derived_newtype_over_a_container.rs:23:22 | -17 | fn seals_one_leaf(_: S) {} +23 | fn seals_one_leaf(_: S) {} | ^^^^^^ required by this bound in `seals_one_leaf` = note: this error originates in the macro `scalar` which comes from the expansion of the derive macro `Encrypt` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0277]: the trait bound `Option: vitaminc_aead::Scalar` is not satisfied - --> tests/ui/scalar/derived_newtype_over_a_container.rs:22:20 + --> tests/ui/scalar/derived_newtype_over_a_container.rs:28:20 | -22 | seals_one_leaf(Nickname(None)); +28 | seals_one_leaf(Nickname(None)); | -------------- ^^^^^^^^^^^^^^ the trait `vitaminc_aead::Scalar` is not implemented for `Option` | | | required by a bound introduced by this call @@ -93,23 +94,24 @@ error[E0277]: the trait bound `Option: vitaminc_aead::Scala &[u8; N] and $N others note: required for `Nickname` to implement `vitaminc_aead::Scalar` - --> tests/ui/scalar/derived_newtype_over_a_container.rs:11:10 + --> tests/ui/scalar/derived_newtype_over_a_container.rs:15:10 | -11 | #[derive(Encrypt)] +15 | #[derive(Encrypt)] | ^^^^^^^ unsatisfied trait bound introduced in this `derive` macro -12 | struct Nickname(Option); +16 | #[aead(crate = "::vitaminc_aead")] +17 | struct Nickname(Option); | ^^^^^^^^ note: required by a bound in `seals_one_leaf` - --> tests/ui/scalar/derived_newtype_over_a_container.rs:17:22 + --> tests/ui/scalar/derived_newtype_over_a_container.rs:23:22 | -17 | fn seals_one_leaf(_: S) {} +23 | fn seals_one_leaf(_: S) {} | ^^^^^^ required by this bound in `seals_one_leaf` = note: this error originates in the derive macro `Encrypt` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0277]: the trait bound `Vec: vitaminc_aead::Scalar` is not satisfied - --> tests/ui/scalar/derived_newtype_over_a_container.rs:23:28 + --> tests/ui/scalar/derived_newtype_over_a_container.rs:29:28 | -23 | seals_one_leaf(Wrapper(vec![1i32])); +29 | seals_one_leaf(Wrapper(vec![1i32])); | -------------- ^^^^^^^^^^ the trait `vitaminc_aead::Scalar` is not implemented for `Vec` | | | required by a bound introduced by this call @@ -132,15 +134,16 @@ help: the following other types implement trait `vitaminc_aead::Scalar` | | } | |_- in this macro invocation note: required for `Wrapper>` to implement `vitaminc_aead::Scalar` - --> tests/ui/scalar/derived_newtype_over_a_container.rs:14:10 + --> tests/ui/scalar/derived_newtype_over_a_container.rs:19:10 | -14 | #[derive(Encrypt)] +19 | #[derive(Encrypt)] | ^^^^^^^ unsatisfied trait bound introduced in this `derive` macro -15 | struct Wrapper(T); +20 | #[aead(crate = "::vitaminc_aead")] +21 | struct Wrapper(T); | ^^^^^^^^^^ note: required by a bound in `seals_one_leaf` - --> tests/ui/scalar/derived_newtype_over_a_container.rs:17:22 + --> tests/ui/scalar/derived_newtype_over_a_container.rs:23:22 | -17 | fn seals_one_leaf(_: S) {} +23 | fn seals_one_leaf(_: S) {} | ^^^^^^ required by this bound in `seals_one_leaf` = note: this error originates in the macro `scalar` which comes from the expansion of the derive macro `Encrypt` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/packages/vitaminc-aead/tests/ui/scalar/derived_struct_is_a_map.rs b/packages/vitaminc-aead/tests/ui/scalar/derived_struct_is_a_map.rs index 816b1ae69..80adc11f8 100644 --- a/packages/vitaminc-aead/tests/ui/scalar/derived_struct_is_a_map.rs +++ b/packages/vitaminc-aead/tests/ui/scalar/derived_struct_is_a_map.rs @@ -1,9 +1,13 @@ //! A derived struct walks as a map, one leaf per field, so it is not a //! `Scalar` even with a single field. -use vitaminc_aead::{Encrypt, Scalar}; +// Stack Encrypt's derives. stack-encrypt depends on this crate, so each +// derive here names this crate with `#[aead(crate = "::vitaminc_aead")]`. +use stack_encrypt_derive::Encrypt; +use vitaminc_aead::Scalar; #[derive(Encrypt)] +#[aead(crate = "::vitaminc_aead")] struct Account { id: u64, } diff --git a/packages/vitaminc-aead/tests/ui/scalar/derived_struct_is_a_map.stderr b/packages/vitaminc-aead/tests/ui/scalar/derived_struct_is_a_map.stderr index 5c585badc..d18d843db 100644 --- a/packages/vitaminc-aead/tests/ui/scalar/derived_struct_is_a_map.stderr +++ b/packages/vitaminc-aead/tests/ui/scalar/derived_struct_is_a_map.stderr @@ -1,15 +1,15 @@ error[E0277]: the trait bound `Account: vitaminc_aead::Scalar` is not satisfied - --> tests/ui/scalar/derived_struct_is_a_map.rs:14:20 + --> tests/ui/scalar/derived_struct_is_a_map.rs:18:20 | -14 | seals_one_leaf(Account { id: 1 }); +18 | seals_one_leaf(Account { id: 1 }); | -------------- ^^^^^^^^^^^^^^^^^ unsatisfied trait bound | | | required by a bound introduced by this call | help: the trait `vitaminc_aead::Scalar` is not implemented for `Account` - --> tests/ui/scalar/derived_struct_is_a_map.rs:7:1 + --> tests/ui/scalar/derived_struct_is_a_map.rs:11:1 | - 7 | struct Account { +11 | struct Account { | ^^^^^^^^^^^^^^ = help: the following other types implement trait `vitaminc_aead::Scalar`: &&'b T @@ -22,7 +22,7 @@ help: the trait `vitaminc_aead::Scalar` is not implemented for `Account` &f32 and $N others note: required by a bound in `seals_one_leaf` - --> tests/ui/scalar/derived_struct_is_a_map.rs:11:22 + --> tests/ui/scalar/derived_struct_is_a_map.rs:15:22 | -11 | fn seals_one_leaf(_: S) {} +15 | fn seals_one_leaf(_: S) {} | ^^^^^^ required by this bound in `seals_one_leaf` diff --git a/packages/vitaminc-aead/tests/ui/scalar_target/derived_newtype_of_a_container.rs b/packages/vitaminc-aead/tests/ui/scalar_target/derived_newtype_of_a_container.rs index 37507ff0b..8aff00df5 100644 --- a/packages/vitaminc-aead/tests/ui/scalar_target/derived_newtype_of_a_container.rs +++ b/packages/vitaminc-aead/tests/ui/scalar_target/derived_newtype_of_a_container.rs @@ -1,9 +1,13 @@ //! A derived newtype reads what its inner type reads. A newtype of a //! sequence needs a sequence, so one scalar does not build it. -use vitaminc_aead::{Decrypt, ScalarTarget}; +// Stack Encrypt's derives. stack-encrypt depends on this crate, so each +// derive here names this crate with `#[aead(crate = "::vitaminc_aead")]`. +use stack_encrypt_derive::Decrypt; +use vitaminc_aead::ScalarTarget; #[derive(Decrypt)] +#[aead(crate = "::vitaminc_aead")] struct Tags(Vec); fn opens_one_leaf() {} diff --git a/packages/vitaminc-aead/tests/ui/scalar_target/derived_newtype_of_a_container.stderr b/packages/vitaminc-aead/tests/ui/scalar_target/derived_newtype_of_a_container.stderr index 392a7de21..607766e95 100644 --- a/packages/vitaminc-aead/tests/ui/scalar_target/derived_newtype_of_a_container.stderr +++ b/packages/vitaminc-aead/tests/ui/scalar_target/derived_newtype_of_a_container.stderr @@ -1,19 +1,19 @@ error[E0277]: `Tags` is not built from one scalar - --> tests/ui/scalar_target/derived_newtype_of_a_container.rs:12:22 + --> tests/ui/scalar_target/derived_newtype_of_a_container.rs:16:22 | -12 | opens_one_leaf::(); +16 | opens_one_leaf::(); | ^^^^ this decrypt target is not a `ScalarTarget` | help: the trait `ScalarTarget` is not implemented for `Tags` - --> tests/ui/scalar_target/derived_newtype_of_a_container.rs:7:1 + --> tests/ui/scalar_target/derived_newtype_of_a_container.rs:11:1 | - 7 | struct Tags(Vec); +11 | struct Tags(Vec); | ^^^^^^^^^^^ = note: a scalar target is a `FromScalar` type, such as `String`, `i64`, or `Vec`. An `Option` or a `Protected` of one is a scalar target too. So is a newtype that derives `Decrypt` over one. = note: a sequence, a map, and a struct with named fields each need a container. So none of them is a scalar target. = note: a target with a hand-written sink is a scalar target when that sink implements `TakesScalar`. note: required by a bound in `opens_one_leaf` - --> tests/ui/scalar_target/derived_newtype_of_a_container.rs:9:22 + --> tests/ui/scalar_target/derived_newtype_of_a_container.rs:13:22 | - 9 | fn opens_one_leaf() {} +13 | fn opens_one_leaf() {} | ^^^^^^^^^^^^ required by this bound in `opens_one_leaf` diff --git a/packages/vitaminc-aead/tests/ui/scalar_target/derived_struct_needs_a_map.rs b/packages/vitaminc-aead/tests/ui/scalar_target/derived_struct_needs_a_map.rs index 30740c98a..b57fe6cff 100644 --- a/packages/vitaminc-aead/tests/ui/scalar_target/derived_struct_needs_a_map.rs +++ b/packages/vitaminc-aead/tests/ui/scalar_target/derived_struct_needs_a_map.rs @@ -1,9 +1,13 @@ //! A derived struct reads a map with one leaf for each field. So one scalar //! does not build it, even when the struct has a single field. -use vitaminc_aead::{Decrypt, ScalarTarget}; +// Stack Encrypt's derives. stack-encrypt depends on this crate, so each +// derive here names this crate with `#[aead(crate = "::vitaminc_aead")]`. +use stack_encrypt_derive::Decrypt; +use vitaminc_aead::ScalarTarget; #[derive(Decrypt)] +#[aead(crate = "::vitaminc_aead")] struct Account { id: u64, } diff --git a/packages/vitaminc-aead/tests/ui/scalar_target/derived_struct_needs_a_map.stderr b/packages/vitaminc-aead/tests/ui/scalar_target/derived_struct_needs_a_map.stderr index e9d66e3da..dd828fced 100644 --- a/packages/vitaminc-aead/tests/ui/scalar_target/derived_struct_needs_a_map.stderr +++ b/packages/vitaminc-aead/tests/ui/scalar_target/derived_struct_needs_a_map.stderr @@ -1,19 +1,19 @@ error[E0277]: `Account` is not built from one scalar - --> tests/ui/scalar_target/derived_struct_needs_a_map.rs:14:22 + --> tests/ui/scalar_target/derived_struct_needs_a_map.rs:18:22 | -14 | opens_one_leaf::(); +18 | opens_one_leaf::(); | ^^^^^^^ this decrypt target is not a `ScalarTarget` | help: the trait `ScalarTarget` is not implemented for `Account` - --> tests/ui/scalar_target/derived_struct_needs_a_map.rs:7:1 + --> tests/ui/scalar_target/derived_struct_needs_a_map.rs:11:1 | - 7 | struct Account { +11 | struct Account { | ^^^^^^^^^^^^^^ = note: a scalar target is a `FromScalar` type, such as `String`, `i64`, or `Vec`. An `Option` or a `Protected` of one is a scalar target too. So is a newtype that derives `Decrypt` over one. = note: a sequence, a map, and a struct with named fields each need a container. So none of them is a scalar target. = note: a target with a hand-written sink is a scalar target when that sink implements `TakesScalar`. note: required by a bound in `opens_one_leaf` - --> tests/ui/scalar_target/derived_struct_needs_a_map.rs:11:22 + --> tests/ui/scalar_target/derived_struct_needs_a_map.rs:15:22 | -11 | fn opens_one_leaf() {} +15 | fn opens_one_leaf() {} | ^^^^^^^^^^^^ required by this bound in `opens_one_leaf` diff --git a/packages/vitaminc-aead/tests/ui/scalar_target/hand_written_impl_for_a_derived_struct.rs b/packages/vitaminc-aead/tests/ui/scalar_target/hand_written_impl_for_a_derived_struct.rs index 6e162e0cf..45db1951d 100644 --- a/packages/vitaminc-aead/tests/ui/scalar_target/hand_written_impl_for_a_derived_struct.rs +++ b/packages/vitaminc-aead/tests/ui/scalar_target/hand_written_impl_for_a_derived_struct.rs @@ -3,9 +3,13 @@ //! implement `TakesScalar`. So the compiler rejects an impl of //! `ScalarTarget` for the struct. -use vitaminc_aead::{Decrypt, ScalarTarget}; +// Stack Encrypt's derives. stack-encrypt depends on this crate, so each +// derive here names this crate with `#[aead(crate = "::vitaminc_aead")]`. +use stack_encrypt_derive::Decrypt; +use vitaminc_aead::ScalarTarget; #[derive(Decrypt)] +#[aead(crate = "::vitaminc_aead")] struct Account { id: u64, } diff --git a/packages/vitaminc-aead/tests/ui/scalar_target/hand_written_impl_for_a_derived_struct.stderr b/packages/vitaminc-aead/tests/ui/scalar_target/hand_written_impl_for_a_derived_struct.stderr index 6235cd78a..76b93974b 100644 --- a/packages/vitaminc-aead/tests/ui/scalar_target/hand_written_impl_for_a_derived_struct.stderr +++ b/packages/vitaminc-aead/tests/ui/scalar_target/hand_written_impl_for_a_derived_struct.stderr @@ -1,13 +1,13 @@ error[E0277]: `ScalarTarget` cannot be implemented for `Account` - --> tests/ui/scalar_target/hand_written_impl_for_a_derived_struct.rs:13:23 + --> tests/ui/scalar_target/hand_written_impl_for_a_derived_struct.rs:17:23 | -13 | impl ScalarTarget for Account {} +17 | impl ScalarTarget for Account {} | ^^^^^^^ the sink of this target does not implement `TakesScalar` | help: the trait `typed::sealed::SinkTakesScalar` is not implemented for `Account` - --> tests/ui/scalar_target/hand_written_impl_for_a_derived_struct.rs:9:1 + --> tests/ui/scalar_target/hand_written_impl_for_a_derived_struct.rs:13:1 | - 9 | struct Account { +13 | struct Account { | ^^^^^^^^^^^^^^ = note: a target is a `ScalarTarget` when its sink, `Decrypt::Sink`, implements `TakesScalar`. No other impl is accepted. note: required by a bound in `ScalarTarget` diff --git a/packages/vitaminc-aead/tests/ui/scalar_target/hand_written_impl_for_a_newtype.rs b/packages/vitaminc-aead/tests/ui/scalar_target/hand_written_impl_for_a_newtype.rs index c81d5de90..7dcf496bd 100644 --- a/packages/vitaminc-aead/tests/ui/scalar_target/hand_written_impl_for_a_newtype.rs +++ b/packages/vitaminc-aead/tests/ui/scalar_target/hand_written_impl_for_a_newtype.rs @@ -3,9 +3,13 @@ //! defined in vitaminc-aead. So an impl of `ScalarTarget` for a newtype of a //! sequence conflicts with the blanket impl. -use vitaminc_aead::{Decrypt, ScalarTarget}; +// Stack Encrypt's derives. stack-encrypt depends on this crate, so each +// derive here names this crate with `#[aead(crate = "::vitaminc_aead")]`. +use stack_encrypt_derive::Decrypt; +use vitaminc_aead::ScalarTarget; #[derive(Decrypt)] +#[aead(crate = "::vitaminc_aead")] struct Tags(Vec); impl ScalarTarget for Tags {} diff --git a/packages/vitaminc-aead/tests/ui/scalar_target/hand_written_impl_for_a_newtype.stderr b/packages/vitaminc-aead/tests/ui/scalar_target/hand_written_impl_for_a_newtype.stderr index 9b29f712a..17ad4f45f 100644 --- a/packages/vitaminc-aead/tests/ui/scalar_target/hand_written_impl_for_a_newtype.stderr +++ b/packages/vitaminc-aead/tests/ui/scalar_target/hand_written_impl_for_a_newtype.stderr @@ -1,7 +1,7 @@ error[E0119]: conflicting implementations of trait `ScalarTarget` for type `Tags` - --> tests/ui/scalar_target/hand_written_impl_for_a_newtype.rs:11:1 + --> tests/ui/scalar_target/hand_written_impl_for_a_newtype.rs:15:1 | -11 | impl ScalarTarget for Tags {} +15 | impl ScalarTarget for Tags {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^ | = note: conflicting implementation in crate `vitaminc_aead`: diff --git a/release-plz.toml b/release-plz.toml index 7f28ee209..6cf8fd9e1 100644 --- a/release-plz.toml +++ b/release-plz.toml @@ -68,6 +68,11 @@ name = "stack-guest-abi" release = false publish = false +[[package]] +name = "stack-encrypt-downstream" +release = false +publish = false + [[package]] name = "stack-auth-node" release = false @@ -85,8 +90,10 @@ publish = false # The AEAD crates moved here from cipherstash/vitaminc. crates.io's 0.10.0 # was published from vitaminc. They publish from here before the next -# stack-encrypt release: vitaminc-aead and vitaminc-aead-derive under the same -# names, and the frame crate as recipher-frame (it was vitaminc-aead-frame). +# stack-encrypt release: vitaminc-aead under the same name, and the frame +# crate as recipher-frame (it was vitaminc-aead-frame). The derives of +# vitaminc-aead are in stack-encrypt-derive. That crate releases with +# stack-encrypt. # Until then they are listed here so that release-plz neither bumps nor # publishes them. [[package]] @@ -98,8 +105,3 @@ publish = false name = "recipher-frame" release = false publish = false - -[[package]] -name = "vitaminc-aead-derive" -release = false -publish = false diff --git a/scripts/__tests__/crates-ci.test.mjs b/scripts/__tests__/crates-ci.test.mjs index 053742b6d..36fa318c4 100644 --- a/scripts/__tests__/crates-ci.test.mjs +++ b/scripts/__tests__/crates-ci.test.mjs @@ -239,13 +239,13 @@ describe('the scan sees every task mise sees', () => { [ 'packages/stack-auth/tasks.toml', 'packages/stack-encrypt/tasks.toml', + 'packages/stack-encrypt-derive/tasks.toml', 'packages/stack-encrypt-jsonpath/tasks.toml', 'packages/stack-guest-abi/tasks.toml', 'packages/stack-kms/tasks.toml', 'packages/stack-profile/tasks.toml', 'packages/vitaminc-aead/tasks.toml', 'packages/recipher-frame/tasks.toml', - 'packages/vitaminc-aead-derive/tasks.toml', ].sort(), ) }) @@ -292,12 +292,12 @@ describe('the scan sees every task mise sees', () => { [ 'doc:stack-auth', 'doc:stack-encrypt', + 'doc:stack-encrypt-derive', 'doc:stack-encrypt-jsonpath', 'doc:stack-guest-abi', 'doc:stack-kms', 'doc:stack-profile', 'doc:vitaminc-aead', - 'doc:vitaminc-aead-derive', 'doc:recipher-frame', ].sort(), ) diff --git a/supply-chain/vitaminc-aead/README.md b/supply-chain/vitaminc-aead/README.md index 39f8778e5..47200c54d 100644 --- a/supply-chain/vitaminc-aead/README.md +++ b/supply-chain/vitaminc-aead/README.md @@ -1,17 +1,22 @@ # 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 -workspace; that is #1842. +This directory contains the `cargo deny` config and the `cargo vet` store for +three crates and their dependency graph **only**: `vitaminc-aead`, +`recipher-frame`, and `stack-encrypt-derive`. The derive is here because it +writes every derived `Encrypt` and `Decrypt` impl. 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 three crates, `Cargo.lock`, `Cargo.toml`, or this directory. `cargo deny` also runs nightly, for advisories published against versions already in the lockfile. - `deny.toml`: advisories, yanked versions, licences, sources, and the crates - allowed a build script. + allowed a build script. The derive's dev-dependencies include + `stack-encrypt`, and `stack-encrypt` reaches the rest of the workspace. So + `cargo deny` checks the derive as the root of its own graph, without its + dev-dependencies. The tests of the other two crates use the derive, so + their checks leave it out. - `config.toml`, `audits.toml`, `imports.lock`: the `cargo vet` store. It started as `cipherstash/vitaminc`'s, with its audits and imported registries. The policies name every root workspace member, because cargo @@ -20,9 +25,19 @@ versions already in the lockfile. `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. + runtime dependencies. Two policies narrow what is vetted: + - `stack-encrypt-derive` sets `dev-criteria = []`. The derive's + dev-dependencies (`stack-encrypt`, `tokio`) serve only its doctests, and + they reach the rest of the workspace. + - `stack-encrypt-jsonpath` sets `dependency-criteria = { miette = [] }`. + `miette` comes only with the `diagnostics` feature of + `stack-encrypt-jsonpath`. `stack-encrypt` turns that feature on, and the + derive does not. `cargo vet` reads the features of the whole workspace at + once. Without this policy, it would ask for an audit of a crate the + derive never builds. - `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 three crates, + `stack-encrypt-jsonpath` (the derive's path grammar), and their dependencies. ## Commands @@ -31,8 +46,15 @@ From the repository root: ```sh # cargo deny, one crate at a time -cargo deny --locked --config supply-chain/vitaminc-aead/deny.toml \ +cargo deny --locked --exclude stack-encrypt-derive \ + --config supply-chain/vitaminc-aead/deny.toml \ --manifest-path packages/vitaminc-aead/Cargo.toml check +cargo deny --locked --exclude stack-encrypt-derive \ + --config supply-chain/vitaminc-aead/deny.toml \ + --manifest-path packages/recipher-frame/Cargo.toml check +cargo deny --locked --exclude-dev \ + --config supply-chain/vitaminc-aead/deny.toml \ + --manifest-path packages/stack-encrypt-derive/Cargo.toml check # cargo vet cargo vet --locked --store-path supply-chain/vitaminc-aead \ diff --git a/supply-chain/vitaminc-aead/config.toml b/supply-chain/vitaminc-aead/config.toml index 111b70e27..f6dadb0a8 100644 --- a/supply-chain/vitaminc-aead/config.toml +++ b/supply-chain/vitaminc-aead/config.toml @@ -34,6 +34,11 @@ audit-as-crates-io = false [policy.stack-encrypt-derive] audit-as-crates-io = false +criteria = "safe-to-deploy" +dev-criteria = [] + +[policy.stack-encrypt-jsonpath] +dependency-criteria = { miette = [] } [policy.stack-kms] audit-as-crates-io = false @@ -44,10 +49,6 @@ audit-as-crates-io = false [policy.temp-env] audit-as-crates-io = false -[policy."vitaminc-aead-derive:0.10.0"] -audit-as-crates-io = false -criteria = "safe-to-deploy" - [policy."vitaminc-aead:0.10.0"] audit-as-crates-io = false criteria = "safe-to-deploy" @@ -432,10 +433,18 @@ criteria = "safe-to-deploy" version = "1.0.2" criteria = "safe-to-run" +[[exemptions.thiserror]] +version = "1.0.69" +criteria = "safe-to-deploy" + [[exemptions.thiserror]] version = "2.0.18" criteria = "safe-to-deploy" +[[exemptions.thiserror-impl]] +version = "1.0.69" +criteria = "safe-to-deploy" + [[exemptions.thiserror-impl]] version = "2.0.18" criteria = "safe-to-deploy" diff --git a/supply-chain/vitaminc-aead/deny.toml b/supply-chain/vitaminc-aead/deny.toml index 8e75f6421..ec707bd89 100644 --- a/supply-chain/vitaminc-aead/deny.toml +++ b/supply-chain/vitaminc-aead/deny.toml @@ -1,16 +1,34 @@ -# cargo-deny configuration for vitaminc-aead, recipher-frame and -# vitaminc-aead-derive, and their dependency graph ONLY. It does not cover -# the rest of the root workspace; that is #1842. +# cargo-deny configuration for three crates and their dependency graph ONLY: +# vitaminc-aead, recipher-frame, and stack-encrypt-derive. The derive is here +# because it writes every derived `Encrypt` and `Decrypt` impl. This file +# does not cover the rest of the root workspace; that is #1842. # # CI (.github/workflows/supply-chain-vitaminc-aead.yml) runs it once per crate: # -# cargo deny --locked --config supply-chain/vitaminc-aead/deny.toml \ -# --manifest-path packages//Cargo.toml check +# cargo deny --locked --exclude stack-encrypt-derive \ +# --config supply-chain/vitaminc-aead/deny.toml \ +# --manifest-path packages/vitaminc-aead/Cargo.toml check +# cargo deny --locked --exclude stack-encrypt-derive \ +# --config supply-chain/vitaminc-aead/deny.toml \ +# --manifest-path packages/recipher-frame/Cargo.toml check +# cargo deny --locked --exclude-dev \ +# --config supply-chain/vitaminc-aead/deny.toml \ +# --manifest-path packages/stack-encrypt-derive/Cargo.toml check # # `--manifest-path` on a workspace member checks that package's graph, not # the workspace's. `cargo deny check` at the repository root does NOT read # this file. # +# The derive's dev-dependencies include stack-encrypt, and stack-encrypt +# reaches the rest of the workspace. So the derive is checked as the root of +# its own graph, with `--exclude-dev`. That graph is the derive's normal +# dependencies and theirs. The normal dependencies are syn, quote, +# proc-macro2, and stack-encrypt-jsonpath. +# +# The tests of the other two crates use the derive, so their checks leave it +# out with `--exclude`. Both are flags, not `[graph] exclude`, because cargo +# deny cannot use an excluded crate as a root. +# # What it holds the lockfile to: # advisories no RustSec advisory, no yanked version # bans no crate with a build script that is not listed below @@ -49,7 +67,15 @@ allow = [ "Unlicense", ] confidence-threshold = 0.8 -exceptions = [] +# stack-encrypt-derive and stack-encrypt-jsonpath are this repository's own +# crates. Their LICENSE file is the PolyForm Internal Use License 1.0.0. SPDX +# has no identifier for that licence, and cargo-deny reads its text as +# PolyForm-Small-Business-1.0.0, the closest licence it knows. Each exception +# names one crate, so a third-party crate under that licence still fails. +exceptions = [ + { crate = "stack-encrypt-derive", allow = ["PolyForm-Small-Business-1.0.0"] }, + { crate = "stack-encrypt-jsonpath", allow = ["PolyForm-Small-Business-1.0.0"] }, +] [licenses.private] ignore = true @@ -66,7 +92,7 @@ deny = [] [bans.build] # A build script runs arbitrary code on every developer machine and in CI, # and a new one is the most common shape of a malicious release. This is -# every crate in the three crates' graph with a build script today +# every crate in the three crates' graphs with a build script today # (platform-specific ones included, because the graph is checked for every # target). A dependency change that adds one fails here, and the review # decides whether to add it. diff --git a/supply-chain/vitaminc-aead/filter-graph b/supply-chain/vitaminc-aead/filter-graph index 6b8e9b3ac..6e02dc3c9 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(stack-encrypt-derive),name(stack-encrypt-jsonpath)))))