diff --git a/.github/workflows/fuzz.yml b/.github/workflows/fuzz.yml index 2b02d041e..7b4dbdf9e 100644 --- a/.github/workflows/fuzz.yml +++ b/.github/workflows/fuzz.yml @@ -14,10 +14,11 @@ name: Fuzz # cache, so coverage compounds; it is minimised with `cargo fuzz cmin`, and # any crash reproducer is uploaded as an artifact. # -# * go-fuzz-campaign (schedule and manual, never on PRs): the same for the -# Go fuzz targets in languages/golang, which fuzz the WASI guests' ABI -# from the host side (`mise run go:fuzz`). Their regression replay is -# plain `go test`, in tests-golang.yml. +# * go-fuzz-campaign (schedule and manual, never on PRs): the same run for +# the Go fuzz targets in languages/golang (`mise run go:fuzz`). Those +# targets fuzz the ABI of the WASI guests from the host side, and the +# decoders of the frame codec. Their regression replay is plain +# `go test`, in tests-golang.yml. # # cargo-fuzz needs nightly; the tasks run `cargo +nightly fuzz`. Pull requests # are the only filtered event, so `push` has no filter to mirror; recorded in @@ -258,11 +259,15 @@ jobs: strategy: fail-fast: false matrix: - # `guest` is the build the target's package runs. + # `guest` is the guest build that the package of the target runs. The + # targets of the frame codec, in encrypt/frame, run no guest. include: - { target: FuzzGuestExportPairs, slug: encrypt-export-pairs, guest: "wasm:guest:build:deterministic" } - { target: FuzzGuestBufferRegistry, slug: encrypt-buffer-registry, guest: "wasm:guest:build:deterministic" } - { target: FuzzAuthGuestExportPairs, slug: auth-export-pairs, guest: "wasm:auth-guest:build" } + - { target: FuzzUnmarshal, slug: frame-value, guest: "" } + - { target: FuzzUnmarshalCipherText, slug: frame-ciphertext, guest: "" } + - { target: FuzzUnmarshalStorage, slug: frame-storage, guest: "" } steps: - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 with: @@ -278,6 +283,7 @@ jobs: cache_key_prefix: mise-v1-ubuntu-2404 - uses: Swatinem/rust-cache@e18b497796c12c097a38f9edb9d0641fb99eee32 # v2 + if: matrix.guest != '' with: workspaces: | languages/golang/encrypt/guest @@ -285,6 +291,7 @@ jobs: key: go-fuzz-${{ matrix.slug }} - name: Build the guest (${{ matrix.slug }}) + if: matrix.guest != '' run: mise run ${{ matrix.guest }} - name: Find the Go fuzz cache diff --git a/.github/workflows/release-golang.yml b/.github/workflows/release-golang.yml index f67a1de44..d313cd44c 100644 --- a/.github/workflows/release-golang.yml +++ b/.github/workflows/release-golang.yml @@ -25,13 +25,15 @@ name: Release (Go) # # gh workflow run release-golang.yml -f version=0.1.0-alpha.1 --ref # -# The ref must carry the EQL v4 bundle (packages/eql's v4 build), or the -# build job stops at "Build the EQL SQL bundles". Its -# languages/golang/CHANGELOG.md must have a `## []` section, which -# becomes the release notes, or the run stops at the `notes` job. A version with a pre-release -# suffix may be cut from any branch and is published as a GitHub pre-release; -# a final version is cut from main only, and not while go.mod pins vitaminc's -# Go bindings at a pseudo-version (scripts/go-release-version.mjs). +# The ref must have the EQL v4 bundle (the v4 build of packages/eql). Without +# it, the build job stops at "Build the EQL SQL bundles". The file +# languages/golang/CHANGELOG.md at the ref must have a `## []` section. +# That section becomes the release notes. Without it, the run stops at the +# `notes` job. +# +# A version with a pre-release suffix can be released from any branch. The +# workflow publishes it as a GitHub pre-release. A final version can be released +# only from main. # # Four jobs, split by what they may touch: # diff --git a/.github/workflows/tests-golang.yml b/.github/workflows/tests-golang.yml index 5d797f220..4b53760ef 100644 --- a/.github/workflows/tests-golang.yml +++ b/.github/workflows/tests-golang.yml @@ -40,6 +40,8 @@ on: - packages/stack-kms/** - packages/stack-encrypt/** - conformance/stack-encrypt/** + # encrypt/frame's tests read the value corpus. + - conformance/vitaminc-aead/** - packages/stack-encrypt-derive/** - packages/stack-encrypt-jsonpath/** - packages/stack-guest-abi/** @@ -88,6 +90,8 @@ on: - packages/stack-kms/** - packages/stack-encrypt/** - conformance/stack-encrypt/** + # encrypt/frame's tests read the value corpus. + - conformance/vitaminc-aead/** - packages/stack-encrypt-derive/** - packages/stack-encrypt-jsonpath/** - packages/stack-guest-abi/** diff --git a/AGENTS.md b/AGENTS.md index eca1b8467..1b8d28f01 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -94,7 +94,7 @@ Every npm package except EQL lives under `languages/typescript/`: packages in `l - `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". - `languages/typescript/packages/auth`, `languages/typescript/packages/profile`, `languages/typescript/packages/stack-auth-wasm`: The node bindings of those crates. `@cipherstash/auth` (napi-rs v2) and its six `platforms/*` packages are published to npm from this repository by `release.yml` (`auth-artifacts`, `publish-auth`); a change to what it ships, the `stack-auth` crate included, needs an `@cipherstash/auth` changeset (`require-auth-npm-changeset.yml`). `@cipherstash/profile` and its platforms are private and never published; `@cipherstash/stack-auth-wasm` is private and builds the wasm that `@cipherstash/auth` ships. Their `build` and `test` scripts never invoke cargo; `build:native`, `build:debug` and `test:cargo` do. `@cipherstash/auth` also ships two pure-JS framework adapters over the wasm `OidcFederationStrategy`: `./next` (Next.js App Router, hands the token to the render on a request header) and `./start` (TanStack Start: `csFederateCurrent` is called inside a function middleware the app declares itself, which hands the token to the server function through `next({ context })`; `@tanstack/react-start` is an optional peer loaded only by that entry). - `languages/typescript/packages/recipher-js`: `@cipherstash/recipher`, the TypeScript SDK on the Stack Encrypt engine (design: `docs/plans/2026-11-22-recipher-typescript-sdk.md`). **Private and unpublished**: it has no platform packages and no release job yet, so it must stay `"private": true` (a public manifest would be published by `changeset publish` on merge) and takes no changeset. Its Rust is **two crates** in a **detached Cargo workspace** with its own `Cargo.lock`. The root workspace names its members, so it needs no `exclude` entry there; leave the root `Cargo.toml` alone, because a change to it starts every stack-* crate workflow. The two crates: `crate/` (crate `recipher-js`, napi-rs 3), which defines the `Cipher`, `Keyset`, `Ciphertext`, and `Json` classes the package exports, runs every operation through the engine, and reads and builds JavaScript values only through the value bridge beside it, `value-napi/` (crate `recipher-value-napi`, a copy of vitaminc's `vitaminc-aead-napi` 0.10.0, unpublished, with a detached test addon workspace of its own at `value-napi/tests/addon` and vitaminc's value conformance corpus at `value-napi/tests/testdata`; Biome does not check that directory). The bridge converts JSON documents too. `JsRef::to_json` writes a JavaScript value as a document's JSON text, with the JavaScript number rules. `JsBuilder::build_json` builds a decrypted document. The addon's `json.rs` contains only the `Json` class, and passes the text to the engine's `JsonPlaintext`. A test fails if it links `eql-bindings` or reaches the engine's `test-support` with its default features. `@napi-rs/cli` v3 builds it (`build:debug`, `build:native`) and writes its generated TypeScript declarations to the committed `native.d.ts`; CI fails when the build changes that file. Each native method returns the package's `Result` itself, and its public signature is written in Rust (napi-rs's `ts_type`, `ts_args_type` and `ts_return_type` attributes, with `native-header.d.ts` as the generated file's header), so `native.d.ts` is the public type: never add a TypeScript wrapper or hand-written interface over a native class. The TypeScript (`src/`) contains only `Result`, `RecipherError`, the loader, stand-ins for a build that did not load, and the types that the generated signatures name. The loader is `src/binding.ts`. The loader gives the addon the `Ok`, `Err`, and `RecipherError` classes. The types are in `src/kinds.ts` and `src/value-types.ts`. `native.d.ts` imports those types, so a module that `native.d.ts` imports from must never load the addon. If one did, the declarations would import themselves. The declaration build of tsup would then fail. Two kinds of call throw: a method called without its object (#1801), and `new` on a class whose type has no constructor (`Cipher`, `Keyset`, `Ciphertext`, and the wrapper classes, which an application makes with `RcDate.from(text)` and the like, each returning a `Result`). Every other call returns or resolves to a `Result`. Its `build` (tsup) and `test` (the suites in `__tests__/unit` and `tsc` over `src`, the tests and `type-tests`) never run cargo; `build:debug` (the addon with the deterministic test cipher behind `@cipherstash/recipher/testing`), `build:native`, `test:addon` (the suites that load `recipher.node`) and `test:cargo` do. `.github/workflows/tests-recipher-js.yml` runs all four, and fmt and clippy over the value bridge's test addon by its manifest: `tests.yml`'s live jobs skip a change that touches only this package, so apart from that file's ungated lint and repo checks it is the only workflow such a change runs. One Dependabot cargo entry covers both lockfiles, and `scripts/__tests__/recipher-js-lock-parity.test.mjs` fails when they resolve different napi or vitaminc crates. -- `languages/golang`: The Go module — the SDK `encrypt` with its generated-code support `encrypt/gensupport`, its test package `encrypt/encrypttest` (context assertions, and `NewClient`: an offline client over the deterministic test builds, for an application's tests; a **nested Go module** of its own, so only a program that imports it downloads those builds, requiring the SDK at the zero pseudo-version with `replace ../..` in the tree, and `NewClient` fails when the two are at different versions) 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. `examples/s3` is a fourth, also never tagged: it encrypts S3 object bodies with a plain `encrypt` field through the AWS SDK for Go v2, and `mise run go:example:s3` runs its tests end to end against S3Mock in Docker (they skip in CI, which has no bucket). `./...` stops at a nested module, so `scripts/go-binding-test.sh`, `go:lint` and the generated-code check find each `go.mod` and run in its directory. +- `languages/golang`: The Go module — the SDK `encrypt` with its generated-code support `encrypt/gensupport`, its test package `encrypt/encrypttest` (context assertions, and `NewClient`: an offline client over the deterministic test builds, for an application's tests; a **nested Go module** of its own, so only a program that imports it downloads those builds, requiring the SDK at the zero pseudo-version with `replace ../..` in the tree, and `NewClient` fails when the two are at different versions) the policy packages `encrypt/policy` and `encrypt/policy/protosource`; the frame codec `encrypt/frame` and its value types `encrypt/value`; the credential package `auth`; the generator `stashgen` and its command `cmd/stashgen`; and `internal` (the shared guest plumbing, the `record` wire model, and `wasmtestrun`, the wazero runner that `wasm:auth-guest:test` runs the auth guest's wasm32 tests under). `encrypt/frame` encodes and decodes the bytes that the Go module exchanges with its guests, and the storage profile; it was vitaminc's Go package `vcffi`. `encrypt/value` declares the value types that the codec reads and writes (`Date`, `Decimal`, `Int128`, `Uint128`, `UUID`, `Object` and the rest); it was vitaminc's `vcvalue`, and imports nothing outside the standard library. `encrypt` names those types with aliases (`encrypt.Date` is `value.Date`), and `encrypt.Encryptable` and `encrypt.Encoder` are aliases of `frame`'s. The Rust crate `recipher-frame` implements the same encodings. The tests of `encrypt/frame` check it against `conformance/vitaminc-aead/value-conformance.json` and `packages/recipher-frame/testdata/storage-v1.json`. A wazero host with no cgo. Its two WASI guests (`encrypt/guest`, `auth/guest`) are detached Cargo workspaces built by `mise run wasm:guest:build` and `mise run wasm:auth-guest:build`; `mise run wasm:guest:build:deterministic` and `wasm:guest:build:eql:deterministic` build the seeded TEST builds into `encrypt/encrypttest/wasm`, which `encrypttest` embeds and the hermetic Go tests read; the `.wasm` files are gitignored. The stack-encrypt guest has a second build with the EQL types (`mise run wasm:guest:build:eql`, cargo feature `eql`, linking `eql-bindings` by path; `wasm:guest:build:eql:deterministic` is its test build), embedded by `encrypt/eql` and registered on import, so a program whose generated code names an EQL type runs it (ADR-0007, amended). `encrypt/eql`'s types and `Types` table are generated from the EQL catalog by `eql-codegen` (`eql_gen.go`, written by `mise run types:generate` in `packages/eql` and drift-gated by `types:check` and `cargo test -p eql-codegen`). Generated `*_stash.go` files are committed and CI fails when `go generate ./...` changes one. Releases are cut by hand with `.github/workflows/release-golang.yml` (`gh workflow run release-golang.yml -f version=X.Y.Z[-pre] --ref `): because the guests are gitignored on main and Go fetches a version as the files committed at its tag, the workflow builds them, commits them on a release-only commit no branch points at, with `encrypt/encrypttest/go.mod` pinned to the SDK version by `scripts/go-release-pin-encrypttest.sh` (run in `build` and in `publish`), tags it `languages/golang/vX.Y.Z` and `languages/golang/encrypt/encrypttest/vX.Y.Z` (the workflow's `MODULES`) and pushes the tags alone, then attaches the EQL v4 SQL bundle to the GitHub release. The ref must carry the EQL v4 bundle, or the build stops at "Build the EQL SQL bundles". `scripts/go-release-version.mjs` refuses, before anything is built, every version Go would refuse (non-canonical semver, `+build` metadata, a v2+ major on a module path with no `/vN` suffix, a version shaped like a pseudo-version), and a final version dispatched from anywhere but `main`. A pre-release may come from a branch. The build job also refuses a version the Go proxy already lists in `@v/list`, which catches a tag deleted after the proxy fetched it; it never asks the proxy for the version itself before the tag exists, because the proxy would cache "not found" for up to 30 minutes and `verify` would fail after the push. The build checks the `Cargo.lock` of the EQL workspace and both guest workspaces with `--locked` first, since none of those builds passes it. It runs in a job with no write token and hands the guests to a `publish` job that holds `contents: write` and runs only git and gh. `publish` fetches the commit with plain unauthenticated git rather than `actions/checkout`, whose `token` input defaults to the job's writable token, and refuses a release commit whose tree is not the one the build tested. `publish` takes the paths it commits from the workflow's fixed `GUESTS` list, never from the artifact, and refuses a `guests.sha256` that is not exactly one SHA-256 line for each of those five guests (the three production guests and the two test builds `encrypttest` embeds): the build job runs third-party code after writing that manifest, so a path read from it could put any file on the tag (`scripts/__tests__/go-release-artifact.test.mjs`). The release page's notes are the version's `## [X.Y.Z]` section of `languages/golang/CHANGELOG.md`, taken by `scripts/go-release-notes.mjs` in a `notes` job that runs no third-party code and that `build` waits for: a version with no section, or an empty one, is refused before anything is built, so write the section before dispatching. A version is immutable once the Go proxy has fetched it, so a tag is never moved or deleted: if `publish` or `verify` fails after the tag is pushed, use "Re-run failed jobs" on the same run, which keeps a tag that run pushed and creates or completes the release; a new dispatch of the same version is refused. Never tag a main commit by hand: `go get` would fetch a module with no guests. `encrypt/example` is a third nested module, never tagged: it requires both modules as an application does. `examples/s3` is a fourth, also never tagged: it encrypts S3 object bodies with a plain `encrypt` field through the AWS SDK for Go v2, and `mise run go:example:s3` runs its tests end to end against S3Mock in Docker (they skip in CI, which has no bucket). `./...` stops at a nested module, so `scripts/go-binding-test.sh`, `go:lint` and the generated-code check find each `go.mod` and run in its directory. - `e2e/*`: Cross-package end-to-end tests (package managers, supply chain, Prisma example README) - `e2e/migration-guide`: Unpublished, separately installed npm examples for the Protect/EQL v2 to Stack/EQL v3 guide. See its README before running; Postgres requires a disposable database and DynamoDB persistence is in memory. - `languages/typescript/examples/*`: Working apps (basic, prisma, supabase-worker) @@ -849,8 +849,10 @@ replays their seeds, and `mise run go:fuzz` fuzzes them (nightly in `fuzz.yml`'s `go-fuzz-campaign`, one matrix row per target). The AEAD crates have no fuzz targets of their own. stack-encrypt's targets (`check_record`, `term_decode`) reach parts of them, and `fuzz.yml` replays -those when the AEAD crates change. vitaminc fuzzed the frame codec from Go (`vcffi`), and -those targets move with that package. +those when the AEAD crates change. Go fuzzes the decoders of its frame codec +with three targets in `languages/golang/encrypt/frame`: `FuzzUnmarshal`, +`FuzzUnmarshalCipherText`, and `FuzzUnmarshalStorage`. `go test` replays +their seeds, and the nightly `go-fuzz-campaign` job fuzzes them. Full walkthrough — layout, adding a target, the CI split — in [`docs/fuzzing.md`](docs/fuzzing.md). For cargo-fuzz mechanics (sanitizers, corpus, crash triage) use the Trail of Bits `cargo-fuzz` skill rather than a diff --git a/conformance/stack-encrypt/exchange-contract.md b/conformance/stack-encrypt/exchange-contract.md index b3707d6d7..bb714c189 100644 --- a/conformance/stack-encrypt/exchange-contract.md +++ b/conformance/stack-encrypt/exchange-contract.md @@ -32,7 +32,7 @@ mise run test:conformance:exchange |---|---|---| | `values` | One record per positive case of `v1/record-values-v1.cases.json` (the value-boundary corpus), under the plan that case declares, with context `["conformance", "exchange"]`: the sealed leaf and every declared index term; nothing for a SQL null | The record opens to the case's typed input. Every stored term equals the term the consumer's own query of the same value derives (`eq` for equality, `lt` for an order index), and the `equal_query` spelling derives the same equality term. | | `record` | The rows of the corpus's one record: a passthrough `int64` id (held on the host by Go, lowered as a `passthrough` output by Rust), text, `uint32`, decimal, date and timestamp fields with equality and order terms, a SQL-null text field and a sealed-null `float32` field, under context `["conformance", "exchange", "people"]` | The passthrough carried equals the corpus input; every sealed field opens to its input, a sealed null opens as null and a SQL null is absent from storage and opens as null; every stored term equals the consumer's derived query term | -| `blobs` | A whole struct (`name`, `age`, `tags`, optional `nickname`) as one opaque ciphertext under `["conformance", "exchange", "blob"]`, field `value`: Rust through `OpaqueBlob`, Go through the storage blob the generated opaque path writes (`vcffi.MarshalStorage` sealed as the one `bytes` field) | The ciphertext opens and decodes to the corpus value through the other SDK's opaque reader (`OpaqueBlob` or `gensupport.Opaque`). A nil Go slice and an empty Rust `Vec` are one value; Rust's `Some` marker and Go's bare pointer are one value | +| `blobs` | A whole struct (`name`, `age`, `tags`, optional `nickname`) as one opaque ciphertext under `["conformance", "exchange", "blob"]`, field `value`. Rust writes it through `OpaqueBlob`. Go writes it through the generated opaque path, as a blob in the storage profile, sealed as the one `bytes` field | The ciphertext opens and decodes to the corpus value through the other SDK's opaque reader (`OpaqueBlob` or `gensupport.Opaque`). A nil Go slice and an empty Rust `Vec` are one value; Rust's `Some` marker and Go's bare pointer are one value | | `eql-rows` | The EQL v4 `profiles` rows: every column of the committed fixture's plaintexts sealed afresh, Rust through eql-bindings' typed targets, Go through its generated code | Each column opens to the plaintext through the other side's typed target, and each equality column's stored `hm` equals the term the consumer's own equality query derives for that plaintext (the generated `*Eq` query in Go, the typed `*EqQuery` target in Rust) | Each kind runs Go to Rust and Rust to Go. Ciphertext bytes are never diff --git a/conformance/vitaminc-aead/README.md b/conformance/vitaminc-aead/README.md index 8733a66cf..5e6e13046 100644 --- a/conformance/vitaminc-aead/README.md +++ b/conformance/vitaminc-aead/README.md @@ -1,7 +1,10 @@ # Value conformance corpus -`value-conformance.json` holds the shared vectors that Rust, Node, the Go -codec and the Go WASM encryption guest all check. Payload bytes are frozen by +`value-conformance.json` contains the shared vectors that three codecs +check: Rust, Node, and the Go frame codec in +`languages/golang/encrypt/frame`. + +Payload bytes are frozen by `vitaminc-aead`'s scalar tag table and leaf codec ([`vitaminc-aead`'s ADR 0001](../../packages/vitaminc-aead/docs/adr/0001-describe-plaintext-once-and-consume-it-with-sinks.md) section 3): fixed-width integers and float bits are little-endian, dates count days from @@ -87,9 +90,9 @@ without their transport decoder, then check both directions: decoding the bytes gives that value, and encoding that value gives the bytes. A bug that decodes and encodes symmetrically wrong therefore still fails. Adding a kind means teaching each language's `expected` helper to build it. The Go fuzz -targets seed themselves from `vectors`, `malformed`, `normalized` and -`ciphertext_malformed`, so every row is also a starting point for the -differential run against the guest. +targets take their seeds from `vectors`, `malformed`, `normalized`, and +`ciphertext_malformed`. Every row is therefore also a starting input for +fuzzing the Go decoders. These are the scalar/value-level vectors needed by #375 and #414. The wider #332 cross-language ciphertext, guest-object and SDK corpus remains separate diff --git a/docs/fuzzing.md b/docs/fuzzing.md index 8d77a74c5..bd68142af 100644 --- a/docs/fuzzing.md +++ b/docs/fuzzing.md @@ -171,7 +171,34 @@ The fuzz tests never pass a pair inside memory but outside the host's own buffers. That breaks the host's side of the contract: an export that wipes its input would zero the guest's own memory. -Run them with mise, after building the guests: +## Go: fuzzing the frame codec + +The Go frame codec, `languages/golang/encrypt/frame`, decodes bytes that +the guest wrote and blobs read from a database. The decoders treat that +input as hostile. Three fuzz targets check two rules for each decoder: + +- The decoder must not panic. +- Any input that the decoder accepts must be written back as the same + bytes. + +Some changes to the bytes are allowed, because a Go value cannot avoid +them. For example, an `undefined` comes back as null. A timestamp in +seconds, milliseconds, or microseconds comes back in nanoseconds. + +The targets need no guest. The seeds come from two files: the value corpus, +`conformance/vitaminc-aead/value-conformance.json`, and the storage corpus, +`packages/recipher-frame/testdata/storage-v1.json`. + +| Go fuzz target | package | what it decodes | +|---|---|---| +| `FuzzUnmarshal` | `encrypt/frame` | a value frame (`Unmarshal`) | +| `FuzzUnmarshalCipherText` | `encrypt/frame` | a ciphertext tree (`UnmarshalCipherText`) | +| `FuzzUnmarshalStorage` | `encrypt/frame` | a storage blob (`UnmarshalStorage`) | + +## Running the Go targets + +Run them with mise. Build the guests first for the targets that call a +guest. The targets of the frame codec need no guest. ```bash mise run wasm:guest:build:deterministic diff --git a/docs/plans/2026-11-14-move-vitaminc-aead-into-the-stack.md b/docs/plans/2026-11-14-move-vitaminc-aead-into-the-stack.md index 5ab0eebda..35fc346f0 100644 --- a/docs/plans/2026-11-14-move-vitaminc-aead-into-the-stack.md +++ b/docs/plans/2026-11-14-move-vitaminc-aead-into-the-stack.md @@ -511,6 +511,39 @@ The work: 5. Delete `vcencrypt` and its guest from vitaminc. It was a demonstration of the approach, and the Go module replaces it. +### Done + +Items 1 to 4 are done, on the branch `refactor/go-frame-codec-in-module`: + +- The two packages moved, and stay two packages. `vcffi` is now + `languages/golang/encrypt/frame`: the codec and the storage profile. + `vcvalue` is now `languages/golang/encrypt/value`: the value model, which + imports nothing outside the standard library. Both are public, as they + were in vitaminc. Both were copied from vitaminc commit `f1fc9ae74`, with + their tests and fuzz targets. The tests read the value corpus + (`conformance/vitaminc-aead`) and the storage corpus + (`packages/recipher-frame/testdata`) from this repository. +- `encrypt.Date`, `Decimal`, `Int128`, and `Uint128` are still aliases, + now of the types in `encrypt/value`. `encrypt.UUID`, `Encryptable`, and + `Encoder` are new aliases, of `value.UUID`, `frame.Encryptable` and + `frame.Encoder`. Each type is declared once, so the codec needs no + conversion. +- The sealed leaf family, `VCValueLeaves`, `TypedNull`, `FixedWidth`, and + `FixedType` are removed. The typed null for a nil pointer is built from + the tag table, so the codec has no list of types. `record.Kind` is the + only list of type names. +- No `go.mod` names a vitaminc module: not the one of the module, and not + those of its two nested modules. `scripts/go-release-version.mjs` no + longer refuses a final version because of a vitaminc pin. +- The Go campaign in `fuzz.yml` fuzzes the three decoders every night. + +Two things are still to do: + +- Item 5, in vitaminc. +- The differential fuzzers that compared the Go codec with a Rust guest, in + vitaminc's `vcencrypt`. Those fuzzers could run against + `languages/golang/encrypt/guest`. + ## What waits on this plan - The TypeScript SDK: #1775, #1776 and the prototype #1829. diff --git a/languages/golang/.golangci.yaml b/languages/golang/.golangci.yaml index 00b010b5e..c77b0f3cf 100644 --- a/languages/golang/.golangci.yaml +++ b/languages/golang/.golangci.yaml @@ -20,6 +20,14 @@ linters: - path: (_test\.go|internal/guesttest/) linters: - gosec + # The frame codec and its value types convert between integer widths + # on purpose. They read and write integers in two's complement, and + # check every length, count and range against a limit before they + # convert one. + - path: encrypt/(frame|value)/ + linters: + - gosec + text: G115 formatters: enable: diff --git a/languages/golang/CHANGELOG.md b/languages/golang/CHANGELOG.md index 691fbf678..171f448e8 100644 --- a/languages/golang/CHANGELOG.md +++ b/languages/golang/CHANGELOG.md @@ -41,12 +41,28 @@ and `languages/golang/encrypt/encrypttest/vX.Y.Z` on the same commit. ### Added -- `gensupport.UUID`, the kind `"uuid"`: a field the engine seals and - opens as a UUID, sixteen bytes under vitaminc's UUID logical type. It - takes an equality index and no order or match index. Its value is a - `vcvalue.UUID`, or a value of any type whose underlying type is - `[16]byte` (`github.com/google/uuid.UUID`, say), which is converted to - one. `stashgen` does not yet map a Go type to it. +- `gensupport.UUID`, the kind `"uuid"`: a field that the engine seals and + opens as a UUID. A UUID is sixteen bytes with the logical type UUID. The + field takes an equality index, and no order or match index. The value of + the field is an `encrypt.UUID`. A value of any other type whose + underlying type is `[16]byte`, such as `github.com/google/uuid.UUID`, is + converted to an `encrypt.UUID`. `stashgen` does not yet map a Go type to + this kind. +- `encrypt.UUID` and `ParseUUID`: sixteen bytes that are sealed as a UUID. + An opened UUID has this type. `encrypt.UUID` is an alias of `value.UUID`. +- `encrypt.Encryptable` and `encrypt.Encoder`, aliases of + `frame.Encryptable` and `frame.Encoder`, for a type that writes its own + value. Give the type a method `EncryptValue(enc encrypt.Encoder) error`. + A field of that type is sealed as the one value that the method writes, + with one of the Encoder's methods, such as `Int64`, `String`, or `Date`. + `Encoder.Err` returns the first error of the encode. + + The zero Encoder keeps nothing and does not panic. The `Err` method of + the zero Encoder returns an error that says so. A unit test of your type + can therefore pass the zero Encoder to `EncryptValue`. +- Two public packages, moved here from vitaminc: `encrypt/frame`, the frame + codec and the storage profile (vitaminc's `vcffi`), and `encrypt/value`, + the value types that the codec reads and writes (vitaminc's `vcvalue`). - `Diagnostic.Row` and `Diagnostic.Found` (#1985). The two accessors give more detail for an error about a plan, a record, or a stored row that is @@ -63,6 +79,34 @@ and `languages/golang/encrypt/encrypttest/vX.Y.Z` on the same commit. ### Breaking +- **vitaminc's Go packages `vcvalue` and `vcffi` are now `encrypt/value` + and `encrypt/frame`.** `encrypt.Date`, `Decimal`, `Int128` and `Uint128` + are still aliases, now of the types in `encrypt/value`. Code that names + only `encrypt` types needs no change. The stored format is unchanged: + every value has the same ciphertext and the same terms as before. + + Code that imports `vcvalue` or `vcffi` changes like this: + + - Import `github.com/cipherstash/stack/languages/golang/encrypt/value` in + place of `vcvalue`, and `.../encrypt/frame` in place of `vcffi`. Or use + the `encrypt` names: `encrypt.Date`, `encrypt.UUID`, + `encrypt.Encoder`, and so on. + - The unsigned methods of the Encoder are `Uint8` to `Uint128`, not + `UInt8` to `UInt128`. + - Error text starts with "value: " or "frame: ", not "vcvalue: " or + "vcffi: ". `errors.Is` matches the same error values as before. + - What only vitaminc's own binding used is gone: `Sealed`, + `SealedEmptySeq`, `SealedEmptyMap`, `TypedNull`, `FixedType`, + `ErrInvalidFixedType`, `Plain.Value`, `Encoder.TypedNull`, + `FixedWidth` and `VCValueLeaves`. + - Without `FixedWidth`, a nil pointer to an `Encryptable` is written as + a null. The engine pads a sealed null to the width of the type that the + field declares, as it does for every null. A field that declares no + type has no width to pad to, so the length of the stored null would + show that it is a null. `Cipher.Seal` therefore refuses a nil + `Encryptable` for such a field, with `ErrEncoding`. Generated code + always declares a type. + - **`Match` refuses `vars` that are not a JSON object with the reason `json_vars_not_object`, not `json_input`** (#1987). If your program compares `Reason()` with `json_input` for this case, change it to the @@ -75,6 +119,14 @@ and `languages/golang/encrypt/encrypttest/vX.Y.Z` on the same commit. ### Changed +- **The module no longer depends on vitaminc's Go packages.** The frame + codec, the storage profile and the value types are now in this module, + in `encrypt/frame` and `encrypt/value`. `go.mod` therefore names no + vitaminc module, so a final version of the module can be released. The + codec writes the same bytes as before. The tests of the codec read the + same value corpus and storage corpus as the Rust codec, from this + repository. + - **A decrypt error names the field and the Go type that the field needs, and never the kind that the value decrypted to** (#1987). The Go type, the kind, and the length of a decrypted value were inside the diff --git a/languages/golang/auth/answer_test.go b/languages/golang/auth/answer_test.go index 3e99bd5ba..a8f0cd233 100644 --- a/languages/golang/auth/answer_test.go +++ b/languages/golang/auth/answer_test.go @@ -5,8 +5,8 @@ import ( "strings" "testing" - "github.com/cipherstash/vitaminc/bindings/go/vcffi" - "github.com/cipherstash/vitaminc/bindings/go/vcvalue" + "github.com/cipherstash/stack/languages/golang/encrypt/frame" + "github.com/cipherstash/stack/languages/golang/encrypt/value" ) // When the answer of an auth guest is not an object, the error is @@ -22,7 +22,7 @@ func TestAnAnswerThatIsNotAnObjectNamesTheExportAndItsKind(t *testing.T) { {"secret-token", "a string"}, {[]byte("secret-key"), "bytes"}, } { - encoded, err := vcffi.Marshal(tc.answer) + encoded, err := frame.Marshal(tc.answer) if err != nil { t.Fatal(err) } @@ -38,7 +38,7 @@ func TestAnAnswerThatIsNotAnObjectNamesTheExportAndItsKind(t *testing.T) { t.Errorf("the error holds the answer: %v", err) } } - encoded, err := vcffi.Marshal(vcvalue.Object{{Key: "access_token", Value: "t"}}) + encoded, err := frame.Marshal(value.Object{{Key: "access_token", Value: "t"}}) if err != nil { t.Fatal(err) } @@ -58,7 +58,7 @@ func TestAnAnswerThatIsNotAnObjectNamesTheExportAndItsKind(t *testing.T) { // value that the answer is. func TestListAnswersNameTheExportAndTheirKind(t *testing.T) { marshal := func(v any) []byte { - out, err := vcffi.Marshal(v) + out, err := frame.Marshal(v) if err != nil { t.Fatal(err) } @@ -95,7 +95,7 @@ func TestListAnswersNameTheExportAndTheirKind(t *testing.T) { // contains the value of the field, because the value can be a token or a // key. func TestAnAnswersFieldsNameTheExport(t *testing.T) { - answer := fields{export: "sa_token", obj: vcvalue.Object{ + answer := fields{export: "sa_token", obj: value.Object{ {Key: "access_token", Value: int64(7)}, {Key: "client_key", Value: "secret-key"}, {Key: "region", Value: []byte("secret")}, @@ -138,7 +138,7 @@ func TestAStepThatDoesNotReadNamesTheExport(t *testing.T) { func mustMarshalAuth(t *testing.T, v any) []byte { t.Helper() - out, err := vcffi.Marshal(v) + out, err := frame.Marshal(v) if err != nil { t.Fatal(err) } diff --git a/languages/golang/auth/guest/Cargo.toml b/languages/golang/auth/guest/Cargo.toml index d22ee9d4c..91281f2b7 100644 --- a/languages/golang/auth/guest/Cargo.toml +++ b/languages/golang/auth/guest/Cargo.toml @@ -31,10 +31,10 @@ url = "2" # Strategies and `Token`, the typed shape of `auth.json`, with default # features off: no reqwest, no native TLS. stack-auth = { path = "../../../../packages/stack-auth", default-features = false } -# The ABI every guest under bindings/go shares: the allocator and buffer -# registry (and with them the `se_alloc`/`se_dealloc` exports), the -# packed-result helpers and the status table. This crate defines only the -# exports that are its own. +# The ABI that every guest under languages/golang shares. The ABI has the +# allocator and the buffer registry, with their `se_alloc` and `se_dealloc` +# exports. The ABI also has the packed-result helpers and the status table. This +# crate defines only the exports that are its own. stack-guest-abi = { path = "../../../../packages/stack-guest-abi" } # The profile directory's API. It builds for wasm32-wasip1 (CIP-4114): the # hostname and the process id are native-only there, and creating a device diff --git a/languages/golang/auth/step.go b/languages/golang/auth/step.go index 89b59b4f7..fef556017 100644 --- a/languages/golang/auth/step.go +++ b/languages/golang/auth/step.go @@ -5,9 +5,9 @@ import ( "errors" "fmt" + "github.com/cipherstash/stack/languages/golang/encrypt/frame" + "github.com/cipherstash/stack/languages/golang/encrypt/value" "github.com/cipherstash/stack/languages/golang/internal/guest" - "github.com/cipherstash/vitaminc/bindings/go/vcffi" - "github.com/cipherstash/vitaminc/bindings/go/vcvalue" "github.com/tetratelabs/wazero/api" ) @@ -81,7 +81,7 @@ var errMalformedStep = guest.BadAnswer("sa_auth_io", errStepMalformed) // [{"method", "url", "headers", "body"}, ...]}`. Every byte slice it // returns is its own copy. func decodeAuthStep(raw []byte) (*authStep, error) { - decoded, err := vcffi.Unmarshal(raw) + decoded, err := frame.Unmarshal(raw) if err != nil { return nil, guest.BadAnswer("sa_auth_io", fmt.Errorf("%w: %w", errStepMalformed, err)) } @@ -97,7 +97,7 @@ func authStepFrom(decoded any) (*authStep, error) { guest.WipeDecoded(decoded) return nil, errMalformedStep } - obj, ok := decoded.(vcvalue.Object) + obj, ok := decoded.(value.Object) if !ok { return refuse() } @@ -144,7 +144,7 @@ func decodeAuthRequest(item any) (authRequest, bool) { guest.WipeDecoded(item) return authRequest{}, false } - obj, ok := item.(vcvalue.Object) + obj, ok := item.(value.Object) if !ok { return refuse() } @@ -213,13 +213,13 @@ func encodeResponses(responses []response) ([]byte, error) { if body == nil { body = []byte{} } - items = append(items, vcvalue.Object{ + items = append(items, value.Object{ {Key: "status", Value: r.status}, {Key: "headers", Value: headers}, {Key: "body", Value: body}, }) } - return vcffi.Marshal(items) + return frame.Marshal(items) } // run drives one token operation, started by the export start selects with diff --git a/languages/golang/auth/steps_test.go b/languages/golang/auth/steps_test.go index 21ed6199c..48be681cc 100644 --- a/languages/golang/auth/steps_test.go +++ b/languages/golang/auth/steps_test.go @@ -16,9 +16,9 @@ import ( "testing" "time" + "github.com/cipherstash/stack/languages/golang/encrypt/frame" + "github.com/cipherstash/stack/languages/golang/encrypt/value" "github.com/cipherstash/stack/languages/golang/internal/guest" - "github.com/cipherstash/vitaminc/bindings/go/vcffi" - "github.com/cipherstash/vitaminc/bindings/go/vcvalue" "github.com/tetratelabs/wazero/api" ) @@ -388,20 +388,20 @@ func TestStrategyAndProfileCloseInAnyOrderReturn(t *testing.T) { } } -// A device session's token read is refused unless it holds both fields, -// with their types, and nothing else. (vcffi refuses a duplicate key -// before decodeDeviceToken sees the frame.) +// A token read for a device session is refused unless the frame has both +// fields, with the right types, and nothing else. The codec refuses a +// duplicate key before decodeDeviceToken receives the frame. func TestDecodeDeviceTokenRefusesAnyOtherShape(t *testing.T) { - type f = vcvalue.Field - frame := func(t *testing.T, v any) []byte { + type f = value.Field + encode := func(t *testing.T, v any) []byte { t.Helper() - raw, err := vcffi.Marshal(v) + raw, err := frame.Marshal(v) if err != nil { t.Fatalf("Marshal: %v", err) } return raw } - token, refresh, err := decodeDeviceToken(frame(t, vcvalue.Object{ + token, refresh, err := decodeDeviceToken(encode(t, value.Object{ {Key: "access_token", Value: "Zq7-secret"}, {Key: "refresh_required", Value: true}, })) if err != nil || token != "Zq7-secret" || !refresh { @@ -409,13 +409,13 @@ func TestDecodeDeviceTokenRefusesAnyOtherShape(t *testing.T) { } for name, raw := range map[string][]byte{ "empty": {}, - "not a map": frame(t, []any{}), - "no token": frame(t, vcvalue.Object{f{Key: "refresh_required", Value: false}}), - "no flag": frame(t, vcvalue.Object{f{Key: "access_token", Value: "Zq7-secret"}}), - "empty token": frame(t, vcvalue.Object{f{Key: "access_token", Value: ""}, f{Key: "refresh_required", Value: false}}), - "token not text": frame(t, vcvalue.Object{f{Key: "access_token", Value: int64(1)}, f{Key: "refresh_required", Value: false}}), - "flag not a bool": frame(t, vcvalue.Object{f{Key: "access_token", Value: "Zq7-secret"}, f{Key: "refresh_required", Value: "no"}}), - "an extra field": frame(t, vcvalue.Object{f{Key: "access_token", Value: "Zq7-secret"}, f{Key: "refresh_required", Value: false}, f{Key: "extra", Value: true}}), + "not a map": encode(t, []any{}), + "no token": encode(t, value.Object{f{Key: "refresh_required", Value: false}}), + "no flag": encode(t, value.Object{f{Key: "access_token", Value: "Zq7-secret"}}), + "empty token": encode(t, value.Object{f{Key: "access_token", Value: ""}, f{Key: "refresh_required", Value: false}}), + "token not text": encode(t, value.Object{f{Key: "access_token", Value: int64(1)}, f{Key: "refresh_required", Value: false}}), + "flag not a bool": encode(t, value.Object{f{Key: "access_token", Value: "Zq7-secret"}, f{Key: "refresh_required", Value: "no"}}), + "an extra field": encode(t, value.Object{f{Key: "access_token", Value: "Zq7-secret"}, f{Key: "refresh_required", Value: false}, f{Key: "extra", Value: true}}), } { _, _, err := decodeDeviceToken(raw) if !errors.Is(err, ErrInternal) { @@ -525,7 +525,7 @@ func byteLeaves(v any) [][]byte { out = append(out, byteLeaves(item)...) } return out - case vcvalue.Object: + case value.Object: var out [][]byte for _, f := range v { out = append(out, byteLeaves(f.Value)...) @@ -539,16 +539,16 @@ func byteLeaves(v any) [][]byte { // body, wherever the refusal comes, carry a credential. func TestARefusedStepIsWipedWhole(t *testing.T) { marker := func() []byte { return []byte("leak-marker-credential") } - request := func(fields ...vcvalue.Field) vcvalue.Object { return vcvalue.Object(fields) } - good := func() vcvalue.Object { + request := func(fields ...value.Field) value.Object { return value.Object(fields) } + good := func() value.Object { return request( - vcvalue.Field{Key: "method", Value: "POST"}, - vcvalue.Field{Key: "url", Value: "https://cts.example/api/authorise"}, - vcvalue.Field{Key: "headers", Value: marker()}, - vcvalue.Field{Key: "body", Value: marker()}, + value.Field{Key: "method", Value: "POST"}, + value.Field{Key: "url", Value: "https://cts.example/api/authorise"}, + value.Field{Key: "headers", Value: marker()}, + value.Field{Key: "body", Value: marker()}, ) } - for name, frame := range map[string]vcvalue.Object{ + for name, step := range map[string]value.Object{ "a field refused before the requests": { {Key: "handle", Value: uint64(1)}, {Key: "unknown", Value: true}, @@ -558,25 +558,25 @@ func TestARefusedStepIsWipedWhole(t *testing.T) { "the requests after a refused one": { {Key: "handle", Value: uint64(1)}, {Key: "parked", Value: false}, - {Key: "requests", Value: []any{request(vcvalue.Field{Key: "method", Value: uint64(5)}), good()}}, + {Key: "requests", Value: []any{request(value.Field{Key: "method", Value: uint64(5)}), good()}}, }, "the fields after a refused one": { {Key: "handle", Value: uint64(1)}, {Key: "parked", Value: false}, {Key: "requests", Value: []any{request( - vcvalue.Field{Key: "method", Value: marker()}, - vcvalue.Field{Key: "url", Value: "https://cts.example"}, - vcvalue.Field{Key: "headers", Value: marker()}, - vcvalue.Field{Key: "body", Value: marker()}, + value.Field{Key: "method", Value: marker()}, + value.Field{Key: "url", Value: "https://cts.example"}, + value.Field{Key: "headers", Value: marker()}, + value.Field{Key: "body", Value: marker()}, )}}, }, } { t.Run(name, func(t *testing.T) { - raw, err := vcffi.Marshal(frame) + raw, err := frame.Marshal(step) if err != nil { t.Fatal(err) } - decoded, err := vcffi.Unmarshal(raw) + decoded, err := frame.Unmarshal(raw) if err != nil { t.Fatal(err) } diff --git a/languages/golang/auth/store.go b/languages/golang/auth/store.go index f5b85c46c..a2a426410 100644 --- a/languages/golang/auth/store.go +++ b/languages/golang/auth/store.go @@ -13,8 +13,8 @@ import ( "sync" "time" + "github.com/cipherstash/stack/languages/golang/encrypt/value" "github.com/cipherstash/stack/languages/golang/internal/guest" - "github.com/cipherstash/vitaminc/bindings/go/vcvalue" "github.com/tetratelabs/wazero/api" ) @@ -546,7 +546,7 @@ func (s *ProfileStore) DeviceIdentity(ctx context.Context) (DeviceIdentity, erro // the export. Every error about the answer names that export. type fields struct { export string - obj vcvalue.Object + obj value.Object } // object decodes the answer of export as an object. For an answer that is @@ -558,7 +558,7 @@ func object(export string, encoded []byte) (fields, error) { if err != nil { return fields{}, err } - obj, ok := decoded.(vcvalue.Object) + obj, ok := decoded.(value.Object) if !ok { return fields{}, guest.BadAnswer(export, fmt.Errorf("it is %s, not an object", guest.KindOf(decoded))) } diff --git a/languages/golang/auth/strategy.go b/languages/golang/auth/strategy.go index 4a789b033..993127a4e 100644 --- a/languages/golang/auth/strategy.go +++ b/languages/golang/auth/strategy.go @@ -10,9 +10,9 @@ import ( "sync" "time" + "github.com/cipherstash/stack/languages/golang/encrypt/frame" + "github.com/cipherstash/stack/languages/golang/encrypt/value" "github.com/cipherstash/stack/languages/golang/internal/guest" - "github.com/cipherstash/vitaminc/bindings/go/vcffi" - "github.com/cipherstash/vitaminc/bindings/go/vcvalue" "github.com/tetratelabs/wazero/api" ) @@ -493,11 +493,11 @@ func (s *Strategy) refreshDeviceSession(ctx context.Context, refresh func(contex // quotes the frame: it carries the token. func decodeDeviceToken(raw []byte) (token string, refresh bool, err error) { malformed := fmt.Errorf("%w: the guest's device session token is malformed", ErrInternal) - decoded, err := vcffi.Unmarshal(raw) + decoded, err := frame.Unmarshal(raw) if err != nil { return "", false, malformed } - obj, ok := decoded.(vcvalue.Object) + obj, ok := decoded.(value.Object) if !ok { return "", false, malformed } diff --git a/languages/golang/cmd/stashgen/README.md b/languages/golang/cmd/stashgen/README.md index 8c6a40b07..66228b829 100644 --- a/languages/golang/cmd/stashgen/README.md +++ b/languages/golang/cmd/stashgen/README.md @@ -512,7 +512,8 @@ No warning, error or log line holds a plaintext value. Generated code sends the engine every sealed field with its value, under the declaration lowered to data: each field's label (`/`), its outputs and its wire type (`int64`, `string`, `bytes`, ...), which `stashgen` chose from the field's Go type. A passthrough field stays on the host: the engine does nothing to it a program could observe, and the FFI codec cannot carry every Go type a program stores beside a ciphertext (a `driver.Valuer`, a `sql.NullTime`). An `opaque` struct crosses as one storage blob and is one column, read back into the exact Go types the struct declares. -The blob is vitaminc's storage profile, version 1 (`vcffi.MarshalStorage`), the format vitaminc keeps readable across releases and languages. +The blob uses version 1 of the storage profile, specified in `packages/recipher-frame/STORAGE.md`. +That format stays readable across releases and languages. A field may be any type that both the storage profile and `encoding/json` carry both ways: a scalar or a type defined over one, `[]byte`, slices, maps with string or integer keys, pointers, structs whose fields are all exported, and types with both `MarshalText` and `UnmarshalText`, such as `time.Time`. `encrypt.Decimal` and `encrypt.Date` have no storage form and are refused in an opaque struct: store them as text, or by their parts. A row an earlier release sealed with one of them in an opaque struct does not decrypt under this release, because no generated file can name the field: decrypt such rows with the earlier release, change the field's type, and encrypt them again before upgrading. diff --git a/languages/golang/encrypt/README.md b/languages/golang/encrypt/README.md index 6e67a1e8a..e9721c470 100644 --- a/languages/golang/encrypt/README.md +++ b/languages/golang/encrypt/README.md @@ -386,9 +386,11 @@ or `ope` index: the engine answers no ordering over bytes, so the term would be stored and never queried, and `stashgen` refuses the declaration (see [Queries](#queries)). -`encrypt.Date`, `Int128`, `Uint128` and `Decimal` are vitaminc's `vcvalue` -types; build them with `encrypt.DateOf`, `ParseInt128`, `ParseUint128` and -`ParseDecimal` (which refuses NaN and the infinities). A `time.Time` opens in +`encrypt.Date`, `Int128`, `Uint128`, and `Decimal` are aliases of the +types in package `encrypt/value`. Build them with `encrypt.DateOf`, `ParseInt128`, `ParseUint128`, +and `ParseDecimal`. `ParseDecimal` refuses NaN and the infinities. + +A `time.Time` opens in UTC: compare it with `Equal`, not `==`. A decimal opens at the scale it was sealed with, but a zero has no sign: `-0.00` opens as `0.00`. The zero `encrypt.Date` is not a date, and `Encrypt` or a query refuses it with diff --git a/languages/golang/encrypt/audit_test.go b/languages/golang/encrypt/audit_test.go index f9e054233..a05bc948f 100644 --- a/languages/golang/encrypt/audit_test.go +++ b/languages/golang/encrypt/audit_test.go @@ -12,7 +12,7 @@ import ( "github.com/cipherstash/stack/languages/golang/encrypt" "github.com/cipherstash/stack/languages/golang/encrypt/internal/testusers" - "github.com/cipherstash/vitaminc/bindings/go/vcvalue" + "github.com/cipherstash/stack/languages/golang/encrypt/value" ) // Audit metadata. The unit tests here need no guest. The round trips run @@ -41,9 +41,9 @@ func sent(t *testing.T, metadata encrypt.AuditMetadata) any { return facts(t, (&encrypt.Client{}).DefaultKeyset().Audit(metadata)) } -func object(fields ...vcvalue.Field) vcvalue.Object { return fields } +func object(fields ...value.Field) value.Object { return fields } -func field(key string, value any) vcvalue.Field { return vcvalue.Field{Key: key, Value: value} } +func field(key string, val any) value.Field { return value.Field{Key: key, Value: val} } // Each method sends its fact as the caller gave it. A time is the // exception: it is sent as RFC 3339 text in UTC. @@ -100,7 +100,7 @@ func TestAuditMetadataSendsEachFactAsBuilt(t *testing.T) { []any{utc}, object(field("at", utc)), }), field("none", []any{}), - field("nothing", vcvalue.Object{}), + field("nothing", value.Object{}), field("purpose", "export"), field("ratio", 0.25), field("request", object(field("id", "req_01J9Z3"))), diff --git a/languages/golang/encrypt/checker.go b/languages/golang/encrypt/checker.go index 890255f30..d9410db0a 100644 --- a/languages/golang/encrypt/checker.go +++ b/languages/golang/encrypt/checker.go @@ -6,10 +6,10 @@ import ( "fmt" "net/http" + "github.com/cipherstash/stack/languages/golang/encrypt/frame" + "github.com/cipherstash/stack/languages/golang/encrypt/value" "github.com/cipherstash/stack/languages/golang/internal/guest" "github.com/cipherstash/stack/languages/golang/internal/record" - "github.com/cipherstash/vitaminc/bindings/go/vcffi" - "github.com/cipherstash/vitaminc/bindings/go/vcvalue" ) // Checker asks the embedded engine about declarations, with no credentials, @@ -53,7 +53,7 @@ func (k *Checker) Check(ctx context.Context, plan *record.Plan) error { // engineCheck asks se_plan_check alone, with no host rule first: the half // of Check that reaches the engine. func (k *Checker) engineCheck(ctx context.Context, plan *record.Plan) error { - encoded, err := vcffi.Marshal(plan.Wire()) + encoded, err := frame.Marshal(plan.Wire()) if err != nil { return fmt.Errorf("%w: %v", ErrEncoding, err) } @@ -94,7 +94,7 @@ func (k *Checker) Operators(ctx context.Context, plan *record.Plan, field string if err := plan.Validate(); err != nil { return nil, fmt.Errorf("%w: %v", ErrEncoding, err) } - encoded, err := vcffi.Marshal(plan.Wire()) + encoded, err := frame.Marshal(plan.Wire()) if err != nil { return nil, fmt.Errorf("%w: %v", ErrEncoding, err) } @@ -133,7 +133,7 @@ func (k *Checker) Contexts(ctx context.Context, plan *record.Plan) (string, erro // contextsOf asks se_contexts about a lowered plan: the half of // [Checker.Contexts] and [Cipher.Contexts] that reaches the engine. func contextsOf(ctx context.Context, c *Client, plan *record.Plan) (string, error) { - encoded, err := vcffi.Marshal(plan.Wire()) + encoded, err := frame.Marshal(plan.Wire()) if err != nil { return "", fmt.Errorf("%w: %v", ErrEncoding, err) } @@ -161,7 +161,7 @@ func contextsOf(ctx context.Context, c *Client, plan *record.Plan) (string, erro // ErrInternal: a decoder that kept a zero value would let stashgen decide an // encrypt_into on a type with no kind or no indexes. func parseTargets(decoded any) ([]record.Target, error) { - obj, ok := decoded.(vcvalue.Object) + obj, ok := decoded.(value.Object) if !ok { return nil, guest.BadAnswer("se_targets", fmt.Errorf("it is %s, not an object", guest.KindOf(decoded))) } @@ -174,7 +174,7 @@ func parseTargets(decoded any) ([]record.Target, error) { } targets := make([]record.Target, 0, len(items)) for i, item := range items { - entry, ok := item.(vcvalue.Object) + entry, ok := item.(value.Object) if !ok { return nil, guest.BadAnswer("se_targets", fmt.Errorf("target %d is %s, not an object", i, guest.KindOf(item))) } @@ -187,7 +187,7 @@ func parseTargets(decoded any) ([]record.Target, error) { return targets, nil } -func parseTarget(entry vcvalue.Object) (record.Target, error) { +func parseTarget(entry value.Object) (record.Target, error) { var t record.Target seen := map[string]bool{} for _, f := range entry { @@ -266,14 +266,14 @@ func parseTarget(entry vcvalue.Object) (record.Target, error) { // parseOperators reads a list of operators, an se_targets entry's or // se_operators's: a list of objects, each with exactly the keys operator, // fidelity, arity, index and input, every value one the engine writes. -func parseOperators(value any) ([]record.Operator, error) { - list, ok := value.([]any) +func parseOperators(val any) ([]record.Operator, error) { + list, ok := val.([]any) if !ok { - return nil, fmt.Errorf("operators is %s, not a list", guest.KindOf(value)) + return nil, fmt.Errorf("operators is %s, not a list", guest.KindOf(val)) } operators := make([]record.Operator, 0, len(list)) for i, item := range list { - entry, ok := item.(vcvalue.Object) + entry, ok := item.(value.Object) if !ok { return nil, fmt.Errorf("operator %d is %s, not an object", i, guest.KindOf(item)) } @@ -361,7 +361,7 @@ func parseOperatorIndex(s string) (record.Output, error) { return "", fmt.Errorf("unknown index %q", s) } -func targetString(f vcvalue.Field) (string, error) { +func targetString(f value.Field) (string, error) { s, ok := f.Value.(string) if !ok { return "", fmt.Errorf("%s is %s, not a string", f.Key, guest.KindOf(f.Value)) @@ -369,7 +369,7 @@ func targetString(f vcvalue.Field) (string, error) { return s, nil } -func targetOptionalString(f vcvalue.Field) (string, error) { +func targetOptionalString(f value.Field) (string, error) { if f.Value == nil { return "", nil } diff --git a/languages/golang/encrypt/ciphertext.go b/languages/golang/encrypt/ciphertext.go index 4ba9dfeb5..294914dda 100644 --- a/languages/golang/encrypt/ciphertext.go +++ b/languages/golang/encrypt/ciphertext.go @@ -4,7 +4,7 @@ import ( "database/sql/driver" "fmt" - "github.com/cipherstash/vitaminc/bindings/go/vcffi" + "github.com/cipherstash/stack/languages/golang/encrypt/frame" ) // Ciphertext is one sealed field as a database column holds it: the frozen @@ -63,24 +63,24 @@ func scanBytes(kind string, src any) ([]byte, error) { // produces. Decoding one is an error at the use site. An absent value is a // sealed null, a Ciphertext like any other value. type otherLeaf struct { - kind vcffi.LeafKind + kind frame.LeafKind bytes []byte } -// leaves is the vcffi.LeafSet of this binding's leaf types. -var leaves = vcffi.LeafSet{ - Classify: func(v any) (vcffi.LeafKind, []byte, bool) { +// leaves is the frame.LeafSet for the leaf types of this package. +var leaves = frame.LeafSet{ + Classify: func(v any) (frame.LeafKind, []byte, bool) { switch n := v.(type) { case Ciphertext: - return vcffi.LeafSingle, n, true + return frame.LeafSingle, n, true case otherLeaf: return n.kind, n.bytes, true default: return 0, nil, false } }, - Make: func(kind vcffi.LeafKind, bytes []byte) any { - if kind == vcffi.LeafSingle { + Make: func(kind frame.LeafKind, bytes []byte) any { + if kind == frame.LeafSingle { return Ciphertext(bytes) } return otherLeaf{kind: kind, bytes: bytes} @@ -88,9 +88,9 @@ var leaves = vcffi.LeafSet{ } func marshalCipherText(v any) ([]byte, error) { - return vcffi.MarshalCipherText(leaves, v) + return frame.MarshalCipherText(leaves, v) } func unmarshalCipherText(buf []byte) (any, error) { - return vcffi.UnmarshalCipherText(leaves, buf) + return frame.UnmarshalCipherText(leaves, buf) } diff --git a/languages/golang/encrypt/client.go b/languages/golang/encrypt/client.go index 0d17c1527..9a73ae096 100644 --- a/languages/golang/encrypt/client.go +++ b/languages/golang/encrypt/client.go @@ -12,9 +12,9 @@ import ( "sync/atomic" "time" + "github.com/cipherstash/stack/languages/golang/encrypt/frame" + "github.com/cipherstash/stack/languages/golang/encrypt/value" "github.com/cipherstash/stack/languages/golang/internal/guest" - "github.com/cipherstash/vitaminc/bindings/go/vcffi" - "github.com/cipherstash/vitaminc/bindings/go/vcvalue" ) // Client is one wasm instance holding one ZeroKMS client: its key, its @@ -376,17 +376,17 @@ func encodeConfig(cfg initConfig) ([]byte, error) { // neither can the marshaller's copy; both live until the collector takes // them: the copies of the key this package cannot zero, accepted for the // length of NewClient. A marshaller that took bytes would remove both. - fields := vcvalue.Object{ + fields := value.Object{ {Key: "client_id", Value: cfg.clientID}, {Key: "client_key", Value: string(guest.KeyBytes(cfg.clientKey))}, } if cfg.zerokmsURL != "" { - fields = append(fields, vcvalue.Field{Key: "zerokms_url", Value: cfg.zerokmsURL}) + fields = append(fields, value.Field{Key: "zerokms_url", Value: cfg.zerokmsURL}) } if cfg.keysetCacheSize > 0 { - fields = append(fields, vcvalue.Field{Key: "keyset_cache_size", Value: strconv.Itoa(cfg.keysetCacheSize)}) + fields = append(fields, value.Field{Key: "keyset_cache_size", Value: strconv.Itoa(cfg.keysetCacheSize)}) } - return vcffi.Marshal(fields) + return frame.Marshal(fields) } // Close shuts the guest down — the client key and every loaded index key @@ -471,7 +471,7 @@ func (c *Client) DefaultKeyset() *Cipher { return &Cipher{client: c, keyset: def // of a name or id on this client is one ZeroKMS round trip, later uses // come from the guest's cache. The default keyset never makes a request. func (c *Client) resolveKeyset(ctx context.Context, sel KeysetSelector) (KeysetID, error) { - encoded, err := vcffi.Marshal(sel.selector()) + encoded, err := frame.Marshal(sel.selector()) if err != nil { return KeysetID{}, err } @@ -604,7 +604,7 @@ func (c *Client) drive(ctx context.Context, kms bool, f stepFunc) ([]byte, error if c.onYield != nil { c.onYield() } - responses, err = vcffi.Marshal([]any{}) + responses, err = frame.Marshal([]any{}) } else { responses, err = c.performStep(ctx, io) } diff --git a/languages/golang/encrypt/conformance_test.go b/languages/golang/encrypt/conformance_test.go index ebccf34ab..6e691f062 100644 --- a/languages/golang/encrypt/conformance_test.go +++ b/languages/golang/encrypt/conformance_test.go @@ -18,8 +18,8 @@ import ( "time" "github.com/cipherstash/stack/languages/golang/encrypt" + "github.com/cipherstash/stack/languages/golang/encrypt/frame" "github.com/cipherstash/stack/languages/golang/internal/record" - "github.com/cipherstash/vitaminc/bindings/go/vcffi" ) // This runner tests the record interface used by generated SDK code. Generated @@ -248,7 +248,7 @@ func TestStackConformance(t *testing.T) { t.Fatal("unexpected equality operand metadata") } want := native.Cases[c.ID] - encoded, err := vcffi.Marshal(input) + encoded, err := frame.Marshal(input) if err != nil { t.Fatal(err) } diff --git a/languages/golang/encrypt/context_conformance_test.go b/languages/golang/encrypt/context_conformance_test.go index 9423114f8..268084ac3 100644 --- a/languages/golang/encrypt/context_conformance_test.go +++ b/languages/golang/encrypt/context_conformance_test.go @@ -12,10 +12,10 @@ import ( "testing" "github.com/cipherstash/stack/languages/golang/encrypt" + "github.com/cipherstash/stack/languages/golang/encrypt/frame" "github.com/cipherstash/stack/languages/golang/encrypt/internal/testusers" + "github.com/cipherstash/stack/languages/golang/encrypt/value" "github.com/cipherstash/stack/languages/golang/internal/record" - "github.com/cipherstash/vitaminc/bindings/go/vcffi" - "github.com/cipherstash/vitaminc/bindings/go/vcvalue" ) type contextCase struct { @@ -144,12 +144,12 @@ func TestContextConformance(t *testing.T) { if len(sentPlans) != 1 { t.Fatalf("expected one encrypt call, got %d", len(sentPlans)) } - decoded, e := vcffi.Unmarshal(sentPlans[0]) + decoded, e := frame.Unmarshal(sentPlans[0]) if e != nil { t.Fatal(e) } field := contextObjectField(t, contextObjectField(t, decoded, "text"), "context") - framed, e := vcffi.Marshal(field) + framed, e := frame.Marshal(field) if e != nil { t.Fatal(e) } @@ -296,7 +296,7 @@ func TestContextBoundaries(t *testing.T) { } tree := make([]any, len(sealed)) for i, row := range sealed { - tree[i] = map[string]any{"tenant": map[string]any{"passthrough": vcvalue.Plain{V: row["tenant"].Context}}, "text": map[string]any{"c": encrypt.Ciphertext(row["text"].Ciphertext), "eq": vcvalue.Plain{V: row["text"].Terms[record.Equality]}}} + tree[i] = map[string]any{"tenant": map[string]any{"passthrough": value.Plain{V: row["tenant"].Context}}, "text": map[string]any{"c": encrypt.Ciphertext(row["text"].Ciphertext), "eq": value.Plain{V: row["text"].Terms[record.Equality]}}} } switch c.Mutation { case "none": @@ -318,7 +318,7 @@ func TestContextBoundaries(t *testing.T) { if c.Mutation == "tamper" { tenant = "tenants/globex" } - row["tenant"] = map[string]any{"passthrough": vcvalue.Plain{V: tenant}} + row["tenant"] = map[string]any{"passthrough": value.Plain{V: tenant}} } default: t.Fatal("unknown mutation") @@ -347,7 +347,7 @@ func TestContextBoundaries(t *testing.T) { generated := make([]testusers.EncryptedNote, len(tree)) for i, row := range tree { fields := row.(map[string]any) - tenant := fields["tenant"].(map[string]any)["passthrough"].(vcvalue.Plain).V.(string) + tenant := fields["tenant"].(map[string]any)["passthrough"].(value.Plain).V.(string) ciphertext := fields["text"].(map[string]any)["c"].(encrypt.Ciphertext) generated[i] = testusers.EncryptedNote{Tenant: tenant, Text: testusers.EncryptedNoteText{Ciphertext: ciphertext}} } @@ -472,11 +472,11 @@ func (c *contextBoundary) UnmarshalJSON(data []byte) error { return decodeRequiredContextJSON(data, (*plain)(c), "id", "tenants", "expected", "mutation", "outcome", "native_retrievals") } -func contextObjectField(t *testing.T, value any, name string) any { +func contextObjectField(t *testing.T, val any, name string) any { t.Helper() - object, ok := value.(vcvalue.Object) + object, ok := val.(value.Object) if !ok { - t.Fatalf("expected object, got %T", value) + t.Fatalf("expected object, got %T", val) } for _, field := range object { if field.Key == name { diff --git a/languages/golang/encrypt/declaration_conformance_test.go b/languages/golang/encrypt/declaration_conformance_test.go index 57e504aae..22fb90b85 100644 --- a/languages/golang/encrypt/declaration_conformance_test.go +++ b/languages/golang/encrypt/declaration_conformance_test.go @@ -13,9 +13,9 @@ import ( "testing" "github.com/cipherstash/stack/languages/golang/encrypt" + "github.com/cipherstash/stack/languages/golang/encrypt/frame" + "github.com/cipherstash/stack/languages/golang/encrypt/value" "github.com/cipherstash/stack/languages/golang/internal/record" - "github.com/cipherstash/vitaminc/bindings/go/vcffi" - "github.com/cipherstash/vitaminc/bindings/go/vcvalue" ) type declarationCase struct { @@ -40,18 +40,18 @@ type declarationError struct { // The corpus JSON projection fixes object order lexically, positive integers // as uint64 and negative integers as int64. This is test input conversion, // not SDK normalization. Non-JSON transport shapes use frame_hex instead. -func declarationValue(t *testing.T, value any) any { +func declarationValue(t *testing.T, val any) any { t.Helper() - switch v := value.(type) { + switch v := val.(type) { case map[string]any: keys := make([]string, 0, len(v)) for key := range v { keys = append(keys, key) } sort.Strings(keys) - object := make(vcvalue.Object, 0, len(keys)) + object := make(value.Object, 0, len(keys)) for _, key := range keys { - object = append(object, vcvalue.Field{Key: key, Value: declarationValue(t, v[key])}) + object = append(object, value.Field{Key: key, Value: declarationValue(t, v[key])}) } return object case []any: @@ -60,11 +60,11 @@ func declarationValue(t *testing.T, value any) any { } return v case json.Number: - value, err := declarationNumber(v.String()) + val, err := declarationNumber(v.String()) if err != nil { t.Fatal(err) } - return value + return val default: return v } @@ -141,10 +141,10 @@ func checkDeclarationCases(t *testing.T, checker *encrypt.Checker, cases []decla if (len(c.Input.JSON) == 0) == (c.Input.FrameHex == nil) { t.Fatal("expected exactly one input representation") } - var frame []byte + var raw []byte var err error if c.Input.FrameHex != nil { - frame, err = hex.DecodeString(*c.Input.FrameHex) + raw, err = hex.DecodeString(*c.Input.FrameHex) } else { decoder := json.NewDecoder(bytes.NewReader(c.Input.JSON)) decoder.UseNumber() @@ -152,7 +152,7 @@ func checkDeclarationCases(t *testing.T, checker *encrypt.Checker, cases []decla if err := decoder.Decode(&value); err != nil { t.Fatal(err) } - frame, err = vcffi.Marshal(declarationValue(t, value)) + raw, err = frame.Marshal(declarationValue(t, value)) } if err != nil { t.Fatal(err) @@ -166,13 +166,13 @@ func checkDeclarationCases(t *testing.T, checker *encrypt.Checker, cases []decla t.Fatalf("host Check: expected ErrEncoding, got %v", hostErr) } } - err = checker.CheckFrameForTest(ctx, frame) + err = checker.CheckFrameForTest(ctx, raw) expected := c.ExpectedError if c.BoundaryError != nil { if accepted || c.Input.FrameHex == nil { t.Fatal("boundary refusal requires a rejected raw frame") } - if _, decodeErr := vcffi.Unmarshal(frame); decodeErr == nil { + if _, decodeErr := frame.Unmarshal(raw); decodeErr == nil { t.Fatal("boundary refusal requires a malformed frame") } expected = c.BoundaryError diff --git a/languages/golang/encrypt/diagnostic_test.go b/languages/golang/encrypt/diagnostic_test.go index c632bde94..505be13ba 100644 --- a/languages/golang/encrypt/diagnostic_test.go +++ b/languages/golang/encrypt/diagnostic_test.go @@ -5,7 +5,7 @@ import ( "errors" "testing" - "github.com/cipherstash/vitaminc/bindings/go/vcffi" + "github.com/cipherstash/stack/languages/golang/encrypt/frame" ) // wantDiagnostic asserts that err carries a *Diagnostic with code and a @@ -44,7 +44,7 @@ func TestGuestRefusalsCarryTheirDiagnostic(t *testing.T) { } wantCode(t, err, "stack_guest_abi::malformed_input") - selector, err := vcffi.Marshal(KeysetName("tenant-b").selector()) + selector, err := frame.Marshal(KeysetName("tenant-b").selector()) if err != nil { t.Fatal(err) } diff --git a/languages/golang/encrypt/doc.go b/languages/golang/encrypt/doc.go index 3003f54b6..9a151f250 100644 --- a/languages/golang/encrypt/doc.go +++ b/languages/golang/encrypt/doc.go @@ -132,12 +132,14 @@ // order index, since over so few values its ordering terms would show which // rows hold which value. // -// Passthrough fields never cross the binding: the engine does nothing to a -// passthrough value that a program could observe, and the FFI codec cannot -// carry every Go type a program stores beside a ciphertext (a -// driver.Valuer, a sql.NullTime). An opaque struct crosses as one storage -// blob (vitaminc's storage profile, vcffi.MarshalStorage) and is one column; -// a row an earlier release sealed as a JSON document still opens. +// A passthrough field never crosses from Go to the engine. The engine does +// nothing to a passthrough value that a program could observe. The codec +// also cannot encode every Go type that a program stores beside a +// ciphertext, such as a driver.Valuer or a sql.NullTime. +// +// An opaque struct crosses to the engine as one storage blob, in version 1 +// of the storage profile. The struct is one column. A row that an earlier +// release sealed as a JSON document still opens. // // # Terms // diff --git a/languages/golang/encrypt/encoder.go b/languages/golang/encrypt/encoder.go new file mode 100644 index 000000000..6359b3a5d --- /dev/null +++ b/languages/golang/encrypt/encoder.go @@ -0,0 +1,25 @@ +package encrypt + +import "github.com/cipherstash/stack/languages/golang/encrypt/frame" + +// Encryptable is the interface of a type that writes its own value. Without +// it, the SDK writes a field by its Go type. With it, the field is sealed as +// the one value that EncryptValue writes. An example is a money type that +// writes its cents with Int64. +// +// The value must be of the kind that the field declares. The engine refuses +// a value of any other kind. +// +// The SDK writes a nil pointer to an Encryptable as a null. EncryptValue is +// not called for a nil pointer. On a field with no declared type, the SDK +// refuses a nil pointer to an Encryptable with ErrEncoding. +// +// Encryptable is frame.Encryptable under another name. +type Encryptable = frame.Encryptable + +// Encoder receives the one value that an Encryptable writes. Use only the +// Encoder that EncryptValue is given. The zero Encoder records nothing, and +// its Err method returns an error that says so. +// +// Encoder is frame.Encoder under another name. +type Encoder = frame.Encoder diff --git a/languages/golang/encrypt/encrypttest/go.mod b/languages/golang/encrypt/encrypttest/go.mod index d9a286f81..0c561380d 100644 --- a/languages/golang/encrypt/encrypttest/go.mod +++ b/languages/golang/encrypt/encrypttest/go.mod @@ -13,8 +13,6 @@ require ( ) require ( - github.com/cipherstash/vitaminc/bindings/go/vcffi v0.0.0-20261119095843-f1fc9ae74882 // indirect - github.com/cipherstash/vitaminc/bindings/go/vcvalue v0.0.0-20261119095843-f1fc9ae74882 // indirect github.com/jackc/pgpassfile v1.0.0 // indirect github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect github.com/jackc/puddle/v2 v2.2.3 // indirect diff --git a/languages/golang/encrypt/encrypttest/go.sum b/languages/golang/encrypt/encrypttest/go.sum index 13d014621..6d8e49bec 100644 --- a/languages/golang/encrypt/encrypttest/go.sum +++ b/languages/golang/encrypt/encrypttest/go.sum @@ -1,7 +1,3 @@ -github.com/cipherstash/vitaminc/bindings/go/vcffi v0.0.0-20261119095843-f1fc9ae74882 h1:T3GexX/bqkB3KS9mbz8TJxEIP/RdUyFgcMH6VQDnRR8= -github.com/cipherstash/vitaminc/bindings/go/vcffi v0.0.0-20261119095843-f1fc9ae74882/go.mod h1:7hPdj2tN3YpcPZYdZ+Fe7+Fsc7dnSyH5bsL9y+LbRuM= -github.com/cipherstash/vitaminc/bindings/go/vcvalue v0.0.0-20261119095843-f1fc9ae74882 h1:5joeyPbldjXj9vRemilG7wYwmICFPZSPBMXiXGsgg7Q= -github.com/cipherstash/vitaminc/bindings/go/vcvalue v0.0.0-20261119095843-f1fc9ae74882/go.mod h1:RJODA1DCSm4H+1pbmCzDdT2pAIkxhinwIu6ewjh5sPs= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= diff --git a/languages/golang/encrypt/errors.go b/languages/golang/encrypt/errors.go index 90158ae44..c04c12f6f 100644 --- a/languages/golang/encrypt/errors.go +++ b/languages/golang/encrypt/errors.go @@ -1,8 +1,8 @@ package encrypt import ( + "github.com/cipherstash/stack/languages/golang/encrypt/frame" "github.com/cipherstash/stack/languages/golang/internal/guest" - "github.com/cipherstash/vitaminc/bindings/go/vcffi" ) // Failure kinds surfaced across the boundary: the guest reports a status @@ -69,11 +69,12 @@ var ( ErrMemoryLock = guest.ErrMemoryLock ) -// ErrStorageVersion is an opaque struct sealed as a storage blob of a -// version this release does not read: a later release wrote it. Its error -// wraps [ErrEncoding] too. It is vcffi.ErrUnsupportedVersion, named here so -// a program can check for it without importing vitaminc's bindings. -var ErrStorageVersion = vcffi.ErrUnsupportedVersion +// ErrStorageVersion means that an opaque struct was sealed as a storage blob +// of a version that this release does not read. A later release wrote the +// blob. The error that the SDK returns wraps [ErrEncoding] too. +// ErrStorageVersion is an error value of the SDK's codec. The value is +// exported here so that a program can check for it with errors.Is. +var ErrStorageVersion = frame.ErrUnsupportedVersion // Diagnostic is the full error behind a failure the guest reports, beside // the kind: every such failure is a *Diagnostic wrapping one of the diff --git a/languages/golang/encrypt/example/go.mod b/languages/golang/encrypt/example/go.mod index 2c8e56347..5f676e80b 100644 --- a/languages/golang/encrypt/example/go.mod +++ b/languages/golang/encrypt/example/go.mod @@ -12,8 +12,6 @@ require ( ) require ( - github.com/cipherstash/vitaminc/bindings/go/vcffi v0.0.0-20261119095843-f1fc9ae74882 // indirect - github.com/cipherstash/vitaminc/bindings/go/vcvalue v0.0.0-20261119095843-f1fc9ae74882 // indirect github.com/jackc/pgpassfile v1.0.0 // indirect github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect github.com/jackc/puddle/v2 v2.2.3 // indirect diff --git a/languages/golang/encrypt/example/go.sum b/languages/golang/encrypt/example/go.sum index 13d014621..6d8e49bec 100644 --- a/languages/golang/encrypt/example/go.sum +++ b/languages/golang/encrypt/example/go.sum @@ -1,7 +1,3 @@ -github.com/cipherstash/vitaminc/bindings/go/vcffi v0.0.0-20261119095843-f1fc9ae74882 h1:T3GexX/bqkB3KS9mbz8TJxEIP/RdUyFgcMH6VQDnRR8= -github.com/cipherstash/vitaminc/bindings/go/vcffi v0.0.0-20261119095843-f1fc9ae74882/go.mod h1:7hPdj2tN3YpcPZYdZ+Fe7+Fsc7dnSyH5bsL9y+LbRuM= -github.com/cipherstash/vitaminc/bindings/go/vcvalue v0.0.0-20261119095843-f1fc9ae74882 h1:5joeyPbldjXj9vRemilG7wYwmICFPZSPBMXiXGsgg7Q= -github.com/cipherstash/vitaminc/bindings/go/vcvalue v0.0.0-20261119095843-f1fc9ae74882/go.mod h1:RJODA1DCSm4H+1pbmCzDdT2pAIkxhinwIu6ewjh5sPs= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= diff --git a/languages/golang/encrypt/exchange_conformance_test.go b/languages/golang/encrypt/exchange_conformance_test.go index 451c8ba8a..53ae0edb2 100644 --- a/languages/golang/encrypt/exchange_conformance_test.go +++ b/languages/golang/encrypt/exchange_conformance_test.go @@ -15,9 +15,9 @@ import ( "testing" "github.com/cipherstash/stack/languages/golang/encrypt" + "github.com/cipherstash/stack/languages/golang/encrypt/frame" "github.com/cipherstash/stack/languages/golang/encrypt/gensupport" "github.com/cipherstash/stack/languages/golang/internal/record" - "github.com/cipherstash/vitaminc/bindings/go/vcffi" ) // The fresh cross-language artifact exchange profile: this runner writes @@ -374,7 +374,7 @@ func produceExchange(t *testing.T, ctx context.Context, cipher *encrypt.Cipher, blobPlan := exchangeBlobPlan(corpus) for _, c := range corpus.Blob.Cases { - encoded, err := vcffi.MarshalStorage(c.Value) + encoded, err := frame.MarshalStorage(c.Value) if err != nil { t.Fatalf("blob: %s: %v", c.ID, err) } diff --git a/languages/golang/encrypt/export_test.go b/languages/golang/encrypt/export_test.go index c5930af7e..a22ec9904 100644 --- a/languages/golang/encrypt/export_test.go +++ b/languages/golang/encrypt/export_test.go @@ -11,10 +11,10 @@ import ( "sync" "testing" + "github.com/cipherstash/stack/languages/golang/encrypt/frame" + "github.com/cipherstash/stack/languages/golang/encrypt/value" "github.com/cipherstash/stack/languages/golang/internal/guest" "github.com/cipherstash/stack/languages/golang/internal/record" - "github.com/cipherstash/vitaminc/bindings/go/vcffi" - "github.com/cipherstash/vitaminc/bindings/go/vcvalue" "github.com/tetratelabs/wazero/api" ) @@ -64,7 +64,7 @@ func FixedCredentials() Credentials { return testCredentials(staticToken("stub-t // names operator as its operation, at path: nil when the engine opens a // read of that operation. func (cph *Cipher) JSONOpensForTest(ctx context.Context, plan *record.Plan, field, operator, path string) error { - _, err := cph.jsonOpen(ctx, plan, field, vcvalue.Object{{Key: "operation", Value: operator}, {Key: "path", Value: path}}, nil) + _, err := cph.jsonOpen(ctx, plan, field, value.Object{{Key: "operation", Value: operator}, {Key: "path", Value: path}}, nil) return err } @@ -323,11 +323,11 @@ func (r *recordingTransport) take() []RecordedRequest { // key, so the SDK leaves the metadata out. The test reads what the guest // answers to a host that sends it anyway. func (cph *Cipher) TermWithAuditForTest(ctx context.Context, value any, fieldContext []any) ([]byte, error) { - encodedValue, err := vcffi.Marshal(value) + encodedValue, err := frame.Marshal(value) if err != nil { return nil, err } - encodedContext, err := vcffi.Marshal(fieldContext) + encodedContext, err := frame.Marshal(fieldContext) if err != nil { return nil, err } @@ -355,11 +355,11 @@ func (cph *Cipher) AuditFactsForTest() (any, error) { if !ok { return nil, nil } - encoded, err := vcffi.Marshal(facts) + encoded, err := frame.Marshal(facts) if err != nil { return nil, err } - return vcffi.Unmarshal(encoded) + return frame.Unmarshal(encoded) } // AuditUncheckedForTest is the cipher with facts as its audit metadata, as diff --git a/languages/golang/encrypt/frame/LICENSE b/languages/golang/encrypt/frame/LICENSE new file mode 100644 index 000000000..2212a9966 --- /dev/null +++ b/languages/golang/encrypt/frame/LICENSE @@ -0,0 +1,25 @@ +Copyright (c) 2024-2026 CipherStash Inc + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/languages/golang/encrypt/frame/ciphertext.go b/languages/golang/encrypt/frame/ciphertext.go new file mode 100644 index 000000000..cc0bbb5ae --- /dev/null +++ b/languages/golang/encrypt/frame/ciphertext.go @@ -0,0 +1,318 @@ +package frame + +import ( + "errors" + "fmt" + "slices" + + "github.com/cipherstash/stack/languages/golang/encrypt/value" +) + +// A ciphertext is a tree of ordinary Go values, with the same structure as a +// decoded plaintext. Marker types show which parts are sealed and which are +// passthrough. A node is one of these: +// +// - A sealed leaf, of one of the caller's [LeafSet] types. A sealed leaf +// is one encrypted value, an authenticated marker for an absent value, +// or an authenticated marker for an empty sequence or map. +// - Plain{V: ...}, a passthrough value. Anyone can read it without the +// key. +// - []any, a sequence of ciphertext nodes. +// - map[string]any, a record of named nodes. +// +// The keys of a map are not encrypted. Each key is cryptographically bound +// to its sealed value, so decryption fails if a key is renamed or two keys +// are swapped. The order of the entries is not authenticated. The encoder +// writes the keys in sorted order, so equal maps have equal bytes. The map +// as a whole is not sealed: any subset of its entries decrypts without the +// rest. +// +// The package deliberately has no type for the tree. Only the bytes of a +// sealed leaf are a format that never changes. The transport bytes that +// cross into and out of the guest are an implementation detail. +// +// The codec does not decide which Go types are leaves. The caller supplies a +// [LeafSet], so that a leaf has a distinct Go type. A value that is not a +// leaf therefore cannot be scanned or marshaled in the place of a leaf. + +// The tags of the nodes in the ciphertext encoding. The Rust codec uses the +// same values. The value 0x02 is not a tag, because an absent value is a +// sealed null leaf. The encoder never writes 0x02. The decoder refuses it, +// as it refuses any unknown tag. +const ( + ctSingle byte = 0x01 + ctSeq byte = 0x03 + ctMap byte = 0x04 + ctPassthrough byte = 0x05 + ctEmptySeq byte = 0x06 + ctEmptyMap byte = 0x07 +) + +// LeafKind is one of the three kinds of sealed leaf in the ciphertext +// encoding. The stored bytes of a leaf do not record its kind. The kind is +// authenticated through the additional authenticated data (AAD) of the leaf. +// Each kind has a different AAD. The ciphertext encoding therefore records +// the kind in the tag. +type LeafKind byte + +const ( + // LeafSingle is one encrypted value. + LeafSingle LeafKind = iota + // LeafEmptySeq is the authenticated marker for an empty sequence. + LeafEmptySeq + // LeafEmptyMap is the authenticated marker for an empty map. + LeafEmptyMap +) + +// LeafSet converts between the caller's sealed-leaf types and the leaves of +// the ciphertext encoding, in both directions. The caller defines its own +// leaf types, so a leaf that one cipher sealed is never used as the leaf of +// another. The caller gives the codec two functions: +// +// - Classify reports whether v is one of the caller's leaf values. If v is +// one, Classify returns its kind and its bytes. The codec never passes +// one of its own node types to Classify: []any, map[string]any, or +// Plain. A LeafSet therefore cannot treat a subtree as one leaf. The +// encoder refuses a value that Classify does not accept, as plaintext +// that is not marked. +// - Make builds the caller's leaf value for a kind that the decoder read. +// The byte slice is newly allocated, and Make owns it. Make returns nil +// to refuse the kind. The decoder then returns an error. A LeafSet that +// builds only some kinds therefore fails with an error, and never puts a +// nil node into the decoded tree. +type LeafSet struct { + Classify func(v any) (LeafKind, []byte, bool) + Make func(kind LeafKind, bytes []byte) any +} + +// check refuses a LeafSet that has a nil function. The check runs before the +// codec encodes or decodes anything. The error then names the mistake. +// Without check, the mistake would be a nil-function panic part of the way +// through a tree. +func (l LeafSet) check() error { + if l.Classify == nil || l.Make == nil { + return errors.New("frame: LeafSet must define both Classify and Make") + } + return nil +} + +// leafTags is the only table that pairs a LeafKind with its tag. The +// functions leafTag and leafKind read it, one in each direction. A new kind +// of leaf therefore cannot be added to one direction and left out of the +// other. +// +// No ciphertext tag is 0x00, so a zero entry means that the kind has no tag. +// A zero entry appears when the LeafKind constants skip a value. An index +// past the end of the table has no tag either. Both leafTag and leafKind +// refuse such a kind. Go therefore never encodes and decodes a kind with a +// tag that the Rust codec does not know. +var leafTags = [...]byte{ + LeafSingle: ctSingle, + LeafEmptySeq: ctEmptySeq, + LeafEmptyMap: ctEmptyMap, +} + +// leafTag returns the tag for a kind that Classify returned. +func leafTag(kind LeafKind) (byte, error) { + if int(kind) >= len(leafTags) || leafTags[kind] == 0 { + return 0, fmt.Errorf("frame: LeafSet.Classify returned an unknown LeafKind %d", kind) + } + return leafTags[kind], nil +} + +// leafKind returns the kind of leaf for a tag. The decoder uses it. +func leafKind(tag byte) (LeafKind, bool) { + if tag == 0 { + return 0, false + } + for kind, t := range leafTags { + if t == tag { + return LeafKind(kind), true + } + } + return 0, false +} + +// MarshalCipherText encodes a ciphertext tree as transport bytes. The leaves +// argument identifies the caller's sealed-leaf types. MarshalCipherText +// refuses a plaintext value that is not marked. A passthrough value must be +// wrapped in Plain, so no value is left unencrypted by accident. +func MarshalCipherText(leaves LeafSet, v any) ([]byte, error) { + if err := leaves.check(); err != nil { + return nil, err + } + return encodeCipherText(leaves, nil, v, 0) +} + +// UnmarshalCipherText decodes the transport bytes of a ciphertext into the +// tree of Go values described above. The Make function of leaves builds each +// leaf node. UnmarshalCipherText returns ErrMalformed if any bytes are left +// after the tree. +func UnmarshalCipherText(leaves LeafSet, buf []byte) (any, error) { + if err := leaves.check(); err != nil { + return nil, err + } + r := &reader{buf: buf} + ct, err := decodeCipherText(leaves, r, 0) + if err != nil { + return nil, err + } + if !r.finished() { + return nil, ErrMalformed + } + return ct, nil +} + +func encodeCipherText(leaves LeafSet, out []byte, v any, depth int) ([]byte, error) { + if depth > maxDepth { + return nil, ErrTooDeep + } + // The cases for the codec's own node types come first, so Classify never + // receives one of them. A LeafSet therefore cannot treat a whole subtree + // as one leaf. Only the default case calls Classify. + switch n := v.(type) { + case []any: + out = append(out, ctSeq) + out, err := appendLen(out, len(n)) + if err != nil { + return nil, err + } + for _, item := range n { + if out, err = encodeCipherText(leaves, out, item, depth+1); err != nil { + return nil, err + } + } + return out, nil + case map[string]any: + out = append(out, ctMap) + out, err := appendLen(out, len(n)) + if err != nil { + return nil, err + } + keys := make([]string, 0, len(n)) + for k := range n { + keys = append(keys, k) + } + slices.Sort(keys) + for _, k := range keys { + if out, err = appendChunk(out, []byte(k)); err != nil { + return nil, err + } + if out, err = encodeCipherText(leaves, out, n[k], depth+1); err != nil { + return nil, err + } + } + return out, nil + case value.Plain: + // The value inside a Plain is one level deeper. Refuse it here if + // that level is too deep, because the scalar methods of the value + // encoder do not check the depth. The decoder applies the same limit + // in decodeValue. Without this check, the encoder would write bytes + // that the decoder always refuses. + if depth+1 > maxDepth { + return nil, ErrTooDeep + } + out = append(out, ctPassthrough) + // Encode the plaintext value as one value node. The node counts + // against the same depth limit as the ciphertext around it, at + // depth+1. The Rust codec encodes CT_PASSTHROUGH the same way. + st := &encState{buf: out} + var done int + encodeAny(Encoder{st: st, depth: depth + 1, done: &done}, n.V) + if st.err != nil { + return nil, st.err + } + if done != 1 { + return nil, fmt.Errorf("frame: EncryptValue must write exactly one complete passthrough value, and wrote %d", done) + } + return st.buf, nil + default: + if kind, bytes, ok := leaves.Classify(v); ok { + tag, err := leafTag(kind) + if err != nil { + return nil, err + } + out = append(out, tag) + return appendChunk(out, bytes) + } + return nil, fmt.Errorf("frame: %T is not a ciphertext node; wrap a passthrough value in Plain", v) + } +} + +func decodeCipherText(leaves LeafSet, r *reader, depth int) (any, error) { + if depth > maxDepth { + return nil, ErrMalformed + } + tag, err := r.byteTag() + if err != nil { + return nil, err + } + if kind, ok := leafKind(tag); ok { + n, err := r.count() + if err != nil { + return nil, err + } + s, err := r.take(n) + if err != nil { + return nil, err + } + leaf := make([]byte, len(s)) + copy(leaf, s) + node := leaves.Make(kind, leaf) + if node == nil { + // A LeafSet that builds no value for this kind is a mistake in + // the caller. The input is not malformed, so the error names the + // mistake. A nil node in the tree would fail only later, + // somewhere in the caller's code. + return nil, fmt.Errorf("frame: LeafSet.Make returned no value for LeafKind %d", kind) + } + return node, nil + } + switch tag { + case ctSeq: + n, err := r.count() + if err != nil { + return nil, err + } + items := make([]any, 0, eagerCap(n)) + for range n { + item, err := decodeCipherText(leaves, r, depth+1) + if err != nil { + return nil, err + } + items = append(items, item) + } + return items, nil + case ctMap: + n, err := r.count() + if err != nil { + return nil, err + } + fields := make(map[string]any, eagerCap(n)) + for range n { + key, err := r.str() + if err != nil { + return nil, err + } + if _, dup := fields[key]; dup { + return nil, ErrMalformed + } + node, err := decodeCipherText(leaves, r, depth+1) + if err != nil { + return nil, err + } + fields[key] = node + } + return fields, nil + case ctPassthrough: + // A passthrough node contains one plaintext value node. The value is + // decoded one level deeper. + v, err := decodeValue(r, depth+1) + if err != nil { + return nil, err + } + return value.Plain{V: v}, nil + default: + return nil, ErrMalformed + } +} diff --git a/languages/golang/encrypt/frame/codec_test.go b/languages/golang/encrypt/frame/codec_test.go new file mode 100644 index 000000000..ebcd9f225 --- /dev/null +++ b/languages/golang/encrypt/frame/codec_test.go @@ -0,0 +1,1058 @@ +package frame + +import ( + "bytes" + "encoding/binary" + "errors" + "math" + "reflect" + "strings" + "testing" + + "github.com/cipherstash/stack/languages/golang/encrypt/value" +) + +// marshalUnmarshal encodes v as transport bytes and decodes the bytes again. +// Every case below uses it. +func marshalUnmarshal(t *testing.T, v any) any { + t.Helper() + buf, err := Marshal(v) + if err != nil { + t.Fatalf("Marshal(%#v): %v", v, err) + } + got, err := Unmarshal(buf) + if err != nil { + t.Fatalf("Unmarshal: %v", err) + } + return got +} + +func TestReflectNatives(t *testing.T) { + cases := []struct { + name string + in any + want any + }{ + {"nil", nil, nil}, + {"bool", true, true}, + {"int", 42, int64(42)}, // an int is written as Int64 + {"int8", int8(-5), int8(-5)}, // exact signed width + {"int16", int16(-300), int16(-300)}, // exact signed width + {"int32", int32(-9), int32(-9)}, // Int32, exact width + {"int64", int64(-9), int64(-9)}, // Int64 + {"uint8", uint8(7), uint8(7)}, // exact unsigned width + {"uint16", uint16(300), uint16(300)}, // exact unsigned width + {"uint32", uint32(7), uint32(7)}, // Uint32, exact width + {"uint", uint(7), uint64(7)}, // a uint is always written as Uint64 + {"uint64-small", uint64(7), uint64(7)}, // a uint64 is written as Uint64 + {"uint64-max", uint64(math.MaxUint64), uint64(math.MaxUint64)}, + {"float32", float32(1.5), float32(1.5)}, // Float32, exact width + {"float", 1.5, 1.5}, // a float64 is written as Float64 + {"string", "hi", "hi"}, + {"bytes", []byte{1, 2, 3}, []byte{1, 2, 3}}, + {"slice", []int{1, 2}, []any{int64(1), int64(2)}}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + got := marshalUnmarshal(t, c.in) + if !reflect.DeepEqual(got, c.want) { + t.Fatalf("got %#v, want %#v", got, c.want) + } + }) + } +} + +func TestReflectStructTags(t *testing.T) { + type inner struct { + A int64 `vc:"a"` + } + type outer struct { + Name string `vc:"name"` + Skipped string `vc:"-"` + hidden string //nolint:unused // unexported, must be skipped + Nested inner + } + got := marshalUnmarshal(t, outer{Name: "x", Skipped: "no", hidden: "no", Nested: inner{A: 1}}) + want := value.Object{ + {Key: "name", Value: "x"}, + {Key: "Nested", Value: value.Object{{Key: "a", Value: int64(1)}}}, + } + if !reflect.DeepEqual(got, want) { + t.Fatalf("got %#v, want %#v", got, want) + } +} + +func TestReflectMapSortsKeys(t *testing.T) { + // Go iterates over a map in a random order. The encoder must sort the + // keys, so that equal maps have the same structure. The decoder keeps + // the sorted order. + got := marshalUnmarshal(t, map[string]int64{"c": 3, "a": 1, "b": 2}) + want := value.Object{ + {Key: "a", Value: int64(1)}, + {Key: "b", Value: int64(2)}, + {Key: "c", Value: int64(3)}, + } + if !reflect.DeepEqual(got, want) { + t.Fatalf("got %#v, want %#v", got, want) + } +} + +func TestReflectPointerDeref(t *testing.T) { + n := int64(5) + if got := marshalUnmarshal(t, &n); !reflect.DeepEqual(got, int64(5)) { + t.Fatalf("got %#v, want int64(5)", got) + } + var nilPtr *int64 + if got := marshalUnmarshal(t, nilPtr); got != nil { + t.Fatalf("nil pointer should decode as nil, got %#v", got) + } +} + +// point implements Encryptable, so it writes itself. +type point struct{ X, Y int64 } + +func (p point) EncryptValue(enc Encoder) error { + m := enc.Map() + m.Field("x").Int64(p.X) + m.Field("y").Int64(p.Y) + return m.End() +} + +func TestEncryptableImpl(t *testing.T) { + got := marshalUnmarshal(t, point{X: 1, Y: 2}) + want := value.Object{{Key: "x", Value: int64(1)}, {Key: "y", Value: int64(2)}} + if !reflect.DeepEqual(got, want) { + t.Fatalf("got %#v, want %#v", got, want) + } +} + +// TestEncryptableNested checks that the encoder calls an Encryptable that it +// reaches through reflection, as a struct field. The top level is not the +// only place. +func TestEncryptableNested(t *testing.T) { + type shape struct { + Origin point + } + got := marshalUnmarshal(t, shape{Origin: point{X: 3, Y: 4}}) + want := value.Object{ + {Key: "Origin", Value: value.Object{ + {Key: "x", Value: int64(3)}, + {Key: "y", Value: int64(4)}, + }}, + } + if !reflect.DeepEqual(got, want) { + t.Fatalf("got %#v, want %#v", got, want) + } +} + +func TestEncoderChannels(t *testing.T) { + // Call the Encoder methods directly, including a nested Seq. + buf, err := Marshal(seqBuilder{}) + if err != nil { + t.Fatalf("Marshal: %v", err) + } + got, err := Unmarshal(buf) + if err != nil { + t.Fatalf("Unmarshal: %v", err) + } + want := []any{ + nil, true, + float64(1.5), float32(0.5), + int32(-1), int64(-1), + uint32(math.MaxUint32), uint64(math.MaxUint64), + "s", []byte{9}, + } + if !reflect.DeepEqual(got, want) { + t.Fatalf("got %#v, want %#v", got, want) + } +} + +type seqBuilder struct{} + +func (seqBuilder) EncryptValue(enc Encoder) error { + s := enc.Seq() + s.Elem().Null() + s.Elem().Bool(true) + s.Elem().Float64(1.5) + s.Elem().Float32(0.5) + s.Elem().Int32(-1) + s.Elem().Int64(-1) + s.Elem().Uint32(math.MaxUint32) + s.Elem().Uint64(math.MaxUint64) + s.Elem().String("s") + s.Elem().Bytes([]byte{9}) + return s.End() +} + +func TestInvalidUTF8StringRejected(t *testing.T) { + if _, err := Marshal(string([]byte{0xff})); err == nil { + t.Fatal("expected invalid UTF-8 string to be rejected") + } +} + +func TestUnmarshalRejectsGarbage(t *testing.T) { + if _, err := Unmarshal([]byte{0x7f}); err == nil { + t.Fatal("unknown tag must be rejected") + } + // The input has bytes after a complete value. + if _, err := Unmarshal([]byte{0x00, 0x00}); err == nil { + t.Fatal("trailing bytes must be rejected") + } +} + +// TestPlainPassthroughRoundTrip checks that a value wrapped in Plain is +// encoded as passthrough, and decodes as Plain{V: ...}. A caller can +// therefore tell that the value was not encrypted. +func TestPlainPassthroughRoundTrip(t *testing.T) { + got := marshalUnmarshal(t, map[string]any{ + "id": value.Plain{V: int64(42)}, + "email": "ada@example.com", + }) + want := value.Object{ + {Key: "email", Value: "ada@example.com"}, + {Key: "id", Value: value.Plain{V: int64(42)}}, + } + if !reflect.DeepEqual(got, want) { + t.Fatalf("got %#v, want %#v", got, want) + } +} + +// A Plain around a whole subtree makes every value in the subtree +// passthrough. +func TestPlainPassthroughSubtree(t *testing.T) { + got := marshalUnmarshal(t, value.Plain{V: []any{int64(1), "two", true}}) + want := value.Plain{V: []any{int64(1), "two", true}} + if !reflect.DeepEqual(got, want) { + t.Fatalf("got %#v, want %#v", got, want) + } +} + +// passthroughBuilder calls Encoder.Passthrough directly: at the root, for a +// sequence element, and for a map entry. +type passthroughBuilder struct{} + +func (passthroughBuilder) EncryptValue(enc Encoder) error { + s := enc.Seq() + s.Elem().Passthrough().Int64(7) // passthrough sequence element + s.Elem().String("sealed") + return s.End() +} + +func TestEncoderPassthroughChannel(t *testing.T) { + got := marshalUnmarshal(t, passthroughBuilder{}) + want := []any{value.Plain{V: int64(7)}, "sealed"} + if !reflect.DeepEqual(got, want) { + t.Fatalf("got %#v, want %#v", got, want) + } +} + +func TestUnmarshalRejectsTruncatedPassthrough(t *testing.T) { + // A passthrough tag, 0xF2, with no value node after it. + if _, err := Unmarshal([]byte{0xF2}); err == nil { + t.Fatal("truncated passthrough node must be rejected") + } +} + +func TestUnmarshalRejectsPassthroughDepthBomb(t *testing.T) { + // Input that nests only passthrough tags must reach the depth limit. + bytes := make([]byte, 0, 200) + for range 130 { // > maxDepth (128) + bytes = append(bytes, 0xF2) + } + bytes = append(bytes, 0x00) // NULL + if _, err := Unmarshal(bytes); err == nil { + t.Fatal("over-deep passthrough nesting must be rejected") + } +} + +// A passthrough node of a ciphertext keeps its readable value when it is +// encoded and decoded. The value comes back wrapped in Plain. A later encode +// therefore cannot treat it as a ciphertext map or sequence. +func TestCipherTextPassthroughTransportRoundTrip(t *testing.T) { + ct := map[string]any{ + "id": value.Plain{V: int64(42)}, + "email": sealed{9, 9, 9}, + } + buf, err := MarshalCipherText(testLeaves(), ct) + if err != nil { + t.Fatalf("MarshalCipherText: %v", err) + } + got, err := UnmarshalCipherText(testLeaves(), buf) + if err != nil { + t.Fatalf("UnmarshalCipherText: %v", err) + } + if !reflect.DeepEqual(got, ct) { + t.Fatalf("got %#v, want %#v", got, ct) + } +} + +func TestCipherTextTransportRoundTrip(t *testing.T) { + ct := map[string]any{ + "a": sealed{9, 9, 9}, + "b": []any{sealed{1}, sealedEmptySeq{2}}, + } + buf, err := MarshalCipherText(testLeaves(), ct) + if err != nil { + t.Fatalf("MarshalCipherText: %v", err) + } + got, err := UnmarshalCipherText(testLeaves(), buf) + if err != nil { + t.Fatalf("UnmarshalCipherText: %v", err) + } + if !reflect.DeepEqual(got, ct) { + t.Fatalf("got %#v, want %#v", got, ct) + } +} + +// A plaintext value that is not marked is refused where a ciphertext node +// belongs. A passthrough value must be wrapped in Plain, so no value is left +// unencrypted by accident. +func TestCipherTextRejectsBarePlaintext(t *testing.T) { + if _, err := MarshalCipherText(testLeaves(), map[string]any{"x": "oops"}); err == nil { + t.Fatal("bare plaintext in ciphertext position must be rejected") + } + if _, err := MarshalCipherText(testLeaves(), []byte{1, 2, 3}); err == nil { + t.Fatal("bare []byte must be rejected (use a leaf type or Plain)") + } +} + +// A struct with no exported fields must be refused. time.Time is the usual +// example. Sealing such a struct as an empty map would lose its value with +// no error. +func TestMarshalRejectsZeroExportedFieldStruct(t *testing.T) { + type opaque struct { + hidden int //nolint:unused // unexported on purpose + } + if _, err := Marshal(opaque{hidden: 1}); err == nil { + t.Fatal("struct with no exported fields must be rejected") + } + // A struct whose fields all have a vc:"-" tag is accepted, because the + // caller asked for the empty encoding. The empty struct is accepted too. + type skipped struct { + ID int `vc:"-"` + } + if _, err := Marshal(skipped{ID: 1}); err != nil { + t.Fatalf("all-skipped struct should encode: %v", err) + } + if _, err := Marshal(struct{}{}); err != nil { + t.Fatalf("empty struct should encode: %v", err) + } +} + +// Object is what a map decodes as. An Object must be encoded as a map again, +// at the root and inside other values. A program that decrypts a record and +// encrypts it again then keeps the structure of the record. +func TestObjectReencodesWithObjectFraming(t *testing.T) { + o := value.Object{ + {Key: "b", Value: int64(2)}, + {Key: "a", Value: int64(1)}, + } + got := marshalUnmarshal(t, o) + if !reflect.DeepEqual(got, o) { + t.Fatalf("root Object: got %#v, want %#v", got, o) + } + + nested := []any{o} + got = marshalUnmarshal(t, nested) + want := []any{o} + if !reflect.DeepEqual(got, want) { + t.Fatalf("nested Object: got %#v, want %#v", got, want) + } +} + +// An Object wrapped in Plain inside a ciphertext must keep its structure +// when it is encoded and decoded as passthrough. +func TestCipherTextPassthroughObjectRoundTrip(t *testing.T) { + o := value.Object{{Key: "id", Value: int64(42)}} + buf, err := MarshalCipherText(testLeaves(), value.Plain{V: o}) + if err != nil { + t.Fatalf("MarshalCipherText: %v", err) + } + got, err := UnmarshalCipherText(testLeaves(), buf) + if err != nil { + t.Fatalf("UnmarshalCipherText: %v", err) + } + if !reflect.DeepEqual(got, value.Plain{V: o}) { + t.Fatalf("got %#v, want Plain{V: %#v}", got, o) + } +} + +// A [N]byte must be written as one Bytes value, as a []byte is. Writing each +// byte as an element would produce a ciphertext structure that no other +// encoder writes. +func TestByteArrayEncodesAsBytes(t *testing.T) { + got := marshalUnmarshal(t, [4]byte{1, 2, 3, 4}) + if !reflect.DeepEqual(got, []byte{1, 2, 3, 4}) { + t.Fatalf("got %#v, want []byte{1,2,3,4}", got) + } + type hashed struct { + Hash [4]byte + } + got = marshalUnmarshal(t, hashed{Hash: [4]byte{9, 8, 7, 6}}) + want := value.Object{{Key: "Hash", Value: []byte{9, 8, 7, 6}}} + if !reflect.DeepEqual(got, want) { + t.Fatalf("got %#v, want %#v", got, want) + } +} + +// nilEncryptable panics if EncryptValue is called on a nil receiver. The +// encoder must detect a nil pointer and never make that call. +type nilEncryptable struct{ n int } + +func (e *nilEncryptable) EncryptValue(enc Encoder) error { + enc.Int64(int64(e.n)) // dereferences e + return nil +} + +// A nil pointer of a type that implements Encryptable must be encoded as +// Null. The encoder must not call the method on a nil receiver. +func TestTypedNilEncryptableEncodesNull(t *testing.T) { + var p *nilEncryptable + if got := marshalUnmarshal(t, p); got != nil { + t.Fatalf("typed nil at root: got %#v, want nil", got) + } + got := marshalUnmarshal(t, []any{p}) + if !reflect.DeepEqual(got, []any{nil}) { + t.Fatalf("typed nil in slice: got %#v, want []any{nil}", got) + } +} + +// A pointer cycle must fail with an error. The encoder must not recurse +// until the stack overflows. +func TestMarshalRejectsPointerCycle(t *testing.T) { + var x any + x = &x + if _, err := Marshal(x); err == nil { + t.Fatal("pointer cycle must be rejected") + } +} + +// MarshalCipherText must refuse a passthrough value that is deeper than the +// depth limit. Otherwise it would write bytes that UnmarshalCipherText +// always refuses. +func TestMarshalCipherTextRejectsPassthroughBeyondDepthBudget(t *testing.T) { + // 129 nested []any put the value inside the Plain deeper than maxDepth + // (128). + var deep any = value.Plain{V: int64(1)} + for range 129 { + deep = []any{deep} + } + if _, err := MarshalCipherText(testLeaves(), deep); !errors.Is(err, ErrTooDeep) { + t.Fatalf("over-deep passthrough must be rejected with ErrTooDeep at encode time, got %v", err) + } + + // A value one level less deep still encodes and decodes, so the limit is + // exact. + var ok any = value.Plain{V: int64(1)} + for range 127 { + ok = []any{ok} + } + buf, err := MarshalCipherText(testLeaves(), ok) + if err != nil { + t.Fatalf("MarshalCipherText at the bound: %v", err) + } + if _, err := UnmarshalCipherText(testLeaves(), buf); err != nil { + t.Fatalf("UnmarshalCipherText at the bound: %v", err) + } +} + +// The tests below give malformed input to the two decoders. The tests build +// the transport bytes by hand, because no Go encoder writes these bytes. + +func u32le(n int) []byte { + b := make([]byte, 4) + binary.LittleEndian.PutUint32(b, uint32(n)) + return b +} + +// ctEntry returns the bytes of one entry of a ciphertext map: the key, then +// a ctSingle leaf of one byte. +func ctEntry(key string) []byte { + e := append(u32le(len(key)), key...) + e = append(e, 0x01) // ctSingle + e = append(e, u32le(1)...) + return append(e, 0xAB) +} + +// decodeCipherText refuses a duplicate map key. A Go map cannot have one, so +// only bytes built by hand or written by another language can contain one. +func TestUnmarshalCipherTextRejectsDuplicateKey(t *testing.T) { + dup := []byte{0x04} // ctMap + dup = append(dup, u32le(2)...) + dup = append(dup, ctEntry("a")...) + dup = append(dup, ctEntry("a")...) + if _, err := UnmarshalCipherText(testLeaves(), dup); err == nil { + t.Fatal("duplicate ciphertext map key must be rejected") + } + + // As a control, the same bytes with distinct keys decode. + ok := []byte{0x04} + ok = append(ok, u32le(2)...) + ok = append(ok, ctEntry("a")...) + ok = append(ok, ctEntry("b")...) + if _, err := UnmarshalCipherText(testLeaves(), ok); err != nil { + t.Fatalf("distinct keys should decode: %v", err) + } +} + +// Unmarshal applies its depth limit and its check on hostile counts to +// arrays and to objects. The Rust codec tests the same cases. +func TestUnmarshalRejectsArrayAndObjectBombs(t *testing.T) { + // Too deep: 130 nested arrays of one element each, more than maxDepth + // (128). + var deep []byte + for range 130 { + deep = append(deep, 0xF0) // tagArray + deep = append(deep, u32le(1)...) + } + deep = append(deep, 0x00) // tagNull + if _, err := Unmarshal(deep); err == nil { + t.Fatal("array depth bomb must be rejected") + } + + // Too deep: 130 nested objects of one entry each. + var deepObj []byte + for range 130 { + deepObj = append(deepObj, 0xF1) // tagObject + deepObj = append(deepObj, u32le(1)...) + deepObj = append(deepObj, u32le(1)...) + deepObj = append(deepObj, 'k') + } + deepObj = append(deepObj, 0x00) + if _, err := Unmarshal(deepObj); err == nil { + t.Fatal("object depth bomb must be rejected") + } + + // A hostile count: an array that declares the largest 32-bit count and + // has no bytes after it. + if _, err := Unmarshal([]byte{0xF0, 0xFF, 0xFF, 0xFF, 0xFF}); err == nil { + t.Fatal("hostile array count must be rejected") + } +} + +// UnmarshalCipherText has its own depth limit, check on hostile counts, and +// check for bytes after the tree. The recursion of UnmarshalCipherText is +// separate from that of the value decoder. +func TestUnmarshalCipherTextRejectsMalformed(t *testing.T) { + // Too deep: 130 nested ctSeq nodes of one element each. + var deep []byte + for range 130 { + deep = append(deep, 0x03) // ctSeq + deep = append(deep, u32le(1)...) + } + deep = append(deep, ctEntry("")[4:]...) // a bare ctSingle leaf + if _, err := UnmarshalCipherText(testLeaves(), deep); err == nil { + t.Fatal("ciphertext depth bomb must be rejected") + } + + // A hostile count. + if _, err := UnmarshalCipherText(testLeaves(), []byte{0x03, 0xFF, 0xFF, 0xFF, 0xFF}); err == nil { + t.Fatal("hostile ciphertext count must be rejected") + } + + // Bytes after a complete node. + leaf := append([]byte{0x01}, u32le(1)...) + leaf = append(leaf, 0xAB, 0xFF) // one extra byte + if _, err := UnmarshalCipherText(testLeaves(), leaf); err == nil { + t.Fatal("trailing bytes must be rejected") + } + + // An unknown tag. + if _, err := UnmarshalCipherText(testLeaves(), []byte{0x7F}); err == nil { + t.Fatal("unknown ciphertext tag must be rejected") + } +} + +// A kind with no encoding reaches the default case of encodeReflect. +// Examples are a channel, a function, and a complex number. The encode must +// return an error. The encode must not panic or write bytes. +func TestMarshalRejectsUnsupportedKind(t *testing.T) { + if _, err := Marshal(make(chan int)); err == nil { + t.Fatal("a channel value has no encoding and must be rejected") + } + if _, err := Marshal(func() {}); err == nil { + t.Fatal("a func value has no encoding and must be rejected") + } + if _, err := Marshal(complex(1, 2)); err == nil { + t.Fatal("a complex value has no encoding and must be rejected") + } +} + +// encodeMap refuses a map whose keys are not strings. The transport encoding +// writes a key as UTF-8 bytes, so it has no form for a key of another type. +func TestMarshalRejectsNonStringMapKey(t *testing.T) { + if _, err := Marshal(map[int]string{1: "a"}); err == nil { + t.Fatal("map with non-string keys must be rejected") + } +} + +// The encoder applies the depth limit too: a Go value that is nested too +// deep fails the encode. Other tests give the decoders input that is too +// deep. This test reaches the same limit from the encoder. +func TestMarshalRejectsDepthBomb(t *testing.T) { + var v any = int64(0) + for range 130 { // > maxDepth (128) + v = []any{v} + } + if _, err := Marshal(v); err == nil { + t.Fatal("over-deep value must be rejected at encode time") + } +} + +// A duplicate object key in the encoded bytes must be refused, as the +// ciphertext decoder refuses a duplicate ctMap key. If an Object with a +// duplicate key were encoded again through a Go map, one entry would be lost +// with no error. Only bytes built by hand can contain a duplicate key, +// because the encoder writes unique keys in sorted order. +func TestUnmarshalRejectsDuplicateObjectKey(t *testing.T) { + key := []byte{1, 0, 0, 0, 'a'} + var buf []byte + buf = append(buf, 0xF1, 2, 0, 0, 0) // tagObject, count 2 + buf = append(buf, key...) + buf = append(buf, 0x00) // Null value + buf = append(buf, key...) + buf = append(buf, 0x00) + if _, err := Unmarshal(buf); err == nil { + t.Fatal("an object with a duplicate key must be rejected") + } + + // As a control, the same bytes with distinct keys decode. + var ok []byte + ok = append(ok, 0xF1, 2, 0, 0, 0) + ok = append(ok, 1, 0, 0, 0, 'a', 0x00) + ok = append(ok, 1, 0, 0, 0, 'b', 0x00) + if _, err := Unmarshal(ok); err != nil { + t.Fatalf("distinct keys must decode: %v", err) + } +} + +// skipsValue writes a key, or asks for an element, and never writes the +// value. Field and Elem must report that mistake at encode. Without their +// check, the mistake would appear only as ErrMalformed at decode. +type skipsValue struct{ inSeq bool } + +func (s skipsValue) EncryptValue(enc Encoder) error { + if s.inSeq { + q := enc.Seq() + q.Elem() // claimed, never written + q.Elem().Int64(1) + return q.End() + } + m := enc.Map() + m.Field("a") // key written, value never written + m.Field("b").Int64(1) + return m.End() +} + +// lastValueMissing tests the check in End. The value of the last entry is +// the one that is skipped, so no later call to Field or Elem can report it. +type lastValueMissing struct{ inSeq bool } + +func (s lastValueMissing) EncryptValue(enc Encoder) error { + if s.inSeq { + q := enc.Seq() + q.Elem().Int64(1) + q.Elem() // claimed, never written + return q.End() + } + m := enc.Map() + m.Field("a").Int64(1) + m.Field("b") // key written, value never written + return m.End() +} + +// unclosedNested writes a scalar inside a nested container and never calls +// End on the container. The slot of the container is incomplete, although a +// value deeper in the tree is complete. The check must therefore count each +// slot separately, not the whole encode. +type unclosedNested struct{ inSeq bool } + +func (u unclosedNested) EncryptValue(enc Encoder) error { + if u.inSeq { + q := enc.Seq() + inner := q.Elem().Seq() + inner.Elem().Int64(1) // inner.End() never called + q.Elem().Int64(2) + return q.End() + } + m := enc.Map() + inner := m.Field("a").Seq() + inner.Elem().Int64(1) // inner.End() never called + m.Field("b").Int64(2) + return m.End() +} + +// doubleWrite writes two scalars through the Encoder of one element or one +// entry. The result is one more value node than the count of the container. +type doubleWrite struct{ inSeq bool } + +func (d doubleWrite) EncryptValue(enc Encoder) error { + if d.inSeq { + q := enc.Seq() + e := q.Elem() + e.Int64(1) + e.Int64(2) // second value in the same element slot + return q.End() + } + m := enc.Map() + f := m.Field("a") + f.Int64(1) + f.Int64(2) // second value in the same entry slot + return m.End() +} + +// rootMiscount writes no value, or several values, at the root. +type rootMiscount struct{ writes int } + +func (r rootMiscount) EncryptValue(enc Encoder) error { + for i := 0; i < r.writes; i++ { + enc.Int64(int64(i)) + } + return nil +} + +// unclosedRoot never calls End on the root container. +type unclosedRoot struct{} + +func (unclosedRoot) EncryptValue(enc Encoder) error { + enc.Seq().Elem().Int64(1) // End() never called + return nil +} + +// encodeCipherText requires exactly one value inside a Plain, as Marshal +// requires exactly one value at the root. Without the rule, a bad value +// would be written as bytes that UnmarshalCipherText refuses later, with +// only ErrMalformed. +func TestMarshalCipherTextRejectsPayloadMiscount(t *testing.T) { + for _, v := range []any{ + value.Plain{V: rootMiscount{writes: 0}}, + value.Plain{V: rootMiscount{writes: 2}}, + value.Plain{V: unclosedRoot{}}, + } { + if _, err := MarshalCipherText(testLeaves(), v); err == nil { + t.Fatalf("malformed passthrough payload %#v must fail the encode", v) + } + } +} + +// missingPassthroughPayload calls Passthrough for a sequence element and +// never writes the value. The mistake is a skipped value, in its passthrough +// form. +type missingPassthroughPayload struct{} + +func (missingPassthroughPayload) EncryptValue(enc Encoder) error { + s := enc.Seq() + s.Elem().Passthrough() // marker written, payload omitted + return s.End() +} + +func TestEncoderPassthroughRequiresWrappedValue(t *testing.T) { + _, err := Marshal(missingPassthroughPayload{}) + if err == nil { + t.Fatal("passthrough without a wrapped value must fail at encode time") + } + if !strings.Contains(err.Error(), "element 0") { + t.Fatalf("diagnostic %q should name the offending element", err) + } +} + +// collidingTag produces a duplicate key through reflection: the vc tag of +// one field is the name of another field. If the encoder accepted it, the +// failure would come from the ciphertext decoder, after the plaintext had +// crossed into the guest. That failure is an ErrMalformed that names neither +// the struct nor the key. +type collidingTag struct { + Name string + Alias string `vc:"Name"` +} + +// duplicateFieldKey produces the same duplicate key through an Encryptable. +type duplicateFieldKey struct{} + +func (duplicateFieldKey) EncryptValue(enc Encoder) error { + m := enc.Map() + m.Field("a").Int64(1) + m.Field("a").Int64(2) + return m.End() +} + +func TestEncoderRejectsDuplicateMapKeys(t *testing.T) { + for _, c := range []struct { + name string + v any + }{ + {"struct tag collision", collidingTag{Name: "n", Alias: "m"}}, + {"encryptable double field", duplicateFieldKey{}}, + } { + t.Run(c.name, func(t *testing.T) { + _, err := Marshal(c.v) + if err == nil { + t.Fatal("a duplicate map key must fail at encode time") + } + if !strings.Contains(err.Error(), `"Name"`) && !strings.Contains(err.Error(), `"a"`) { + t.Fatalf("diagnostic %q should name the colliding key", err) + } + }) + } +} + +func TestEncoderCatchesSkippedValuesAtEncodeTime(t *testing.T) { + for _, c := range []struct { + name string + v any + want string // text that the error must contain + }{ + {"map middle", skipsValue{}, `key "a"`}, + {"map last", lastValueMissing{}, `key "b"`}, + {"seq middle", skipsValue{inSeq: true}, "element 0"}, + {"seq last", lastValueMissing{inSeq: true}, "element 1"}, + {"map unclosed nested container", unclosedNested{}, `key "a"`}, + {"seq unclosed nested container", unclosedNested{inSeq: true}, "element 0"}, + {"map double write", doubleWrite{}, `key "a"`}, + {"seq double write", doubleWrite{inSeq: true}, "element 0"}, + {"root zero values", rootMiscount{writes: 0}, "root"}, + {"root two values", rootMiscount{writes: 2}, "root"}, + {"root unclosed container", unclosedRoot{}, "root"}, + } { + t.Run(c.name, func(t *testing.T) { + _, err := Marshal(c.v) + if err == nil { + t.Fatal("a contract violation must fail the encode") + } + if !strings.Contains(err.Error(), c.want) { + t.Fatalf("diagnostic %q does not name the offending slot (want substring %q)", err, c.want) + } + }) + } +} + +// innerFailsOuterReports tests which error End returns. End returns the +// first error of the whole encode, not only an error from its own container. +// An outer End therefore reports a failure from inside another subtree. +type innerFailsOuterReports struct{} + +func (innerFailsOuterReports) EncryptValue(enc Encoder) error { + m := enc.Map() + inner := m.Field("bad").Map() + inner.Field("\xff").Int64(1) // invalid UTF-8 key: the first (and only) error + _ = inner.End() + m.Field("good").Int64(2) + return m.End() +} + +func TestEndReturnsFirstEncodeErrorNotContainerScoped(t *testing.T) { + _, err := Marshal(innerFailsOuterReports{}) + if err == nil { + t.Fatal("the inner container's error must surface from the outer End") + } + if !strings.Contains(err.Error(), "UTF-8") { + t.Fatalf("outer End should carry the first encode error verbatim, got %q", err) + } +} + +// A caller's LeafSet encodes and decodes the caller's own leaf types. The +// ciphertext codec takes a LeafSet for this reason. A leaf must decode as +// the caller's type, never as the type of another LeafSet. +type otherSealed []byte + +var otherLeaves = LeafSet{ + Classify: func(v any) (LeafKind, []byte, bool) { + if s, ok := v.(otherSealed); ok { + return LeafSingle, s, true + } + return 0, nil, false + }, + Make: func(kind LeafKind, bytes []byte) any { + if kind == LeafSingle { + return otherSealed(bytes) + } + return nil + }, +} + +func TestCipherTextLeafSetKeepsBindingTypesDistinct(t *testing.T) { + ct := map[string]any{"email": otherSealed{9, 9, 9}} + buf, err := MarshalCipherText(otherLeaves, ct) + if err != nil { + t.Fatalf("MarshalCipherText: %v", err) + } + got, err := UnmarshalCipherText(otherLeaves, buf) + if err != nil { + t.Fatalf("UnmarshalCipherText: %v", err) + } + if !reflect.DeepEqual(got, ct) { + t.Fatalf("got %#v, want %#v", got, ct) + } + + // Every LeafSet produces the same bytes, and only the Go types differ. + // The same buffer therefore decodes to the test leaf types with + // testLeaves. A LeafSet therefore changes only the Go types that are + // built, never the encoding. + asVC, err := UnmarshalCipherText(testLeaves(), buf) + if err != nil { + t.Fatalf("UnmarshalCipherText(testLeaves): %v", err) + } + want := map[string]any{"email": sealed{9, 9, 9}} + if !reflect.DeepEqual(asVC, want) { + t.Fatalf("got %#v, want %#v", asVC, want) + } + + // A LeafSet treats a leaf type that it does not accept as plaintext that + // is not marked. The encoder refuses the value, and does not write it as + // passthrough. + if _, err := MarshalCipherText(testLeaves(), ct); err == nil { + t.Fatal("a leaf type outside the LeafSet must be rejected as bare plaintext") + } +} + +func TestCipherTextRejectsPartialLeafSet(t *testing.T) { + for _, l := range []LeafSet{ + {}, + {Classify: otherLeaves.Classify}, + {Make: otherLeaves.Make}, + } { + if _, err := MarshalCipherText(l, otherSealed{1}); err == nil { + t.Fatal("a LeafSet missing Classify or Make must be rejected") + } + if _, err := UnmarshalCipherText(l, []byte{0x01, 1, 0, 0, 0, 0xAB}); err == nil { + t.Fatal("a LeafSet missing Classify or Make must be rejected") + } + } +} + +func TestCipherTextMakeMustMaterializeDecodedKind(t *testing.T) { + // otherLeaves builds only a LeafSingle. Bytes that contain the + // authenticated marker for an absent value must fail with an error that + // names the cause. The bytes must never decode to a nil node. Such a + // node would fail only later, in the caller's code. + none := []byte{0x02, 0, 0, 0, 0} + if _, err := UnmarshalCipherText(otherLeaves, none); err == nil { + t.Fatal("a kind the LeafSet does not materialize must be rejected") + } + + // The test LeafSet also refuses a kind that it does not list, and builds + // no leaf for it. The function leafTag refuses the same kind when it + // encodes. + if got := testLeaves().Make(LeafKind(9), []byte{1}); got != nil { + t.Fatalf("an unknown LeafKind must not materialize, got %#v", got) + } +} + +func TestMarshalCipherTextRejectsOutOfRangeLeafKind(t *testing.T) { + // The encoder has the matching check. When Classify returns a kind that + // the tag table does not have, the encoder refuses the leaf before it + // writes any tag. A kind added later therefore cannot be encoded without + // a tag of its own. + badLeaves := LeafSet{ + Classify: func(v any) (LeafKind, []byte, bool) { + if s, ok := v.(otherSealed); ok { + return LeafKind(9), s, true + } + return 0, nil, false + }, + Make: otherLeaves.Make, + } + if _, err := MarshalCipherText(badLeaves, otherSealed{1, 2, 3}); err == nil { + t.Fatal("a Classify returning an out-of-range LeafKind must be rejected") + } +} + +func TestCipherTextRoundTripsAllLeafKinds(t *testing.T) { + // The test uses every kind in the tag table, so it runs every case of + // Classify and Make. Two cases that are swapped fail here, and not at + // some later decrypt. An example is a Make that builds the empty-map + // marker where the empty-sequence marker belongs. + ct := map[string]any{ + "single": sealed{9, 9, 9}, + "emptySeq": sealedEmptySeq{7}, + "emptyMap": sealedEmptyMap{8}, + } + buf, err := MarshalCipherText(testLeaves(), ct) + if err != nil { + t.Fatalf("MarshalCipherText: %v", err) + } + got, err := UnmarshalCipherText(testLeaves(), buf) + if err != nil { + t.Fatalf("UnmarshalCipherText: %v", err) + } + if !reflect.DeepEqual(got, ct) { + t.Fatalf("got %#v, want %#v", got, ct) + } +} + +func TestLeafTagsHasNoUnwiredKinds(t *testing.T) { + // A LeafKind constant that skips a value would leave a zero entry in + // leafTags. Without the check for zero, leafTag would write the tag 0x00 + // with no error. The function leafKind would read that tag back. Go + // would then encode and decode a tag that the Rust codec does not + // define. + // + // Both functions refuse zero. The table must also have no zero entry. + for kind, tag := range leafTags { + if tag == 0 { + t.Fatalf("LeafKind %d has no wire tag — a hole in leafTags", kind) + } + } + if _, err := leafTag(LeafKind(len(leafTags))); err == nil { + t.Fatal("a LeafKind past the end of the table must be refused") + } + if _, ok := leafKind(0); ok { + t.Fatal("tag 0x00 is not a ciphertext tag and must not map to a kind") + } + if _, err := UnmarshalCipherText(testLeaves(), []byte{0x00, 0, 0, 0, 0}); err == nil { + t.Fatal("a 0x00 tag must be rejected on the wire") + } +} + +func TestFramingTags(t *testing.T) { + cases := []struct { + value any + wire []byte + }{ + {[]any{}, []byte{0xF0, 0, 0, 0, 0}}, + {value.Object{}, []byte{0xF1, 0, 0, 0, 0}}, + {value.Plain{V: nil}, []byte{0xF2, 0}}, + } + for _, tc := range cases { + got, err := Marshal(tc.value) + if err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(got, tc.wire) { + t.Fatalf("framing: got %x, want %x", got, tc.wire) + } + } + for _, old := range []byte{0x10, 0x11, 0x12} { + if _, err := Unmarshal([]byte{old}); err == nil { + t.Fatalf("truncated scalar tag %x accepted", old) + } + } +} + +// A signaling NaN must keep its bits. Widening it to float64 before it is +// encoded would set the quiet bit. The type namedFloat32 has no Encryptable +// method, so the encoder writes it by reflection. +type namedFloat32 float32 + +func TestFloat32SignalingNaNKeepsItsBits(t *testing.T) { + for _, bits := range []uint32{0xff833030, 0x7fba3030, 0x7f800001} { + wire := binary.LittleEndian.AppendUint32([]byte{tagFloat32}, bits) + value, err := Unmarshal(wire) + if err != nil { + t.Fatal(err) + } + f := value.(float32) + for _, v := range []any{ + value, []any{value}, struct{ F float32 }{f}, + namedFloat32(f), []namedFloat32{namedFloat32(f)}, struct{ F namedFloat32 }{namedFloat32(f)}, + } { + encoded, err := Marshal(v) + if err != nil { + t.Fatal(err) + } + if !bytes.Contains(encoded, wire) { + t.Fatalf("%08x re-encoded as %x", bits, encoded) + } + } + } +} diff --git a/languages/golang/encrypt/frame/conformance_test.go b/languages/golang/encrypt/frame/conformance_test.go new file mode 100644 index 000000000..1575119bb --- /dev/null +++ b/languages/golang/encrypt/frame/conformance_test.go @@ -0,0 +1,274 @@ +package frame + +import ( + "encoding/hex" + "encoding/json" + "fmt" + "reflect" + "regexp" + "strconv" + "testing" + "time" + + "github.com/cipherstash/stack/languages/golang/encrypt/value" +) + +// valueCorpus is the path of the value corpus. Go, Rust, and Node all read +// that file. The README beside the corpus says which sections each language +// checks. +const valueCorpus = "../../../../conformance/vitaminc-aead/value-conformance.json" + +// isoDate and rfc3339ish match the date and timestamp forms in the corpus. +// Those forms include a negative year, written as a sign and six digits. The +// function time.Parse cannot read such a year. +var ( + isoDate = regexp.MustCompile(`^([+-]\d{6}|\d{4})-(\d{2})-(\d{2})$`) + rfc3339ish = regexp.MustCompile(`^([+-]\d{6}|\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,9}))?Z$`) +) + +// expected builds the Go value that the kind and value fields of a vector +// describe, without the transport decoder. A bug that makes the decoder and +// the encoder wrong in the same way therefore cannot pass. +func expected(kind string, raw json.RawMessage) (any, error) { + if kind == "unknown" { + // A logical id that this version does not know. The vector has the + // id, the parameter, and the physical scalar. The value decodes as a + // Tagged and encodes as the same bytes. + var inner struct { + ID, Param uint8 + Kind string + Value json.RawMessage + } + if err := json.Unmarshal(raw, &inner); err != nil { + return nil, err + } + v, err := expected(inner.Kind, inner.Value) + if err != nil { + return nil, err + } + return value.Tagged{ID: inner.ID, Param: inner.Param, V: v}, nil + } + var text string + _ = json.Unmarshal(raw, &text) + integer := func(bits int) (int64, error) { return strconv.ParseInt(text, 10, bits) } + natural := func(bits int) (uint64, error) { return strconv.ParseUint(text, 10, bits) } + switch kind { + case "null", "undefined": + return nil, nil + case "bool": + var v bool + return v, json.Unmarshal(raw, &v) + case "int8": + v, err := integer(8) + return int8(v), err + case "uint8": + v, err := natural(8) + return uint8(v), err + case "int16": + v, err := integer(16) + return int16(v), err + case "uint16": + v, err := natural(16) + return uint16(v), err + case "int32": + v, err := integer(32) + return int32(v), err + case "uint32": + v, err := natural(32) + return uint32(v), err + case "int64": + return integer(64) + case "uint64": + return natural(64) + case "int128": + return value.ParseInt128(text) + case "uint128": + return value.ParseUint128(text) + case "float32": + var v float32 + return v, json.Unmarshal(raw, &v) + case "float64": + var v float64 + return v, json.Unmarshal(raw, &v) + case "string": + return text, nil + case "bytes": + return hex.DecodeString(text) + case "date": + m := isoDate.FindStringSubmatch(text) + if m == nil { + return nil, fmt.Errorf("unparseable date %q", text) + } + n := make([]int, 3) + for i := range n { + v, err := strconv.Atoi(m[i+1]) + if err != nil { + return nil, err + } + n[i] = v + } + return value.Date{Year: n[0], Month: time.Month(n[1]), Day: n[2]}, nil + case "timestamp": + return timestamp(text) + case "decimal": + return value.ParseDecimal(text) + case "uuid": + return value.ParseUUID(text) + case "array": + if string(raw) == "[]" { + return []any{}, nil + } + case "object": + if string(raw) == "{}" { + return value.Object{}, nil + } + } + return nil, fmt.Errorf("teach expected() the %s vector %s", kind, raw) +} + +func timestamp(text string) (any, error) { + m := rfc3339ish.FindStringSubmatch(text) + if m == nil { + return nil, fmt.Errorf("unparseable timestamp %q", text) + } + n := make([]int, 6) + for i := range n { + v, err := strconv.Atoi(m[i+1]) + if err != nil { + return nil, err + } + n[i] = v + } + nanos, err := strconv.Atoi((m[7] + "000000000")[:9]) + if err != nil { + return nil, err + } + return time.Date(n[0], time.Month(n[1]), n[2], n[3], n[4], n[5], nanos, time.UTC), nil +} + +func sameValue(got, want any) bool { + if want, ok := want.(time.Time); ok { + got, ok := got.(time.Time) + return ok && got.Equal(want) + } + return reflect.DeepEqual(got, want) +} + +func TestSharedValueConformance(t *testing.T) { + data, ok := readCorpus(t, valueCorpus) + if !ok { + t.Skip("no value corpus") + } + var corpus struct { + Vectors []struct { + Name, Kind, Transport string + Value json.RawMessage + GoReencode string `json:"go_reencode"` + } + Normalized []struct { + Name, Kind, Transport, Reencode string + Value json.RawMessage + ReencodeValue json.RawMessage `json:"reencode_value"` + } + Malformed []struct{ Name, Transport string } + CiphertextMalformed []struct{ Name, Transport string } `json:"ciphertext_malformed"` + } + if err := json.Unmarshal(data, &corpus); err != nil { + t.Fatal(err) + } + for _, row := range corpus.Vectors { + t.Run(row.Name, func(t *testing.T) { + raw, err := hex.DecodeString(row.Transport) + if err != nil { + t.Fatal(err) + } + value, err := Unmarshal(raw) + if err != nil { + t.Fatal(err) + } + expect, err := expected(row.Kind, row.Value) + if err != nil { + t.Fatal(err) + } + if !sameValue(value, expect) { + t.Fatalf("decoded %#v, want %#v", value, expect) + } + want := row.Transport + if row.GoReencode != "" { + want = row.GoReencode + } + // Encode the decoded value and, independently, the expected one. + for _, v := range []any{value, expect} { + encoded, err := Marshal(v) + if err != nil { + t.Fatal(err) + } + if hex.EncodeToString(encoded) != want { + t.Fatalf("got %x, want %s (%#v)", encoded, want, v) + } + } + }) + } + // A normalized vector reads, and writes back as its canonical bytes: + // from the decoded value, and from either spelling built independently. + if len(corpus.Normalized) == 0 { + t.Fatal("the corpus has no normalized vectors") + } + for _, row := range corpus.Normalized { + t.Run(row.Name, func(t *testing.T) { + raw, err := hex.DecodeString(row.Transport) + if err != nil { + t.Fatal(err) + } + value, err := Unmarshal(raw) + if err != nil { + t.Fatal(err) + } + canonical, err := expected(row.Kind, row.ReencodeValue) + if err != nil { + t.Fatal(err) + } + if !sameValue(value, canonical) { + t.Fatalf("decoded %#v, want %#v", value, canonical) + } + given, err := expected(row.Kind, row.Value) + if err != nil { + t.Fatal(err) + } + for _, v := range []any{value, canonical, given} { + encoded, err := Marshal(v) + if err != nil { + t.Fatal(err) + } + if hex.EncodeToString(encoded) != row.Reencode { + t.Fatalf("got %x, want %s (%#v)", encoded, row.Reencode, v) + } + } + }) + } + for _, row := range corpus.Malformed { + t.Run(row.Name, func(t *testing.T) { + raw, err := hex.DecodeString(row.Transport) + if err != nil { + t.Fatal(err) + } + if _, err := Unmarshal(raw); err != ErrMalformed { + t.Fatalf("got %v, want ErrMalformed", err) + } + }) + } + if len(corpus.CiphertextMalformed) == 0 { + t.Fatal("the corpus has no malformed ciphertexts") + } + for _, row := range corpus.CiphertextMalformed { + t.Run(row.Name, func(t *testing.T) { + raw, err := hex.DecodeString(row.Transport) + if err != nil { + t.Fatal(err) + } + if _, err := UnmarshalCipherText(testLeaves(), raw); err != ErrMalformed { + t.Fatalf("got %v, want ErrMalformed", err) + } + }) + } +} diff --git a/languages/golang/encrypt/frame/corpus_test.go b/languages/golang/encrypt/frame/corpus_test.go new file mode 100644 index 000000000..72c1d64f0 --- /dev/null +++ b/languages/golang/encrypt/frame/corpus_test.go @@ -0,0 +1,62 @@ +package frame + +import ( + "errors" + "io/fs" + "os" + "testing" +) + +// The corpora that these tests read are files of the repository, outside +// this Go module. A module that a program downloads therefore does not +// include them. In a downloaded module, a missing corpus is not a failure. +// The function readCorpus reports that the corpus is missing. The caller +// then skips its test, or seeds its fuzz target from testdata alone. +// +// A missing corpus fails the test in the repository. A missing corpus also +// fails where STACK_CONFORMANCE_REQUIRED=1 is set. + +// repositoryMarker is the repository's .git, a directory in a clone and a +// file in a worktree. A downloaded module has neither. +const repositoryMarker = "../../../../.git" + +// readCorpus returns the corpus at path. The second result is false when the +// corpus is missing outside the repository. +func readCorpus(tb testing.TB, path string) ([]byte, bool) { + tb.Helper() + data, err := os.ReadFile(path) + if err == nil { + return data, true + } + if errors.Is(err, fs.ErrNotExist) && !corpusRequired() { + tb.Logf("%s is not here, as in a downloaded module: not checked", path) + return nil, false + } + tb.Fatal(err) + return nil, false +} + +// corpusRequired reports whether a missing corpus is a failure. A missing +// corpus is a failure in the repository, and where +// STACK_CONFORMANCE_REQUIRED=1 is set. +func corpusRequired() bool { + if os.Getenv("STACK_CONFORMANCE_REQUIRED") == "1" { + return true + } + _, err := os.Stat(repositoryMarker) + return err == nil +} + +func TestACorpusIsRequiredInTheRepository(t *testing.T) { + if _, err := os.Stat(repositoryMarker); err != nil { + t.Skip("not in the repository") + } + if !corpusRequired() { + t.Fatal("a missing corpus would be skipped in the repository") + } + for _, path := range []string{valueCorpus, storageCorpus} { + if _, err := os.Stat(path); err != nil { + t.Errorf("%s: %v", path, err) + } + } +} diff --git a/languages/golang/encrypt/frame/decode.go b/languages/golang/encrypt/frame/decode.go new file mode 100644 index 000000000..f889ef398 --- /dev/null +++ b/languages/golang/encrypt/frame/decode.go @@ -0,0 +1,331 @@ +package frame + +import ( + "encoding/binary" + "math" + "math/big" + "time" + + "github.com/cipherstash/stack/languages/golang/encrypt/value" +) + +// Unmarshal decodes the transport bytes of a value into Go values: +// +// - Null and Undefined decode as nil. Go has no undefined value. +// - A typed null decodes as nil. The type of an absent value matters only +// while the value is sealed. The nil therefore encodes again as the +// plain null. +// - Bool decodes as bool. +// - Int32 decodes as int32. +// - Int64 decodes as int64. +// - Uint32 decodes as uint32. +// - Uint64 decodes as uint64. +// - Float32 decodes as float32. +// - Float64 decodes as float64. +// - String decodes as string. +// - Bytes decodes as []byte. +// - Array decodes as []any. +// - Object decodes as [value.Object], an ordered []Field. +// - Passthrough decodes as Plain{V: v}, where v is the decoded value. +// Plain marks a value that was not encrypted. +// - An envelope starts with the tag 0xF3, and decodes by its logical type. +// A timestamp in seconds, milliseconds, or microseconds decodes as +// time.Time. A UUID decodes as UUID. A logical type id that this version +// does not know decodes as [value.Tagged]. A Tagged encodes as the same bytes. +// - The 8-bit, 16-bit, and 128-bit integers decode as int8, uint8, int16, +// uint16, Int128, and Uint128. +// - Date decodes as Date, Timestamp as time.Time, and Decimal as Decimal. +// +// Go has a type for every tag, so Unmarshal never widens a value. The 32-bit +// tags decode as int32, uint32, and float32, never as 64-bit types. +// JavaScript differs: it decodes every integer tag as a BigInt, and widens +// Float32 to a number. +func Unmarshal(buf []byte) (any, error) { + r := &reader{buf: buf} + v, err := decodeValue(r, 0) + if err != nil { + return nil, err + } + if !r.finished() { + return nil, ErrMalformed + } + return v, nil +} + +func decodeValue(r *reader, depth int) (any, error) { + if depth > maxDepth { + return nil, ErrMalformed + } + tag, err := r.byteTag() + if err != nil { + return nil, err + } + return decodeTagged(r, tag, depth) +} + +// decodeTagged decodes a node. The caller has already read the tag of the +// node. +func decodeTagged(r *reader, tag byte, depth int) (any, error) { + switch tag { + case tagInt8, tagUint8, tagInt16, tagUint16, tagInt128, tagUint128, tagDate, tagTimestamp, tagDecimal: + return decodeScalar(r, tag) + case tagNull, tagUndefined: + return nil, nil + case tagFalse: + return false, nil + case tagTrue: + return true, nil + case tagInt32: + s, err := r.take(4) + if err != nil { + return nil, err + } + return int32(binary.LittleEndian.Uint32(s)), nil + case tagInt64: + s, err := r.take(8) + if err != nil { + return nil, err + } + return int64(binary.LittleEndian.Uint64(s)), nil + case tagUint32: + s, err := r.take(4) + if err != nil { + return nil, err + } + return binary.LittleEndian.Uint32(s), nil + case tagUint64: + s, err := r.take(8) + if err != nil { + return nil, err + } + return binary.LittleEndian.Uint64(s), nil + case tagFloat32: + s, err := r.take(4) + if err != nil { + return nil, err + } + return math.Float32frombits(binary.LittleEndian.Uint32(s)), nil + case tagFloat64: + s, err := r.take(8) + if err != nil { + return nil, err + } + return math.Float64frombits(binary.LittleEndian.Uint64(s)), nil + case tagString: + return r.str() + case tagBytes: + n, err := r.count() + if err != nil { + return nil, err + } + s, err := r.take(n) + if err != nil { + return nil, err + } + out := make([]byte, len(s)) + copy(out, s) + return out, nil + case tagArray: + n, err := r.count() + if err != nil { + return nil, err + } + items := make([]any, 0, eagerCap(n)) + for range n { + item, err := decodeValue(r, depth+1) + if err != nil { + return nil, err + } + items = append(items, item) + } + return items, nil + case tagObject: + n, err := r.count() + if err != nil { + return nil, err + } + fields := make(value.Object, 0, eagerCap(n)) + // A duplicate key is refused. The ciphertext decoder and both Rust + // decoders refuse one too. If an Object with a duplicate key were + // encoded again through a Go map, one entry would be lost with no + // error. + seen := make(map[string]struct{}, eagerCap(n)) + for range n { + key, err := r.str() + if err != nil { + return nil, err + } + if _, dup := seen[key]; dup { + return nil, ErrMalformed + } + seen[key] = struct{}{} + v, err := decodeValue(r, depth+1) + if err != nil { + return nil, err + } + fields = append(fields, value.Field{Key: key, Value: v}) + } + return fields, nil + case tagPassthrough: + // A passthrough value decodes as Plain{V: v}, where v is the decoded + // value. Plain is also how a caller asks the Encoder for + // passthrough. The caller can therefore tell that the value was not + // encrypted. + inner, err := decodeValue(r, depth+1) + if err != nil { + return nil, err + } + return value.Plain{V: inner}, nil + case tagEnvelope: + return decodeEnvelope(r) + case tagTypedNull: + return decodeTypedNull(r) + default: + return nil, ErrMalformed + } +} + +// physicalTag reports whether tag is the tag of a physical scalar. Only a +// physical scalar can follow the header of an envelope. The tags of the +// logical types Undefined, Date, Timestamp, and Decimal are not physical. +// The container tags are not physical either. +func physicalTag(tag byte) bool { + switch tag { + case tagNull, tagFalse, tagTrue, tagInt32, tagInt64, tagUint32, tagUint64, tagFloat32, tagFloat64, + tagString, tagBytes, tagInt8, tagUint8, tagInt16, tagUint16, tagInt128, tagUint128: + return true + } + return false +} + +// decodeEnvelope reads an envelope, after its tag 0xF3. An envelope is the +// id of a logical type, a parameter, and a physical scalar. Every value has +// exactly one encoding, so three kinds of envelope are malformed: +// +// - one for a logical type that has a tag of its own +// - one with an id of zero +// - one with a known id and a parameter that the type does not accept +func decodeEnvelope(r *reader) (any, error) { + id, err := r.byteTag() + if err != nil { + return nil, err + } + param, err := r.byteTag() + if err != nil { + return nil, err + } + tag, err := r.byteTag() + if err != nil { + return nil, err + } + if !physicalTag(tag) { + return nil, ErrMalformed + } + physical, err := decodeTagged(r, tag, maxDepth) + if err != nil { + return nil, err + } + switch id { + case 0, logicalUndefined, logicalDate, logicalDecimal: + return nil, ErrMalformed + case logicalTimestamp: + return envelopeTimestamp(param, physical) + case logicalUUID: + b, ok := physical.([]byte) + if param != 0 || !ok || len(b) != 16 { + return nil, ErrMalformed + } + var u value.UUID + copy(u[:], b) + return u, nil + default: + return value.Tagged{ID: id, Param: param, V: physical}, nil + } +} + +// envelopeTimestamp converts a count of seconds, milliseconds, or +// microseconds since the epoch to a time.Time. The instant must be in the +// range that the encoding accepts, about the years -9999 to 9999. See +// [value.Timestamp]. The function refuses the nanosecond unit, because a timestamp +// in nanoseconds uses tagTimestamp. +func envelopeTimestamp(unit byte, physical any) (any, error) { + var per int64 + switch unit { + case unitSeconds: + per = 1_000_000_000 + case unitMillis: + per = 1_000_000 + case unitMicros: + per = 1_000 + default: + return nil, ErrMalformed + } + var t value.Timestamp + if count, ok := smallIntegerOf(physical); ok { + // Most counts fit an int64, including every Date that Node writes. + // Those counts are converted without math/big. The count is split + // into whole seconds and a remainder. The remainder is never + // negative, as with DivMod below. + perSecond := 1_000_000_000 / per + seconds, rem := count/perSecond, count%perSecond + if rem < 0 { + seconds, rem = seconds-1, rem+perSecond + } + t = value.Timestamp{Seconds: seconds, Nanoseconds: uint32(rem * per)} + } else { + count, ok := wideIntegerOf(physical) + if !ok { + return nil, ErrMalformed + } + nanos := new(big.Int).Mul(count, big.NewInt(per)) + seconds, sub := new(big.Int).DivMod(nanos, big.NewInt(1_000_000_000), new(big.Int)) + if !seconds.IsInt64() { + return nil, ErrMalformed + } + t = value.Timestamp{Seconds: seconds.Int64(), Nanoseconds: uint32(sub.Int64())} + } + if t.Validate() != nil { + return nil, ErrMalformed + } + return time.Unix(t.Seconds, int64(t.Nanoseconds)).UTC(), nil +} + +// smallIntegerOf returns the value of a decoded integer that fits an int64. +// The second result is false for any other value. +func smallIntegerOf(v any) (int64, bool) { + switch x := v.(type) { + case int8: + return int64(x), true + case int16: + return int64(x), true + case int32: + return int64(x), true + case int64: + return x, true + case uint8: + return int64(x), true + case uint16: + return int64(x), true + case uint32: + return int64(x), true + case uint64: + return int64(x), x <= math.MaxInt64 + } + return 0, false +} + +// wideIntegerOf returns the value of a decoded integer that smallIntegerOf +// does not accept: a uint64 above math.MaxInt64, an Int128, or a Uint128. +func wideIntegerOf(v any) (*big.Int, bool) { + switch x := v.(type) { + case uint64: + return new(big.Int).SetUint64(x), true + case value.Int128: + value, ok := new(big.Int).SetString(x.String(), 10) + return value, ok + case value.Uint128: + value, ok := new(big.Int).SetString(x.String(), 10) + return value, ok + } + return nil, false +} diff --git a/languages/golang/encrypt/frame/doc.go b/languages/golang/encrypt/frame/doc.go new file mode 100644 index 000000000..69c8e2b59 --- /dev/null +++ b/languages/golang/encrypt/frame/doc.go @@ -0,0 +1,100 @@ +// Package frame encodes and decodes the bytes that the Go module exchanges +// with its guests. A guest is a WebAssembly module that the Go module runs. +// The Stack Encrypt guest is the guest that encrypts and decrypts. +// +// A frame is the bytes that encode one value. The package has three +// encodings: +// +// - The value encoding is for a value that crosses between Go and a guest. +// [Marshal] writes it and [Unmarshal] reads it. +// - The ciphertext encoding is for a ciphertext tree that crosses between +// Go and the Stack Encrypt guest. [MarshalCipherText] writes it and +// [UnmarshalCipherText] reads it. +// - The storage profile is for a value that a program stores, as a blob. +// [MarshalStorage] writes it and [UnmarshalStorage] reads it. +// +// The Rust crate recipher-frame implements the same encodings. The Go code +// and the Rust code share nothing. The tests of both read the same two files +// of expected bytes: the value corpus in conformance/vitaminc-aead, and the +// storage corpus in packages/recipher-frame/testdata. +// +// The codec reads and writes the types of package +// [github.com/cipherstash/stack/languages/golang/encrypt/value]: +// +// - The value types value.Date, value.Decimal, value.Int128, +// value.Uint128, and value.UUID. +// - value.Object and value.Field, for a decoded map. The fields are in the +// order they were encoded. +// - value.Plain, for a passthrough value. A passthrough value is neither +// encrypted nor authenticated. +// +// # Transport bytes and the storage profile +// +// Never store the bytes that [Marshal], [Encode], or [MarshalCipherText] +// writes. Those are transport bytes. Transport bytes exist only while a call +// crosses into or out of a guest. A later release can change their encoding. +// +// Store only the bytes of the storage profile. [MarshalStorage] writes a +// value as a versioned blob, and [UnmarshalStorage] reads one. The format is +// version 1 of packages/recipher-frame/STORAGE.md, and that version never +// changes. The Rust module recipher_frame::storage reads and writes the same +// format. The tests of this package check the format against the storage +// corpus. +// +// # Values and ciphertexts +// +// [Marshal] and [Unmarshal] encode and decode a value. A value is one of +// these: +// +// - a Go scalar +// - a value type +// - a []any, for a list +// - a value.Object, for a decoded map +// - a value.Plain, for a passthrough value +// +// Marshal encodes any other Go value by reflection, with rules like those of +// encoding/json. Before Marshal uses reflection, it checks whether the value +// implements [Encryptable]. A type that implements Encryptable writes itself +// through an [Encoder]. +// +// [MarshalCipherText] and [UnmarshalCipherText] encode and decode a +// ciphertext tree. The codec defines the structural nodes of the tree: +// []any, map[string]any, and value.Plain. The caller defines the types of the +// sealed leaves. A sealed leaf is one encrypted value in the tree. +// +// The caller gives the codec a [LeafSet]. The LeafSet converts between the +// caller's leaf types and the encoded leaves. A leaf therefore has a Go type +// of its own. No other value can be used in place of a leaf. +// +// # Hostile input +// +// The decoders treat their input as untrusted. Every decoder applies these +// rules: +// +// - The nesting depth, every length prefix, and every item count have a +// limit. +// - Every string must be valid UTF-8. +// - A map must not have a duplicate key. +// +// A decoder returns [ErrMalformed] for every malformed input. A decoder +// never panics, and never allocates more memory than its input can fill. The +// fuzz targets in this package test these rules. +// +// [ErrMalformed] means that the bytes are bad. A mistake by the caller fails +// with a different error. That error names the mistake. There are two such +// mistakes: +// +// - A [LeafSet] has a nil function. +// - The Make function of a LeafSet returns nil for a kind of leaf that the +// input contains. +// +// So errors.Is(err, [ErrMalformed]) tests for bad input. That test is not +// true for every decode failure. +// +// # Origin +// +// The package was vitaminc's Go package vcffi +// (github.com/cipherstash/vitaminc/bindings/go/vcffi), and keeps its MIT +// licence. Package encrypt is built on it. A program needs the package only +// to write a type that encodes itself: see [Encryptable]. +package frame diff --git a/languages/golang/encrypt/frame/encoder.go b/languages/golang/encrypt/frame/encoder.go new file mode 100644 index 000000000..dfff12559 --- /dev/null +++ b/languages/golang/encrypt/frame/encoder.go @@ -0,0 +1,912 @@ +package frame + +import ( + "encoding/binary" + "errors" + "fmt" + "math" + "reflect" + "slices" + "strings" + "sync" + "time" + "unicode/utf8" + + "github.com/cipherstash/stack/languages/golang/encrypt/value" +) + +// encState is the buffer and the first error of one encode. An Encoder +// shares it with every Encoder made from it. After the first error is +// recorded, every later write does nothing. Code that writes a value can +// therefore make several writes without a check after each one. End and +// Marshal return the first error. +type encState struct { + buf []byte + err error +} + +func (s *encState) fail(err error) { + if s.err == nil { + s.err = err + } +} + +// Encryptable is the interface of a type that writes its own value. Without +// it, the codec writes a value by its Go type. With it, the value is the one +// that EncryptValue writes. An example is a money type that writes its cents +// with Int64. +// +// The codec writes a nil pointer to an Encryptable as a null, and does not +// call EncryptValue for it. +type Encryptable interface { + // EncryptValue writes exactly one value to enc, with one of the methods + // of enc. The encode fails if EncryptValue writes no value, writes a + // second value, or returns an error. + EncryptValue(enc Encoder) error +} + +// encryptableType is the reflect.Type of Encryptable. +var encryptableType = reflect.TypeFor[Encryptable]() + +// Encoder records one value as transport bytes. The methods of an Encoder +// match the methods of the Rust Cipher. An Encoder only writes bytes. An +// Encoder does not encrypt. +// +// Call exactly one method on an Encoder. That method is one of these: +// +// - A method that writes a scalar: Null, Undefined, Bool, String, Bytes, +// Date, Timestamp, TimestampParts, Decimal, UUID, Tagged, or one of the +// integer and float methods. The scalar methods are in this file and in +// scalars.go. +// - A method that starts a container: Seq or Map. +// +// Pass and store an Encoder by value. Every Encoder of one encode points at +// the same buffer and the same first error, so a copy is cheap and safe. +// +// The zero Encoder is not usable. Its methods record nothing and do not +// panic, and its Err method returns an error that says so. A usable Encoder +// comes from one of two places: +// +// - The codec gives one to the EncryptValue method of an [Encryptable]. +// - Passthrough, Elem, and Field each return one. +// +// [Encoder.Usable] reports whether an Encoder is usable. +type Encoder struct { + st *encState + depth int + // done points at the counter for the slot that this Encoder writes into. + // A slot is the place for one value: the root, one element of a + // sequence, or the value of one map entry. A scalar method adds one to + // the counter. The End of a container adds one too. The owner of the + // slot then checks that the counter is exactly one. + // + // Each slot has a counter of its own. With one counter for the whole + // encode, a value completed deeper in the tree could count as the value + // of the slot. An example is a scalar inside a nested container that was + // never ended. A decoder would then read the bytes that follow as the + // wrong values. The only sign would be ErrMalformed at decode. + done *int +} + +// dead reports whether a write to e must do nothing: e is the zero Encoder, +// or its encode already failed. +func (e Encoder) dead() bool { + return e.st == nil || e.st.err != nil +} + +// orDead returns e, or for the zero Encoder an Encoder over a state that has +// already failed. A container or passthrough started from the zero Encoder +// then records nothing, and its own methods do not panic. +func (e Encoder) orDead() Encoder { + if e.st == nil { + e.st = &encState{err: errZeroEncoder} + } + return e +} + +// Usable reports whether e came from the codec. Only such an Encoder records +// what is written to it. The zero Encoder is not usable. +func (e Encoder) Usable() bool { return e.st != nil } + +// Err returns the first error of the encode that e belongs to. For the zero +// Encoder, Err returns an error that says so. +func (e Encoder) Err() error { + if e.st == nil { + return errZeroEncoder + } + return e.st.err +} + +var errZeroEncoder = errors.New("frame: the zero Encoder records nothing; use the Encoder that EncryptValue is given") + +func (e Encoder) push(b ...byte) { + e.st.buf = append(e.st.buf, b...) +} + +// complete records that the slot of this Encoder received one complete +// value. +func (e Encoder) complete() { + if e.done != nil { + *e.done++ + } +} + +// Null records a null. A null is nil in Go, null in JavaScript, and None in +// Python. +func (e Encoder) Null() { + if !e.dead() { + e.push(tagNull) + e.complete() + } +} + +// Undefined records the JavaScript value undefined. Go has no such value, so +// Go code rarely calls this method. The method exists so that a value +// decoded from JavaScript can be encoded again. An undefined decodes as nil, +// as a null does. +func (e Encoder) Undefined() { + if !e.dead() { + e.push(tagUndefined) + e.complete() + } +} + +// Bool records a boolean. +func (e Encoder) Bool(b bool) { + if e.dead() { + return + } + if b { + e.push(tagTrue) + } else { + e.push(tagFalse) + } + e.complete() +} + +// Float64 records a 64-bit IEEE 754 float. The value decodes as a 64-bit +// float in every language, never as an integer. Float64 writes the bits of f +// unchanged, so a NaN keeps its payload and -0.0 keeps its sign. +func (e Encoder) Float64(f float64) { + if e.dead() { + return + } + e.push(tagFloat64) + e.st.buf = binary.LittleEndian.AppendUint64(e.st.buf, math.Float64bits(f)) + e.complete() +} + +// Float32 records a 32-bit IEEE 754 float. To match the float4 type of EQL, +// the encoding keeps the 32-bit width. Float32 writes the bits of f +// unchanged. +func (e Encoder) Float32(f float32) { + if e.dead() { + return + } + e.push(tagFloat32) + e.st.buf = binary.LittleEndian.AppendUint32(e.st.buf, math.Float32bits(f)) + e.complete() +} + +// Int32 records a signed 32-bit integer. To match the int4 type of EQL, the +// encoding keeps an Int32 distinct from an Int64. +func (e Encoder) Int32(i int32) { + if e.dead() { + return + } + e.push(tagInt32) + e.st.buf = binary.LittleEndian.AppendUint32(e.st.buf, uint32(i)) + e.complete() +} + +// Int64 records a signed 64-bit integer. The encoding keeps an Int64 +// distinct from a Float64. A language that has integer types therefore +// decodes an integer as an integer. +func (e Encoder) Int64(i int64) { + if e.dead() { + return + } + e.push(tagInt64) + e.st.buf = binary.LittleEndian.AppendUint64(e.st.buf, uint64(i)) + e.complete() +} + +// Uint32 records an unsigned 32-bit integer. To match the types of an EQL +// schema, the encoding keeps the 32-bit width. +func (e Encoder) Uint32(u uint32) { + if e.dead() { + return + } + e.push(tagUint32) + e.st.buf = binary.LittleEndian.AppendUint32(e.st.buf, u) + e.complete() +} + +// Uint64 records an unsigned 64-bit integer without changing its width. +func (e Encoder) Uint64(u uint64) { + if e.dead() { + return + } + e.push(tagUint64) + e.st.buf = binary.LittleEndian.AppendUint64(e.st.buf, u) + e.complete() +} + +// String records a string. The encode fails if s is not valid UTF-8. +func (e Encoder) String(s string) { + if e.dead() { + return + } + if !utf8.ValidString(s) { + e.st.fail(errors.New("frame: string is not valid UTF-8")) + return + } + e.push(tagString) + if buf, err := appendChunk(e.st.buf, []byte(s)); err != nil { + e.st.fail(err) + } else { + e.st.buf = buf + e.complete() + } +} + +// Bytes records binary data. +func (e Encoder) Bytes(b []byte) { + if e.dead() { + return + } + e.push(tagBytes) + if buf, err := appendChunk(e.st.buf, b); err != nil { + e.st.fail(err) + } else { + e.st.buf = buf + e.complete() + } +} + +// Passthrough marks the next value as passthrough, and returns an Encoder +// for that value. A passthrough value is neither encrypted nor +// authenticated, so use Passthrough only for data that is not secret. +// +// The returned Encoder has the same methods as any other Encoder: +// +// m.Field("id").Passthrough().Int64(42) // a passthrough map entry +// enc.Passthrough().String("v") // a passthrough root value +// s.Elem().Passthrough().Bool(true) // a passthrough sequence element +// +// Write exactly one value through the returned Encoder: a scalar or a +// container. +func (e Encoder) Passthrough() Encoder { + e = e.orDead() + if !e.dead() { + if e.depth+1 > maxDepth { + e.st.fail(ErrTooDeep) + } else { + e.push(tagPassthrough) + } + } + // The passthrough tag and the value after it are one value in the slot + // of this Encoder. The returned Encoder therefore uses the same counter. + return Encoder{st: e.st, depth: e.depth + 1, done: e.done} +} + +// Seq starts a sequence. Call Elem once for each element, then call End. +func (e Encoder) Seq() *SeqEncoder { + e = e.orDead() + s := &SeqEncoder{st: e.st, depth: e.depth + 1, done: e.done} + if e.dead() { + return s + } + if e.depth+1 > maxDepth { + e.st.fail(ErrTooDeep) + return s + } + e.push(tagArray) + s.lenOff = len(e.st.buf) + e.push(0, 0, 0, 0) // End writes the count here + return s +} + +// Map starts a map with string keys. Call Field once for each entry, then +// call End. The entries are encoded in the order of the Field calls. Each +// key must be valid UTF-8. +func (e Encoder) Map() *MapEncoder { + e = e.orDead() + m := &MapEncoder{st: e.st, depth: e.depth + 1, done: e.done} + if e.dead() { + return m + } + if e.depth+1 > maxDepth { + e.st.fail(ErrTooDeep) + return m + } + e.push(tagObject) + m.lenOff = len(e.st.buf) + e.push(0, 0, 0, 0) // End writes the count here + return m +} + +// SeqEncoder records the elements of a sequence. Seq reserves four bytes for +// the element count, and End writes the count into them. +type SeqEncoder struct { + st *encState + depth int + lenOff int + count int + // done is the counter of the slot that the sequence is written into. See + // Encoder.done. End adds one to the counter, because the sequence is one + // value in that slot. + done *int + // childDone counts the elements of this sequence that are complete. Elem + // and End check that childDone equals count. The encode therefore fails + // for an element that was skipped, an element written twice, or a nested + // container that was never ended. Without the check, those mistakes + // would appear only as ErrMalformed at decode. + childDone int +} + +// checkPrev checks that exactly one value was written for the previous +// element. +func (s *SeqEncoder) checkPrev() { + if s.childDone > s.count { + s.st.fail(fmt.Errorf("frame: more than one value was written for sequence element %d", s.count-1)) + } else if s.count > 0 && s.childDone < s.count { + s.st.fail(fmt.Errorf("frame: no complete value was written for sequence element %d", s.count-1)) + } +} + +// Elem returns an Encoder for the next element. Write the whole element +// before the next call to Elem: call one method, and end any container that +// it starts. +func (s *SeqEncoder) Elem() Encoder { + if s.st.err == nil { + s.checkPrev() + if s.st.err == nil { + s.count++ + } + } + return Encoder{st: s.st, depth: s.depth, done: &s.childDone} +} + +// End completes the sequence and writes its element count. +// +// End returns the first error of the whole encode so far. The error is not +// limited to this sequence, so the End of a nested container can return an +// error from another part of the tree. This rule is deliberate. A later +// release will not change it. +// +// After the first error, every later write does nothing. An EncryptValue +// method can therefore make its writes without a check after each one, and +// return the result of the outermost End. Do not use the error of an inner +// End to find which value failed. The text of the error names that value. +func (s *SeqEncoder) End() error { + if s.st.err == nil { + s.checkPrev() + } + err := patchLen(s.st, s.lenOff, s.count) + if err == nil { + // The sequence is one complete value in the slot it was written + // into. + if s.done != nil { + *s.done++ + } + } + return err +} + +// MapEncoder records the entries of a map. Map reserves four bytes for the +// entry count, and End writes the count into them. +type MapEncoder struct { + st *encState + depth int + lenOff int + count int + // done is the counter of the slot that the map is written into. See + // Encoder.done. End adds one to the counter, because the map is one + // value in that slot. + done *int + // childDone counts the entries of this map whose values are complete, as + // SeqEncoder.childDone does for elements. Field and End check that + // childDone equals count. The encode therefore fails for a key whose + // value was skipped, written twice, or left as a container that was + // never ended. Without the check, a decoder would read the next key as + // the missing value. The only sign would be ErrMalformed at decode. + childDone int + // lastKey is the key of the most recent Field call. An error about a + // value that was skipped or written twice names this key. + lastKey string + // seen is the set of keys written so far. Field uses it to refuse a + // duplicate key. A Go map never has a duplicate key. Two other sources + // can produce one: + // + // - encodeStruct, when the vc tag of one field is the name of another + // field + // - an Encryptable written by hand + // + // Without this check, the duplicate would be found only after the + // plaintext has crossed into the guest. The ciphertext decoder would + // then return ErrMalformed. That error names neither the struct nor the + // key. + seen map[string]struct{} +} + +// checkPrev checks that exactly one value was written for the previous +// entry. +func (m *MapEncoder) checkPrev() { + if m.childDone > m.count { + m.st.fail(fmt.Errorf("frame: more than one value was written for key %q", m.lastKey)) + } else if m.count > 0 && m.childDone < m.count { + m.st.fail(fmt.Errorf("frame: no complete value was written for key %q", m.lastKey)) + } +} + +// Field writes the key of an entry and returns an Encoder for its value. +// Write the whole value before the next call to Field: call one method, and +// end any container that it starts. The key must be valid UTF-8. A key that +// repeats an earlier key fails the encode. The entries are encoded in the +// order of the Field calls. +func (m *MapEncoder) Field(key string) Encoder { + if m.st.err == nil { + m.checkPrev() + } + if m.st.err == nil { + if !utf8.ValidString(key) { + m.st.fail(errors.New("frame: object key is not valid UTF-8")) + } else if _, dup := m.seen[key]; dup { + m.st.fail(fmt.Errorf("frame: key %q is repeated", key)) + } else if buf, err := appendChunk(m.st.buf, []byte(key)); err != nil { + m.st.fail(err) + } else { + m.st.buf = buf + if m.seen == nil { + m.seen = make(map[string]struct{}) + } + m.seen[key] = struct{}{} + m.lastKey = key + m.count++ + } + } + return Encoder{st: m.st, depth: m.depth, done: &m.childDone} +} + +// End completes the map and writes its entry count. End returns the first +// error of the whole encode, as [SeqEncoder.End] does. The error is not +// limited to this map. +func (m *MapEncoder) End() error { + if m.st.err == nil { + m.checkPrev() + } + err := patchLen(m.st, m.lenOff, m.count) + if err == nil { + // The map is one complete value in the slot it was written into. + if m.done != nil { + *m.done++ + } + } + return err +} + +func patchLen(st *encState, off, count int) error { + if st.err != nil { + return st.err + } + if count < 0 || uint64(count) > maxUint32 { + st.fail(fmt.Errorf("frame: item count %d out of range", count)) + return st.err + } + binary.LittleEndian.PutUint32(st.buf[off:off+4], uint32(count)) + return nil +} + +// Marshal encodes v as the transport bytes of a value. A guest reads a value +// in that form, and [Unmarshal] decodes it. +func Marshal(v any) ([]byte, error) { + st := &encState{} + var root int + if err := Encode(Encoder{st: st, done: &root}, v); err != nil { + return nil, err + } + // The reflection code always writes exactly one value. Only an + // Encryptable can write no value, leave a container without its End, or + // write more than one value. + if root != 1 { + return nil, fmt.Errorf("frame: EncryptValue must write exactly one complete root value, and wrote %d", root) + } + return st.buf, nil +} + +// Encode records v into enc. Encode first checks whether v implements +// [Encryptable]. If v does, Encode calls its EncryptValue +// method. Otherwise Encode chooses a method by the type of v, with rules +// like those of encoding/json: +// +// - nil is written with Null. +// - A bool is written with Bool. +// - An int8, int16, or int32 is written with Int8, Int16, or Int32. +// - An int or int64 is written with Int64. +// - A uint8, uint16, or uint32 is written with Uint8, Uint16, or Uint32. +// - A uint, uint64, or uintptr is written with Uint64. +// - A float32 is written with Float32. +// - A float64 is written with Float64. +// - A string is written with String. +// - A []byte is written with Bytes. +// - A slice or an array is written with Seq. +// - A map[string]T is written with Map, with its keys in sorted order. +// - A struct is written with Map, with one entry for each field, in the +// order the struct declares them. The key is the field name, or the name +// in a `vc:"name"` tag. A `vc:"-"` tag skips the field. Options after a +// comma do not change the name. One such option is `,default` of the +// storage profile. +// - A pointer is written as the value it points at. A nil pointer is +// written as a typed null if its element type has a fixed width, and +// with Null otherwise. See [typedNullOf]. +// +// Encode sorts the keys of a map because Go iterates over a map in a random +// order. Sorted keys give equal maps the same encrypted structure. The +// fields of a struct stay in the order the struct declares them. +// +// Encode returns the first error recorded while it wrote to enc. An +// Encryptable can therefore pass part of its value to Encode, as in +// Encode(m.Field(k), x). +func Encode(enc Encoder, v any) error { + encodeAny(enc, v) + return enc.st.err +} + +func encodeAny(enc Encoder, v any) { + if enc.st.err != nil { + return + } + if v == nil { + enc.Null() + return + } + if interceptMarkers(enc, v) { + return + } + if b, ok := v.([]byte); ok { + enc.Bytes(b) + return + } + encodeReflect(enc, reflect.ValueOf(v)) +} + +// interceptMarkers writes v if the codec handles its type before reflection, +// and reports whether it wrote v. Both encodeAny and encodeReflect call it: +// the first for an interface value, the second for a value reached through +// reflection. +// +// The function handles these types: +// +// - Plain marks a passthrough value. The function checks for Plain before +// Encryptable and before the struct case, so a Plain is never encoded as +// an ordinary struct. +// - Object is what a map decodes as. A program that decrypts a record and +// encrypts it again passes an Object back in. Without this case, +// reflection would encode the Object as a sequence of structs with Key +// and Value fields. The structure of the record would change, with no +// error. +// - A type that implements Encryptable writes itself. A nil pointer of +// such a type is the exception. The pointer implements the interface, +// but most EncryptValue methods would dereference it. The function +// writes it with Null, as for any other nil whose type has no fixed +// width. +func interceptMarkers(enc Encoder, v any) bool { + if m, ok := markers[reflect.TypeOf(v)]; ok { + m.encode(enc, v) + return true + } + if x, ok := v.(Encryptable); ok { + if ev := reflect.ValueOf(v); ev.Kind() == reflect.Pointer && ev.IsNil() { + enc.Null() + return true + } + if err := x.EncryptValue(enc); err != nil { + enc.st.fail(err) + } + return true + } + return false +} + +// encodeObject writes a decoded Object as a map, with its fields in the +// order the Object lists them. Object exists to keep that order. +func encodeObject(enc Encoder, o value.Object) { + m := enc.Map() + for _, f := range o { + encodeAny(m.Field(f.Key), f.Value) + } + _ = m.End() +} + +func encodeReflect(enc Encoder, rv reflect.Value) { + if enc.st.err != nil { + return + } + if !rv.IsValid() { + enc.Null() + return + } + // A value reached through reflection can have one of the types that + // interceptMarkers handles. Such a value is a struct field, a slice + // element, or a map value. Plain is a struct, so this check must come + // before the reflect.Struct case below. + if rv.CanInterface() && interceptMarkers(enc, rv.Interface()) { + return + } + + if k, ok := numericKinds[rv.Kind()]; ok { + k.encode(enc, rv) + return + } + switch rv.Kind() { + case reflect.Bool: + enc.Bool(rv.Bool()) + case reflect.String: + enc.String(rv.String()) + case reflect.Slice: + if rv.Type().Elem().Kind() == reflect.Uint8 { + enc.Bytes(rv.Bytes()) + return + } + encodeSeq(enc, rv) + case reflect.Array: + if rv.Type().Elem().Kind() == reflect.Uint8 { + // A byte array is written as one Bytes value, as a byte slice is + // above. Rust writes a [u8; N] as one leaf too. Writing each + // byte as an element would seal N leaves. No other encoder + // produces a ciphertext of that structure. + b := make([]byte, rv.Len()) + reflect.Copy(reflect.ValueOf(b), rv) + enc.Bytes(b) + return + } + encodeSeq(enc, rv) + case reflect.Map: + encodeMap(enc, rv) + case reflect.Struct: + encodeStruct(enc, rv) + case reflect.Pointer, reflect.Interface: + if rv.IsNil() { + // A nil pointer still has an element type. If that type has a + // fixed width, the absent value is written as a typed null, as + // Rust writes an Option. A nil interface has no type, so it + // is written with Null. + if rv.Kind() != reflect.Pointer { + enc.Null() + } else if null := typedNullOf(rv.Type()); null != nil { + enc.typedNull(null) + } else { + enc.Null() + } + return + } + // Count the dereference as one level of depth. A dereference writes + // no bytes, so nothing else would limit a pointer cycle such as x = + // &x. Without this check, a cycle would overflow the stack and + // return no error. + if enc.depth+1 > maxDepth { + enc.st.fail(ErrTooDeep) + return + } + // The value the pointer points at is written into the same slot, so + // it uses the same counter. + encodeReflect(Encoder{st: enc.st, depth: enc.depth + 1, done: enc.done}, rv.Elem()) + default: + enc.st.fail(fmt.Errorf("frame: cannot encode value of kind %s", rv.Kind())) + } +} + +func encodeSeq(enc Encoder, rv reflect.Value) { + s := enc.Seq() + for i := 0; i < rv.Len(); i++ { + encodeReflect(s.Elem(), rv.Index(i)) + } + _ = s.End() +} + +func encodeMap(enc Encoder, rv reflect.Value) { + if rv.Type().Key().Kind() != reflect.String { + enc.st.fail(fmt.Errorf("frame: map keys must be strings, got %s", rv.Type().Key())) + return + } + keys := rv.MapKeys() + // Sort the keys. Go iterates over a map in a random order. Sorted keys + // give equal maps the same encrypted structure. + slices.SortFunc(keys, func(a, b reflect.Value) int { return strings.Compare(a.String(), b.String()) }) + m := enc.Map() + for _, k := range keys { + encodeReflect(m.Field(k.String()), rv.MapIndex(k)) + } + _ = m.End() +} + +func encodeStruct(enc Encoder, rv reflect.Value) { + t := rv.Type() + // The fields are named as the storage profile names them. A `vc:"name"` + // tag sets the name, and options follow a comma. A `vc:"-"` tag skips + // the field. An unknown option is refused. + fields, err := structFields(t) + if err != nil { + enc.st.fail(err) + return + } + m := enc.Map() + encoded, unexported := 0, 0 + for _, f := range fields { + if f.unexported { + unexported++ + continue + } + encodeReflect(m.Field(f.name), rv.Field(f.index)) + encoded++ + } + // Refuse a struct whose fields are all unexported. time.Time is the + // usual example. Such a struct would be sealed as an empty map. The + // value would be lost, with no error at encode or at decode. The Node + // binding of vitaminc has the same check, in ensure_plain_object. A + // struct whose fields all have a `vc:"-"` tag is accepted, because the + // caller asked for the empty encoding. + if encoded == 0 && unexported > 0 { + enc.st.fail(fmt.Errorf( + "frame: struct %s has no exported fields to encode; implement encrypt.Encryptable so that the type writes its own value", t)) + return + } + _ = m.End() +} + +// marker is one entry of the markers table. The encode function writes a +// value of a type that interceptMarkers matches exactly. The null field is +// the typed null of that type, or nil if the type has no fixed width. +// +// One table has both, so a new type cannot be written in one way and padded +// in another. A typed null is built from the tag that a value of the type is +// written with. The tag table is therefore the only list of types. +type marker struct { + null []byte + encode func(Encoder, any) +} + +// numeric is one entry of the numericKinds table. The encode function writes +// a value of an int, uint, or float kind for encodeReflect. The null field +// is the typed null of that kind. One table has both, as for marker. +type numeric struct { + null []byte + encode func(Encoder, reflect.Value) +} + +var ( + float32Type = reflect.TypeOf(float32(0)) + + // markers is filled in init because the entries for Plain and Object + // call encodeAny, and encodeAny reads this table. + markers map[reflect.Type]marker + + numericKinds = map[reflect.Kind]numeric{ + reflect.Int8: {nullOf(tagInt8), func(e Encoder, rv reflect.Value) { e.Int8(int8(rv.Int())) }}, + reflect.Int16: {nullOf(tagInt16), func(e Encoder, rv reflect.Value) { e.Int16(int16(rv.Int())) }}, + reflect.Int32: {nullOf(tagInt32), func(e Encoder, rv reflect.Value) { e.Int32(int32(rv.Int())) }}, + reflect.Int: {nullOf(tagInt64), func(e Encoder, rv reflect.Value) { e.Int64(rv.Int()) }}, + reflect.Int64: {nullOf(tagInt64), func(e Encoder, rv reflect.Value) { e.Int64(rv.Int()) }}, + reflect.Uint8: {nullOf(tagUint8), func(e Encoder, rv reflect.Value) { e.Uint8(uint8(rv.Uint())) }}, + reflect.Uint16: {nullOf(tagUint16), func(e Encoder, rv reflect.Value) { + e.Uint16(uint16(rv.Uint())) + }}, + reflect.Uint32: {nullOf(tagUint32), func(e Encoder, rv reflect.Value) { + e.Uint32(uint32(rv.Uint())) + }}, + // A uint, uint64, or uintptr is always written as a Uint64. The + // codec never checks whether the value would fit a narrower or a + // signed type. + reflect.Uint: {nullOf(tagUint64), func(e Encoder, rv reflect.Value) { e.Uint64(rv.Uint()) }}, + reflect.Uint64: {nullOf(tagUint64), func(e Encoder, rv reflect.Value) { e.Uint64(rv.Uint()) }}, + reflect.Uintptr: {nullOf(tagUint64), func(e Encoder, rv reflect.Value) { e.Uint64(rv.Uint()) }}, + reflect.Float32: {nullOf(tagFloat32), func(e Encoder, rv reflect.Value) { + // rv.Float() widens the value to float64. On the hardware, + // widening sets the quiet bit of a signaling NaN. A conversion + // to the built-in float32 copies the bits unchanged, because + // reflect treats a conversion from float32 to float32 as a copy. + // See Go issue 36400. A named float32 type therefore keeps its + // bits too. + // + // Only a value that cannot be read as an interface is widened. + if f, ok := interfaceOf(rv.Convert(float32Type)).(float32); ok { + e.Float32(f) + } else { + e.Float32(float32(rv.Float())) + } + }}, + reflect.Float64: {nullOf(tagFloat64), func(e Encoder, rv reflect.Value) { e.Float64(rv.Float()) }}, + } + + // typedNulls caches the result of typedNullOf for each pointer type. + // Without the cache, every nil pointer in a record would repeat the + // reflection. + typedNulls sync.Map +) + +func init() { + markers = map[reflect.Type]marker{ + reflect.TypeOf(value.Int128{}): {nullOf(tagInt128), func(e Encoder, v any) { + e.Int128(v.(value.Int128)) + }}, + reflect.TypeOf(value.Uint128{}): {nullOf(tagUint128), func(e Encoder, v any) { + e.Uint128(v.(value.Uint128)) + }}, + reflect.TypeOf(value.Date{}): {nullOf(tagDate), func(e Encoder, v any) { + e.Date(v.(value.Date)) + }}, + reflect.TypeOf(time.Time{}): {nullOf(tagTimestamp), func(e Encoder, v any) { + e.Timestamp(v.(time.Time)) + }}, + reflect.TypeOf(value.Timestamp{}): {nullOf(tagTimestamp), func(e Encoder, v any) { + e.TimestampParts(v.(value.Timestamp)) + }}, + reflect.TypeOf(value.Decimal{}): {nullOf(tagDecimal), func(e Encoder, v any) { + e.Decimal(v.(value.Decimal)) + }}, + reflect.TypeOf(value.UUID{}): {uuidNull, func(e Encoder, v any) { + e.UUID(v.(value.UUID)) + }}, + // The scalar type of a Tagged is known only from its value, so + // Tagged has no typed null. + reflect.TypeOf(value.Tagged{}): {nil, func(e Encoder, v any) { e.Tagged(v.(value.Tagged)) }}, + reflect.TypeOf(value.Plain{}): {nil, func(e Encoder, v any) { + encodeAny(e.Passthrough(), v.(value.Plain).V) + }}, + reflect.TypeOf(value.Object{}): {nil, func(e Encoder, v any) { + encodeObject(e, v.(value.Object)) + }}, + } +} + +// typedNullOf returns the typed null for a nil pointer of type t. The +// function follows t through any number of pointers to the type at the end. +// That type has a typed null when encodeReflect writes every value of it +// with one fixed-width tag. Two groups of types qualify: +// +// - The int, uint, and float kinds. A named type over one of these kinds +// qualifies too. +// - The fixed-width types in the markers table, matched exactly. A named +// type over one of them does not qualify. Reflection reads such a type +// as a struct, and writes it field by field. +// +// The result is nil for any other type. A type that implements Encryptable +// has no typed null either. Such a type chooses its own encoding, and that +// encoding might not have a fixed width. +func typedNullOf(t reflect.Type) []byte { + if cached, ok := typedNulls.Load(t); ok { + return cached.([]byte) + } + var null []byte + elem := t + // A pointer type can point at itself, as in type P *P. Such a type never + // leads to a type that is not a pointer. The loop therefore stops after + // maxDepth steps, the same limit as for a cycle of values. A type beyond + // that limit has no fixed width. + for depth := 0; elem.Kind() == reflect.Pointer && !elem.Implements(encryptableType); depth++ { + if depth == maxDepth { + typedNulls.Store(t, null) + return nil + } + elem = elem.Elem() + } + if !elem.Implements(encryptableType) { + if m, ok := markers[elem]; ok { + null = m.null + } else { + null = numericKinds[elem.Kind()].null + } + } + typedNulls.Store(t, null) + return null +} + +// interfaceOf returns rv.Interface(). The result is nil when reflection does +// not allow the call, as for a value reached through an unexported field. +func interfaceOf(rv reflect.Value) any { + if !rv.CanInterface() { + return nil + } + return rv.Interface() +} diff --git a/languages/golang/encrypt/frame/encryptable_test.go b/languages/golang/encrypt/frame/encryptable_test.go new file mode 100644 index 000000000..29d71c75c --- /dev/null +++ b/languages/golang/encrypt/frame/encryptable_test.go @@ -0,0 +1,119 @@ +package frame + +import ( + "bytes" + "errors" + "strings" + "testing" + "time" + + "github.com/cipherstash/stack/languages/golang/encrypt/value" +) + +// cents is a caller's type that writes itself: a money amount in whole +// units, written as its cents. +type cents int64 + +func (c cents) EncryptValue(enc Encoder) error { + enc.Int64(int64(c) * 100) + return nil +} + +func TestAnEncryptableWritesItself(t *testing.T) { + got := mustMarshal(t, cents(3)) + if want := mustMarshal(t, int64(300)); !bytes.Equal(got, want) { + t.Fatalf("got %x, want %x", got, want) + } + // A nil pointer to one is written as the plain null. The encoder does + // not call its method. + if got := mustMarshal(t, (*cents)(nil)); !bytes.Equal(got, []byte{tagNull}) { + t.Fatalf("a nil pointer writes %x", got) + } + // The type has no storage form, because no Encryptable has one. + if _, err := MarshalStorage(struct{ C cents }{}); !errors.Is(err, ErrUnwritable) { + t.Fatalf("storage: %v", err) + } +} + +func mustMarshal(t *testing.T, v any) []byte { + t.Helper() + b, err := Marshal(v) + if err != nil { + t.Fatal(err) + } + return b +} + +// checksEncoder records what the Encoder it is handed reports, and writes a +// value only when that Encoder is usable. +type checksEncoder struct{ usable *bool } + +func (c checksEncoder) EncryptValue(enc Encoder) error { + *c.usable = enc.Usable() + if enc.Err() != nil { + return enc.Err() + } + enc.Bool(true) + return nil +} + +func TestTheZeroEncoderIsNotUsable(t *testing.T) { + var zero Encoder + if zero.Usable() || zero.Err() == nil { + t.Fatalf("the zero Encoder: usable %v, err %v", zero.Usable(), zero.Err()) + } + var usable bool + if _, err := Marshal(checksEncoder{usable: &usable}); err != nil || !usable { + t.Fatalf("the Encoder the codec hands out: usable %v, %v", usable, err) + } + // Err reports the first error of the encode so far. + enc := func(e Encoder) error { + e.String(string([]byte{0xff})) + if e.Err() == nil { + return errors.New("Err reported nothing after a refused string") + } + return nil + } + if _, err := Marshal(encryptableFunc(enc)); err == nil || strings.Contains(err.Error(), "reported nothing") { + t.Fatalf("got %v", err) + } +} + +// Every method of the zero Encoder does nothing and does not panic, the +// containers and passthrough included. +func TestTheZeroEncoderDoesNotPanic(t *testing.T) { + var zero Encoder + zero.Null() + zero.Undefined() + zero.Bool(true) + zero.Int8(1) + zero.Int16(1) + zero.Int32(1) + zero.Int64(1) + zero.Int128(value.Int128{}) + zero.Uint8(1) + zero.Uint16(1) + zero.Uint32(1) + zero.Uint64(1) + zero.Uint128(value.Uint128{}) + zero.Float32(1) + zero.Float64(1) + zero.String("s") + zero.Bytes(nil) + zero.Date(value.Date{Year: 2000, Month: 1, Day: 1}) + zero.Timestamp(time.Now()) + zero.TimestampParts(value.Timestamp{}) + zero.Decimal(value.Decimal{}) + zero.UUID(value.UUID{}) + zero.Tagged(value.Tagged{ID: 200, V: int64(1)}) + zero.Passthrough().Int64(1) + s := zero.Seq() + s.Elem().Int64(1) + _ = s.End() + m := zero.Map() + m.Field("k").Int64(1) + _ = m.End() + if zero.Usable() || zero.Err() == nil { + t.Fatalf("the zero Encoder: usable %v, err %v", zero.Usable(), zero.Err()) + } +} diff --git a/languages/golang/encrypt/frame/fuzz_test.go b/languages/golang/encrypt/frame/fuzz_test.go new file mode 100644 index 000000000..2534bb845 --- /dev/null +++ b/languages/golang/encrypt/frame/fuzz_test.go @@ -0,0 +1,401 @@ +package frame + +import ( + "bytes" + "cmp" + "encoding/binary" + "encoding/hex" + "encoding/json" + "math/big" + "slices" + "testing" +) + +// Unmarshal and UnmarshalCipherText decode input that can be hostile: any +// bytes from the guest or from a database column. The fuzz targets check two +// things: +// +// - A decoder never panics. +// - Any input that a decoder accepts encodes again as the same bytes. See +// requireCanonical. +// +// An error is an acceptable result. +// +// The targets run in three ways: +// +// - CI runs them as ordinary tests over the seed corpus. +// - The nightly workflow .github/workflows/fuzz.yml fuzzes them. +// - A developer can fuzz them locally with `go test -fuzz`. + +// addCorpusSeeds adds every valid and every malformed vector of the shared +// value corpus to a fuzz target as a seed. The fuzzer therefore starts with +// an input for each scalar tag. +func addCorpusSeeds(f *testing.F, wrap func([]byte) []byte) { + data, ok := readCorpus(f, valueCorpus) + if !ok { + // The fuzz target still runs, with the seeds in its testdata + // directory. + return + } + var corpus struct { + Vectors, Malformed, Normalized []struct{ Transport string } + CiphertextMalformed []struct{ Transport string } `json:"ciphertext_malformed"` + } + if err := json.Unmarshal(data, &corpus); err != nil { + f.Fatal(err) + } + rows := append(append(corpus.Vectors, corpus.Malformed...), corpus.Normalized...) + for _, row := range rows { + raw, err := hex.DecodeString(row.Transport) + if err != nil { + f.Fatal(err) + } + f.Add(wrap(raw)) + } + // The malformed ciphertext vectors are added as seeds unchanged. The + // ciphertext targets must refuse them. The value targets must not read + // them as a value. + for _, row := range corpus.CiphertextMalformed { + raw, err := hex.DecodeString(row.Transport) + if err != nil { + f.Fatal(err) + } + f.Add(raw) + } +} + +// canonicalForm returns the bytes that an accepted value encoding encodes +// again as. Only four things can change: +// +// - An Undefined tag (0x01) becomes Null (0x00). Go documents that it +// decodes undefined as nil. +// - A typed null becomes Null too, as the frame writer in Rust writes it. +// - A decimal negative zero becomes zero, with its scale kept. +// - A timestamp in an envelope, in seconds, milliseconds, or microseconds, +// becomes the nanosecond form with tagTimestamp. Go reads it as a +// time.Time. +// +// canonicalForm reads the transport format with its own code, not with the +// decoder. If that code and the decoder disagree, canonicalForm returns the +// wrong bytes and requireCanonical fails. +func canonicalForm(data []byte) []byte { + r := &reader{buf: data} + var out []byte + canonicalValue(r, &out) + return out +} + +func requireCanonical(t *testing.T, data, out, want []byte) { + t.Helper() + if !bytes.Equal(out, want) { + t.Fatalf("accepted %x re-encoded as %x, want %x", data, out, want) + } +} + +func canonicalValue(r *reader, out *[]byte) { + tag, _ := r.byteTag() + switch tag { + case tagUndefined: + *out = append(*out, tagNull) + case tagDecimal: + b, _ := r.take(16) + b = bytes.Clone(b) + // Four bytes of flags, then twelve bytes of coefficient. A sign bit + // that is set with a zero coefficient is a negative zero. A negative + // zero reads back as zero. + if len(b) == 16 && bytes.Equal(b[4:], make([]byte, 12)) { + b[3] &^= 0x80 + } + *out = append(append(*out, tag), b...) + case tagEnvelope: + header, _ := r.take(2) + if len(header) == 2 && header[0] == logicalTimestamp && header[1] <= unitMicros { + if shorthand, ok := shorthandTimestamp(r, header[1]); ok { + *out = append(*out, shorthand...) + return + } + } + *out = append(append(*out, tag), header...) + canonicalValue(r, out) + case tagInt32, tagUint32, tagFloat32: + b, _ := r.take(4) + *out = append(append(*out, tag), b...) + case tagInt64, tagUint64, tagFloat64: + b, _ := r.take(8) + *out = append(append(*out, tag), b...) + case tagString, tagBytes: + start := r.pos + n, _ := r.count() + _, _ = r.take(n) + *out = append(append(*out, tag), r.buf[start:r.pos]...) + case tagArray: + start := r.pos + n, _ := r.count() + *out = append(append(*out, tag), r.buf[start:r.pos]...) + for range n { + canonicalValue(r, out) + } + case tagObject: + start := r.pos + n, _ := r.count() + *out = append(append(*out, tag), r.buf[start:r.pos]...) + for range n { + start := r.pos + _, _ = r.str() + *out = append(*out, r.buf[start:r.pos]...) + canonicalValue(r, out) + } + case tagPassthrough: + *out = append(*out, tag) + canonicalValue(r, out) + case tagTypedNull: + // The header names the type, and the type decides the length of the + // padding. The whole typed null comes back as the plain null. + header, _ := r.byteTag() + width := fixedWidth(header) + if header == tagEnvelope { + b, _ := r.take(3) + if len(b) == 3 { + width = fixedWidth(b[2]) + if b[2] == tagBytes { + width = 16 + } + } + } + _, _ = r.take(width - 1) + *out = append(*out, tagNull) + default: + // Null, the booleans, and the fixed-width extended scalars. + b, _ := r.take(fixedWidth(tag)) + *out = append(append(*out, tag), b...) + } +} + +// shorthandTimestamp reads the integer in an envelope and writes the instant +// with tagTimestamp. The bytes are the seconds as a signed 64-bit integer, +// then the nanoseconds as an unsigned 32-bit integer. The function reads +// each integer encoding by its width, and does not use the decoder. +func shorthandTimestamp(r *reader, unit byte) ([]byte, bool) { + tag, _ := r.byteTag() + var count *big.Int + switch tag { + case tagInt8, tagInt16, tagInt32, tagInt64, tagInt128: + b, _ := r.take(fixedWidth(tag)) + if len(b) == 0 { + return nil, false + } + count = signedLittle(b) + case tagUint8, tagUint16, tagUint32, tagUint64, tagUint128: + b, _ := r.take(fixedWidth(tag)) + if len(b) == 0 { + return nil, false + } + count = unsignedLittle(b) + default: + return nil, false + } + per := map[byte]int64{unitSeconds: 1_000_000_000, unitMillis: 1_000_000, unitMicros: 1_000}[unit] + nanos := new(big.Int).Mul(count, big.NewInt(per)) + seconds, sub := new(big.Int).DivMod(nanos, big.NewInt(1_000_000_000), new(big.Int)) + if !seconds.IsInt64() { + return nil, false + } + out := []byte{tagTimestamp} + out = binary.LittleEndian.AppendUint64(out, uint64(seconds.Int64())) + return binary.LittleEndian.AppendUint32(out, uint32(sub.Int64())), true +} + +func unsignedLittle(b []byte) *big.Int { + be := make([]byte, len(b)) + for i, x := range b { + be[len(b)-1-i] = x + } + return new(big.Int).SetBytes(be) +} + +func signedLittle(b []byte) *big.Int { + v := unsignedLittle(b) + if b[len(b)-1]&0x80 != 0 { + v.Sub(v, new(big.Int).Lsh(big.NewInt(1), uint(8*len(b)))) + } + return v +} + +// cipherCanonicalForm is canonicalForm for an accepted ciphertext tree. In a +// ciphertext tree, a value appears only inside a passthrough node. One more +// thing can change here: the entries of a map come back sorted by key. +// +// Rust writes the entries of a map in the order it has them, such as the +// order of the fields of a struct. Go reads a map into a map[string]any. +// That type has no order, so Go writes the map with its keys sorted. The +// order of the entries is not authenticated, so the decoder accepts either +// order. The function therefore sorts the entries. +func cipherCanonicalForm(data []byte) []byte { + r := &reader{buf: data} + var out []byte + var walk func() + walk = func() { + tag, _ := r.byteTag() + if _, ok := leafKind(tag); ok { + start := r.pos + n, _ := r.count() + _, _ = r.take(n) + out = append(append(out, tag), r.buf[start:r.pos]...) + return + } + switch tag { + case ctSeq: + start := r.pos + n, _ := r.count() + out = append(append(out, tag), r.buf[start:r.pos]...) + for range n { + walk() + } + case ctMap: + start := r.pos + n, _ := r.count() + out = append(append(out, tag), r.buf[start:r.pos]...) + // Each entry is first written to the end of out. The bytes of + // the entry are then removed from out and kept, so that the + // entries can be written in key order. + type entry struct { + key string + bytes []byte + } + var entries []entry + for range n { + start := r.pos + key, _ := r.str() + mark := len(out) + out = append(out, r.buf[start:r.pos]...) + walk() + entries = append(entries, entry{key, bytes.Clone(out[mark:])}) + out = out[:mark] + } + // The order is the one that slices.Sort gives the keys in + // encodeCipherText. + slices.SortFunc(entries, func(a, b entry) int { return cmp.Compare(a.key, b.key) }) + for _, e := range entries { + out = append(out, e.bytes...) + } + case ctPassthrough: + out = append(out, tag) + canonicalValue(r, &out) + } + } + walk() + return out +} + +func FuzzUnmarshal(f *testing.F) { + // The seeds: one input for each kind of node, and some hostile inputs. + f.Add([]byte{0x00}) // Null + f.Add([]byte{0x04, 7, 0, 0, 0}) // Int32 + f.Add([]byte{0x0A, 2, 0, 0, 0, 'h', 'i'}) // String + f.Add([]byte{0xF0, 1, 0, 0, 0, 0x03}) // Array[true] + f.Add([]byte{0xF1, 1, 0, 0, 0, 1, 0, 0, 0, 'a', 0x00}) // Object{a: null} + f.Add([]byte{0xF2, 0x05}) // Passthrough(Int64) truncated + f.Add([]byte{0xF0, 0xFF, 0xFF, 0xFF, 0xFF}) // hostile count + f.Add([]byte{0xF1, 2, 0, 0, 0, 1, 0, 0, 0, 'a', 0x00}) // short object + addCorpusSeeds(f, func(raw []byte) []byte { return raw }) + // Extended scalars nested in containers and passthrough. + addCorpusSeeds(f, func(raw []byte) []byte { return append([]byte{0xF0, 1, 0, 0, 0}, raw...) }) + addCorpusSeeds(f, func(raw []byte) []byte { return append([]byte{0xF2}, raw...) }) + + f.Fuzz(func(t *testing.T, data []byte) { + v, err := Unmarshal(data) + if err != nil { + return + } + out, err := Marshal(v) + if err != nil { + t.Fatalf("accepted decode failed to re-encode: %v (value %#v)", err, v) + } + requireCanonical(t, data, out, canonicalForm(data)) + // The bytes are in canonical form. A second decode and encode must + // therefore give the same bytes. + again, err := Unmarshal(out) + if err != nil { + t.Fatalf("re-encoding %x does not decode: %v", out, err) + } + if twice, err := Marshal(again); err != nil || !bytes.Equal(twice, out) { + t.Fatalf("re-encoding %x is not stable: %x (%v)", out, twice, err) + } + }) +} + +func FuzzUnmarshalCipherText(f *testing.F) { + f.Add([]byte{0x01, 1, 0, 0, 0, 0xAB}) // ctSingle leaf + f.Add([]byte{0x02, 1, 0, 0, 0, 0xAB}) // 0x02 is not a tag: malformed + f.Add([]byte{0x03, 1, 0, 0, 0, 0x01, 1, 0, 0, 0, 0xAB}) // ctSeq[leaf] + f.Add([]byte{0x04, 1, 0, 0, 0, 1, 0, 0, 0, 'a', 0x01, 1, 0, 0, 0, 0xAB}) // ctMap{a: leaf} + f.Add([]byte{0x06, 1, 0, 0, 0, 0xAB}) // ctEmptySeq + f.Add([]byte{0x07, 1, 0, 0, 0, 0xAB}) // ctEmptyMap + f.Add([]byte{0x05, 0x00}) // ctPassthrough(Null) + f.Add([]byte{0x03, 0xFF, 0xFF, 0xFF, 0xFF}) // hostile count + // Extended scalars as passthrough nodes inside a ciphertext. + addCorpusSeeds(f, func(raw []byte) []byte { return append([]byte{0x05}, raw...) }) + + f.Fuzz(func(t *testing.T, data []byte) { + v, err := UnmarshalCipherText(testLeaves(), data) + if err != nil { + return + } + out, err := MarshalCipherText(testLeaves(), v) + if err != nil { + t.Fatalf("accepted ciphertext decode failed to re-encode: %v (value %#v)", err, v) + } + requireCanonical(t, data, out, cipherCanonicalForm(data)) + }) +} + +// canonicalForm and cipherCanonicalForm decide what can change. This test +// checks that they change only these things: +// +// - a nested Undefined tag +// - the sign of a negative zero +// - a timestamp in an envelope +// - the order of the entries of a ciphertext map +func TestCanonicalWalkers(t *testing.T) { + negativeZero := []byte{0x14, 0, 0, 2, 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} + zero := []byte{0x14, 0, 0, 2, 0x00, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} + negativeOne := []byte{0x14, 0, 0, 2, 0x80, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} + millis := []byte{0xF3, 3, 1, 0x05, 0x7b, 0, 0, 0, 0, 0, 0, 0} // 123 ms + nanos := []byte{0x13, 0, 0, 0, 0, 0, 0, 0, 0, 0xc0, 0xd4, 0x54, 0x07} // 0 s, 123000000 ns + cat := func(parts ...[]byte) []byte { return bytes.Join(parts, nil) } + ctMapHeader := []byte{0x04, 2, 0, 0, 0} // ctMap of two entries + entryA := []byte{1, 0, 0, 0, 'a', 0x01, 1, 0, 0, 0, 0xAA} // "a": sealed leaf AA + entryB := []byte{1, 0, 0, 0, 'b', 0x01, 1, 0, 0, 0, 0xBB} // "b": sealed leaf BB + for _, tc := range []struct { + name string + walk func([]byte) []byte + data []byte + want []byte + }{ + {"bare", canonicalForm, []byte{0x01}, []byte{0x00}}, + {"bytes payload of 0x01", canonicalForm, []byte{0x0B, 1, 0, 0, 0, 0x01}, []byte{0x0B, 1, 0, 0, 0, 0x01}}, + {"array", canonicalForm, []byte{0xF0, 2, 0, 0, 0, 0x0B, 1, 0, 0, 0, 0x01, 0x01}, []byte{0xF0, 2, 0, 0, 0, 0x0B, 1, 0, 0, 0, 0x01, 0x00}}, + {"object", canonicalForm, []byte{0xF1, 1, 0, 0, 0, 1, 0, 0, 0, 0x01, 0x01}, []byte{0xF1, 1, 0, 0, 0, 1, 0, 0, 0, 0x01, 0x00}}, + {"passthrough", canonicalForm, []byte{0xF2, 0x01}, []byte{0xF2, 0x00}}, + {"extended scalar", canonicalForm, []byte{0xF0, 2, 0, 0, 0, 0x0D, 0x01, 0x01}, []byte{0xF0, 2, 0, 0, 0, 0x0D, 0x01, 0x00}}, + {"unknown envelope", canonicalForm, []byte{0xF3, 200, 9, 0x06, 34, 0, 0, 0}, []byte{0xF3, 200, 9, 0x06, 34, 0, 0, 0}}, + {"uuid envelope", canonicalForm, cat([]byte{0xF3, 5, 0, 0x0B, 2, 0, 0, 0, 0x01, 0x01}), cat([]byte{0xF3, 5, 0, 0x0B, 2, 0, 0, 0, 0x01, 0x01})}, + {"negative zero", canonicalForm, negativeZero, zero}, + {"negative zero in an array", canonicalForm, cat([]byte{0xF0, 1, 0, 0, 0}, negativeZero), cat([]byte{0xF0, 1, 0, 0, 0}, zero)}, + {"negative one", canonicalForm, negativeOne, negativeOne}, + {"millisecond envelope", canonicalForm, millis, nanos}, + {"millisecond envelope in an object", canonicalForm, cat([]byte{0xF1, 1, 0, 0, 0, 1, 0, 0, 0, 'k'}, millis), cat([]byte{0xF1, 1, 0, 0, 0, 1, 0, 0, 0, 'k'}, nanos)}, + {"second envelope over an i8", canonicalForm, []byte{0xF3, 3, 0, 0x0C, 10}, []byte{0x13, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, + {"sealed leaf of 0x01", cipherCanonicalForm, []byte{0x01, 1, 0, 0, 0, 0x01}, []byte{0x01, 1, 0, 0, 0, 0x01}}, + {"ciphertext passthrough", cipherCanonicalForm, []byte{0x03, 1, 0, 0, 0, 0x05, 0xF0, 1, 0, 0, 0, 0x01}, []byte{0x03, 1, 0, 0, 0, 0x05, 0xF0, 1, 0, 0, 0, 0x00}}, + {"ciphertext passthrough negative zero", cipherCanonicalForm, cat([]byte{0x05}, negativeZero), cat([]byte{0x05}, zero)}, + {"ciphertext map in key order", cipherCanonicalForm, cat(ctMapHeader, entryA, entryB), cat(ctMapHeader, entryA, entryB)}, + {"ciphertext map out of key order", cipherCanonicalForm, cat(ctMapHeader, entryB, entryA), cat(ctMapHeader, entryA, entryB)}, + {"ciphertext map nested in a sequence", cipherCanonicalForm, cat([]byte{0x03, 1, 0, 0, 0}, ctMapHeader, entryB, entryA), cat([]byte{0x03, 1, 0, 0, 0}, ctMapHeader, entryA, entryB)}, + {"ciphertext map entries keep their own children", cipherCanonicalForm, cat(ctMapHeader, entryB, cat([]byte{1, 0, 0, 0, 'a', 0x05}, negativeZero)), cat(ctMapHeader, cat([]byte{1, 0, 0, 0, 'a', 0x05}, zero), entryB)}, + } { + if got := tc.walk(tc.data); !bytes.Equal(got, tc.want) { + t.Errorf("%s: got %x, want %x", tc.name, got, tc.want) + } + } +} diff --git a/languages/golang/encrypt/frame/leaves_test.go b/languages/golang/encrypt/frame/leaves_test.go new file mode 100644 index 000000000..9642bb5ae --- /dev/null +++ b/languages/golang/encrypt/frame/leaves_test.go @@ -0,0 +1,42 @@ +package frame + +// The leaf types and the LeafSet of these tests. The codec has no leaf types +// of its own, so each caller supplies a LeafSet. The LeafSet of the SDK is +// in package encrypt. The three types here take the place of a caller's +// types, with one type for each LeafKind. +type ( + sealed []byte + sealedEmptySeq []byte + sealedEmptyMap []byte +) + +func testLeaves() LeafSet { + return LeafSet{ + Classify: func(v any) (LeafKind, []byte, bool) { + switch n := v.(type) { + case sealed: + return LeafSingle, n, true + case sealedEmptySeq: + return LeafEmptySeq, n, true + case sealedEmptyMap: + return LeafEmptyMap, n, true + default: + return 0, nil, false + } + }, + Make: func(kind LeafKind, bytes []byte) any { + switch kind { + case LeafSingle: + return sealed(bytes) + case LeafEmptySeq: + return sealedEmptySeq(bytes) + case LeafEmptyMap: + return sealedEmptyMap(bytes) + default: + // A kind that is not listed is refused with nil, as leafTag + // refuses one when it encodes. + return nil + } + }, + } +} diff --git a/languages/golang/encrypt/frame/scalars.go b/languages/golang/encrypt/frame/scalars.go new file mode 100644 index 000000000..ad5e20ae1 --- /dev/null +++ b/languages/golang/encrypt/frame/scalars.go @@ -0,0 +1,338 @@ +package frame + +import ( + "encoding/binary" + "time" + + "github.com/cipherstash/stack/languages/golang/encrypt/value" +) + +func (e Encoder) scalar(tag byte, payload []byte) { + if e.dead() { + return + } + e.push(tag) + e.push(payload...) + e.complete() +} + +func (e Encoder) Int8(v int8) { e.scalar(tagInt8, []byte{byte(v)}) } +func (e Encoder) Uint8(v uint8) { e.scalar(tagUint8, []byte{v}) } +func (e Encoder) Int16(v int16) { e.scalar(tagInt16, binary.LittleEndian.AppendUint16(nil, uint16(v))) } +func (e Encoder) Uint16(v uint16) { e.scalar(tagUint16, binary.LittleEndian.AppendUint16(nil, v)) } +func (e Encoder) Int128(v value.Int128) { e.scalar(tagInt128, v[:]) } +func (e Encoder) Uint128(v value.Uint128) { e.scalar(tagUint128, v[:]) } + +func (e Encoder) Date(v value.Date) { + if e.dead() { + return + } + days, err := v.DaysFromCE() + if err != nil { + e.st.fail(err) + return + } + e.scalar(tagDate, binary.LittleEndian.AppendUint32(nil, uint32(days))) +} + +// Timestamp records the instant of v, to the nanosecond. Timestamp does not +// record the location of v or its monotonic clock reading. +func (e Encoder) Timestamp(v time.Time) { + e.TimestampParts(value.Timestamp{Seconds: v.Unix(), Nanoseconds: uint32(v.Nanosecond())}) +} +func (e Encoder) TimestampParts(v value.Timestamp) { + if e.dead() { + return + } + if err := v.Validate(); err != nil { + e.st.fail(err) + return + } + b := binary.LittleEndian.AppendUint64(nil, uint64(v.Seconds)) + b = binary.LittleEndian.AppendUint32(b, v.Nanoseconds) + e.scalar(tagTimestamp, b) +} + +// Decimal records a finite decimal. Decimal writes a zero with no sign, +// whatever the sign of v. +func (e Encoder) Decimal(v value.Decimal) { + if e.dead() { + return + } + if err := v.Validate(); err != nil { + e.st.fail(err) + return + } + v = v.Normalized() + flags := uint32(v.Scale) << 16 + if v.Negative { + flags |= 0x80000000 + } + b := binary.LittleEndian.AppendUint32(nil, flags) + b = append(b, v.Coefficient[:]...) + e.scalar(tagDecimal, b) +} + +// UUID records the sixteen bytes of u with the logical type Uuid. The bytes +// are an envelope around a bytes scalar. The envelope starts with the tag +// 0xF3. +func (e Encoder) UUID(u value.UUID) { + if e.dead() { + return + } + e.push(uuidEnvelope[:]...) + e.Bytes(u[:]) +} + +// uuidEnvelope is the envelope header that starts an encoded UUID. The typed +// null of a UUID uses the same header. The header is the envelope tag, the +// id of the logical type Uuid, and a parameter of zero. +var uuidEnvelope = [3]byte{tagEnvelope, logicalUUID, 0} + +// Tagged records a physical scalar with a logical type id that this version +// of the codec does not know. The bytes are an envelope, as for any logical +// type with no tag of its own. [Unmarshal] returns a Tagged for such a +// value, and Tagged writes the same bytes back. +// +// Tagged refuses an id that this version knows. Tagged also refuses a V that +// is not a physical scalar. +func (e Encoder) Tagged(t value.Tagged) { + if e.dead() { + return + } + if t.ID <= logicalLastKnown { + e.st.fail(value.ErrInvalidTagged) + return + } + e.push(tagEnvelope, t.ID, t.Param) + if !e.physical(t.V) { + e.st.fail(value.ErrInvalidTagged) + } +} + +// physical writes v with the scalar method for its type, when an envelope +// can contain that kind of scalar. The function reports whether it wrote v. +func (e Encoder) physical(v any) bool { + switch x := v.(type) { + case nil: + e.Null() + case bool: + e.Bool(x) + case int8: + e.Int8(x) + case uint8: + e.Uint8(x) + case int16: + e.Int16(x) + case uint16: + e.Uint16(x) + case int32: + e.Int32(x) + case uint32: + e.Uint32(x) + case int64: + e.Int64(x) + case uint64: + e.Uint64(x) + case int: + // Encode writes an int and a uint the same way. + e.Int64(int64(x)) + case uint: + e.Uint64(uint64(x)) + case value.Int128: + e.Int128(x) + case value.Uint128: + e.Uint128(x) + case float32: + e.Float32(x) + case float64: + e.Float64(x) + case string: + e.String(x) + case []byte: + e.Bytes(x) + default: + return false + } + return true +} + +func decodeScalar(r *reader, tag byte) (any, error) { + b, err := r.take(fixedWidth(tag)) + if err != nil { + return nil, err + } + switch tag { + case tagInt8: + return int8(b[0]), nil + case tagUint8: + return b[0], nil + case tagInt16: + return int16(binary.LittleEndian.Uint16(b)), nil + case tagUint16: + return binary.LittleEndian.Uint16(b), nil + case tagInt128: + return value.Int128(b), nil + case tagUint128: + return value.Uint128(b), nil + case tagDate: + d, err := value.DateFromDaysCE(int32(binary.LittleEndian.Uint32(b))) + if err != nil { + return nil, ErrMalformed + } + return d, nil + case tagTimestamp: + // Validate refuses nanoseconds of one billion or more. Such a value + // is a leap second. A leap second has no count since the epoch. + t := value.Timestamp{Seconds: int64(binary.LittleEndian.Uint64(b)), Nanoseconds: binary.LittleEndian.Uint32(b[8:])} + if t.Validate() != nil { + return nil, ErrMalformed + } + return time.Unix(t.Seconds, int64(t.Nanoseconds)).UTC(), nil + case tagDecimal: + flags := binary.LittleEndian.Uint32(b) + if flags&0x7f00ffff != 0 { + return nil, ErrMalformed + } + d := value.Decimal{Scale: uint8(flags >> 16), Negative: flags>>31 != 0} + copy(d.Coefficient[:], b[4:]) + if d.Validate() != nil { + return nil, ErrMalformed + } + // A negative zero reads as zero, with its scale kept. + return d.Normalized(), nil + default: + return nil, ErrMalformed + } +} + +// fixedWidth returns the number of payload bytes that follow a fixed-width +// scalar tag. The result is zero for a tag whose payload varies in length, +// and for a tag with no payload. +func fixedWidth(tag byte) int { + switch tag { + case tagInt8, tagUint8: + return 1 + case tagInt16, tagUint16: + return 2 + case tagInt32, tagUint32, tagFloat32, tagDate: + return 4 + case tagInt64, tagUint64, tagFloat64: + return 8 + case tagTimestamp: + return 12 + case tagInt128, tagUint128, tagDecimal: + return 16 + } + return 0 +} + +// numericTag reports whether tag is an integer tag, or a float tag when +// floats is true. A typed null in an envelope must name such a tag as its +// scalar. Under a timestamp unit the scalar must be an integer. Under an id +// that this version does not know, the scalar can be an integer or a float. +func numericTag(tag byte, floats bool) bool { + switch tag { + case tagInt8, tagUint8, tagInt16, tagUint16, tagInt32, tagUint32, tagInt64, tagUint64, + tagInt128, tagUint128: + return true + case tagFloat32, tagFloat64: + return floats + } + return false +} + +// nullOf returns the typed null of a type whose values are written with the +// scalar tag. The bytes are tagTypedNull, then tag, then zeros. The typed +// null is as long as an encoded value of the type, so both seal to the same +// length. The first byte, tagTypedNull, counts towards that length. The +// zeros are therefore one byte shorter than the payload. +func nullOf(tag byte) []byte { + return typedNull([]byte{tag}, fixedWidth(tag)) +} + +// uuidNull is the typed null of a UUID. The header is the UUID envelope, +// then the bytes tag. The sealed leaf of a UUID has no length prefix. The +// padding is therefore sized for the sixteen bytes of the UUID alone. +var uuidNull = typedNull(append(uuidEnvelope[:], tagBytes), len(value.UUID{})) + +func typedNull(header []byte, payload int) []byte { + out := append([]byte{tagTypedNull}, header...) + return append(out, make([]byte, payload-1)...) +} + +// typedNull records an absent value of a fixed-width type. null is the bytes +// that nullOf or uuidNull built. Encode calls typedNull for a nil pointer to +// a fixed-width type. +func (e Encoder) typedNull(null []byte) { + if e.dead() { + return + } + e.push(null...) + e.complete() +} + +// decodeTypedNull reads a typed null, after its tag. A typed null has two +// parts: +// +// - the header that starts a value of some fixed-width type +// - exactly the zeros that pad the typed null to the length of that value +// +// The function refuses anything else, as the Rust codec does. Every absent +// value therefore has one encoding. +// +// A typed null decodes as nil. The padding matters only when a value is +// sealed. A frame is never sealed. The frame writer in Rust therefore writes +// the plain null for an absent value too. +func decodeTypedNull(r *reader) (any, error) { + tag, err := r.byteTag() + if err != nil { + return nil, err + } + var payload int + switch { + case tag == tagEnvelope: + h, err := r.take(3) + if err != nil { + return nil, err + } + id, param, physical := h[0], h[1], h[2] + switch id { + case logicalTimestamp: + // A timestamp in nanoseconds uses tagTimestamp, so an envelope + // must not name that unit. + if param > unitMicros || !numericTag(physical, false) { + return nil, ErrMalformed + } + payload = fixedWidth(physical) + case logicalUUID: + if param != 0 || physical != tagBytes { + return nil, ErrMalformed + } + payload = 16 + case 0, logicalUndefined, logicalDate, logicalDecimal: + return nil, ErrMalformed + default: + // An id that this version does not know. The scalar must be an + // integer or a float. + if !numericTag(physical, true) { + return nil, ErrMalformed + } + payload = fixedWidth(physical) + } + case tag == tagDate || tag == tagTimestamp || tag == tagDecimal || numericTag(tag, true): + payload = fixedWidth(tag) + default: + return nil, ErrMalformed + } + padding, err := r.take(payload - 1) + if err != nil { + return nil, err + } + for _, b := range padding { + if b != 0 { + return nil, ErrMalformed + } + } + return nil, nil +} diff --git a/languages/golang/encrypt/frame/scalars_test.go b/languages/golang/encrypt/frame/scalars_test.go new file mode 100644 index 000000000..4f6aa4a66 --- /dev/null +++ b/languages/golang/encrypt/frame/scalars_test.go @@ -0,0 +1,218 @@ +package frame + +import ( + "encoding/hex" + "errors" + "reflect" + "strings" + "testing" + "time" + + "github.com/cipherstash/stack/languages/golang/encrypt/value" +) + +func TestScalarHostEncoding(t *testing.T) { + signed, err := value.ParseInt128("-170141183460469231731687303715884105728") + if err != nil { + t.Fatal(err) + } + unsigned, err := value.ParseUint128("340282366920938463463374607431768211455") + if err != nil { + t.Fatal(err) + } + decimal, err := value.ParseDecimal("1.50") + if err != nil { + t.Fatal(err) + } + uuid, err := value.ParseUUID("123e4567-e89b-12d3-a456-426614174000") + if err != nil { + t.Fatal(err) + } + cases := []struct { + value any + wire string + }{ + {int8(-128), "0c80"}, {uint8(255), "0dff"}, {int16(-32768), "0e0080"}, {uint16(65535), "0fffff"}, + {signed, "1000000000000000000000000000000080"}, {unsigned, "11ffffffffffffffffffffffffffffffff"}, + {value.Date{Year: 1, Month: 1, Day: 1}, "1201000000"}, + {time.Unix(0, 123456789).UTC(), "13000000000000000015cd5b07"}, + {decimal, "1400000200960000000000000000000000"}, + // The 0xF3 envelope: a logical type with no shorthand tag. + {uuid, "f305000b10000000123e4567e89b12d3a456426614174000"}, + {value.Tagged{ID: 200, Param: 9, V: uint32(34)}, "f3c8090622000000"}, + {value.Tagged{ID: 255, Param: 0, V: nil}, "f3ff0000"}, + {value.Tagged{ID: 6, Param: 1, V: "hi"}, "f306010a020000006869"}, + } + for _, tc := range cases { + encoded, err := Marshal(tc.value) + if err != nil { + t.Fatal(err) + } + if hex.EncodeToString(encoded) != tc.wire { + t.Fatalf("%T: %x != %s", tc.value, encoded, tc.wire) + } + decoded, err := Unmarshal(encoded) + if err != nil || !reflect.DeepEqual(decoded, tc.value) { + t.Fatalf("%T: got %#v: %v", tc.value, decoded, err) + } + // The same rule applies through pointers, fields, and interfaces. + nested := struct{ Value any }{Value: &tc.value} + if _, err := Marshal(nested); err != nil { + t.Fatal(err) + } + } +} + +func TestInvalidScalarHostEncoding(t *testing.T) { + cases := []struct { + value any + err error + }{ + {value.Date{Year: 2023, Month: 2, Day: 29}, value.ErrInvalidDate}, + {value.Timestamp{Seconds: 0, Nanoseconds: 1000000000}, value.ErrInvalidTimestamp}, + {time.Date(10000, 1, 1, 0, 0, 0, 0, time.UTC), value.ErrInvalidTimestamp}, + {time.Date(-9999, 1, 1, 0, 0, 0, 0, time.UTC), value.ErrInvalidTimestamp}, + {value.Decimal{Scale: 29}, value.ErrInvalidDecimal}, + // A tagged value must be a physical scalar under an unknown id. + {value.Tagged{ID: 5, V: []byte{1}}, value.ErrInvalidTagged}, + {value.Tagged{ID: 0, V: int8(1)}, value.ErrInvalidTagged}, + {value.Tagged{ID: 200, V: []any{int8(1)}}, value.ErrInvalidTagged}, + {value.Tagged{ID: 200, V: time.Unix(0, 0)}, value.ErrInvalidTagged}, + } + for _, tc := range cases { + if _, err := Marshal(tc.value); !errors.Is(err, tc.err) { + t.Fatalf("got %v, want %v", err, tc.err) + } + } +} + +// A timestamp in an envelope decodes as a time.Time, for each unit. The +// nanosecond unit uses tagTimestamp, so the decoder refuses it in an +// envelope. The decoder also refuses the other bad envelopes below. The +// corpus does not cover those. +func TestEnvelopeTimestampsDecodeToTime(t *testing.T) { + for _, tc := range []struct { + wire string + want time.Time + }{ + {"f30301057b00000000000000", time.Unix(0, 123_000_000).UTC()}, // 123 ms + {"f3030205c8ff ffffffffffff", time.Unix(0, -56_000).UTC()}, // -56 µs, as an i64 + {"f303000c0a", time.Unix(10, 0).UTC()}, // 10 s, as an i8 + {"f3030210" + "00f1" + "ffffffffffffffffffffffffffff", time.Unix(0, -3_840_000).UTC()}, // -3840 µs, as an i128 + {"f3030005e0d3f2ff3a000000", time.Unix(253402207200, 0).UTC()}, // the last second in the accepted range, as an i64 + {"f30300051fb9060fa8ffffff", time.Unix(-377705023201, 0).UTC()}, // the first second in the accepted range + } { + t.Run(tc.wire, func(t *testing.T) { + raw, err := hex.DecodeString(strings.ReplaceAll(tc.wire, " ", "")) + if err != nil { + t.Fatal(err) + } + got, err := Unmarshal(raw) + if err != nil { + t.Fatal(err) + } + if ts, ok := got.(time.Time); !ok || !ts.Equal(tc.want) { + t.Fatalf("got %#v, want %v", got, tc.want) + } + }) + } + for _, wire := range []string{ + "f3030305" + "0000000000000000", // nanoseconds: the shorthand tag exists + "f3030405" + "0000000000000000", // no such unit + "f303010a" + "00000000", // a count that is not an int + "f3030010" + "0000000000000000000000000000ff7f", // outside the accepted range + "f3030005" + "e1d3f2ff3a000000", // one second after the accepted range, as an i64 + "f3030005" + "1eb9060fa8ffffff", // one second before it + "f3030107" + "18fcffffffffffff", // 2^64 - 1000 ms, a u64 above the i64 range + } { + t.Run(wire, func(t *testing.T) { + raw, err := hex.DecodeString(wire) + if err != nil { + t.Fatal(err) + } + if _, err := Unmarshal(raw); err != ErrMalformed { + t.Fatalf("got %v, want ErrMalformed", err) + } + }) + } +} + +// Every integer width is a valid count for an envelope timestamp. +func TestEnvelopeTimestampAcceptsEveryIntegerWidth(t *testing.T) { + i128, err := value.ParseInt128("1") + if err != nil { + t.Fatal(err) + } + u128, err := value.ParseUint128("1") + if err != nil { + t.Fatal(err) + } + for _, value := range []any{int8(1), int16(1), int32(1), int64(1), uint8(1), uint16(1), uint32(1), uint64(1), i128, u128} { + got, err := envelopeTimestamp(unitSeconds, value) + ts, ok := got.(time.Time) + if err != nil || !ok || !ts.Equal(time.Unix(1, 0).UTC()) { + t.Errorf("%T: got %#v, err %v", value, got, err) + } + } +} + +// A decimal negative zero built as a struct literal is written without its +// sign: Go never writes the sign bit of a zero. +func TestDecimalNegativeZeroIsWrittenUnsigned(t *testing.T) { + encoded, err := Marshal(value.Decimal{Negative: true, Scale: 2}) + if err != nil { + t.Fatal(err) + } + if got, want := hex.EncodeToString(encoded), "1400000200000000000000000000000000"; got != want { + t.Fatalf("got %s, want %s", got, want) + } +} + +// Every physical scalar can be written with an unknown id. Each one reads +// back as the same Tagged value. +func TestTaggedRoundTripsEveryPhysicalScalar(t *testing.T) { + i128, err := value.ParseInt128("-1") + if err != nil { + t.Fatal(err) + } + u128, err := value.ParseUint128("1") + if err != nil { + t.Fatal(err) + } + for _, v := range []any{nil, true, int8(-1), uint8(1), int16(-1), uint16(1), int32(-1), uint32(1), int64(-1), uint64(1), i128, u128, float32(1.5), float64(1.5), "text", []byte{1}} { + want := value.Tagged{ID: 200, Param: 9, V: v} + wire, err := Marshal(want) + if err != nil { + t.Fatal(err) + } + got, err := Unmarshal(wire) + if err != nil || !reflect.DeepEqual(got, want) { + t.Errorf("%T: got %#v, err %v", v, got, err) + } + } +} + +// A Go int or uint in a Tagged value is written as an Int64 or a Uint64, as +// Encode writes it for every value. The value reads back at that width. +func TestTaggedWritesIntAndUintAtSixtyFourBits(t *testing.T) { + for _, tc := range []struct { + value any + wire string + back any + }{ + {-34, "f3c80905deffffffffffffff", int64(-34)}, + {uint(34), "f3c809072200000000000000", uint64(34)}, + } { + wire, err := Marshal(value.Tagged{ID: 200, Param: 9, V: tc.value}) + if err != nil { + t.Fatalf("%T: %v", tc.value, err) + } + if got := hex.EncodeToString(wire); got != tc.wire { + t.Errorf("%T: got %s, want %s", tc.value, got, tc.wire) + } + got, err := Unmarshal(wire) + if want := (value.Tagged{ID: 200, Param: 9, V: tc.back}); err != nil || !reflect.DeepEqual(got, want) { + t.Errorf("%T: got %#v, err %v", tc.value, got, err) + } + } +} diff --git a/languages/golang/encrypt/frame/storage.go b/languages/golang/encrypt/frame/storage.go new file mode 100644 index 000000000..d04551af0 --- /dev/null +++ b/languages/golang/encrypt/frame/storage.go @@ -0,0 +1,748 @@ +package frame + +import ( + "cmp" + "encoding" + "encoding/binary" + "errors" + "fmt" + "math" + "reflect" + "slices" + "strings" + "unicode/utf8" + + "github.com/cipherstash/stack/languages/golang/encrypt/value" +) + +// This file is the storage profile, version 1. The storage profile writes a +// value as one versioned blob, for bytes that a program stores. The Rust +// module recipher_frame::storage implements the same format. The file +// packages/recipher-frame/STORAGE.md specifies the format. The tests check +// it against the expected blobs in +// packages/recipher-frame/testdata/storage-v1.json. +// +// The rest of this package writes transport bytes, and a later release can +// change those. A later release never changes the bytes that +// [MarshalStorage] writes and [UnmarshalStorage] reads. Go and Rust both +// read and write them. + +// StorageVersion is the version that this package writes. No other version +// is read. +const StorageVersion = 1 + +// StorageSome is the tag of an optional value that is present. The bytes are +// StorageSome, then the value. Rust writes the tag for every Some. +// +// Go writes the tag only for a pointer to a value that is itself written +// starting with null or StorageSome. Without the tag, such a pointer would +// read back as nil. In every other case Go writes the value with no tag. +// +// A reader accepts a value with no tag as a present value, for a Go pointer +// and for a Rust Option. A reader also accepts it for a field that is not +// optional. Both languages therefore read what a Go pointer wrote, whatever +// type the reader declares. +const StorageSome = 0xF5 + +// StorageMap is the tag of a map whose keys are nodes. The bytes are +// StorageMap, a 32-bit count, then a key and a value for each entry. A Go +// map is written as such a map. A struct is written as an object. +const StorageMap = 0xF6 + +// StorageHeader is the four bytes that start every blob: "VCS", then +// [StorageVersion]. +var StorageHeader = [4]byte{'V', 'C', 'S', StorageVersion} + +// The kinds of error that the storage profile returns. The kinds correspond +// to storage::ErrorKind in Rust. Match them with errors.Is. A blob that +// breaks a rule of its version fails with [ErrMalformed], as malformed +// transport bytes do. +var ( + // ErrNotABlob means that the bytes are shorter than the header, or do + // not start with "VCS". + ErrNotABlob = errors.New("frame: not a storage blob") + // ErrUnsupportedVersion means that the blob has a version that this + // package does not read. The blob is not corrupt. A later release of + // this package might read it, so upgrade the reader. + ErrUnsupportedVersion = errors.New("frame: an unsupported storage version") + // ErrMismatch means that a well-formed blob contains a value that does + // not fit the destination. Examples are a string where a number is + // expected, and a missing field. + ErrMismatch = errors.New("frame: the stored value does not fit the destination") + // ErrUnwritable means that the value cannot be written as a blob. The + // causes are these: + // + // - The value is nested too deep. + // - A map key is not an integer, text, or bytes. + // - A key is repeated. + // - The value is of a kind that has no storage form. + ErrUnwritable = errors.New("frame: the value cannot be written as a storage blob") +) + +// Some is an optional value that is present, as a blob stores it. +// UnmarshalStorage returns a Some when it reads such a value into an `any`. +// To write an optional value, the usual way is a pointer. +type Some struct { + V any +} + +// StorageEntries is a map as a blob stores it: the entries, in the order +// they were written. UnmarshalStorage returns a StorageEntries when it reads +// a map into an `any`. Each key is an integer, a string, or a []byte. +// MarshalStorage writes a StorageEntries as a map, with the entries in the +// same order. +type StorageEntries []StorageEntry + +// StorageEntry is one entry of [StorageEntries]. +type StorageEntry struct { + Key any + Value any +} + +func unwritable(format string, args ...any) error { + return fmt.Errorf("%w: "+format, append([]any{ErrUnwritable}, args...)...) +} + +// MarshalStorage writes v as a version 1 blob. The type of v decides how it +// is written: +// +// - nil and a nil interface are written as null. +// - A bool is written as a bool. +// - An int8, int16, int32, or int64 is written at its own width. An int is +// written as an int64. +// - A uint8, uint16, uint32, or uint64 is written at its own width. A uint +// or uintptr is written as a uint64. +// - An Int128 or Uint128 is written as a 128-bit integer. +// - A float32 or float64 is written at its own width, with its bits +// unchanged. +// - A string is written as text. The string must be valid UTF-8. +// - A []byte or [N]byte is written as bytes. A UUID is therefore written +// as its 16 bytes. +// - A type that implements encoding.TextMarshaler is written as text. A +// time.Time is therefore written in RFC 3339 form. +// - A slice or an array is written as an array. A nil slice is written as +// an empty array. +// - A map[K]V is written as a map, with its keys in sorted order. The +// order of integer keys is by value. The order of text keys and of bytes +// keys is by their bytes. A Rust BTreeMap has the same order. K must be +// an integer, a string, a byte array, or a TextMarshaler. +// - A struct is written as an object, with one entry for each field, in +// the order the struct declares them. The key is the field name, or the +// name in a `vc:"name"` tag. A `vc:"-"` tag skips the field. A field +// tagged `vc:"name,default"` reads as its zero value from a blob that +// does not have it. +// - A nil pointer is written as null. Any other pointer is written as the +// value it points at, as encoding/json does. One case differs: a pointer +// to a value whose bytes start with null or [StorageSome]. Such a value +// is a nil pointer, a nil interface, a [Some], or a pointer to one of +// those. The pointer is then written as [StorageSome] followed by the +// value, so every level of pointer reads back. +// - A [Some], a [StorageEntries], an Object, and a []any are each written +// as the node they are read from. +// +// Some types of the transport encoding have no storage form. MarshalStorage +// refuses them: an Encryptable, the passthrough type Plain, and the logical +// types Date, Timestamp, Decimal, and Tagged. +func MarshalStorage(v any) ([]byte, error) { + w := &storageWriter{buf: append([]byte(nil), StorageHeader[:]...)} + if err := w.any(v, 0); err != nil { + return nil, err + } + return w.buf, nil +} + +type storageWriter struct { + buf []byte +} + +var ( + textMarshalerType = reflect.TypeOf((*encoding.TextMarshaler)(nil)).Elem() + textUnmarshalerType = reflect.TypeOf((*encoding.TextUnmarshaler)(nil)).Elem() +) + +func (w *storageWriter) any(v any, depth int) error { + return w.reflect(reflect.ValueOf(v), depth) +} + +// The types, of this package and of package value, that +// [storageWriter.model] writes. Int128 and Uint128 are [16]byte types, so +// [byteArray] excludes them too. That second check covers a value that model +// cannot read as an interface. The reader relies on it as well. +var ( + int128Type = reflect.TypeOf(value.Int128{}) + uint128Type = reflect.TypeOf(value.Uint128{}) + someType = reflect.TypeOf(Some{}) + objectType = reflect.TypeOf(value.Object{}) + entriesType = reflect.TypeOf(StorageEntries{}) + plainType = reflect.TypeOf(value.Plain{}) + dateType = reflect.TypeOf(value.Date{}) + timestampType = reflect.TypeOf(value.Timestamp{}) + decimalType = reflect.TypeOf(value.Decimal{}) + taggedType = reflect.TypeOf(value.Tagged{}) +) + +// model writes rv if its type is one of the types listed above, and +// reports whether it wrote rv. Each of those types has a storage form of +// its own, different from the form reflection would give it. Only a value of +// those types is converted to an interface to be written. +func (w *storageWriter) model(rv reflect.Value, depth int) (bool, error) { + if !rv.CanInterface() { + return false, nil + } + switch rv.Type() { + case someType: + w.buf = append(w.buf, StorageSome) + return true, w.any(rv.Interface().(Some).V, depth+1) + case objectType: + return true, w.object(rv.Interface().(value.Object), depth) + case entriesType: + return true, w.entries(rv.Interface().(StorageEntries), depth) + case int128Type: + x := rv.Interface().(value.Int128) + w.buf = append(append(w.buf, tagInt128), x[:]...) + return true, nil + case uint128Type: + x := rv.Interface().(value.Uint128) + w.buf = append(append(w.buf, tagUint128), x[:]...) + return true, nil + case plainType, dateType, timestampType, decimalType, taggedType: + return true, unwritable("%s has no storage form", rv.Type()) + } + return false, nil +} + +func (w *storageWriter) reflect(rv reflect.Value, depth int) error { + if depth > maxDepth { + return fmt.Errorf("%w: %w", ErrUnwritable, ErrTooDeep) + } + if !rv.IsValid() { + w.buf = append(w.buf, tagNull) + return nil + } + // This check is by type, and comes before a nil pointer is written as + // null. A field of an Encryptable type is therefore refused even when it + // is nil. + if encryptable(rv.Type()) { + return unwritable("%s implements Encryptable, which has no storage form", rv.Type()) + } + switch rv.Kind() { + case reflect.Pointer, reflect.Interface: + return w.indirect(rv, depth) + } + if handled, err := w.model(rv, depth); handled { + return err + } + if byteArray(rv.Type()) { + return w.bytes(arrayBytes(rv)) + } + if text, ok, err := marshalText(rv); ok { + if err != nil { + return unwritable("the MarshalText method of %s returned an error", rv.Type()) + } + return w.text(text) + } + if k, ok := numericKinds[rv.Kind()]; ok { + // The numeric table of the transport encoding writes each kind as a + // blob does: the same tag and the same width. The two encodings + // differ only in the bytes around a value, and a number has none. + st := &encState{buf: w.buf} + k.encode(Encoder{st: st}, rv) + w.buf = st.buf + return st.err + } + switch rv.Kind() { + case reflect.Bool: + if rv.Bool() { + w.buf = append(w.buf, tagTrue) + } else { + w.buf = append(w.buf, tagFalse) + } + return nil + case reflect.String: + return w.text([]byte(rv.String())) + case reflect.Slice: + if rv.Type().Elem().Kind() == reflect.Uint8 { + return w.bytes(rv.Bytes()) + } + return w.array(rv, depth) + case reflect.Array: + return w.array(rv, depth) + case reflect.Map: + return w.goMap(rv, depth) + case reflect.Struct: + return w.goStruct(rv, depth) + } + return unwritable("a value of kind %s has no storage form", rv.Kind()) +} + +// indirect writes the value that the pointer or interface rv refers to. A +// nil rv is written as null. Otherwise the value is written, after +// [StorageSome] if the value starts with null or StorageSome. See +// [startsOptional]. +// +// StorageSome is a node, so it counts as one level of depth, as a reader +// counts it. A pointer or an interface that writes no bytes of its own adds +// no depth, because the blob is no deeper for it. A chain of those has a +// separate limit. A cycle such as p = &p is therefore refused, and the loop +// ends. +func (w *storageWriter) indirect(rv reflect.Value, depth int) error { + for hops := 0; ; hops++ { + if hops > maxDepth { + return fmt.Errorf("%w: %w", ErrUnwritable, ErrTooDeep) + } + if encryptable(rv.Type()) { + return unwritable("%s implements Encryptable, which has no storage form", rv.Type()) + } + if rv.IsNil() { + w.buf = append(w.buf, tagNull) + return nil + } + elem := rv.Elem() + if rv.Kind() == reflect.Pointer && startsOptional(elem) { + w.buf = append(w.buf, StorageSome) + return w.reflect(elem, depth+1) + } + if k := elem.Kind(); k != reflect.Pointer && k != reflect.Interface { + return w.reflect(elem, depth) + } + rv = elem + } +} + +// startsOptional reports whether the bytes written for rv start with null or +// [StorageSome]. Such a value is a nil pointer, a nil interface, a [Some], +// or a pointer or interface to one of those. A pointer to such a value is +// written with StorageSome first. Otherwise a reader would treat the null or +// the tag as belonging to the outer pointer. The value would then read back +// with one level of pointer missing. +// +// The loop stops after maxDepth+2 steps. A chain of pointers longer than a +// blob can nest, such as a cycle, is refused when it is written. This +// function therefore does not follow such a chain further. +func startsOptional(rv reflect.Value) bool { + for range maxDepth + 2 { + switch rv.Kind() { + case reflect.Pointer, reflect.Interface: + if rv.IsNil() { + return true + } + rv = rv.Elem() + default: + return rv.Type() == someType + } + } + return false +} + +// byteArray reports whether t is a [N]byte type that is written as bytes. A +// UUID is one. Int128 and Uint128 are [16]byte types too. The codec writes +// those two as integers, so the result for them is false. +func byteArray(t reflect.Type) bool { + return t.Kind() == reflect.Array && t.Elem().Kind() == reflect.Uint8 && t != int128Type && t != uint128Type +} + +func arrayBytes(rv reflect.Value) []byte { + b := make([]byte, rv.Len()) + reflect.Copy(reflect.ValueOf(b), rv) + return b +} + +// encryptable reports whether t, or a pointer to t, implements Encryptable. +// The fields of such a type are not its value, so reflection must not write +// them. +func encryptable(t reflect.Type) bool { + return t.Implements(encryptableType) || reflect.PointerTo(t).Implements(encryptableType) +} + +// marshalText calls the MarshalText method of rv, if the type of rv has one. +// The second result reports whether the type has one. When the method has a +// pointer receiver, marshalText calls it on a pointer to a copy of rv. +func marshalText(rv reflect.Value) ([]byte, bool, error) { + if rv.Type().Implements(textMarshalerType) && rv.CanInterface() { + text, err := rv.Interface().(encoding.TextMarshaler).MarshalText() + return text, true, err + } + if reflect.PointerTo(rv.Type()).Implements(textMarshalerType) { + p := reflect.New(rv.Type()) + p.Elem().Set(rv) + text, err := p.Interface().(encoding.TextMarshaler).MarshalText() + return text, true, err + } + return nil, false, nil +} + +func (w *storageWriter) text(s []byte) error { + if !utf8.Valid(s) { + return unwritable("a string is not valid UTF-8") + } + w.buf = append(w.buf, tagString) + buf, err := appendChunk(w.buf, s) + if err != nil { + return unwritable("a string is too long") + } + w.buf = buf + return nil +} + +func (w *storageWriter) bytes(b []byte) error { + w.buf = append(w.buf, tagBytes) + buf, err := appendChunk(w.buf, b) + if err != nil { + return unwritable("bytes are too long") + } + w.buf = buf + return nil +} + +// open writes the tag of a container and four zero bytes for its count. The +// function returns the position of those bytes, and close writes the count +// there. +func (w *storageWriter) open(tag byte) int { + w.buf = append(w.buf, tag, 0, 0, 0, 0) + return len(w.buf) - 4 +} + +func (w *storageWriter) close(at, count int) error { + if uint64(count) > maxUint32 { + return unwritable("a container has too many entries") + } + binary.LittleEndian.PutUint32(w.buf[at:], uint32(count)) + return nil +} + +func (w *storageWriter) array(rv reflect.Value, depth int) error { + at := w.open(tagArray) + for i := range rv.Len() { + if err := w.reflect(rv.Index(i), depth+1); err != nil { + return err + } + } + return w.close(at, rv.Len()) +} + +func (w *storageWriter) object(o value.Object, depth int) error { + at := w.open(tagObject) + seen := make(map[string]struct{}, len(o)) + for _, f := range o { + if err := w.field(f.Key, seen); err != nil { + return err + } + if err := w.any(f.Value, depth+1); err != nil { + return err + } + } + return w.close(at, len(o)) +} + +// field writes one key of an object. The function refuses a key that the +// object already has. +func (w *storageWriter) field(key string, seen map[string]struct{}) error { + if _, dup := seen[key]; dup { + return unwritable("a key is repeated") + } + seen[key] = struct{}{} + if !utf8.ValidString(key) { + return unwritable("a key is not valid UTF-8") + } + buf, err := appendChunk(w.buf, []byte(key)) + if err != nil { + return unwritable("a key is too long") + } + w.buf = buf + return nil +} + +func (w *storageWriter) goStruct(rv reflect.Value, depth int) error { + at := w.open(tagObject) + seen := make(map[string]struct{}) + fields, err := structFields(rv.Type()) + if err != nil { + return fmt.Errorf("%w: %w", ErrUnwritable, err) + } + written, unexported := 0, 0 + for _, f := range fields { + if f.unexported { + unexported++ + continue + } + if err := w.field(f.name, seen); err != nil { + return err + } + if err := w.reflect(rv.Field(f.index), depth+1); err != nil { + return err + } + written++ + } + // The transport encoding has the same rule. A struct with only + // unexported fields would be stored as an empty object. An example is + // time.Time, if it had no MarshalText. The value would be lost, with no + // error when it is written or read. + if written == 0 && unexported > 0 { + return unwritable("struct %s has no exported fields", rv.Type()) + } + return w.close(at, written) +} + +// storageField describes one field of a struct, with the name that a blob +// uses for it. +type storageField struct { + name string + index int + unexported bool + // defaulted is true for a field that reads as its zero value when a blob + // does not have it. + defaulted bool +} + +// structFields returns the fields of t, in the order t declares them. Each +// field has the name from its `vc` tag, or its own name. A field with a +// `vc:"-"` tag is left out. +// +// A tag is a name, then options after commas, as in `vc:"age,default"`. +// Write `vc:",default"` to keep the field's own name. The only option is +// `default`. Any other option is refused, so a misspelt option is not +// ignored without an error. The transport encoding names fields in the same +// way. +func structFields(t reflect.Type) ([]storageField, error) { + fields := make([]storageField, 0, t.NumField()) + for i := range t.NumField() { + f := t.Field(i) + if f.PkgPath != "" { + fields = append(fields, storageField{index: i, unexported: true}) + continue + } + field := storageField{name: f.Name, index: i} + if tag, ok := f.Tag.Lookup("vc"); ok { + if tag == "-" { + continue + } + name, options, _ := strings.Cut(tag, ",") + if name != "" { + field.name = name + } + for options != "" { + var option string + option, options, _ = strings.Cut(options, ",") + switch option { + case "default": + field.defaulted = true + case "": + default: + return nil, fmt.Errorf("frame: field %s of %s has an unknown vc tag option %q", f.Name, t, option) + } + } + } + fields = append(fields, field) + } + return fields, nil +} + +// mapKey is a map key: the node that is written for it, and an id that +// decides which keys are equal: +// +// - Two integers are the same key when their values are equal, whatever +// their widths. So 1 as a uint8 and 1 as an int64 are one key. +// - Two text keys are the same when their bytes are equal. The same rule +// applies to two bytes keys. +// - A text key never equals a bytes key or an integer. +// +// The id also gives the order in which keys are written. Integers come +// first, then text, then bytes. The order of integers is by value. The order +// of text and of bytes is by their bytes. +type mapKey struct { + node []byte + id keyID +} + +// keyKind is the kind of a map key. The constants are in the order that keys +// of different kinds are written in. +type keyKind byte + +const ( + keyInteger keyKind = iota + keyText + keyBytes +) + +type keyID struct { + kind keyKind + // For an integer: the sign, and the 128-bit word in two's complement. + negative bool + hi, lo uint64 + // For text or bytes: the bytes. + s string +} + +func compareKeys(a, b keyID) int { + if c := cmp.Compare(a.kind, b.kind); c != 0 { + return c + } + if a.negative != b.negative { + if a.negative { + return -1 + } + return 1 + } + return cmp.Or(cmp.Compare(a.hi, b.hi), cmp.Compare(a.lo, b.lo), cmp.Compare(a.s, b.s)) +} + +// wideKey returns the keyID of a 128-bit integer. The word argument is the +// integer in little-endian byte order. +func wideKey(word []byte, signed bool) keyID { + return keyID{ + lo: binary.LittleEndian.Uint64(word), + hi: binary.LittleEndian.Uint64(word[8:]), + negative: signed && word[15]&0x80 != 0, + } +} + +// decodedKeyID returns the keyID of a key that the reader decoded. Such a +// key is a Go integer, an Int128, a Uint128, a string, or bytes. +func decodedKeyID(k any) (keyID, bool) { + switch x := k.(type) { + case int8: + return signedKey(int64(x)), true + case int16: + return signedKey(int64(x)), true + case int32: + return signedKey(int64(x)), true + case int64: + return signedKey(x), true + case uint8: + return keyID{lo: uint64(x)}, true + case uint16: + return keyID{lo: uint64(x)}, true + case uint32: + return keyID{lo: uint64(x)}, true + case uint64: + return keyID{lo: x}, true + case value.Int128: + return wideKey(x[:], true), true + case value.Uint128: + return wideKey(x[:], false), true + case string: + return keyID{kind: keyText, s: x}, true + case []byte: + return keyID{kind: keyBytes, s: string(x)}, true + } + return keyID{}, false +} + +func signedKey(v int64) keyID { + id := keyID{negative: v < 0, lo: uint64(v)} + if id.negative { + id.hi = math.MaxUint64 + } + return id +} + +// keyOf returns the node and the id for the map key k. +func keyOf(k any) (mapKey, error) { + rv := reflect.ValueOf(k) + if !rv.IsValid() { + return mapKey{}, unwritable("a map key must be an integer, text or bytes") + } + // A nil pointer has no value to write. If its type has a MarshalText + // method, that method would be called on nil. + if (rv.Kind() == reflect.Pointer || rv.Kind() == reflect.Interface) && rv.IsNil() { + return mapKey{}, unwritable("a map key must be an integer, text or bytes, not a nil %s", rv.Type()) + } + w := &storageWriter{} + var id keyID + switch t := rv.Type(); { + case t == int128Type || t == uint128Type: + b := arrayBytes(rv) + signed := t == int128Type + id = wideKey(b, signed) + tag := byte(tagUint128) + if signed { + tag = tagInt128 + } + w.buf = append(append(w.buf, tag), b...) + case byteArray(t): + b := arrayBytes(rv) + id = keyID{kind: keyBytes, s: string(b)} + _ = w.bytes(b) + case t.Kind() == reflect.Slice && t.Elem().Kind() == reflect.Uint8: + id = keyID{kind: keyBytes, s: string(rv.Bytes())} + _ = w.bytes(rv.Bytes()) + default: + if text, ok, err := marshalText(rv); ok { + if err != nil { + return mapKey{}, unwritable("the MarshalText method of the map key type %s returned an error", t) + } + id = keyID{kind: keyText, s: string(text)} + if err := w.text(text); err != nil { + return mapKey{}, err + } + break + } + switch t.Kind() { + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + id = signedKey(rv.Int()) + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + id = keyID{lo: rv.Uint()} + case reflect.String: + id = keyID{kind: keyText, s: rv.String()} + if err := w.text([]byte(rv.String())); err != nil { + return mapKey{}, err + } + return mapKey{node: w.buf, id: id}, nil + default: + return mapKey{}, unwritable("a map key must be an integer, text or bytes, not %s", t) + } + if err := w.reflect(rv, 0); err != nil { + return mapKey{}, err + } + } + return mapKey{node: w.buf, id: id}, nil +} + +func (w *storageWriter) goMap(rv reflect.Value, depth int) error { + keys := make([]mapKey, 0, rv.Len()) + values := make(map[keyID]reflect.Value, rv.Len()) + for it := rv.MapRange(); it.Next(); { + key, err := keyOf(interfaceOf(it.Key())) + if err != nil { + return err + } + if _, dup := values[key.id]; dup { + // Two Go keys can be written as the same key. An example is two + // values that a TextMarshaler writes as the same text. + return unwritable("a key is repeated") + } + keys = append(keys, key) + values[key.id] = it.Value() + } + // Go iterates over a map in a random order. Sorted keys give equal maps + // equal blobs. + slices.SortFunc(keys, func(a, b mapKey) int { return compareKeys(a.id, b.id) }) + at := w.open(StorageMap) + for _, key := range keys { + w.buf = append(w.buf, key.node...) + if err := w.reflect(values[key.id], depth+1); err != nil { + return err + } + } + return w.close(at, len(keys)) +} + +func (w *storageWriter) entries(entries StorageEntries, depth int) error { + at := w.open(StorageMap) + seen := make(map[keyID]struct{}, len(entries)) + for _, e := range entries { + key, err := keyOf(e.Key) + if err != nil { + return err + } + if _, dup := seen[key.id]; dup { + return unwritable("a key is repeated") + } + seen[key.id] = struct{}{} + w.buf = append(w.buf, key.node...) + if err := w.any(e.Value, depth+1); err != nil { + return err + } + } + return w.close(at, len(entries)) +} diff --git a/languages/golang/encrypt/frame/storage_decode.go b/languages/golang/encrypt/frame/storage_decode.go new file mode 100644 index 000000000..771a24c5e --- /dev/null +++ b/languages/golang/encrypt/frame/storage_decode.go @@ -0,0 +1,512 @@ +package frame + +import ( + "encoding" + "fmt" + "math/big" + "reflect" + "strconv" + + "github.com/cipherstash/stack/languages/golang/encrypt/value" +) + +// UnmarshalStorage reads a version 1 blob into the value that v points at. +// +// UnmarshalStorage checks the whole blob before it sets anything. The +// function returns one of three errors for a blob it cannot read: +// +// - [ErrNotABlob] for bytes that are not a blob +// - [ErrUnsupportedVersion] for a blob of another version +// - [ErrMalformed] for a blob with a malformed body +// +// UnmarshalStorage then reads the value into v, by the type of v, as serde +// reads it in Rust. The `reads` rows of the storage corpus test these rules: +// +// - An integer type reads any integer that fits it. A float type reads a +// float or an integer. An integer type never reads a float. +// - A pointer reads null as nil. A pointer reads any other value as a +// pointer to that value. The value can have the [StorageSome] tag or +// not. A Rust Some and a Go pointer therefore read the same way. +// - A string reads only text. A []byte reads only bytes. A [N]byte reads +// only bytes of length N. A slice or an array reads only an array. +// - A map reads a map or an object. Each key is read as a value of the key +// type would be. +// - A struct reads an object, or a map whose keys are all text. Unknown +// keys are ignored. A missing field is refused, with two exceptions. A +// missing pointer field is left nil. A missing field tagged +// `vc:"name,default"` is left as its zero value, as #[serde(default)] +// does in Rust. +// - A type that implements encoding.TextUnmarshaler reads text. +// - An `any` reads the value as the blob stores it. A scalar reads as nil, +// a bool, an integer of the stored width, a float32, a float64, a +// string, or a []byte. A 128-bit integer reads as an Int128 or a +// Uint128. An array reads as a []any, an object as an Object, a map as a +// [StorageEntries], and an optional value as a [Some]. +// +// UnmarshalStorage returns [ErrMismatch] for a value that does not fit. The +// message names the kind of value found and its position, and never the +// value itself. +func UnmarshalStorage(blob []byte, v any) error { + rv := reflect.ValueOf(v) + if rv.Kind() != reflect.Pointer || rv.IsNil() { + return fmt.Errorf("frame: UnmarshalStorage needs a non-nil pointer, not %T", v) + } + model, err := decodeStorage(blob) + if err != nil { + return err + } + return assign(model, rv.Elem(), "") +} + +// decodeStorage reads a whole blob and returns the value in it. The function +// refuses every blob that a version 1 reader must refuse. +func decodeStorage(blob []byte) (any, error) { + if len(blob) < len(StorageHeader) || string(blob[:3]) != "VCS" { + return nil, ErrNotABlob + } + if blob[3] != StorageVersion { + return nil, ErrUnsupportedVersion + } + r := &reader{buf: blob[len(StorageHeader):]} + v, err := storageNode(r, 0) + if err != nil { + return nil, err + } + if !r.finished() { + return nil, ErrMalformed + } + return v, nil +} + +// storageScalar reports whether tag starts a version 1 scalar. +func storageScalar(tag byte) bool { + switch tag { + case tagNull, tagFalse, tagTrue, tagFloat32, tagFloat64: + return true + } + return storageKeyTag(tag) +} + +// storageKeyTag reports whether tag can start the key of a map. +func storageKeyTag(tag byte) bool { + switch tag { + case tagInt8, tagInt16, tagInt32, tagInt64, tagInt128, + tagUint8, tagUint16, tagUint32, tagUint64, tagUint128, tagString, tagBytes: + return true + } + return false +} + +func storageNode(r *reader, depth int) (any, error) { + if depth > maxDepth { + return nil, ErrMalformed + } + tag, err := r.byteTag() + if err != nil { + return nil, err + } + switch tag { + case StorageSome: + inner, err := storageNode(r, depth+1) + if err != nil { + return nil, err + } + return Some{V: inner}, nil + case tagArray: + n, err := r.count() + if err != nil { + return nil, err + } + items := make([]any, 0, eagerCap(n)) + for range n { + item, err := storageNode(r, depth+1) + if err != nil { + return nil, err + } + items = append(items, item) + } + return items, nil + case tagObject: + n, err := r.count() + if err != nil { + return nil, err + } + fields := make(value.Object, 0, eagerCap(n)) + seen := make(map[string]struct{}, eagerCap(n)) + for range n { + key, err := r.str() + if err != nil { + return nil, err + } + if _, dup := seen[key]; dup { + return nil, ErrMalformed + } + seen[key] = struct{}{} + v, err := storageNode(r, depth+1) + if err != nil { + return nil, err + } + fields = append(fields, value.Field{Key: key, Value: v}) + } + return fields, nil + case StorageMap: + n, err := r.count() + if err != nil { + return nil, err + } + entries := make(StorageEntries, 0, eagerCap(n)) + seen := make(map[keyID]struct{}, eagerCap(n)) + for range n { + tag, err := r.byteTag() + if err != nil { + return nil, err + } + if !storageKeyTag(tag) { + return nil, ErrMalformed + } + key, err := decodeTagged(r, tag, depth+1) + if err != nil { + return nil, err + } + id, ok := decodedKeyID(key) + if !ok { + return nil, ErrMalformed + } + if _, dup := seen[id]; dup { + return nil, ErrMalformed + } + seen[id] = struct{}{} + value, err := storageNode(r, depth+1) + if err != nil { + return nil, err + } + entries = append(entries, StorageEntry{Key: key, Value: value}) + } + return entries, nil + } + if !storageScalar(tag) { + return nil, ErrMalformed + } + return decodeTagged(r, tag, depth) +} + +// ============================================================================= +// Reading into a Go value +// ============================================================================= + +// kindOf returns the name of the kind of m, for an error message. The name +// never contains the value. +func kindOf(m any) string { + switch m.(type) { + case nil: + return "null" + case bool: + return "a boolean" + case int8, int16, int32, int64, value.Int128, uint8, uint16, uint32, uint64, value.Uint128: + return "an integer" + case float32, float64: + return "a float" + case string: + return "text" + case []byte: + return "bytes" + case []any: + return "an array" + case value.Object, StorageEntries: + return "an object" + case Some: + return "an optional value" + } + return "a value of another kind" +} + +func mismatch(path, want string, found any) error { + return fmt.Errorf("%w: %s: expected %s, found %s", ErrMismatch, orRoot(path), want, kindOf(found)) +} + +// integerOf returns the value of m, when m is a decoded integer. +func integerOf(m any) (*big.Int, bool) { + if small, ok := smallIntegerOf(m); ok { + return big.NewInt(small), true + } + return wideIntegerOf(m) +} + +// int128Of returns v as a 128-bit word in two's complement: 16 bytes in +// little-endian order. +func int128Of(v *big.Int) [16]byte { + word := new(big.Int).Set(v) + if word.Sign() < 0 { + word.Add(word, new(big.Int).Lsh(big.NewInt(1), 128)) + } + var out [16]byte + b := word.FillBytes(make([]byte, 16)) + for i := range out { + out[i] = b[15-i] + } + return out +} + +var ( + minInt128 = new(big.Int).Neg(new(big.Int).Lsh(big.NewInt(1), 127)) + maxInt128 = new(big.Int).Sub(new(big.Int).Lsh(big.NewInt(1), 127), big.NewInt(1)) + maxUint128 = new(big.Int).Sub(new(big.Int).Lsh(big.NewInt(1), 128), big.NewInt(1)) +) + +func assign(m any, rv reflect.Value, path string) error { + switch rv.Kind() { + case reflect.Interface: + if m == nil { + rv.SetZero() + return nil + } + if mv := reflect.ValueOf(m); mv.Type().AssignableTo(rv.Type()) { + rv.Set(mv) + return nil + } + return mismatch(path, rv.Type().String(), m) + case reflect.Pointer: + switch x := m.(type) { + case nil: + rv.SetZero() + return nil + case Some: + m = x.V + } + p := reflect.New(rv.Type().Elem()) + if err := assign(m, p.Elem(), path); err != nil { + return err + } + rv.Set(p) + return nil + } + if _, ok := m.(Some); ok { + return mismatch(path, rv.Type().String(), m) + } + switch t := rv.Type(); { + case t == int128Type || t == uint128Type: + return assignInteger(m, rv, path) + case byteArray(t): + b, ok := m.([]byte) + if !ok || len(b) != rv.Len() { + return mismatch(path, fmt.Sprintf("%d bytes", rv.Len()), m) + } + reflect.Copy(rv, reflect.ValueOf(b)) + return nil + case reflect.PointerTo(t).Implements(textUnmarshalerType) && rv.CanAddr(): + text, ok := m.(string) + if !ok { + return mismatch(path, "text", m) + } + if err := rv.Addr().Interface().(encoding.TextUnmarshaler).UnmarshalText([]byte(text)); err != nil { + return fmt.Errorf("%w: %s: the UnmarshalText method of %s returned an error", ErrMismatch, orRoot(path), t) + } + return nil + } + switch rv.Kind() { + case reflect.Bool: + b, ok := m.(bool) + if !ok { + return mismatch(path, "a boolean", m) + } + rv.SetBool(b) + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, + reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + return assignInteger(m, rv, path) + case reflect.Float32, reflect.Float64: + return assignFloat(m, rv, path) + case reflect.String: + s, ok := m.(string) + if !ok { + return mismatch(path, "text", m) + } + rv.SetString(s) + case reflect.Slice: + if rv.Type().Elem().Kind() == reflect.Uint8 { + b, ok := m.([]byte) + if !ok { + return mismatch(path, "bytes", m) + } + rv.SetBytes(append([]byte{}, b...)) + return nil + } + items, ok := m.([]any) + if !ok { + return mismatch(path, "an array", m) + } + s := reflect.MakeSlice(rv.Type(), len(items), len(items)) + for i, item := range items { + if err := assign(item, s.Index(i), path+"["+strconv.Itoa(i)+"]"); err != nil { + return err + } + } + rv.Set(s) + case reflect.Array: + items, ok := m.([]any) + if !ok || len(items) != rv.Len() { + return mismatch(path, fmt.Sprintf("an array of %d", rv.Len()), m) + } + for i, item := range items { + if err := assign(item, rv.Index(i), path+"["+strconv.Itoa(i)+"]"); err != nil { + return err + } + } + case reflect.Map: + return assignMap(m, rv, path) + case reflect.Struct: + return assignStruct(m, rv, path) + default: + return fmt.Errorf("%w: %s: a %s cannot be read", ErrMismatch, orRoot(path), rv.Type()) + } + return nil +} + +func orRoot(path string) string { + if path == "" { + return "the value" + } + return path +} + +func assignInteger(m any, rv reflect.Value, path string) error { + v, ok := integerOf(m) + if !ok { + return mismatch(path, "an integer", m) + } + fits := false + switch t := rv.Type(); { + case t == int128Type: + if fits = v.Cmp(minInt128) >= 0 && v.Cmp(maxInt128) <= 0; fits { + rv.Set(reflect.ValueOf(value.Int128(int128Of(v))).Convert(rv.Type())) + } + case t == uint128Type: + if fits = v.Sign() >= 0 && v.Cmp(maxUint128) <= 0; fits { + rv.Set(reflect.ValueOf(value.Uint128(int128Of(v))).Convert(rv.Type())) + } + case rv.CanInt(): + if fits = v.IsInt64() && !rv.OverflowInt(v.Int64()); fits { + rv.SetInt(v.Int64()) + } + default: + if fits = v.IsUint64() && !rv.OverflowUint(v.Uint64()); fits { + rv.SetUint(v.Uint64()) + } + } + if !fits { + return fmt.Errorf("%w: %s: the integer is outside the range of %s", ErrMismatch, orRoot(path), rv.Type()) + } + return nil +} + +func assignFloat(m any, rv reflect.Value, path string) error { + switch x := m.(type) { + case float32: + // The value is converted, not widened, so a float32 keeps its bits. + // The reflect package copies a float32 to a float32. See Go issue + // 36400. + rv.Set(reflect.ValueOf(x).Convert(rv.Type())) + return nil + case float64: + rv.SetFloat(x) + return nil + } + v, ok := integerOf(m) + if !ok { + return mismatch(path, "a float", m) + } + // The integer is rounded once, to the width of the destination, as the + // `as` operator rounds in Rust. + if rv.Kind() == reflect.Float32 { + f, _ := new(big.Float).SetInt(v).Float32() + rv.SetFloat(float64(f)) + return nil + } + f, _ := new(big.Float).SetInt(v).Float64() + rv.SetFloat(f) + return nil +} + +// entriesOf returns the entries of m, when m is an object or a map. +func entriesOf(m any) (StorageEntries, bool) { + switch x := m.(type) { + case StorageEntries: + return x, true + case value.Object: + entries := make(StorageEntries, len(x)) + for i, f := range x { + entries[i] = StorageEntry{Key: f.Key, Value: f.Value} + } + return entries, true + } + return nil, false +} + +func assignMap(m any, rv reflect.Value, path string) error { + entries, ok := entriesOf(m) + if !ok { + return mismatch(path, "a map", m) + } + out := reflect.MakeMapWithSize(rv.Type(), len(entries)) + for i, e := range entries { + at := path + "{" + strconv.Itoa(i) + "}" + key := reflect.New(rv.Type().Key()).Elem() + if err := assign(e.Key, key, at); err != nil { + return err + } + // A bytes key that is read into an interface key is a []byte. A Go + // map cannot hash a []byte, so SetMapIndex would panic. + if !key.Comparable() { + return mismatch(at, "a key of a comparable type", e.Key) + } + value := reflect.New(rv.Type().Elem()).Elem() + if err := assign(e.Value, value, at); err != nil { + return err + } + out.SetMapIndex(key, value) + } + rv.Set(out) + return nil +} + +func assignStruct(m any, rv reflect.Value, path string) error { + entries, ok := entriesOf(m) + if !ok { + return mismatch(path, "an object", m) + } + fields, err := structFields(rv.Type()) + if err != nil { + return err + } + byName := make(map[string]int, len(fields)) + for i, f := range fields { + if !f.unexported { + byName[f.name] = i + } + } + set := make([]bool, len(fields)) + for _, e := range entries { + name, ok := e.Key.(string) + if !ok { + return mismatch(path, "a field name", e.Key) + } + i, known := byName[name] + if !known { + continue + } + set[i] = true + if err := assign(e.Value, rv.Field(fields[i].index), path+"."+name); err != nil { + return err + } + } + for i, f := range fields { + if set[i] || f.unexported { + continue + } + field := rv.Field(f.index) + if field.Kind() != reflect.Pointer && !f.defaulted { + return fmt.Errorf("%w: %s: missing field %q", ErrMismatch, orRoot(path), f.name) + } + field.SetZero() + } + return nil +} diff --git a/languages/golang/encrypt/frame/storage_test.go b/languages/golang/encrypt/frame/storage_test.go new file mode 100644 index 000000000..112aea46b --- /dev/null +++ b/languages/golang/encrypt/frame/storage_test.go @@ -0,0 +1,990 @@ +package frame + +import ( + "bytes" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "math" + "reflect" + "strconv" + "strings" + "testing" + "time" + + "github.com/cipherstash/stack/languages/golang/encrypt/value" +) + +// Go and Rust share the storage corpus. The Rust crate in +// packages/recipher-frame tests every byte of version 1 against it. This +// file tests Go against the same rows. +const storageCorpus = "../../../../packages/recipher-frame/testdata/storage-v1.json" + +type storageRow struct { + Name string `json:"name"` + Value json.RawMessage `json:"value"` + Blob string `json:"blob"` + Refusal string `json:"refusal"` + Type json.RawMessage `json:"type"` + ReadsAs json.RawMessage `json:"reads_as"` + HasReads bool `json:"-"` +} + +type storageCorpusFile struct { + Version int `json:"version"` + Header string `json:"header"` + Vectors []storageRow `json:"vectors"` + Refused []storageRow `json:"refused"` + Reads []storageRow `json:"reads"` +} + +// loadStorageCorpus returns the storage corpus. Outside the repository the +// corpus file is missing. A test then skips, and a fuzz target gets no seed +// rows from the corpus. +func loadStorageCorpus(t testing.TB) storageCorpusFile { + t.Helper() + data, ok := readCorpus(t, storageCorpus) + if !ok { + if _, fuzzing := t.(*testing.F); !fuzzing { + t.Skip("no storage corpus") + } + return storageCorpusFile{} + } + var c storageCorpusFile + if err := json.Unmarshal(data, &c); err != nil { + t.Fatal(err) + } + // A row that reads as null has a reads_as of null. The refusal field is + // therefore what tells a refused row from a row that reads. + for i := range c.Reads { + c.Reads[i].HasReads = c.Reads[i].Refusal == "" + } + return c +} + +func mustHex(t testing.TB, s string) []byte { + t.Helper() + b, err := hex.DecodeString(s) + if err != nil { + t.Fatal(err) + } + return b +} + +// storageModel builds the Go value that a corpus value describes, without +// the storage reader. A reader and a writer that are wrong in the same way +// therefore cannot pass the test. +func storageModel(t testing.TB, raw json.RawMessage) any { + t.Helper() + if len(raw) == 0 || string(raw) == "null" { + return nil + } + var kind map[string]json.RawMessage + if err := json.Unmarshal(raw, &kind); err != nil || len(kind) != 1 { + t.Fatalf("a value names one kind: %s", raw) + } + for k, v := range kind { + var text string + _ = json.Unmarshal(v, &text) + signed := func(bits int) int64 { + n, err := strconv.ParseInt(text, 10, bits) + if err != nil { + t.Fatal(err) + } + return n + } + unsigned := func(bits int) uint64 { + n, err := strconv.ParseUint(text, 10, bits) + if err != nil { + t.Fatal(err) + } + return n + } + pairs := func() [][2]json.RawMessage { + var p [][2]json.RawMessage + if err := json.Unmarshal(v, &p); err != nil { + t.Fatal(err) + } + return p + } + switch k { + case "bool": + var b bool + _ = json.Unmarshal(v, &b) + return b + case "i8": + return int8(signed(8)) + case "i16": + return int16(signed(16)) + case "i32": + return int32(signed(32)) + case "i64": + return signed(64) + case "i128": + n, err := value.ParseInt128(text) + if err != nil { + t.Fatal(err) + } + return n + case "u8": + return uint8(unsigned(8)) + case "u16": + return uint16(unsigned(16)) + case "u32": + return uint32(unsigned(32)) + case "u64": + return unsigned(64) + case "u128": + n, err := value.ParseUint128(text) + if err != nil { + t.Fatal(err) + } + return n + case "f32_bits": + bits, _ := strconv.ParseUint(text, 16, 32) + return math.Float32frombits(uint32(bits)) + case "f64_bits": + bits, _ := strconv.ParseUint(text, 16, 64) + return math.Float64frombits(bits) + case "text": + return text + case "bytes": + return mustHex(t, text) + case "some": + return Some{V: storageModel(t, v)} + case "array": + var items []json.RawMessage + _ = json.Unmarshal(v, &items) + out := make([]any, len(items)) + for i, item := range items { + out[i] = storageModel(t, item) + } + return out + case "object": + out := value.Object{} + for _, p := range pairs() { + var key string + _ = json.Unmarshal(p[0], &key) + out = append(out, value.Field{Key: key, Value: storageModel(t, p[1])}) + } + return out + case "map": + out := StorageEntries{} + for _, p := range pairs() { + out = append(out, StorageEntry{Key: storageModel(t, p[0]), Value: storageModel(t, p[1])}) + } + return out + case "nest": + var n struct { + Kind string `json:"kind"` + Depth int `json:"depth"` + Leaf json.RawMessage `json:"leaf"` + } + _ = json.Unmarshal(v, &n) + m := storageModel(t, n.Leaf) + for range n.Depth { + switch n.Kind { + case "array": + m = []any{m} + case "object": + m = value.Object{{Key: "k", Value: m}} + case "some": + m = Some{V: m} + case "map": + m = StorageEntries{{Key: uint8(0), Value: m}} + default: + t.Fatalf("unknown nest kind %s", n.Kind) + } + } + return m + default: + t.Fatalf("unknown kind %s", k) + } + } + return nil +} + +// sameModel reports whether two decoded values are equal. The function +// compares floats by their bits, so two NaNs with the same bits are equal. +func sameModel(a, b any) bool { + switch x := a.(type) { + case float32: + y, ok := b.(float32) + return ok && math.Float32bits(x) == math.Float32bits(y) + case float64: + y, ok := b.(float64) + return ok && math.Float64bits(x) == math.Float64bits(y) + case Some: + y, ok := b.(Some) + return ok && sameModel(x.V, y.V) + case []any: + y, ok := b.([]any) + if !ok || len(x) != len(y) { + return false + } + for i := range x { + if !sameModel(x[i], y[i]) { + return false + } + } + return true + case value.Object: + y, ok := b.(value.Object) + if !ok || len(x) != len(y) { + return false + } + for i := range x { + if x[i].Key != y[i].Key || !sameModel(x[i].Value, y[i].Value) { + return false + } + } + return true + case StorageEntries: + y, ok := b.(StorageEntries) + if !ok || len(x) != len(y) { + return false + } + for i := range x { + if !sameModel(x[i].Key, y[i].Key) || !sameModel(x[i].Value, y[i].Value) { + return false + } + } + return true + } + return reflect.DeepEqual(a, b) +} + +func storageClass(t testing.TB, name, refusal string) error { + t.Helper() + switch refusal { + case "not_a_blob": + return ErrNotABlob + case "unsupported_version": + return ErrUnsupportedVersion + case "malformed": + return ErrMalformed + case "mismatch": + return ErrMismatch + } + t.Fatalf("%s: unknown refusal %s", name, refusal) + return nil +} + +func TestStorageCorpusHeader(t *testing.T) { + c := loadStorageCorpus(t) + if c.Version != StorageVersion || !bytes.Equal(mustHex(t, c.Header), StorageHeader[:]) { + t.Fatalf("corpus version %d header %s", c.Version, c.Header) + } +} + +// Every vector reads as its value and writes as its bytes. +func TestStorageCorpusVectors(t *testing.T) { + c := loadStorageCorpus(t) + if len(c.Vectors) == 0 { + t.Fatal("no vectors") + } + for _, row := range c.Vectors { + blob := mustHex(t, row.Blob) + want := storageModel(t, row.Value) + var got any + if err := UnmarshalStorage(blob, &got); err != nil { + t.Errorf("%s: %v", row.Name, err) + continue + } + if !sameModel(got, want) { + t.Errorf("%s: read %#v, want %#v", row.Name, got, want) + } + written, err := MarshalStorage(want) + if err != nil { + t.Errorf("%s: %v", row.Name, err) + } else if !bytes.Equal(written, blob) { + t.Errorf("%s: wrote %x, want %x", row.Name, written, blob) + } + } +} + +// Every refused row fails with the error of its class, whatever type it is +// read into. +func TestStorageCorpusRefused(t *testing.T) { + c := loadStorageCorpus(t) + if len(c.Refused) == 0 { + t.Fatal("no refused rows") + } + for _, row := range c.Refused { + blob := mustHex(t, row.Blob) + class := storageClass(t, row.Name, row.Refusal) + var anything any + if err := UnmarshalStorage(blob, &anything); !errors.Is(err, class) { + t.Errorf("%s: %v, want %v", row.Name, err, class) + } + var nothing struct{} + if err := UnmarshalStorage(blob, ¬hing); !errors.Is(err, class) { + t.Errorf("%s: into a struct: %v, want %v", row.Name, err, class) + } + } +} + +// goType returns the Go type that a corpus type describes, or the reason Go +// has no such type. Go has no enums and no unit type. A []byte cannot be a +// map key. +func goType(t testing.TB, raw json.RawMessage) (reflect.Type, string) { + t.Helper() + var name string + if json.Unmarshal(raw, &name) == nil { + types := map[string]reflect.Type{ + "bool": reflect.TypeOf(false), "f32": reflect.TypeOf(float32(0)), "f64": reflect.TypeOf(float64(0)), + "i8": reflect.TypeOf(int8(0)), "i16": reflect.TypeOf(int16(0)), "i32": reflect.TypeOf(int32(0)), + "i64": reflect.TypeOf(int64(0)), "i128": int128Type, + "u8": reflect.TypeOf(uint8(0)), "u16": reflect.TypeOf(uint16(0)), "u32": reflect.TypeOf(uint32(0)), + "u64": reflect.TypeOf(uint64(0)), "u128": uint128Type, + "text": reflect.TypeOf(""), "bytes": reflect.TypeOf([]byte(nil)), + } + if ty, ok := types[name]; ok { + return ty, "" + } + if name == "unit" { + return nil, "Go has no unit type" + } + t.Fatalf("unknown type %s", name) + } + var kind map[string]json.RawMessage + if err := json.Unmarshal(raw, &kind); err != nil { + t.Fatal(err) + } + for k, v := range kind { + switch k { + case "option": + inner, why := goType(t, v) + if inner == nil { + return nil, why + } + return reflect.PointerTo(inner), "" + case "seq": + inner, why := goType(t, v) + if inner == nil { + return nil, why + } + if inner.Kind() == reflect.Uint8 { + return nil, "Go's []uint8 is []byte, which is bytes; a Rust Vec is an array unless it uses serde_bytes" + } + return reflect.SliceOf(inner), "" + case "map": + var kv [2]json.RawMessage + _ = json.Unmarshal(v, &kv) + key, why := goType(t, kv[0]) + if key == nil { + return nil, why + } + if !key.Comparable() { + return nil, "a Go map key cannot be " + key.String() + } + value, why := goType(t, kv[1]) + if value == nil { + return nil, why + } + return reflect.MapOf(key, value), "" + // UnmarshalStorage ignores unknown fields. A struct that denies + // unknown fields therefore reads as a struct that allows them. The + // rows that refuse such a struct are skipped below. + case "unit_struct": + return nil, "Go has no unit type" + case "struct", "struct_deny_unknown": + var pairs [][2]json.RawMessage + _ = json.Unmarshal(v, &pairs) + fields := make([]reflect.StructField, len(pairs)) + for i, p := range pairs { + var fieldName string + _ = json.Unmarshal(p[0], &fieldName) + ty, why := goType(t, p[1]) + if ty == nil { + return nil, why + } + fields[i] = reflect.StructField{ + Name: fmt.Sprintf("F%d", i), + Type: ty, + Tag: reflect.StructTag(`vc:"` + fieldName + `"`), + } + } + return reflect.StructOf(fields), "" + case "enum": + return nil, "Go has no enums" + } + } + t.Fatalf("unknown type %s", raw) + return nil, "" +} + +// deniesUnknown reports whether the type of a row is a struct that denies +// unknown keys. UnmarshalStorage cannot deny unknown keys. A refused row of +// such a type is therefore skipped when Go reads it. When Go refuses the +// row, the test still checks the class of the error. +// +// The function does not look for such a struct nested inside another type. A +// row that is refused for that reason would fail below. The test would not +// skip it. +func deniesUnknown(raw json.RawMessage) bool { + var kind map[string]json.RawMessage + if json.Unmarshal(raw, &kind) != nil { + return false + } + _, ok := kind["struct_deny_unknown"] + return ok +} + +// Every `reads` row that Go can express reads as the row says, or fails as a +// mismatch. The test compares the result by the blob that it is written back +// as. +func TestStorageCorpusReads(t *testing.T) { + c := loadStorageCorpus(t) + expressed := 0 + for _, row := range c.Reads { + ty, why := goType(t, row.Type) + if ty == nil { + t.Logf("%s: not expressible in Go: %s", row.Name, why) + continue + } + blob := mustHex(t, row.Blob) + into := reflect.New(ty) + err := UnmarshalStorage(blob, into.Interface()) + if !row.HasReads && err == nil && deniesUnknown(row.Type) { + t.Logf("%s: not expressible in Go: UnmarshalStorage has no way to deny unknown fields", row.Name) + continue + } + expressed++ + if !row.HasReads { + if class := storageClass(t, row.Name, row.Refusal); !errors.Is(err, class) { + t.Errorf("%s: %v, want %v", row.Name, err, class) + } + continue + } + if err != nil { + t.Errorf("%s: %v", row.Name, err) + continue + } + // The blob for the value that the row reads as, read into the same + // type. Both blobs must read as this Go value. + canonical, err := MarshalStorage(storageModel(t, row.ReadsAs)) + if err != nil { + t.Fatal(err) + } + want := reflect.New(ty) + if err := UnmarshalStorage(canonical, want.Interface()); err != nil { + t.Fatalf("%s: the canonical form: %v", row.Name, err) + } + if !reflect.DeepEqual(into.Elem().Interface(), want.Elem().Interface()) { + t.Errorf("%s: read as %#v, want %#v", row.Name, into.Elem().Interface(), want.Elem().Interface()) + } + } + // Go can express most rows, and a new row that Go cannot express is + // logged above. This check fails if a typo makes the test skip every + // row. + if expressed < len(c.Reads)/2 { + t.Fatalf("only %d of %d reads rows are expressed in Go", expressed, len(c.Reads)) + } +} + +// ============================================================================= +// The Go mapping +// ============================================================================= + +type stamp struct{ at string } + +// folded writes itself as text in lower case, so two different keys can be +// written as the same key. +type folded string + +func (f folded) MarshalText() ([]byte, error) { return []byte(strings.ToLower(string(f))), nil } + +func (s stamp) MarshalText() ([]byte, error) { return []byte("<" + s.at + ">"), nil } +func (s *stamp) UnmarshalText(b []byte) error { s.at = strings.Trim(string(b), "<>"); return nil } + +type record struct { + Name string `vc:"name"` + Age uint8 `vc:"age"` + Pinned *bool `vc:"pinned"` + Nested **int32 `vc:"nested"` + Absent **int32 `vc:"absent"` + Tags []string `vc:"tags"` + Raw []byte `vc:"raw"` + ID value.UUID `vc:"id"` + Scores map[uint32]string `vc:"scores"` + When time.Time `vc:"when"` + Stamp stamp `vc:"stamp"` + Big value.Int128 `vc:"big"` + Ratio float32 `vc:"ratio"` + Skipped string `vc:"-"` + Untyped any `vc:"untyped"` +} + +func TestStorageRecordRoundTrips(t *testing.T) { + yes := true + n := int32(-3) + np := &n + var nilInt *int32 + big, _ := value.ParseInt128("-170141183460469231731687303715884105728") + in := record{ + Name: "ada", + Age: 36, + Pinned: &yes, + Nested: &np, + Absent: &nilInt, + Tags: []string{"x", "y"}, + Raw: []byte{1, 2}, + ID: value.UUID{15: 1}, + Scores: map[uint32]string{7: "a", 1: "b"}, + When: time.Date(2026, 10, 25, 1, 2, 3, 4, time.UTC), + Stamp: stamp{at: "noon"}, + Big: big, + Ratio: math.Float32frombits(0x7fa00001), + Skipped: "gone", + Untyped: StorageEntries{{Key: int16(-1), Value: Some{V: nil}}}, + } + blob, err := MarshalStorage(in) + if err != nil { + t.Fatal(err) + } + var out record + if err := UnmarshalStorage(blob, &out); err != nil { + t.Fatal(err) + } + in.Skipped = "" + if math.Float32bits(out.Ratio) != 0x7fa00001 { + t.Fatalf("a signaling NaN lost its bits: %x", math.Float32bits(out.Ratio)) + } + in.Ratio, out.Ratio = 0, 0 + if !reflect.DeepEqual(out, in) { + t.Fatalf("read %+v, want %+v", out, in) + } + // Rust must write the same bytes for each of these values. + var model any + if err := UnmarshalStorage(blob, &model); err != nil { + t.Fatal(err) + } + fields := model.(value.Object) + for _, f := range fields { + switch f.Key { + case "pinned": + if !sameModel(f.Value, true) { + t.Errorf("a pointer is its value: %#v", f.Value) + } + case "nested": + if !sameModel(f.Value, int32(-3)) { + t.Errorf("a pointer to a pointer is its value: %#v", f.Value) + } + case "absent": + if !sameModel(f.Value, Some{V: nil}) { + t.Errorf("a pointer to nil is marked, so it is not read as nil: %#v", f.Value) + } + case "id": + if !sameModel(f.Value, append(make([]byte, 15), 1)) { + t.Errorf("a UUID is its 16 bytes: %#v", f.Value) + } + case "scores": + want := StorageEntries{{Key: uint32(1), Value: "b"}, {Key: uint32(7), Value: "a"}} + if !sameModel(f.Value, want) { + t.Errorf("a map is sorted by key: %#v", f.Value) + } + case "when": + if f.Value != "2026-10-25T01:02:03.000000004Z" { + t.Errorf("a time is its RFC 3339 text: %#v", f.Value) + } + case "stamp": + if f.Value != "" { + t.Errorf("a TextMarshaler is its text: %#v", f.Value) + } + case "big": + if !sameModel(f.Value, big) { + t.Errorf("an Int128 is an integer: %#v", f.Value) + } + case "-", "Skipped": + t.Errorf("a vc:\"-\" field is written") + } + } +} + +// Integer keys are written in order of value, as a Rust BTreeMap orders +// them. The same map is therefore written as the same bytes in both +// languages. +func TestStorageMapKeysSortLikeRust(t *testing.T) { + cases := []struct { + in any + keys []any + }{ + {map[int8]bool{1: true, -1: true, -128: true, 0: true}, []any{int8(-128), int8(-1), int8(0), int8(1)}}, + {map[uint64]bool{math.MaxUint64: true, 2: true}, []any{uint64(2), uint64(math.MaxUint64)}}, + {map[string]bool{"b": true, "B": true, "": true, "é": true}, []any{"", "B", "b", "é"}}, + {map[[2]byte]bool{{2, 0}: true, {1, 9}: true}, []any{[]byte{1, 9}, []byte{2, 0}}}, + } + for _, c := range cases { + blob, err := MarshalStorage(c.in) + if err != nil { + t.Fatal(err) + } + var model any + if err := UnmarshalStorage(blob, &model); err != nil { + t.Fatal(err) + } + entries := model.(StorageEntries) + for i, k := range c.keys { + if !sameModel(entries[i].Key, k) { + t.Errorf("%T: key %d is %#v, want %#v", c.in, i, entries[i].Key, k) + } + } + back := reflect.New(reflect.TypeOf(c.in)) + if err := UnmarshalStorage(blob, back.Interface()); err != nil || !reflect.DeepEqual(back.Elem().Interface(), c.in) { + t.Errorf("%T: %v", c.in, err) + } + } +} + +func TestStorageNilSliceAndMapAreEmpty(t *testing.T) { + var s []int32 + var m map[string]int32 + for _, v := range []any{s, m} { + blob, err := MarshalStorage(v) + if err != nil { + t.Fatal(err) + } + if blob[4] == tagNull { + t.Errorf("%T: a nil container is written as null; Rust reads only an empty one", v) + } + } +} + +func TestStorageRefusesWhatHasNoStorageForm(t *testing.T) { + type hidden struct{ secret string } + deep := any(nil) + for range maxDepth + 1 { + deep = []any{deep} + } + for name, v := range map[string]any{ + "a channel": make(chan int), + "a function": func() {}, + "a complex number": complex(1, 2), + "a passthrough": value.Plain{V: 1}, + "a date": value.Date{}, + "a decimal": value.Decimal{}, + "unexported fields": hidden{secret: "s3cr3t"}, + "a float key": map[float64]bool{1.5: true}, + "a bool key": map[bool]bool{true: true}, + "a nil key": StorageEntries{{Key: nil, Value: 1}}, + "a repeated key": StorageEntries{{Key: uint8(1)}, {Key: int64(1)}}, + "a repeated field": value.Object{{Key: "k"}, {Key: "k"}}, + "invalid UTF-8": string([]byte{0xff}), + "invalid UTF-8 key": map[string]bool{string([]byte{0xff}): true}, + "too deep": deep, + "a key spelled twice": map[folded]bool{"A": true, "a": true}, + "an array element too": [1]any{make(chan int)}, + "an Encryptable": point{X: 1, Y: 2}, + "a pointer-receiver Encryptable": sealedSecret{Secret: "s3cr3t"}, + "a pointer to one": &sealedSecret{Secret: "s3cr3t"}, + "a nil pointer to one": (*sealedSecret)(nil), + "an Encryptable field": struct{ S sealedSecret }{}, + } { + _, err := MarshalStorage(v) + if !errors.Is(err, ErrUnwritable) { + t.Errorf("%s: %v, want ErrUnwritable", name, err) + } + if err != nil && strings.Contains(err.Error(), "s3cr3t") { + t.Errorf("%s: the error echoes a value: %v", name, err) + } + } + _, err := MarshalStorage(deep) + if !errors.Is(err, ErrTooDeep) { + t.Errorf("too deep: %v, want ErrTooDeep as well", err) + } +} + +// sealedSecret chooses its own encoding, so its fields are not its value. +type sealedSecret struct{ Secret string } + +func (s *sealedSecret) EncryptValue(enc Encoder) error { + enc.String("redacted") + return nil +} + +// A bytes key that is read into an interface key would be a []byte. A Go map +// cannot hash a []byte. The read must fail as a mismatch, with no panic. +func TestStorageBytesKeyIntoAnyKeyIsAMismatch(t *testing.T) { + blob, err := MarshalStorage(map[[1]byte]int{{1}: 42}) + if err != nil { + t.Fatal(err) + } + var into map[any]any + if err := UnmarshalStorage(blob, &into); !errors.Is(err, ErrMismatch) { + t.Fatalf("%v, want ErrMismatch", err) + } + var keyed map[[1]byte]int + if err := UnmarshalStorage(blob, &keyed); err != nil || keyed[[1]byte{1}] != 42 { + t.Fatalf("%v, %v", err, keyed) + } +} + +func TestStorageMismatchNamesWhereAndNotWhat(t *testing.T) { + blob, err := MarshalStorage(map[string]any{"secret_key": "s3cr3t"}) + if err != nil { + t.Fatal(err) + } + var into map[string]int + err = UnmarshalStorage(blob, &into) + if !errors.Is(err, ErrMismatch) { + t.Fatalf("%v, want ErrMismatch", err) + } + if strings.Contains(err.Error(), "s3cr3t") || strings.Contains(err.Error(), "secret_key") { + t.Fatalf("the error echoes the blob: %v", err) + } + type inner struct { + N uint8 `vc:"n"` + } + type outer struct { + List []inner `vc:"list"` + } + blob, _ = MarshalStorage(map[string]any{"list": []any{map[string]any{"n": int32(300)}}}) + err = UnmarshalStorage(blob, &outer{}) + if !errors.Is(err, ErrMismatch) || !strings.Contains(err.Error(), "list[0].n") { + t.Fatalf("%v, want a mismatch at list[0].n", err) + } + if err := UnmarshalStorage(blob, outer{}); err == nil || errors.Is(err, ErrMismatch) { + t.Fatalf("a non-pointer destination: %v", err) + } +} + +// A field that is now a pointer reads a value that was written before the +// change. A missing pointer field reads as nil. Any other missing field is +// refused. +func TestStorageOptionalFields(t *testing.T) { + type before struct { + N uint32 `vc:"n"` + } + type after struct { + N *uint32 `vc:"n"` + M *string `vc:"m"` + } + type stricter struct { + N uint32 `vc:"n"` + M string `vc:"m"` + } + blob, _ := MarshalStorage(before{N: 7}) + var a after + if err := UnmarshalStorage(blob, &a); err != nil || a.N == nil || *a.N != 7 || a.M != nil { + t.Fatalf("%+v %v", a, err) + } + if err := UnmarshalStorage(blob, &stricter{}); !errors.Is(err, ErrMismatch) { + t.Fatalf("a missing field: %v, want ErrMismatch", err) + } + // A field with the `default` option reads as its zero value when the + // blob does not have it. The field has the name in its tag, or its own + // name when the tag has no name. + type defaulted struct { + N uint32 `vc:"n"` + M string `vc:"m,default"` + K []int8 `vc:",default"` + } + d := defaulted{M: "x", K: []int8{1}} + if err := UnmarshalStorage(blob, &d); err != nil || d.N != 7 || d.M != "" || d.K != nil { + t.Fatalf("%+v %v", d, err) + } + full, _ := MarshalStorage(defaulted{N: 1, M: "m", K: []int8{2}}) + var model any + _ = UnmarshalStorage(full, &model) + if names := []string{model.(value.Object)[1].Key, model.(value.Object)[2].Key}; names[0] != "m" || names[1] != "K" { + t.Fatalf("a tag's options are not part of its name: %v", names) + } + // A Go pointer is written with no [StorageSome] tag, so a field that is + // not a pointer can read it. A Rust Some is written with the tag, and + // reads only into a pointer. + blob, _ = MarshalStorage(after{N: a.N}) + if err := UnmarshalStorage(blob, &before{}); err != nil { + t.Fatalf("a pointer into a plain field: %v", err) + } + blob, _ = MarshalStorage(value.Object{{Key: "n", Value: Some{V: uint32(7)}}}) + if err := UnmarshalStorage(blob, &before{}); !errors.Is(err, ErrMismatch) { + t.Fatalf("a marked value into a plain field: %v, want ErrMismatch", err) + } + if err := UnmarshalStorage(blob, &a); err != nil || *a.N != 7 { + t.Fatalf("a marked value into a pointer: %v", err) + } +} + +// The transport encoding names the fields of a struct by the same tags, +// including the options. +func TestTransportFieldNamesIgnoreTagOptions(t *testing.T) { + type tagged struct { + Age uint8 `vc:"age,default"` + } + buf, err := Marshal(tagged{Age: 3}) + if err != nil { + t.Fatal(err) + } + v, err := Unmarshal(buf) + if err != nil { + t.Fatal(err) + } + if got := v.(value.Object)[0].Key; got != "age" { + t.Fatalf("the transport named the field %q", got) + } +} + +// ============================================================================= +// Fuzzing +// ============================================================================= + +func addStorageSeeds(f *testing.F) { + c := loadStorageCorpus(f) + for _, rows := range [][]storageRow{c.Vectors, c.Refused, c.Reads} { + for _, row := range rows { + f.Add(mustHex(f, row.Blob)) + } + } +} + +// FuzzUnmarshalStorage checks three rules of the reader on hostile bytes: +// +// - The reader never panics. +// - A blob that the reader accepts is written back as exactly the same +// bytes, because every value has one encoding. +// - The reader never panics when it reads into a struct. +func FuzzUnmarshalStorage(f *testing.F) { + addStorageSeeds(f) + f.Fuzz(func(t *testing.T, blob []byte) { + var model any + if err := UnmarshalStorage(blob, &model); err == nil { + again, err := MarshalStorage(model) + if err != nil { + t.Fatalf("read but cannot write back: %v", err) + } + if !bytes.Equal(again, blob) { + t.Fatalf("read %x but wrote back %x", blob, again) + } + } + var r record + _ = UnmarshalStorage(blob, &r) + }) +} + +// Every level of a pointer to a pointer reads back. A pointer is written +// with the StorageSome tag when its value is itself written as null or with +// the tag. A reader therefore never treats the null or the tag of an inner +// level as that of the outer pointer. +func TestStoragePointerLevelsReadBack(t *testing.T) { + five := 5 + var leaf *int + middle := &leaf + present := &five + presentMiddle := &present + var nilMiddle **int + for name, original := range map[string]***int{ + "all present": &presentMiddle, + "innermost nil": &middle, + "middle nil": &nilMiddle, + "outermost nil": nil, + } { + blob, err := MarshalStorage(original) + if err != nil { + t.Fatalf("%s: %v", name, err) + } + var back ***int + if err := UnmarshalStorage(blob, &back); err != nil { + t.Fatalf("%s: %v", name, err) + } + if !reflect.DeepEqual(back, original) { + t.Errorf("%s: %x read back as a different shape", name, blob) + } + } + + // The innermost nil is written as two StorageSome tags, then null. + blob, err := MarshalStorage(&middle) + if err != nil { + t.Fatal(err) + } + if want := []byte{0x56, 0x43, 0x53, 0x01, StorageSome, StorageSome, tagNull}; !bytes.Equal(blob, want) { + t.Errorf("%x, want %x", blob, want) + } + + // A pointer to a [Some] is written with the tag too, so the Some keeps + // its own tag. + some := Some{V: int64(1)} + blob, err = MarshalStorage(&some) + if err != nil { + t.Fatal(err) + } + if !bytes.HasPrefix(blob[4:], []byte{StorageSome, StorageSome}) { + t.Errorf("%x: a pointer to Some is not marked", blob) + } +} + +// A nil pointer cannot be a map key. The writer refuses it. The writer never +// calls the MarshalText method of its type, because the receiver would be +// nil. +func TestStorageRefusesANilPointerKey(t *testing.T) { + for name, v := range map[string]any{ + "a map": map[*time.Time]int{nil: 1}, + "entries": StorageEntries{{Key: (*time.Time)(nil), Value: 1}}, + "an interface key": map[any]int{(*time.Time)(nil): 1}, + } { + if _, err := MarshalStorage(v); !errors.Is(err, ErrUnwritable) { + t.Errorf("%s: %v, want ErrUnwritable", name, err) + } + } +} + +// A `vc` tag option other than `default` is refused, not ignored. The rule +// applies wherever a struct is written or read, in a blob and in the +// transport encoding. +func TestUnknownTagOptionsAreRefused(t *testing.T) { + type misspelt struct { + Email string `vc:"email,defualt"` + } + if _, err := MarshalStorage(misspelt{}); !errors.Is(err, ErrUnwritable) || !strings.Contains(err.Error(), `"defualt"`) { + t.Errorf("writing: %v", err) + } + blob, err := MarshalStorage(map[string]string{"email": "x"}) + if err != nil { + t.Fatal(err) + } + if err := UnmarshalStorage(blob, &misspelt{}); err == nil || !strings.Contains(err.Error(), `"defualt"`) { + t.Errorf("reading: %v", err) + } + if _, err := Marshal(misspelt{Email: "x"}); err == nil || !strings.Contains(err.Error(), `"defualt"`) { + t.Errorf("the transport: %v", err) + } + type empty struct { + Email string `vc:"email,"` + } + if _, err := MarshalStorage(empty{}); err != nil { + t.Errorf("an empty option: %v", err) + } +} + +// A pointer that writes no node of its own adds no depth. A linked list is +// therefore as deep in Go as its blob is. A pointer cycle is still refused. +func TestStoragePointersCostOnlyTheDepthTheyWrite(t *testing.T) { + type node struct { + Next *node `vc:"next"` + } + var list *node + for range 100 { + list = &node{Next: list} + } + blob, err := MarshalStorage(list) + if err != nil { + t.Fatalf("a 100-deep list: %v", err) + } + var back *node + if err := UnmarshalStorage(blob, &back); err != nil || !reflect.DeepEqual(back, list) { + t.Fatalf("a 100-deep list read back as %v", err) + } + + type loop *loop + var p loop + p = &p + if _, err := MarshalStorage(p); !errors.Is(err, ErrTooDeep) { + t.Errorf("a pointer cycle: %v, want ErrTooDeep", err) + } + var a any + a = &a + if _, err := MarshalStorage(a); !errors.Is(err, ErrTooDeep) { + t.Errorf("an interface cycle: %v, want ErrTooDeep", err) + } +} diff --git a/languages/golang/encrypt/frame/testdata/fuzz/FuzzUnmarshal/505ffa2ed15a4b90 b/languages/golang/encrypt/frame/testdata/fuzz/FuzzUnmarshal/505ffa2ed15a4b90 new file mode 100644 index 000000000..06201ec77 --- /dev/null +++ b/languages/golang/encrypt/frame/testdata/fuzz/FuzzUnmarshal/505ffa2ed15a4b90 @@ -0,0 +1,2 @@ +go test fuzz v1 +[]byte("\b00\x83\xff") diff --git a/languages/golang/encrypt/frame/testdata/fuzz/FuzzUnmarshalCipherText/27336d1f7f4edceb b/languages/golang/encrypt/frame/testdata/fuzz/FuzzUnmarshalCipherText/27336d1f7f4edceb new file mode 100644 index 000000000..942121844 --- /dev/null +++ b/languages/golang/encrypt/frame/testdata/fuzz/FuzzUnmarshalCipherText/27336d1f7f4edceb @@ -0,0 +1,2 @@ +go test fuzz v1 +[]byte("\x04\x02\x00\x00\x00\x01\x00\x00\x000\x01\x00\x00\x00\x00\x00\x00\x00\x00\x01\x01\x00\x00\x000") diff --git a/languages/golang/encrypt/frame/testdata/fuzz/FuzzUnmarshalCipherText/27dc9fccff066f08 b/languages/golang/encrypt/frame/testdata/fuzz/FuzzUnmarshalCipherText/27dc9fccff066f08 new file mode 100644 index 000000000..a387993de --- /dev/null +++ b/languages/golang/encrypt/frame/testdata/fuzz/FuzzUnmarshalCipherText/27dc9fccff066f08 @@ -0,0 +1,2 @@ +go test fuzz v1 +[]byte("\x04\x02\x00\x00\x00\x01\x00\x00\x000\x01\x01\x00\x00\x000\x01\x00\x00\x00 \x01\x01\x00\x00\x000") diff --git a/languages/golang/encrypt/frame/testdata/fuzz/FuzzUnmarshalCipherText/b69fb6cf28e5d74f b/languages/golang/encrypt/frame/testdata/fuzz/FuzzUnmarshalCipherText/b69fb6cf28e5d74f new file mode 100644 index 000000000..806ae1fe6 --- /dev/null +++ b/languages/golang/encrypt/frame/testdata/fuzz/FuzzUnmarshalCipherText/b69fb6cf28e5d74f @@ -0,0 +1,2 @@ +go test fuzz v1 +[]byte("\x05\b00\xba\x7f") diff --git a/languages/golang/encrypt/frame/transport.go b/languages/golang/encrypt/frame/transport.go new file mode 100644 index 000000000..ff0984831 --- /dev/null +++ b/languages/golang/encrypt/frame/transport.go @@ -0,0 +1,246 @@ +package frame + +import ( + "encoding/binary" + "errors" + "fmt" + "unicode/utf8" +) + +// The tags of the value encoding. A tag is the first byte of an encoded +// node. The tag says what kind of node follows. +// +// Each scalar tag has the same value as the tag of a sealed leaf in +// vitaminc-aead, so one byte means one type in both encodings. The +// sealed-leaf tags never change. The tags for an array and an object exist +// only in the transport bytes. The sealed format has no tags for containers, +// because the ciphertext tree has a node for each container. +// +// The transport bytes are not a storage format. See the package +// documentation. +const ( + tagNull = 0x00 + tagUndefined = 0x01 + tagFalse = 0x02 + tagTrue = 0x03 + tagInt32 = 0x04 + tagInt64 = 0x05 + tagUint32 = 0x06 + tagUint64 = 0x07 + tagFloat32 = 0x08 + tagFloat64 = 0x09 + tagString = 0x0A + tagBytes = 0x0B + tagInt8 = 0x0C + tagUint8 = 0x0D + tagInt16 = 0x0E + tagUint16 = 0x0F + tagInt128 = 0x10 + tagUint128 = 0x11 + tagDate = 0x12 + tagTimestamp = 0x13 + tagDecimal = 0x14 + // tagTypedNull starts a typed null. A typed null is an absent value of a + // fixed-width type. The bytes are tagTypedNull, then the header that a + // value of the type starts with, then zeros. A typed null is as long as + // an encoded value of the type. + tagTypedNull = 0x15 + tagArray = 0xF0 + tagObject = 0xF1 + // tagPassthrough starts a passthrough value: the tag, then one value + // node. A passthrough value is neither encrypted nor authenticated. This + // tag exists only in the transport bytes, as the array and object tags + // do. + tagPassthrough = 0xF2 + // tagEnvelope starts an envelope. An envelope records a logical type + // that has no tag of its own. The bytes are the tag, the id of the + // logical type, a parameter, then a physical scalar. A physical scalar + // is a scalar that the encoding stores as it is, such as an integer or + // bytes. The tag 0xF4 is reserved for a longer envelope, and the + // decoders refuse it. + tagEnvelope = 0xF3 +) + +// The ids of the logical types, as an envelope records them. Undefined, +// Date, Decimal, and a Timestamp in nanoseconds each have a tag of their +// own. An envelope is never used for those four, so every value has exactly +// one encoding. +const ( + logicalUndefined = 1 + logicalDate = 2 + logicalTimestamp = 3 + logicalDecimal = 4 + logicalUUID = 5 + // logicalLastKnown is the highest id that this version of the codec + // knows. A value with a higher id decodes as a value.Tagged. A Tagged + // encodes as the same bytes. + logicalLastKnown = logicalUUID +) + +// The units of a timestamp, as the parameter of an envelope records them. A +// timestamp in nanoseconds uses tagTimestamp. Only a timestamp in seconds, +// milliseconds, or microseconds uses an envelope. +const ( + unitSeconds = 0 + unitMillis = 1 + unitMicros = 2 + unitNanos = 3 +) + +// maxUint32 is the largest length or count that the codec writes or reads. +// Every length and count is an unsigned 32-bit integer in little-endian byte +// order. +// +// The constant has the type uint64. An untyped 1<<32-1 does not compile when +// it is compared with an int on a 32-bit GOARCH, because the constant +// overflows int. +// +// The check is needed on those platforms. There, a count that is too large +// converts to a negative int. A negative count would pass the check against +// the bytes remaining. The call to make would then panic. The decoder must +// return ErrMalformed instead. +// +// Each comparison converts its int operand to uint64. That conversion loses +// nothing for a value that is not negative. The n < 0 checks refuse a +// negative value first. +const maxUint32 = uint64(1<<32 - 1) + +// maxDepth is the deepest nesting that the codec accepts. The Rust codec has +// the same limit. The limit stops hostile input from overflowing the stack. +const maxDepth = 128 + +// maxEagerCapacity is the largest capacity that a decoder reserves before it +// reads the items of a container. The Rust codecs have the same limit, +// MAX_EAGER_CAPACITY. +// +// The reader already checks one count against the bytes remaining. That +// check does not limit the total that nested containers reserve. One level +// of nesting takes 5 to 9 encoded bytes, but a reserved item takes many +// times that. Up to maxDepth containers can each have a reservation at the +// same time. Without this limit, about 1 MB of hostile bytes could reserve +// gigabytes of memory. +// +// A slice still grows past the limit as items are appended. Only the first +// reservation is limited. +const maxEagerCapacity = 1024 + +func eagerCap(n int) int { + // On a 64-bit platform n is never negative, because a 32-bit count fits + // an int. On a 32-bit GOARCH, a hostile count of 2^31 or more converts + // to a negative int. Without this check, min would pass the negative + // value to make. + if n < 0 { + return 0 + } + return min(n, maxEagerCapacity) +} + +// ErrMalformed is the error the decoders return for transport bytes or a +// storage blob that they cannot parse. Examples are truncated input, input +// that is nested too deep, a hostile count, a duplicate key, and an unknown +// tag. The error does not say which. The decoders treat their input as +// hostile, so they report no detail about it. +// +// The decoders return ErrMalformed itself, never wrapped. errors.Is and == +// therefore give the same answer today. Use errors.Is. +// +// A [LeafSet] that is set up wrongly is a different failure. The caller made +// that mistake, so the bytes are not at fault. [UnmarshalCipherText] reports +// it with a different error that names the mistake. +var ErrMalformed = errors.New("frame: malformed transport bytes or storage blob") + +// ErrTooDeep is the error the encoders return for a value or a ciphertext +// tree that is nested deeper than maxDepth. The caller's own code built that +// value, so the caller can match on this error. The decoders return +// [ErrMalformed] for input that is nested too deep, as they do for all bad +// input. +var ErrTooDeep = errors.New("frame: value is nested too deeply") + +func appendLen(out []byte, n int) ([]byte, error) { + if n < 0 || uint64(n) > maxUint32 { + return nil, fmt.Errorf("frame: length %d out of range", n) + } + return binary.LittleEndian.AppendUint32(out, uint32(n)), nil +} + +func appendChunk(out, chunk []byte) ([]byte, error) { + out, err := appendLen(out, len(chunk)) + if err != nil { + return nil, err + } + return append(out, chunk...), nil +} + +// reader reads a buffer from start to end, and records how many bytes it has +// read. A decoder uses that number to check that it read the whole buffer. +type reader struct { + buf []byte + pos int +} + +func (r *reader) byteTag() (byte, error) { + if r.pos >= len(r.buf) { + return 0, ErrMalformed + } + b := r.buf[r.pos] + r.pos++ + return b, nil +} + +func (r *reader) take(n int) ([]byte, error) { + if n < 0 || n > len(r.buf)-r.pos { + return nil, ErrMalformed + } + s := r.buf[r.pos : r.pos+n] + r.pos += n + return s, nil +} + +func (r *reader) u32() (int, error) { + s, err := r.take(4) + if err != nil { + return 0, err + } + return int(binary.LittleEndian.Uint32(s)), nil +} + +// count reads a 32-bit item count. The function refuses a count that is +// greater than the number of bytes remaining, because every item takes at +// least one byte. Hostile input therefore cannot make a decoder reserve much +// memory. +// +// The function also refuses a negative n, as take and appendLen do. On a +// 32-bit GOARCH, a count of 2^31 or more converts to a negative int. A +// negative count would pass the check against the bytes remaining. The call +// to make would then panic. +func (r *reader) count() (int, error) { + n, err := r.u32() + if err != nil { + return 0, err + } + if n < 0 || n > len(r.buf)-r.pos { + return 0, ErrMalformed + } + return n, nil +} + +func (r *reader) finished() bool { + return r.pos == len(r.buf) +} + +// str reads a string: a length, then that many bytes. The bytes must be +// valid UTF-8. +func (r *reader) str() (string, error) { + n, err := r.count() + if err != nil { + return "", err + } + s, err := r.take(n) + if err != nil { + return "", err + } + if !utf8.Valid(s) { + return "", ErrMalformed + } + return string(s), nil +} diff --git a/languages/golang/encrypt/frame/transport_internal_test.go b/languages/golang/encrypt/frame/transport_internal_test.go new file mode 100644 index 000000000..d1aa55a24 --- /dev/null +++ b/languages/golang/encrypt/frame/transport_internal_test.go @@ -0,0 +1,35 @@ +package frame + +import "testing" + +// This test calls eagerCap directly, as the eager_capacity test of the Rust +// transport codec does. The limit only changes the capacity that the decoder +// reserves. A test that encodes a value and decodes it again cannot observe +// the limit. The test checks three cases: +// +// - A count below maxEagerCapacity is returned unchanged. +// - A count above maxEagerCapacity returns maxEagerCapacity. +// - A negative count returns zero. On a 32-bit GOARCH, a 32-bit count of +// 2^31 or more converts to a negative int. Such a count must never reach +// make. +// +// The test also checks the value of the constant, so a change to the +// constant fails here. +func TestEagerCapClampsOnlyAboveThreshold(t *testing.T) { + if maxEagerCapacity != 1024 { + t.Fatalf("maxEagerCapacity: got %d, want 1024", maxEagerCapacity) + } + cases := []struct{ in, want int }{ + {-1, 0}, + {0, 0}, + {5, 5}, + {maxEagerCapacity, maxEagerCapacity}, + {maxEagerCapacity + 1, maxEagerCapacity}, + {1 << 30, maxEagerCapacity}, + } + for _, c := range cases { + if got := eagerCap(c.in); got != c.want { + t.Fatalf("eagerCap(%d) = %d, want %d", c.in, got, c.want) + } + } +} diff --git a/languages/golang/encrypt/frame/typed_null_test.go b/languages/golang/encrypt/frame/typed_null_test.go new file mode 100644 index 000000000..4133210ba --- /dev/null +++ b/languages/golang/encrypt/frame/typed_null_test.go @@ -0,0 +1,324 @@ +package frame + +import ( + "bytes" + "encoding/hex" + "reflect" + "testing" + "time" + + "github.com/cipherstash/stack/languages/golang/encrypt/value" +) + +// typedNullAnswers lists the typed null of each fixed-width type. The +// encoder writes a typed null for a nil pointer to the type. The Rust codec +// writes the same bytes for the same type, and the leaf tests of +// vitaminc-aead check them. Each row also has a value of the type. The typed +// null must be as long as the encoded value. +var typedNullAnswers = []struct { + name string + nilPtr any + hex string + present any +}{ + {"int8", (*int8)(nil), "150c", int8(-1)}, + {"int16", (*int16)(nil), "150e00", int16(-1)}, + {"int32", (*int32)(nil), "1504000000", int32(-1)}, + {"int64", (*int64)(nil), "1505" + zeros(7), int64(-1)}, + {"int128", (*value.Int128)(nil), "1510" + zeros(15), value.Int128{1}}, + {"uint8", (*uint8)(nil), "150d", uint8(1)}, + {"uint16", (*uint16)(nil), "150f00", uint16(1)}, + {"uint32", (*uint32)(nil), "1506000000", uint32(1)}, + {"uint64", (*uint64)(nil), "1507" + zeros(7), uint64(1)}, + {"uint128", (*value.Uint128)(nil), "1511" + zeros(15), value.Uint128{1}}, + {"float32", (*float32)(nil), "1508000000", float32(1.5)}, + {"float64", (*float64)(nil), "1509" + zeros(7), 1.5}, + {"date", (*value.Date)(nil), "1512000000", value.Date{Year: 1999, Month: 12, Day: 31}}, + {"timestamp", (*time.Time)(nil), "1513" + zeros(11), time.Unix(1_700_000_000, 5).UTC()}, + {"decimal", (*value.Decimal)(nil), "1514" + zeros(15), value.Decimal{Scale: 2, Coefficient: [12]byte{150}}}, + {"uuid", (*value.UUID)(nil), "15f305000b" + zeros(15), value.UUID{0xAB}}, +} + +func zeros(n int) string { return hex.EncodeToString(make([]byte, n)) } + +func TestTypedNullKnownAnswers(t *testing.T) { + for _, row := range typedNullAnswers { + t.Run(row.name, func(t *testing.T) { + got, err := Marshal(row.nilPtr) + if err != nil { + t.Fatal(err) + } + if hex.EncodeToString(got) != row.hex { + t.Fatalf("got %x, want %s", got, row.hex) + } + present, err := Marshal(row.present) + if err != nil { + t.Fatal(err) + } + // A frame writes bytes with a length prefix. The typed null of a + // UUID has no length prefix, because the sealed leaf of a UUID + // has none. + want := len(present) + if row.name == "uuid" { + want -= 4 + } + if len(got) != want { + t.Fatalf("typed null is %d bytes, a value %d", len(got), want) + } + // The typed null reads back as nil, as every null does. The nil + // is then written as a plain null. + v, err := Unmarshal(got) + if err != nil || v != nil { + t.Fatalf("decoded %#v, %v", v, err) + } + }) + } +} + +type selfEncoded int32 + +func (s selfEncoded) EncryptValue(enc Encoder) error { + enc.String("custom") + return nil +} + +// An Encryptable with a pointer receiver: only *ptrEncoded implements it. +type ptrEncoded int32 + +func (p *ptrEncoded) EncryptValue(enc Encoder) error { + enc.String("custom") + return nil +} + +// A pointer type that points at itself never reaches a non-pointer. +type selfPointer *selfPointer + +// A nil pointer to a fixed-width type is written as a typed null, as Rust +// writes an Option. A nil whose type has no fixed width is written as the +// plain null. Each case is encoded twice, because the second encode reads +// the cache for the type. +func TestANilPointerIsATypedNullWhenItsTypeIsFixedWidth(t *testing.T) { + type age int32 + var missing *int32 + cases := []struct { + name string + v any + want string + }{ + {"*int8", (*int8)(nil), "150c"}, + {"*int16", (*int16)(nil), "150e00"}, + {"*int32", (*int32)(nil), "1504000000"}, + {"*int64", (*int64)(nil), "1505" + zeros(7)}, + {"*int", (*int)(nil), "1505" + zeros(7)}, + {"*uint8", (*uint8)(nil), "150d"}, + {"*uint16", (*uint16)(nil), "150f00"}, + {"*uint32", (*uint32)(nil), "1506000000"}, + {"*uint64", (*uint64)(nil), "1507" + zeros(7)}, + {"*uint", (*uint)(nil), "1507" + zeros(7)}, + {"*float32", (*float32)(nil), "1508000000"}, + {"*float64", (*float64)(nil), "1509" + zeros(7)}, + {"*time.Time", (*time.Time)(nil), "1513" + zeros(11)}, + {"*Date", (*value.Date)(nil), "1512000000"}, + {"*Timestamp", (*value.Timestamp)(nil), "1513" + zeros(11)}, + {"*Decimal", (*value.Decimal)(nil), "1514" + zeros(15)}, + {"*UUID", (*value.UUID)(nil), "15f305000b" + zeros(15)}, + {"*Int128", (*value.Int128)(nil), "1510" + zeros(15)}, + {"*Uint128", (*value.Uint128)(nil), "1511" + zeros(15)}, + {"named *age", (*age)(nil), "1504000000"}, + {"**int32", (**int32)(nil), "1504000000"}, + {"&(nil *int32)", &missing, "1504000000"}, + // No fixed width: the plain null. + {"*bool", (*bool)(nil), "00"}, + {"*string", (*string)(nil), "00"}, + {"*[]byte", (*[]byte)(nil), "00"}, + {"*[16]byte", (*[16]byte)(nil), "00"}, + {"*struct", (*struct{ A int32 })(nil), "00"}, + {"*Encryptable", (*selfEncoded)(nil), "00"}, + {"**Encryptable", (**selfEncoded)(nil), "00"}, + {"*pointer-receiver Encryptable", (*ptrEncoded)(nil), "00"}, + {"**pointer-receiver Encryptable", (**ptrEncoded)(nil), "00"}, + {"*any", (*any)(nil), "00"}, + {"self-pointing type", selfPointer(nil), "00"}, + {"nil", nil, "00"}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + for range 2 { + got, err := Marshal(c.v) + if err != nil { + t.Fatal(err) + } + if hex.EncodeToString(got) != c.want { + t.Fatalf("got %x, want %s", got, c.want) + } + } + }) + } +} + +func TestAStructsNilFieldsAreTypedNulls(t *testing.T) { + type person struct { + Name string + Born *value.Date + Age *int32 + Tags []string + Any any + } + got, err := Marshal(person{Name: "Ada"}) + if err != nil { + t.Fatal(err) + } + v, err := Unmarshal(got) + if err != nil { + t.Fatal(err) + } + for _, f := range v.(value.Object) { + if (f.Key == "Born" || f.Key == "Age" || f.Key == "Any") && f.Value != nil { + t.Fatalf("%s decoded %#v", f.Key, f.Value) + } + } + // Born and Age are written as typed nulls, with their padding. Any has + // no type, so it is written as the plain null. A nil slice is written as + // an empty sequence. + if !bytes.Contains(got, []byte{tagTypedNull, tagDate, 0, 0, 0}) || + !bytes.Contains(got, []byte{tagTypedNull, tagInt32, 0, 0, 0}) { + t.Fatalf("no typed nulls in %x", got) + } +} + +// An Encryptable in this package calls the method that Encode uses to write +// a typed null. +type maybeAge struct{ v *int32 } + +func (m maybeAge) EncryptValue(enc Encoder) error { + if m.v == nil { + enc.typedNull(nullOf(tagInt32)) + } else { + enc.Int32(*m.v) + } + return nil +} + +func TestTheTypedNullChannel(t *testing.T) { + got, err := Marshal(maybeAge{}) + if err != nil { + t.Fatal(err) + } + if hex.EncodeToString(got) != "1504000000" { + t.Fatalf("got %x", got) + } + // The typed null counts as exactly one value in its slot, as every + // scalar does. + enc := func(e Encoder) error { + s := e.Seq() + s.Elem().typedNull(nullOf(tagUint8)) + s.Elem().Null() + return s.End() + } + got, err = Marshal(encryptableFunc(enc)) + if err != nil { + t.Fatal(err) + } + if hex.EncodeToString(got) != "f002000000150d00" { + t.Fatalf("got %x", got) + } +} + +type encryptableFunc func(Encoder) error + +func (f encryptableFunc) EncryptValue(e Encoder) error { return f(e) } + +// Every absent value has one encoding, so the decoder refuses any bytes that +// no encoder writes. The shared corpus tests the same refusals in every +// language. The cases below are specific to Go. +func TestATypedNullIsReadStrictly(t *testing.T) { + refused := []string{ + "15", "1504", "15040000", "1504000001", "150400000000", + "1500", "1502", "150a", "150b" + zeros(15), "1515040000", + "15f3", "15f303", "15f30301", "15f3030304" + zeros(3), "15f3030409" + zeros(7), + "15f3050104" + zeros(3), "15f3c8000a", "15f3c8000b" + zeros(15), + "f0010000001502", + } + for _, h := range refused { + raw, _ := hex.DecodeString(h) + if _, err := Unmarshal(raw); err != ErrMalformed { + t.Fatalf("%s: got %v, want ErrMalformed", h, err) + } + } + accepted := []string{ + "15f3030004000000", // seconds over an int32 + "15f3030210" + zeros(15), // microseconds over an int128 + "15f3c8ff09" + zeros(7), // an unknown id, any parameter, over a float64 + "f0010000001506000000", // inside an array + "f2150c", // as passthrough + "f101000000010000006115120000" + "00", // as an object value + } + for _, h := range accepted { + raw, _ := hex.DecodeString(h) + if _, err := Unmarshal(raw); err != nil { + t.Fatalf("%s: %v", h, err) + } + } +} + +// For every fixed-width type in the markers table and every numeric kind, a +// value starts with the header that its typed null has. The table therefore +// cannot pad a type as if it were a different type. The test fails for a +// type that is added to the markers table with no sample here. +func TestEveryFixedTypeIsWrittenWithItsTypedNullsHeader(t *testing.T) { + samples := map[reflect.Type]any{ + reflect.TypeOf(value.Int128{}): value.Int128{1}, + reflect.TypeOf(value.Uint128{}): value.Uint128{1}, + reflect.TypeOf(value.Date{}): value.Date{Year: 2000, Month: 1, Day: 1}, + reflect.TypeOf(time.Time{}): time.Unix(7, 0), + reflect.TypeOf(value.Timestamp{}): value.Timestamp{Seconds: 7}, + reflect.TypeOf(value.Decimal{}): value.Decimal{Scale: 1}, + reflect.TypeOf(value.UUID{}): value.UUID{1}, + } + check := func(name string, null []byte, sample any) { + value, err := Marshal(sample) + if err != nil { + t.Fatalf("%s: %v", name, err) + } + // The header of the typed null, after its tag, starts the encoded + // value. + header := null[1:] + for len(header) > 0 && header[len(header)-1] == 0 { + header = header[:len(header)-1] + } + if !bytes.HasPrefix(value, header) { + t.Fatalf("%s: value %x does not start with its typed null's header %x", name, value, header) + } + } + // Every sample is of a fixed-width type in the markers table. The test + // therefore fails for a type that stops being fixed width, and does not + // skip it. + for typ := range samples { + if markers[typ].null == nil { + t.Fatalf("%v has a sample but no typed null", typ) + } + } + for typ, m := range markers { + if m.null == nil { + continue + } + sample, ok := samples[typ] + if !ok { + t.Fatalf("no sample for the fixed-width marker %v", typ) + } + check(typ.String(), m.null, sample) + } + for kind, n := range numericKinds { + check(kind.String(), n.null, reflect.Zero(kindTypes[kind]).Interface()) + } +} + +var kindTypes = map[reflect.Kind]reflect.Type{ + reflect.Int8: reflect.TypeOf(int8(0)), reflect.Int16: reflect.TypeOf(int16(0)), + reflect.Int32: reflect.TypeOf(int32(0)), reflect.Int: reflect.TypeOf(0), + reflect.Int64: reflect.TypeOf(int64(0)), reflect.Uint8: reflect.TypeOf(uint8(0)), + reflect.Uint16: reflect.TypeOf(uint16(0)), reflect.Uint32: reflect.TypeOf(uint32(0)), + reflect.Uint: reflect.TypeOf(uint(0)), reflect.Uint64: reflect.TypeOf(uint64(0)), + reflect.Uintptr: reflect.TypeOf(uintptr(0)), reflect.Float32: reflect.TypeOf(float32(0)), + reflect.Float64: reflect.TypeOf(float64(0)), +} diff --git a/languages/golang/encrypt/gensupport/codec.go b/languages/golang/encrypt/gensupport/codec.go index e2ecb3046..80abe328a 100644 --- a/languages/golang/encrypt/gensupport/codec.go +++ b/languages/golang/encrypt/gensupport/codec.go @@ -8,8 +8,8 @@ import ( "sync" "github.com/cipherstash/stack/languages/golang/encrypt" + "github.com/cipherstash/stack/languages/golang/encrypt/frame" "github.com/cipherstash/stack/languages/golang/internal/record" - "github.com/cipherstash/vitaminc/bindings/go/vcffi" ) // Values is a struct's field values by declared name: what Source gives and @@ -378,19 +378,23 @@ func (c *RecordsCodec[P, R]) Decrypt(ctx context.Context, d encrypt.Decrypter, r return c.decrypt(ctx, d, rows) } -// opaqueBytes is an opaque struct's fields as the one value the engine -// seals: a storage blob (vitaminc's storage profile, version 1, written by -// vcffi.MarshalStorage) of the generated shape struct, so the struct is one -// column and every field comes back at the Go type the struct declares. The -// storage profile is the format for bytes that are kept: unlike the -// transport, its version 1 is a compatibility commitment shared with Rust, -// and it carries every float, NaN and the infinities included. +// opaqueBytes returns the fields of an opaque struct as the one value that +// the engine seals. That value is a storage blob of the generated shape +// struct. frame.MarshalStorage writes the blob, in version 1 of the storage +// profile. The struct is therefore one column, and every field opens as the +// Go type that the struct declares. +// +// The storage profile is the format for bytes that a program stores. Version +// 1 never changes, and Rust reads and writes the same format. The transport +// bytes have no such rule. The storage profile can store every float, +// including NaN and the infinities. func opaqueBytes(fields any) ([]byte, error) { - encoded, err := vcffi.MarshalStorage(fields) + encoded, err := frame.MarshalStorage(fields) if err != nil { - // vcffi's error names a type or a kind (no storage form, a string - // that is not UTF-8, a repeated key, nesting too deep), never a - // value, so it is wrapped: errors.Is reads vcffi.ErrUnwritable. + // The codec's error names a type or a kind, never a value, so it is + // safe to wrap. The cause is one of four: a type with no storage + // form, a string with invalid UTF-8, a repeated key, or nesting too + // deep. With the wrap, errors.Is matches frame.ErrUnwritable. return nil, fmt.Errorf("%w: the opaque value cannot be written as a storage blob: %w", encrypt.ErrEncoding, err) } return encoded, nil @@ -414,12 +418,13 @@ func Opaque[T any](vals Values, out *T) error { if !ok { return fmt.Errorf("gensupport: %w: the decrypted opaque value is not bytes", encrypt.ErrEncoding) } - if bytes.HasPrefix(encoded, vcffi.StorageHeader[:3]) { - if err := vcffi.UnmarshalStorage(encoded, out); err != nil { - // The vcffi error names the kind found and where, never the - // value; it is wrapped so errors.Is reads its class - // (encrypt.ErrStorageVersion for a blob a later release - // wrote, say). + if bytes.HasPrefix(encoded, frame.StorageHeader[:3]) { + if err := frame.UnmarshalStorage(encoded, out); err != nil { + // The codec's error names the kind of value found and its + // position, never the value. The error is wrapped so that + // errors.Is matches its class. One class is + // encrypt.ErrStorageVersion, for a blob that a later release + // wrote. return fmt.Errorf("gensupport: %w: the opaque value does not read into a %T: %w", encrypt.ErrEncoding, *out, err) } return nil diff --git a/languages/golang/encrypt/gensupport/convert.go b/languages/golang/encrypt/gensupport/convert.go index 1c56d591d..f9c1c907f 100644 --- a/languages/golang/encrypt/gensupport/convert.go +++ b/languages/golang/encrypt/gensupport/convert.go @@ -8,19 +8,30 @@ import ( "reflect" "strconv" - "github.com/cipherstash/vitaminc/bindings/go/vcvalue" + "github.com/cipherstash/stack/languages/golang/encrypt/value" ) -// convert writes an opened sealed value into out, a pointer to the Go type -// the struct declares. The engine returns a value at the field's declared -// kind — an integer of its own width (int8 to uint64, or vcvalue.Int128 and -// vcvalue.Uint128), float32, float64, string, []byte, bool, time.Time for a -// timestamp, vcvalue.Date, vcvalue.Decimal, or a vcvalue.Object for a -// composite — and the struct's type is that type, or in the same family and -// narrower at most (an EQL type's int32 opening into the int16 field it was -// widened from). A value outside the target's range, or of another family, -// is an error. A time, date, decimal or 128-bit integer is read only into -// its own type, which Get matches before it calls this. +// convert writes an opened sealed value into out. The out argument is a +// pointer to the Go type that the struct declares. +// +// The engine returns a value of the kind that the field declares. That value +// is one of these: +// +// - an integer of its own width: int8 to uint64, encrypt.Int128, or +// encrypt.Uint128 +// - a float32 or a float64 +// - a string, a []byte, or a bool +// - a time.Time, for a timestamp +// - an encrypt.Date, an encrypt.Decimal, or an encrypt.UUID +// - a value.Object, for a composite +// +// The type in the struct is that type, or a narrower type of the same +// family. An example is an int16 field that was widened to the int32 of an +// EQL type, and opens from that int32. The function returns an error for a +// value outside the range of the target, and for a value of another family. +// +// A time, a date, a decimal, or a 128-bit integer is read only into its own +// type. Get matches those types before it calls convert. // // An error names types and positions, never the value: the value is // decrypted plaintext, and an error is what a program logs. @@ -408,10 +419,10 @@ func setSlice[E any](v any, out *[]E) error { // kind was inside the ciphertext. func valuesOf(v any, want string) (Values, error) { switch obj := v.(type) { - case vcvalue.Object: + case value.Object: vals := make(Values, len(obj)) for _, f := range obj { - if inner, ok := f.Value.(vcvalue.Object); ok { + if inner, ok := f.Value.(value.Object); ok { nested, err := valuesOf(inner, want) if err != nil { return nil, err diff --git a/languages/golang/encrypt/gensupport/declaration.go b/languages/golang/encrypt/gensupport/declaration.go index 60be1b7de..fa5af12a9 100644 --- a/languages/golang/encrypt/gensupport/declaration.go +++ b/languages/golang/encrypt/gensupport/declaration.go @@ -55,10 +55,11 @@ const ( Timestamp Kind = "timestamp" String Kind = "string" Bytes Kind = "bytes" - // UUID is a UUID: sixteen bytes under vitaminc's uuid logical type. - // Its value is a vcvalue.UUID, or a value of any type whose underlying - // type is [16]byte (github.com/google/uuid.UUID, say), which is - // converted to one. + // UUID is the kind of a UUID field: sixteen bytes with the logical type + // uuid. The value of the field is an encrypt.UUID. The field also + // accepts a value of any type whose underlying type is [16]byte, such as + // github.com/google/uuid.UUID. Such a value is converted to an + // encrypt.UUID. UUID Kind = "uuid" // JSON is a field stored as a JSON document (the EQL types JSONSearch // and JSON): it crosses as its JSON text, which the engine parses. A json.RawMessage is that @@ -67,13 +68,17 @@ const ( JSON Kind = "json" ) -// OpaqueField is the one field of an opaque declaration: the whole struct, -// sealed as one value under /value. The struct crosses the binding -// as one storage blob (vitaminc's storage profile, version 1) — the engine -// seals a composite value as a tree of leaves, and an opaque struct is one -// column. A field of a struct, map or slice type that names an EQL type -// holding a JSON document is the other way one is stored as one column. A value an earlier release sealed is a JSON document, which -// [Opaque] still reads. +// OpaqueField is the name of the one field of an opaque declaration. That +// field is the whole struct, sealed as one value under /value. +// +// The struct crosses to the engine as one storage blob, in version 1 of the +// storage profile. The engine seals a composite value as a tree of leaves, +// but an opaque struct must be one column. A struct, map, or slice can be +// stored as one column in one other way. That way is a field that names an +// EQL type for a JSON document. +// +// A value that an earlier release sealed is a JSON document. [Opaque] still +// reads such a value. const OpaqueField = "value" type verb uint8 diff --git a/languages/golang/encrypt/gensupport/gensupport_internal_test.go b/languages/golang/encrypt/gensupport/gensupport_internal_test.go index 44ece19a8..ee209a576 100644 --- a/languages/golang/encrypt/gensupport/gensupport_internal_test.go +++ b/languages/golang/encrypt/gensupport/gensupport_internal_test.go @@ -14,9 +14,9 @@ import ( "time" "github.com/cipherstash/stack/languages/golang/encrypt" + "github.com/cipherstash/stack/languages/golang/encrypt/frame" + "github.com/cipherstash/stack/languages/golang/encrypt/value" "github.com/cipherstash/stack/languages/golang/internal/record" - "github.com/cipherstash/vitaminc/bindings/go/vcffi" - "github.com/cipherstash/vitaminc/bindings/go/vcvalue" ) func TestDeclarationLowersToTheEnginesPlan(t *testing.T) { @@ -138,7 +138,7 @@ func TestConvertStaysWithinAFamily(t *testing.T) { t.Fatal("a mixed array became []string") } var vals Values - obj := vcvalue.Object{{Key: "title", Value: "x"}, {Key: "inner", Value: vcvalue.Object{{Key: "n", Value: int64(1)}}}} + obj := value.Object{{Key: "title", Value: "x"}, {Key: "inner", Value: value.Object{{Key: "n", Value: int64(1)}}}} if err := convert(obj, &vals); err != nil { t.Fatal(err) } @@ -162,7 +162,7 @@ func TestConvertStaysWithinAFamily(t *testing.T) { if err != nil { t.Fatal(err) } - if !bytes.HasPrefix(encoded, vcffi.StorageHeader[:]) { + if !bytes.HasPrefix(encoded, frame.StorageHeader[:]) { t.Fatalf("opaqueBytes wrote % x, not a version 1 storage blob", encoded[:4]) } var back shape @@ -178,9 +178,9 @@ func TestConvertStaysWithinAFamily(t *testing.T) { // A blob of a storage version this release does not read is refused as // such, not misread as JSON. future := append([]byte(nil), encoded...) - future[3] = vcffi.StorageVersion + 1 - if err := Opaque(Values{OpaqueField: future}, &back); !errors.Is(err, encrypt.ErrEncoding) || !errors.Is(err, vcffi.ErrUnsupportedVersion) { - t.Fatalf("Opaque of a version %d blob: %v", vcffi.StorageVersion+1, err) + future[3] = frame.StorageVersion + 1 + if err := Opaque(Values{OpaqueField: future}, &back); !errors.Is(err, encrypt.ErrEncoding) || !errors.Is(err, frame.ErrUnsupportedVersion) { + t.Fatalf("Opaque of a version %d blob: %v", frame.StorageVersion+1, err) } // A value that is neither a storage blob nor a JSON object (a JSON // array, a header cut short of its "S", nothing at all) is refused as @@ -331,8 +331,9 @@ func TestDecryptErrorsHoldNoPlaintext(t *testing.T) { if err := Opaque(Values{OpaqueField: old}, &grown); err != nil || grown.N != 7 || grown.New != "" { t.Fatalf("a grown struct read %+v, %v", grown, err) } - // A blob of a later storage version is encrypt.ErrStorageVersion, which - // needs no import of vitaminc's bindings to check. + // A blob of a later storage version fails with + // encrypt.ErrStorageVersion. A program checks for that error with + // errors.Is. later := append([]byte(nil), old...) later[3]++ if err := Opaque(Values{OpaqueField: later}, &grown); !errors.Is(err, encrypt.ErrStorageVersion) || !errors.Is(err, encrypt.ErrEncoding) { @@ -375,7 +376,7 @@ func TestAnOpaqueStructCarriesAPointerToATextType(t *testing.T) { // mustStorage is v as a storage blob. func mustStorage(t *testing.T, v any) []byte { t.Helper() - b, err := vcffi.MarshalStorage(v) + b, err := frame.MarshalStorage(v) if err != nil { t.Fatal(err) } @@ -456,7 +457,7 @@ func TestGetReadsEveryTypeTheGeneratorAccepts(t *testing.T) { return check(err, v["a"] == "b") }, "map[string]int": func() error { - v, err := Get[map[string]int](Values{"v": vcvalue.Object{{Key: "a", Value: int64(3)}}}, "v") + v, err := Get[map[string]int](Values{"v": value.Object{{Key: "a", Value: int64(3)}}}, "v") return check(err, v["a"] == 3) }, "exact passthrough": func() error { @@ -544,7 +545,7 @@ func TestAsKindConvertsAnIntegerThatFitsAndRefusesOneThatDoesNot(t *testing.T) { // plus 100. type encodedInt int16 -func (v encodedInt) EncryptValue(enc vcffi.Encoder) error { +func (v encodedInt) EncryptValue(enc encrypt.Encoder) error { enc.Int32(int32(v) + 100) return nil } @@ -565,19 +566,22 @@ func TestAsKindLeavesAValueThatWritesItself(t *testing.T) { // say: sixteen bytes and no EncryptValue. type googleUUID [16]byte -// A UUID field's value crosses as a vcvalue.UUID, which vcffi writes under the -// uuid logical type: any other type whose underlying type is [16]byte is -// converted, since vcffi writes that as plain bytes and the engine would refuse -// it. A value of another shape is left for the engine to refuse. +// The value of a UUID field crosses to the engine as an encrypt.UUID. The +// codec writes an encrypt.UUID with the logical type uuid. A value of any +// other type whose underlying type is [16]byte is converted first. Without +// the conversion, the codec would write such a value as plain bytes. The +// engine would refuse those bytes. +// +// A value of any other kind is not converted, and the engine refuses it. func TestAsKindMakesASixteenByteArrayAUUID(t *testing.T) { id := [16]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16} - for _, in := range []any{id, googleUUID(id), vcvalue.UUID(id)} { + for _, in := range []any{id, googleUUID(id), encrypt.UUID(id)} { got, err := asKind(UUID, in) - if err != nil || got != vcvalue.UUID(id) { - t.Errorf("asKind(UUID, %T) = %v (%T), %v; want a vcvalue.UUID", in, got, got, err) + if err != nil || got != encrypt.UUID(id) { + t.Errorf("asKind(UUID, %T) = %v (%T), %v; want an encrypt.UUID", in, got, got, err) } } - for _, in := range []any{id[:], [15]byte{}, "0102", encodedInt(7), vcvalue.Int128(id)} { + for _, in := range []any{id[:], [15]byte{}, "0102", encodedInt(7), encrypt.Int128(id)} { got, err := asKind(UUID, in) if err != nil || fmt.Sprint(got) != fmt.Sprint(in) { t.Errorf("asKind(UUID, %T) = %v (%T), %v; want it unchanged", in, got, got, err) @@ -638,7 +642,7 @@ func TestOpaqueReadsARustWrittenBlob(t *testing.T) { // a non-nil pointer as the bare value. The bytes differ in that one // byte, and both read as the same value here. nick := "ada" - ours, err := vcffi.MarshalStorage(profile{Name: "Ada Lovelace", Age: 36, Tags: []string{"maths", "engines"}, Nickname: &nick}) + ours, err := frame.MarshalStorage(profile{Name: "Ada Lovelace", Age: 36, Tags: []string{"maths", "engines"}, Nickname: &nick}) if err != nil { t.Fatal(err) } diff --git a/languages/golang/encrypt/gensupport/json.go b/languages/golang/encrypt/gensupport/json.go index 9f0ca9ef3..24c1f9197 100644 --- a/languages/golang/encrypt/gensupport/json.go +++ b/languages/golang/encrypt/gensupport/json.go @@ -12,8 +12,8 @@ import ( "strings" "github.com/cipherstash/stack/languages/golang/encrypt" + "github.com/cipherstash/stack/languages/golang/encrypt/value" "github.com/cipherstash/stack/languages/golang/internal/record" - "github.com/cipherstash/vitaminc/bindings/go/vcvalue" ) // The operators of a field stored as a JSONSearch document, for the @@ -150,7 +150,7 @@ func GetDocumentPtr[T any](vals Values, name string) (*T, error) { // jsonTerm derives one JSON operator's term on the field: an exact term in // encoding, of parts byte strings ("eql") or texts ("text"); parts 0 takes // any number of texts ("text_array"). -func (f Field[T]) jsonTerm(ctx context.Context, c *encrypt.Cipher, operator, encoding string, parts int, input vcvalue.Object) (encrypt.QueryTerm, error) { +func (f Field[T]) jsonTerm(ctx context.Context, c *encrypt.Cipher, operator, encoding string, parts int, input value.Object) (encrypt.QueryTerm, error) { if f.err != nil { return encrypt.QueryTerm{}, f.err } @@ -214,7 +214,7 @@ func JSONQuery[Q ~[]byte, T any](ctx context.Context, f Field[T], c *encrypt.Cip if bytes.Equal(text, []byte("null")) { return nil, fmt.Errorf("%w: gensupport: %s: a %T needle that writes JSON null (a nil one) matches only a null document; pass a map, a struct or JSON text", encrypt.ErrEncoding, f.name, needle) } - term, err := f.jsonTerm(ctx, c, operator, "eql", 1, vcvalue.Object{{Key: "json", Value: text}}) + term, err := f.jsonTerm(ctx, c, operator, "eql", 1, value.Object{{Key: "json", Value: text}}) if err != nil { return nil, err } @@ -230,7 +230,7 @@ func JSONQueryAt[Q ~[]byte, T any](ctx context.Context, f Field[T], c *encrypt.C if err != nil { return nil, err } - term, err := f.jsonTerm(ctx, c, operator, "eql", 1, vcvalue.Object{{Key: "path", Value: path}, {Key: "json", Value: text}}) + term, err := f.jsonTerm(ctx, c, operator, "eql", 1, value.Object{{Key: "path", Value: path}, {Key: "json", Value: text}}) if err != nil { return nil, err } @@ -248,7 +248,7 @@ func JSONBetweenAt[Q ~[]byte, T any](ctx context.Context, f Field[T], c *encrypt if err != nil { return encrypt.JSONRange[Q]{}, err } - term, err := f.jsonTerm(ctx, c, "between_at", "eql", 2, vcvalue.Object{{Key: "path", Value: path}, {Key: "low", Value: low}, {Key: "high", Value: high}}) + term, err := f.jsonTerm(ctx, c, "between_at", "eql", 2, value.Object{{Key: "path", Value: path}, {Key: "low", Value: low}, {Key: "high", Value: high}}) if err != nil { return encrypt.JSONRange[Q]{}, err } @@ -296,7 +296,7 @@ func JSONElementMatch[Q ~[]byte, T, E any](ctx context.Context, f Field[T], c *e if !slices.Contains(members, member) { return nil, fmt.Errorf("%w: gensupport: %s: Match at %s: the member %q is not ordered, so no element carries a term to compare (%s); order its full path in the field's tag, ordered=", encrypt.ErrTerm, f.name, path, member, orderedMembers(members)) } - entry := vcvalue.Object{{Key: "member", Value: member}, {Key: "op", Value: op}} + entry := value.Object{{Key: "member", Value: member}, {Key: "op", Value: op}} // Each comparison gives its op its values: between the low and // the high, every other op one. keys := []string{"json"} @@ -308,15 +308,15 @@ func JSONElementMatch[Q ~[]byte, T, E any](ctx context.Context, f Field[T], c *e if err != nil { return nil, err } - entry = append(entry, vcvalue.Field{Key: key, Value: text}) + entry = append(entry, value.Field{Key: key, Value: text}) } list[i] = entry } - input := vcvalue.Object{{Key: "path", Value: path}} + input := value.Object{{Key: "path", Value: path}} if opts.WildcardBound != 0 { - input = append(input, vcvalue.Field{Key: "wildcard_bound", Value: opts.WildcardBound}) + input = append(input, value.Field{Key: "wildcard_bound", Value: opts.WildcardBound}) } - input = append(input, vcvalue.Field{Key: "predicates", Value: list}) + input = append(input, value.Field{Key: "predicates", Value: list}) term, err := f.jsonTerm(ctx, c, "element_match", "eql", 1, input) if err != nil { return nil, err @@ -361,9 +361,9 @@ func JSONMatch[Q ~[]byte, T any](ctx context.Context, f Field[T], c *encrypt.Cip if f.err != nil { return nil, f.err } - input := vcvalue.Object{{Key: "predicate", Value: predicate}} + input := value.Object{{Key: "predicate", Value: predicate}} if opts.WildcardBound != 0 { - input = append(input, vcvalue.Field{Key: "wildcard_bound", Value: opts.WildcardBound}) + input = append(input, value.Field{Key: "wildcard_bound", Value: opts.WildcardBound}) } if isNilValue(vars) { // SQL NULL vars: compile with none for what plaintext refuses @@ -380,7 +380,7 @@ func JSONMatch[Q ~[]byte, T any](ctx context.Context, f Field[T], c *encrypt.Cip if err != nil { return nil, err } - input = append(input, vcvalue.Field{Key: "vars", Value: text}) + input = append(input, value.Field{Key: "vars", Value: text}) term, err := f.jsonTerm(ctx, c, "match", "eql", 1, input) if err != nil { return nil, err @@ -437,7 +437,7 @@ func (f Field[T]) elementMembers(path string) []string { // JSONSelect prepares `->` at a path on a JSON field: the selector to // bind, and what opens the entries it returns. E is the field's entry type. func JSONSelect[E ~[]byte, T any](ctx context.Context, f Field[T], c *encrypt.Cipher, path string) (encrypt.JSONSelection[E], error) { - term, err := f.jsonTerm(ctx, c, record.JSONSelector, "text", 1, vcvalue.Object{{Key: "path", Value: path}}) + term, err := f.jsonTerm(ctx, c, record.JSONSelector, "text", 1, value.Object{{Key: "path", Value: path}}) if err != nil { return encrypt.JSONSelection[E]{}, err } @@ -449,9 +449,9 @@ func JSONSelect[E ~[]byte, T any](ctx context.Context, f Field[T], c *encrypt.Ci // built once, here, and the read keeps it: opening sends the engine the // same request the tokens were derived from. func JSONSubtree[E ~[]byte, T any](ctx context.Context, f Field[T], c *encrypt.Cipher, path string, opts encrypt.JSONReadOptions) (encrypt.JSONRead[E], error) { - input := vcvalue.Object{{Key: "path", Value: path}} + input := value.Object{{Key: "path", Value: path}} if opts.WildcardBound != 0 { - input = append(input, vcvalue.Field{Key: "wildcard_bound", Value: opts.WildcardBound}) + input = append(input, value.Field{Key: "wildcard_bound", Value: opts.WildcardBound}) } term, err := f.jsonTerm(ctx, c, record.JSONSubtree, "text_array", 0, input) if err != nil { @@ -465,7 +465,7 @@ func JSONSubtree[E ~[]byte, T any](ctx context.Context, f Field[T], c *encrypt.C // each entry eql_v4.json_tree_children returns. E is the field's entry // type. func JSONChildren[E ~[]byte, T any](ctx context.Context, f Field[T], c *encrypt.Cipher, path string) (encrypt.JSONChildren[E], error) { - term, err := f.jsonTerm(ctx, c, record.JSONChildren, "text", 1, vcvalue.Object{{Key: "path", Value: path}}) + term, err := f.jsonTerm(ctx, c, record.JSONChildren, "text", 1, value.Object{{Key: "path", Value: path}}) if err != nil { return encrypt.JSONChildren[E]{}, err } @@ -485,7 +485,7 @@ func JSONNodeToken[T any](ctx context.Context, f Field[T], c *encrypt.Cipher, op if operator != record.JSONChildCount && operator != record.JSONChildren { return "", fmt.Errorf("%w: gensupport: %s: %s derives no node token", encrypt.ErrEncoding, f.name, operator) } - term, err := f.jsonTerm(ctx, c, record.JSONChildCount, "text", 1, vcvalue.Object{{Key: "path", Value: path}}) + term, err := f.jsonTerm(ctx, c, record.JSONChildCount, "text", 1, value.Object{{Key: "path", Value: path}}) if err != nil { return "", err } diff --git a/languages/golang/encrypt/gensupport/widen.go b/languages/golang/encrypt/gensupport/widen.go index 499926e2b..f0c64a8cc 100644 --- a/languages/golang/encrypt/gensupport/widen.go +++ b/languages/golang/encrypt/gensupport/widen.go @@ -1,14 +1,14 @@ package gensupport import ( + "errors" "fmt" "math" "reflect" "time" "github.com/cipherstash/stack/languages/golang/encrypt" - "github.com/cipherstash/vitaminc/bindings/go/vcffi" - "github.com/cipherstash/vitaminc/bindings/go/vcvalue" + "github.com/cipherstash/stack/languages/golang/encrypt/value" ) // asKind is a sealed field's value as the Go type of its declared kind, the @@ -21,17 +21,21 @@ import ( // with encrypt.ErrEncoding: a Go type wider than the kind is accepted by // stashgen and range checked here, value by value. // -// A value whose type writes itself (vcffi.Encryptable) crosses as it is too: -// converting it to a built-in integer would drop its EncryptValue, and the -// engine holds what it writes to the field's kind. A write and a query of one -// field both convert here ([Field.Encrypt], [Field.Term]), so they agree. +// A value whose type implements encrypt.Encryptable also crosses unchanged. +// A conversion to a built-in integer would remove its EncryptValue method. +// The engine checks that the value it writes is of the kind that the field +// declares. Both a write and a query of a field convert their values here, +// in [Field.Encrypt] and [Field.Term], so the two agree. // -// A UUID field's value crosses as a vcvalue.UUID, which vcffi writes under -// the uuid logical type. A value of another type whose underlying type is -// [16]byte (github.com/google/uuid.UUID, say) is converted to it here, since -// vcffi writes such a value as plain bytes and the engine refuses bytes in a -// UUID field. vcvalue.Int128 and Uint128 are integers, not UUIDs, and are not -// converted. +// The value of a UUID field crosses as an encrypt.UUID. The codec writes an +// encrypt.UUID with the logical type uuid. A value of another type whose +// underlying type is [16]byte is converted to an encrypt.UUID here. One such +// type is github.com/google/uuid.UUID. Without the conversion, the codec +// would write the value as plain bytes, and the engine refuses bytes in a +// UUID field. +// +// An encrypt.Int128 and an encrypt.Uint128 are integers, not UUIDs, so they +// are not converted. // // The error names the kind and not the value, which is plaintext. func asKind(kind Kind, v any) (any, error) { @@ -51,7 +55,7 @@ func asKind(kind Kind, v any) (any, error) { return v, nil } switch v.(type) { - case vcvalue.Int128, vcvalue.Uint128, vcffi.Encryptable: + case encrypt.Int128, encrypt.Uint128, encrypt.Encryptable: return v, nil } rv := reflect.ValueOf(v) @@ -77,15 +81,19 @@ func asKind(kind Kind, v any) (any, error) { return out, nil } -// uuidType is vcvalue.UUID's reflect.Type. -var uuidType = reflect.TypeFor[vcvalue.UUID]() +// uuidType is encrypt.UUID's reflect.Type. +var uuidType = reflect.TypeFor[encrypt.UUID]() -// asUUID is v as a vcvalue.UUID when its underlying type is [16]byte, and v -// unchanged otherwise: a vcvalue.UUID already, a value that writes itself, a -// 128-bit integer, or a value of another shape, which the engine refuses. +// asUUID converts v to an encrypt.UUID when the underlying type of v is +// [16]byte. The function returns v unchanged in four cases: +// +// - v is already an encrypt.UUID. +// - v implements encrypt.Encryptable. +// - v is a 128-bit integer. +// - v is a value of any other kind. The engine refuses such a value. func asUUID(v any) any { switch v.(type) { - case vcvalue.UUID, vcvalue.Int128, vcvalue.Uint128, vcffi.Encryptable: + case encrypt.UUID, encrypt.Int128, encrypt.Uint128, encrypt.Encryptable: return v } rv := reflect.ValueOf(v) @@ -95,20 +103,28 @@ func asUUID(v any) any { return v } -// checkValue refuses a date, decimal or timestamp the codec cannot write, before -// it reaches the codec, so the caller can name the field: the codec's own -// refusal names neither. A zero encrypt.Date (year 0, month 0, day 0) is not -// a date and is refused here. The error is vitaminc's, which names the type -// and not the value. +// errInvalidTimestamp is the error for an instant outside the years -9999 to +// 9999. +var errInvalidTimestamp = errors.New("encrypt: the timestamp is outside the years -9999 to 9999") + +// checkValue refuses a date, a decimal, or a timestamp that the codec cannot +// write. The check runs before the value reaches the codec, so that the +// caller can name the field. The codec's own error does not name the field. +// +// A zero encrypt.Date has year 0, month 0, and day 0. A zero date is not a +// date, so the function refuses it. The error names the type and not the +// value. func checkValue(v any) error { var err error switch v := v.(type) { - case vcvalue.Date: + case encrypt.Date: err = v.Validate() - case vcvalue.Decimal: + case encrypt.Decimal: err = v.Validate() case time.Time: - err = vcvalue.Timestamp{Seconds: v.Unix(), Nanoseconds: uint32(v.Nanosecond())}.Validate() //nolint:gosec // Nanosecond is in [0, 1e9) + if (value.Timestamp{Seconds: v.Unix(), Nanoseconds: uint32(v.Nanosecond())}).Validate() != nil { //nolint:gosec // Nanosecond is in [0, 1e9) + err = errInvalidTimestamp + } } if err != nil { return fmt.Errorf("%w: %w", encrypt.ErrEncoding, err) diff --git a/languages/golang/encrypt/guest/Cargo.toml b/languages/golang/encrypt/guest/Cargo.toml index c501fb6c6..0021505b3 100644 --- a/languages/golang/encrypt/guest/Cargo.toml +++ b/languages/golang/encrypt/guest/Cargo.toml @@ -51,10 +51,10 @@ stack-auth = { path = "../../../../packages/stack-auth", default-features = fals # `dynamic`: the runtime value model this guest speaks — contexts, index # terms and record plans read from frames, shared with every other binding. stack-encrypt = { path = "../../../../packages/stack-encrypt", default-features = false, features = ["dynamic"] } -# The guest ABI every guest under bindings/go shares: the allocator and -# buffer registry (and with them the `se_alloc`/`se_dealloc` exports), the -# packed-result helpers, the status table and the step loop. -# This crate defines only the exports that are its own. +# The guest ABI that every guest under languages/golang shares. The ABI has the +# allocator and the buffer registry, with their `se_alloc` and `se_dealloc` +# exports. The ABI also has the packed-result helpers, the status table, and the +# step loop. This crate defines only the exports that are its own. stack-guest-abi = { path = "../../../../packages/stack-guest-abi" } # `wasm-simd`: re-encrypts key material with wasm SIMD, the costly part of # deriving a data key. The module then holds SIMD instructions, which wazero diff --git a/languages/golang/encrypt/guest_fuzz_test.go b/languages/golang/encrypt/guest_fuzz_test.go index 562dbce26..16aec3ff6 100644 --- a/languages/golang/encrypt/guest_fuzz_test.go +++ b/languages/golang/encrypt/guest_fuzz_test.go @@ -5,9 +5,9 @@ import ( "errors" "testing" + "github.com/cipherstash/stack/languages/golang/encrypt/frame" "github.com/cipherstash/stack/languages/golang/internal/guest" "github.com/cipherstash/stack/languages/golang/internal/record" - "github.com/cipherstash/vitaminc/bindings/go/vcffi" "github.com/tetratelabs/wazero/api" ) @@ -98,7 +98,7 @@ func newFuzzClient(tb testing.TB) *fuzzClient { // takes and decodes the answer before it looks at the handle, so the // fuzzed pair is read in full, and then answers STATUS_STATE: handle 1 // names no paused step. - seed, err := vcffi.Marshal(fuzzSeed[:]) + seed, err := frame.Marshal(fuzzSeed[:]) if err != nil { _ = c.Close() tb.Fatal(err) @@ -162,7 +162,7 @@ func (fc *fuzzClient) call(in guest.FuzzInput, which uint8) error { // plaintext and wiped first (se_term, se_encrypt_record, se_resume). func FuzzGuestExportPairs(f *testing.F) { fc := keepFuzzClient(f) - plan, err := vcffi.Marshal(fc.plan.Wire()) + plan, err := frame.Marshal(fc.plan.Wire()) if err != nil { f.Fatal(err) } diff --git a/languages/golang/encrypt/json.go b/languages/golang/encrypt/json.go index b7c682d09..711b6c1ec 100644 --- a/languages/golang/encrypt/json.go +++ b/languages/golang/encrypt/json.go @@ -11,10 +11,10 @@ import ( "log/slog" "strings" + "github.com/cipherstash/stack/languages/golang/encrypt/frame" + "github.com/cipherstash/stack/languages/golang/encrypt/value" "github.com/cipherstash/stack/languages/golang/internal/guest" "github.com/cipherstash/stack/languages/golang/internal/record" - "github.com/cipherstash/vitaminc/bindings/go/vcffi" - "github.com/cipherstash/vitaminc/bindings/go/vcvalue" ) // JSONOpen opens the rows that a read of a JSON document field returned. @@ -58,7 +58,7 @@ import ( // Opening does not prove the database returned every row the read asked // for, or rows of the database row the caller meant: see the EQL json_tree // leakage reference. -func (cph *Cipher) JSONOpen(ctx context.Context, plan *record.Plan, field string, request vcvalue.Object, rows [][][]byte) ([][][]byte, error) { +func (cph *Cipher) JSONOpen(ctx context.Context, plan *record.Plan, field string, request value.Object, rows [][][]byte) ([][][]byte, error) { for _, f := range request { if f.Key == "operation" && f.Value == record.JSONChildren { return nil, fmt.Errorf("%w: a children read opens with JSONChildren.Open, which returns each child's key or index", ErrEncoding) @@ -91,7 +91,7 @@ func (cph *Cipher) JSONOpen(ctx context.Context, plan *record.Plan, field string // jsonOpen calls se_json_open with the request and the rows. It returns the // decoded list, with one item per group of rows. Each read's Open reads its // values from that list. -func (cph *Cipher) jsonOpen(ctx context.Context, plan *record.Plan, field string, request vcvalue.Object, rows [][][]byte) ([]any, error) { +func (cph *Cipher) jsonOpen(ctx context.Context, plan *record.Plan, field string, request value.Object, rows [][][]byte) ([]any, error) { p, err := cph.readPlan(plan, field) if err != nil { return nil, err @@ -104,15 +104,15 @@ func (cph *Cipher) jsonOpen(ctx context.Context, plan *record.Plan, field string } groups[i] = entries } - encodedRows, err := vcffi.Marshal(groups) + encodedRows, err := frame.Marshal(groups) if err != nil { return nil, fmt.Errorf("%w: %v", ErrEncoding, err) } - encodedRequest, err := vcffi.Marshal(request) + encodedRequest, err := frame.Marshal(request) if err != nil { return nil, fmt.Errorf("%w: %v", ErrEncoding, err) } - encodedPlan, err := vcffi.Marshal(p.Wire()) + encodedPlan, err := frame.Marshal(p.Wire()) if err != nil { return nil, fmt.Errorf("%w: %v", ErrEncoding, err) } @@ -402,7 +402,7 @@ func (s JSONSelection[E]) Open(ctx context.Context, rows []*E) ([]JSONValue, err if !entries { return make([]JSONValue, len(rows)), nil } - opened, err := s.cipher.JSONOpen(ctx, s.plan, s.field, vcvalue.Object{{Key: "operation", Value: record.JSONSelector}, {Key: "path", Value: s.path}}, groups) + opened, err := s.cipher.JSONOpen(ctx, s.plan, s.field, value.Object{{Key: "operation", Value: record.JSONSelector}, {Key: "path", Value: s.path}}, groups) if err != nil { return nil, err } @@ -436,14 +436,14 @@ type JSONRead[E ~[]byte] struct { plan *record.Plan // input is the subtree operator's input the tokens were derived from; // opening sends it back as the read's request, unchanged. - input vcvalue.Object + input value.Object tokens JSONTokens } // NewJSONRead is a read prepared by [Cipher.QueryTerm]'s subtree operator // on field of the record type that declaration declares, from input, its // {"path", "wildcard_bound"?} object. For generated code. -func NewJSONRead[E ~[]byte](c *Cipher, declaration *record.Plan, field string, input vcvalue.Object, tokens []string) JSONRead[E] { +func NewJSONRead[E ~[]byte](c *Cipher, declaration *record.Plan, field string, input value.Object, tokens []string) JSONRead[E] { return JSONRead[E]{redactedRead: redactedRead[subtreeRead]{field: field, count: len(tokens)}, cipher: c, plan: declaration, input: input, tokens: JSONTokens(tokens)} } @@ -480,7 +480,7 @@ func (r JSONRead[E]) Open(ctx context.Context, rows [][]E) ([][]json.RawMessage, groups[i][j] = []byte(entry) } } - request := append(vcvalue.Object{{Key: "operation", Value: record.JSONSubtree}}, r.input...) + request := append(value.Object{{Key: "operation", Value: record.JSONSubtree}}, r.input...) opened, err := r.cipher.JSONOpen(ctx, r.plan, r.field, request, groups) if err != nil { return nil, err @@ -628,7 +628,7 @@ func (c JSONChildren[E]) Open(ctx context.Context, entries []E) ([]JSONChildValu for i, entry := range entries { groups[i] = [][]byte{[]byte(entry)} } - request := vcvalue.Object{{Key: "operation", Value: record.JSONChildren}, {Key: "path", Value: c.path}} + request := value.Object{{Key: "operation", Value: record.JSONChildren}, {Key: "path", Value: c.path}} list, err := c.cipher.jsonOpen(ctx, c.plan, c.field, request, groups) if err != nil { return nil, err @@ -705,7 +705,7 @@ func (v JSONChildValue) LogValue() slog.Value { return slog.StringValue(redacted // {"key": string, "json": bytes} for a member, or {"index": uint64, "json": // bytes} for an element. An error names what is wrong, never a value. func jsonChildValue(item any) (JSONChildValue, error) { - fields, ok := item.(vcvalue.Object) + fields, ok := item.(value.Object) if !ok || len(fields) != 2 { return JSONChildValue{}, errors.New(`it is not an object with "json" and either "key" or "index"`) } diff --git a/languages/golang/encrypt/json_elements_test.go b/languages/golang/encrypt/json_elements_test.go index 9d4655a5f..50fc20b6d 100644 --- a/languages/golang/encrypt/json_elements_test.go +++ b/languages/golang/encrypt/json_elements_test.go @@ -15,8 +15,8 @@ import ( "github.com/cipherstash/stack/languages/golang/encrypt" "github.com/cipherstash/stack/languages/golang/encrypt/internal/testusers" + "github.com/cipherstash/stack/languages/golang/encrypt/value" "github.com/cipherstash/stack/languages/golang/internal/record" - "github.com/cipherstash/vitaminc/bindings/go/vcvalue" "golang.org/x/tools/go/packages" ) @@ -243,11 +243,11 @@ func TestElementMatchEngineRefusalsAreTypedErrors(t *testing.T) { c := deterministicEQLClient(t) ctx := context.Background() cipher := c.DefaultKeyset() - type obj = vcvalue.Object - pred := func(member, op string, kv ...vcvalue.Field) obj { + type obj = value.Object + pred := func(member, op string, kv ...value.Field) obj { return append(obj{{Key: "member", Value: member}, {Key: "op", Value: op}}, kv...) } - eq := func(member, v string) obj { return pred(member, "eq", vcvalue.Field{Key: "json", Value: []byte(v)}) } + eq := func(member, v string) obj { return pred(member, "eq", value.Field{Key: "json", Value: []byte(v)}) } input := func(path string, preds ...any) obj { return obj{{Key: "path", Value: path}, {Key: "predicates", Value: preds}} } @@ -260,10 +260,10 @@ func TestElementMatchEngineRefusalsAreTypedErrors(t *testing.T) { code string // or the index's code }{ {"a path with no wildcard", input("$.extra", eq("relationship", `"secret"`)), encrypt.ErrEncoding, "json_path_no_wildcard", ""}, - {"a bound of 0", append(input(emergencyContacts, eq("relationship", `"secret"`)), vcvalue.Field{Key: "wildcard_bound", Value: uint32(0)}), encrypt.ErrEncoding, "json_wildcard_bound_zero", ""}, + {"a bound of 0", append(input(emergencyContacts, eq("relationship", `"secret"`)), value.Field{Key: "wildcard_bound", Value: uint32(0)}), encrypt.ErrEncoding, "json_wildcard_bound_zero", ""}, {"no predicates", input(emergencyContacts), encrypt.ErrEncoding, "json_no_predicates", ""}, - {"an unknown op", input(emergencyContacts, pred("age", "ne", vcvalue.Field{Key: "json", Value: []byte(`1`)})), encrypt.ErrEncoding, "json_unknown_predicate_op", ""}, - {"keys that do not fit the op", input(emergencyContacts, pred("age", "eq", vcvalue.Field{Key: "low", Value: []byte(`1`)}, vcvalue.Field{Key: "high", Value: []byte(`2`)})), encrypt.ErrEncoding, "json_input", ""}, + {"an unknown op", input(emergencyContacts, pred("age", "ne", value.Field{Key: "json", Value: []byte(`1`)})), encrypt.ErrEncoding, "json_unknown_predicate_op", ""}, + {"keys that do not fit the op", input(emergencyContacts, pred("age", "eq", value.Field{Key: "low", Value: []byte(`1`)}, value.Field{Key: "high", Value: []byte(`2`)})), encrypt.ErrEncoding, "json_input", ""}, {"a wildcard in a member", input(emergencyContacts, eq("calls[*].at", `1`)), encrypt.ErrEncoding, "json_path_wildcard", ""}, {"a position in the path", input("$.extra.emergency_contacts[*].x[2].y[*]", eq("age", `1`)), encrypt.ErrTerm, "", "stack_encrypt::json_ordering_at_position"}, {"an unordered member", input(emergencyContacts, eq("name", `"secret"`)), encrypt.ErrTerm, "", "stack_encrypt::json_path_not_ordered"}, diff --git a/languages/golang/encrypt/json_match_test.go b/languages/golang/encrypt/json_match_test.go index e0aeaca1f..cd3656da1 100644 --- a/languages/golang/encrypt/json_match_test.go +++ b/languages/golang/encrypt/json_match_test.go @@ -14,7 +14,7 @@ import ( "github.com/cipherstash/stack/languages/golang/encrypt" "github.com/cipherstash/stack/languages/golang/encrypt/eql" "github.com/cipherstash/stack/languages/golang/encrypt/internal/testusers" - "github.com/cipherstash/vitaminc/bindings/go/vcvalue" + "github.com/cipherstash/stack/languages/golang/encrypt/value" ) // The compiled predicate of a document field (match): the generated Match @@ -385,7 +385,7 @@ func TestMatchRefusalsNameTheConstructAndItsOffset(t *testing.T) { // A bound of 0 is the engine's default through Match, so the engine's // own refusal of 0 is reached through QueryTerm alone. - input := vcvalue.Object{{Key: "predicate", Value: `exists($.a)`}, {Key: "wildcard_bound", Value: uint32(0)}} + input := value.Object{{Key: "predicate", Value: `exists($.a)`}, {Key: "wildcard_bound", Value: uint32(0)}} _, err := cipher.QueryTerm(ctx, contactsPlan(), "custom", "match", input) var d *encrypt.Diagnostic if !errors.Is(err, encrypt.ErrEncoding) || !errors.As(err, &d) || d.Reason() != "json_wildcard_bound_zero" { diff --git a/languages/golang/encrypt/json_tree_test.go b/languages/golang/encrypt/json_tree_test.go index 6b693101c..2d860ddf9 100644 --- a/languages/golang/encrypt/json_tree_test.go +++ b/languages/golang/encrypt/json_tree_test.go @@ -14,8 +14,8 @@ import ( "github.com/cipherstash/stack/languages/golang/encrypt" "github.com/cipherstash/stack/languages/golang/encrypt/eql" + "github.com/cipherstash/stack/languages/golang/encrypt/value" "github.com/cipherstash/stack/languages/golang/internal/record" - "github.com/cipherstash/vitaminc/bindings/go/vcvalue" ) // An encrypted JSON document (the EQL type JsonSearch) through the guest @@ -151,7 +151,7 @@ func TestJSONOperatorsDeriveTaggedTerms(t *testing.T) { if !reflect.DeepEqual(inputs, want) { t.Fatalf("operators = %v", inputs) } - type obj = vcvalue.Object + type obj = value.Object for _, tc := range []struct { op, encoding, domain string input obj @@ -198,7 +198,7 @@ func TestJSONSelectorReadsOpenAgainstTheirRequest(t *testing.T) { t.Fatal(err) } selector := func(path string) string { - term, err := cipher.QueryTerm(ctx, jsonPlan(), "profile", "selector", vcvalue.Object{{Key: "path", Value: path}}) + term, err := cipher.QueryTerm(ctx, jsonPlan(), "profile", "selector", value.Object{{Key: "path", Value: path}}) if err != nil { t.Fatal(err) } @@ -227,7 +227,7 @@ func TestJSONSelectorReadsOpenAgainstTheirRequest(t *testing.T) { return nil } name := extract(selector("$.name")) - opened, err := cipher.JSONOpen(ctx, jsonPlan(), "profile", vcvalue.Object{{Key: "operation", Value: "selector"}, {Key: "path", Value: "$.name"}}, [][][]byte{{name}, {}}) + opened, err := cipher.JSONOpen(ctx, jsonPlan(), "profile", value.Object{{Key: "operation", Value: "selector"}, {Key: "path", Value: "$.name"}}, [][][]byte{{name}, {}}) if err != nil { t.Fatal(err) } @@ -237,7 +237,7 @@ func TestJSONSelectorReadsOpenAgainstTheirRequest(t *testing.T) { // A read through a cipher that has audit metadata opens the same rows: // a read asks for data keys, so the guest takes the metadata there. audited := cipher.Audit(encrypt.NewAuditMetadata().Text("purpose", "read a profile")) - opened, err = audited.JSONOpen(ctx, jsonPlan(), "profile", vcvalue.Object{{Key: "operation", Value: "selector"}, {Key: "path", Value: "$.name"}}, [][][]byte{{name}, {}}) + opened, err = audited.JSONOpen(ctx, jsonPlan(), "profile", value.Object{{Key: "operation", Value: "selector"}, {Key: "path", Value: "$.name"}}, [][][]byte{{name}, {}}) if err != nil || len(opened) != 2 || len(opened[0]) != 1 || string(opened[0][0]) != `"Alice"` { t.Fatalf("opened through an audited cipher: %q, %v", opened, err) } @@ -246,11 +246,11 @@ func TestJSONSelectorReadsOpenAgainstTheirRequest(t *testing.T) { // holds one fails. A read that sent no metadata would succeed. The // builder has no method for such an integer, so the test puts it there. refused := cipher.AuditUncheckedForTest(map[string]any{"fact": uint64(math.MaxUint64)}) - _, err = refused.JSONOpen(ctx, jsonPlan(), "profile", vcvalue.Object{{Key: "operation", Value: "selector"}, {Key: "path", Value: "$.name"}}, [][][]byte{{name}}) + _, err = refused.JSONOpen(ctx, jsonPlan(), "profile", value.Object{{Key: "operation", Value: "selector"}, {Key: "path", Value: "$.name"}}, [][][]byte{{name}}) if !errors.Is(err, encrypt.ErrEncoding) { t.Fatalf("a read through a cipher with metadata the engine refuses: %v, want ErrEncoding", err) } - _, err = cipher.JSONOpen(ctx, jsonPlan(), "profile", vcvalue.Object{{Key: "operation", Value: "selector"}, {Key: "path", Value: "$.age"}}, [][][]byte{{name}}) + _, err = cipher.JSONOpen(ctx, jsonPlan(), "profile", value.Object{{Key: "operation", Value: "selector"}, {Key: "path", Value: "$.age"}}, [][][]byte{{name}}) if !errors.Is(err, encrypt.ErrEncoding) { t.Fatalf("another path's entry: %v", err) } @@ -259,7 +259,7 @@ func TestJSONSelectorReadsOpenAgainstTheirRequest(t *testing.T) { // the refusal is ErrEncoding (a container or an altered entry, the // client cannot tell which), never ErrAuthentication. visits := extract(selector("$.visits")) - _, err = cipher.JSONOpen(ctx, jsonPlan(), "profile", vcvalue.Object{{Key: "operation", Value: "selector"}, {Key: "path", Value: "$.visits"}}, [][][]byte{{visits}}) + _, err = cipher.JSONOpen(ctx, jsonPlan(), "profile", value.Object{{Key: "operation", Value: "selector"}, {Key: "path", Value: "$.visits"}}, [][][]byte{{visits}}) var d *encrypt.Diagnostic if !errors.Is(err, encrypt.ErrEncoding) || errors.Is(err, encrypt.ErrAuthentication) || !errors.As(err, &d) || d.Code != "stack_encrypt::json_not_a_leaf" { t.Fatalf("a container through ->: %v", err) @@ -270,12 +270,12 @@ func TestJSONSelectorReadsOpenAgainstTheirRequest(t *testing.T) { // be refused as ErrEncoding. (A read past the bound is refused as // ErrEncoding too; TestJSONDocumentsQueryAndReadInPostgres reads one // from PostgreSQL's own rows.) - bounded := vcvalue.Object{{Key: "operation", Value: "subtree"}, {Key: "path", Value: "$.visits[*].at"}, {Key: "wildcard_bound", Value: uint32(1)}} + bounded := value.Object{{Key: "operation", Value: "subtree"}, {Key: "path", Value: "$.visits[*].at"}, {Key: "wildcard_bound", Value: uint32(1)}} opened, err = cipher.JSONOpen(ctx, jsonPlan(), "profile", bounded, [][][]byte{{}}) if err != nil || len(opened) != 1 || len(opened[0]) != 0 { t.Fatalf("a bounded subtree read of no rows: %q %v", opened, err) } - unreadable := vcvalue.Object{{Key: "operation", Value: "subtree"}, {Key: "path", Value: "$.visits[*].at"}, {Key: "wildcard_bound", Value: "1"}} + unreadable := value.Object{{Key: "operation", Value: "subtree"}, {Key: "path", Value: "$.visits[*].at"}, {Key: "wildcard_bound", Value: "1"}} if _, err := cipher.JSONOpen(ctx, jsonPlan(), "profile", unreadable, [][][]byte{{}}); !errors.Is(err, encrypt.ErrEncoding) { t.Fatalf("a bound that is not an integer: %v", err) } @@ -297,7 +297,7 @@ func TestJSONChildrenOpenAgainstTheirParent(t *testing.T) { document := sealed[0]["profile"].EQL term := func(operator, path string) string { t.Helper() - term, err := cipher.QueryTerm(ctx, jsonPlan(), "profile", operator, vcvalue.Object{{Key: "path", Value: path}}) + term, err := cipher.QueryTerm(ctx, jsonPlan(), "profile", operator, value.Object{{Key: "path", Value: path}}) if err != nil { t.Fatal(err) } @@ -376,7 +376,7 @@ func TestJSONChildrenOpenAgainstTheirParent(t *testing.T) { if !errors.Is(err, encrypt.ErrEncoding) || !errors.As(err, &d) || d.Reason() != "json_path_wildcard" || d.Field() != "profile" { t.Fatalf("a parent path with a wildcard: %v", err) } - request := vcvalue.Object{{Key: "operation", Value: record.JSONChildren}, {Key: "path", Value: "$.tags"}} + request := value.Object{{Key: "operation", Value: record.JSONChildren}, {Key: "path", Value: "$.tags"}} if _, err := cipher.JSONOpen(ctx, jsonPlan(), "profile", request, [][][]byte{{[]byte(entries("$.tags[*]", 2)[0])}}); !errors.Is(err, encrypt.ErrEncoding) || errors.As(err, &d) { t.Fatalf("JSONOpen of a children read: %v, want ErrEncoding before the guest", err) } @@ -488,10 +488,10 @@ func TestAJSONDocumentIsFoundAndReadUnderItsScopeAndBinding(t *testing.T) { tenant := plain.Scope(uint64(7)) bound := tenant.Bind(uint64(9)) source := []record.Source{{"profile": []byte(`{"name":"Alice","age":34}`)}} - request := vcvalue.Object{{Key: "operation", Value: "selector"}, {Key: "path", Value: "$.name"}} + request := value.Object{{Key: "operation", Value: "selector"}, {Key: "path", Value: "$.name"}} selector := func(cipher *encrypt.Cipher) string { t.Helper() - term, err := cipher.QueryTerm(ctx, jsonPlan(), "profile", "selector", vcvalue.Object{{Key: "path", Value: "$.name"}}) + term, err := cipher.QueryTerm(ctx, jsonPlan(), "profile", "selector", value.Object{{Key: "path", Value: "$.name"}}) if err != nil { t.Fatal(err) } @@ -572,7 +572,7 @@ func TestAJSONDocumentIsFoundAndReadUnderItsScopeAndBinding(t *testing.T) { t.Errorf("a selector through a cipher with a binding is not the tenant's") } subtree := func(cipher *encrypt.Cipher) ([]string, error) { - term, err := cipher.QueryTerm(ctx, jsonPlan(), "profile", "subtree", vcvalue.Object{{Key: "path", Value: "$.name"}}) + term, err := cipher.QueryTerm(ctx, jsonPlan(), "profile", "subtree", value.Object{{Key: "path", Value: "$.name"}}) return term.Text, err } boundTokens, err := subtree(bound) @@ -583,7 +583,7 @@ func TestAJSONDocumentIsFoundAndReadUnderItsScopeAndBinding(t *testing.T) { t.Errorf("a subtree read's tokens through a cipher with a binding are not the tenant's: %v", err) } children := func(cipher *encrypt.Cipher) ([]string, error) { - term, err := cipher.QueryTerm(ctx, jsonPlan(), "profile", "children", vcvalue.Object{{Key: "path", Value: "$.name"}}) + term, err := cipher.QueryTerm(ctx, jsonPlan(), "profile", "children", value.Object{{Key: "path", Value: "$.name"}}) return term.Text, err } boundToken, err := children(bound) @@ -594,9 +594,9 @@ func TestAJSONDocumentIsFoundAndReadUnderItsScopeAndBinding(t *testing.T) { t.Errorf("a children read's token through a cipher with a binding is not the tenant's: %v", err) } for _, operator := range []string{"child_count", "eq_at"} { - input := vcvalue.Object{{Key: "path", Value: "$.name"}} + input := value.Object{{Key: "path", Value: "$.name"}} if operator == "eq_at" { - input = append(input, vcvalue.Field{Key: "json", Value: []byte(`"Alice"`)}) + input = append(input, value.Field{Key: "json", Value: []byte(`"Alice"`)}) } if _, err := bound.QueryTerm(ctx, jsonPlan(), "profile", operator, input); !errors.Is(err, encrypt.ErrEncoding) { t.Errorf("%s through a cipher with a binding: %v, want ErrEncoding", operator, err) diff --git a/languages/golang/encrypt/keyset.go b/languages/golang/encrypt/keyset.go index 39e9f40dd..dc04bb4c8 100644 --- a/languages/golang/encrypt/keyset.go +++ b/languages/golang/encrypt/keyset.go @@ -4,7 +4,7 @@ import ( "encoding/hex" "fmt" - "github.com/cipherstash/vitaminc/bindings/go/vcffi" + "github.com/cipherstash/stack/languages/golang/encrypt/frame" ) // KeysetSelector names the keyset a call binds to, as Rust's IdentifiedBy @@ -107,7 +107,7 @@ func (o callOptions) wire() map[string]any { // marshal is the options object in the transport codec. func (o callOptions) marshal() ([]byte, error) { - return vcffi.Marshal(o.wire()) + return frame.Marshal(o.wire()) } // dataKeyCall is the options of a call through this cipher that asks diff --git a/languages/golang/encrypt/kinds_test.go b/languages/golang/encrypt/kinds_test.go index 2569233fa..d1d46fa2f 100644 --- a/languages/golang/encrypt/kinds_test.go +++ b/languages/golang/encrypt/kinds_test.go @@ -14,9 +14,9 @@ import ( "time" "github.com/cipherstash/stack/languages/golang/encrypt" + "github.com/cipherstash/stack/languages/golang/encrypt/frame" "github.com/cipherstash/stack/languages/golang/encrypt/gensupport" "github.com/cipherstash/stack/languages/golang/encrypt/internal/testusers" - "github.com/cipherstash/vitaminc/bindings/go/vcffi" ) // Everything the generator accepts round-trips: one sealed field of every @@ -326,16 +326,17 @@ func TestARedactedStructPrintsNoSealedField(t *testing.T) { } } -// A value with no storage form (here a string that is not UTF-8, which the -// JSON document of earlier releases wrote as U+FFFD) refuses the batch as -// ErrEncoding naming the value, with vcffi's class wrapped and no byte of -// the value in the error. +// A value with no storage form fails the whole batch with ErrEncoding. The +// value here is a string that is not valid UTF-8. The JSON document of +// earlier releases wrote such a string with U+FFFD. The error says which +// value failed, wraps the codec's error class, and contains no byte of the +// value. func TestAnOpaqueStructWithNoStorageFormIsErrEncoding(t *testing.T) { c := deterministicClient(t) in := []testusers.Everything{{S: "fine"}, {S: "secret-4242\xff"}} _, err := testusers.EncryptEverything(context.Background(), c.DefaultKeyset(), in) - if !errors.Is(err, encrypt.ErrEncoding) || !errors.Is(err, vcffi.ErrUnwritable) { - t.Fatalf("err = %v, want ErrEncoding wrapping vcffi.ErrUnwritable", err) + if !errors.Is(err, encrypt.ErrEncoding) || !errors.Is(err, frame.ErrUnwritable) { + t.Fatalf("err = %v, want ErrEncoding wrapping frame.ErrUnwritable", err) } if !strings.Contains(err.Error(), "value 1") || strings.Contains(err.Error(), "4242") { t.Fatalf("err = %v, want it to name value 1 and hold none of the value", err) diff --git a/languages/golang/encrypt/query.go b/languages/golang/encrypt/query.go index 99d9a0d7c..07b07cf96 100644 --- a/languages/golang/encrypt/query.go +++ b/languages/golang/encrypt/query.go @@ -8,10 +8,10 @@ import ( "log/slog" "math" + "github.com/cipherstash/stack/languages/golang/encrypt/frame" + "github.com/cipherstash/stack/languages/golang/encrypt/value" "github.com/cipherstash/stack/languages/golang/internal/guest" "github.com/cipherstash/stack/languages/golang/internal/record" - "github.com/cipherstash/vitaminc/bindings/go/vcffi" - "github.com/cipherstash/vitaminc/bindings/go/vcvalue" ) // Queries named by operator (ADR-0009; ADR-0007, amended 2026-10-16): the @@ -79,17 +79,17 @@ type Stats struct { } // wire is the statistics as se_target_limit reads them. -func (s Stats) wire() vcvalue.Object { - out := vcvalue.Object{{Key: "rows", Value: s.Rows}} +func (s Stats) wire() value.Object { + out := value.Object{{Key: "rows", Value: s.Rows}} if s.Histogram != nil { buckets := make([]any, len(s.Histogram)) for i, b := range s.Histogram { buckets[i] = []any{b.Bits, b.Rows} } - out = append(out, vcvalue.Field{Key: "histogram", Value: buckets}) + out = append(out, value.Field{Key: "histogram", Value: buckets}) } if s.Confidence != 0 { - out = append(out, vcvalue.Field{Key: "confidence", Value: s.Confidence}) + out = append(out, value.Field{Key: "confidence", Value: s.Confidence}) } return out } @@ -117,18 +117,31 @@ func (l Limit) FetchOr(page uint64) uint64 { return min(page, math.MaxInt64) } -// QueryTerm derives the query term for one field of the plan, an operator -// and its input under this cipher's keyset: one value for every operator -// but between, whose input is a two-element slice, low then high, and a -// document's operators (contains, eq_at, selector, ...), whose input is a -// vcvalue.Object of named inputs with JSON values as JSON text. The -// engine reads the input as the field's declared type, finds the index -// that answers the operator, and derives that index's term under the -// field's context; for a field that names an EQL type it runs the type's -// query. An operator the field does not answer, or one the engine does not -// know, is [ErrEncoding] naming the field, as a mistyped value is; match -// text that cuts no token is [ErrTerm]. A range the wrong way round is not -// refused: it matches no row, as SQL's BETWEEN does. +// QueryTerm derives the query term for one field of the plan, from an +// operator and its input, under the keyset of this cipher. The form of the +// input depends on the operator: +// +// - For between, the input is a slice of two elements: the low value, then +// the high value. +// - For an operator on a document, such as contains, eq_at, or selector, +// the input is the named inputs of the operator, in order. A JSON value +// is given as JSON text. Generated code builds this input. +// - For every other operator, the input is one value. +// +// The engine reads the input as the declared type of the field. The engine +// then finds the index that supports the operator, and derives the term of +// that index under the context of the field. For a field that names an EQL +// type, the engine runs the query of that type. +// +// QueryTerm returns [ErrEncoding], naming the field, in three cases: +// +// - The field does not support the operator. +// - The engine does not know the operator. +// - The value has the wrong type. +// +// QueryTerm returns [ErrTerm] for match text that produces no token. A range +// whose low value is above its high value is not refused. Such a range +// matches no row, as BETWEEN does in SQL. // // A query through a cipher with a binding is refused as [ErrEncoding]: a // binding is in no query context. Three operators prepare a read of a @@ -142,14 +155,14 @@ func (cph *Cipher) QueryTerm(ctx context.Context, plan *record.Plan, field, oper if err != nil { return QueryTerm{}, err } - encodedInput, err := vcffi.Marshal(input) + encodedInput, err := frame.Marshal(input) if err != nil { return QueryTerm{}, fmt.Errorf("%w: %v", ErrEncoding, err) } // The input is plaintext: its transport copy is wiped once it is in the // guest. defer wipe(encodedInput) - encodedPlan, err := vcffi.Marshal(p.Wire()) + encodedPlan, err := frame.Marshal(p.Wire()) if err != nil { return QueryTerm{}, fmt.Errorf("%w: %v", ErrEncoding, err) } @@ -182,7 +195,7 @@ func (cph *Cipher) QueryTerm(ctx context.Context, plan *record.Plan, field, oper // strings, perhaps empty. The operator, fidelity and index take only the // values the engine writes, as the catalog reader's do. func parseQueryTerm(decoded any) (QueryTerm, error) { - obj, ok := decoded.(vcvalue.Object) + obj, ok := decoded.(value.Object) if !ok { return QueryTerm{}, fmt.Errorf("it is %s, not an object", guest.KindOf(decoded)) } @@ -294,7 +307,7 @@ func (cph *Cipher) Verify(ctx context.Context, plan *record.Plan, field, operato if err != nil { return nil, err } - encodedInput, err := vcffi.Marshal(input) + encodedInput, err := frame.Marshal(input) if err != nil { return nil, fmt.Errorf("%w: %v", ErrEncoding, err) } @@ -302,13 +315,13 @@ func (cph *Cipher) Verify(ctx context.Context, plan *record.Plan, field, operato if values == nil { values = []any{} } - encodedValues, err := vcffi.Marshal(values) + encodedValues, err := frame.Marshal(values) if err != nil { return nil, fmt.Errorf("%w: %v", ErrEncoding, err) } // The values are decrypted plaintext: wiped once they are in the guest. defer wipe(encodedValues) - encodedPlan, err := vcffi.Marshal(p.Wire()) + encodedPlan, err := frame.Marshal(p.Wire()) if err != nil { return nil, fmt.Errorf("%w: %v", ErrEncoding, err) } @@ -356,11 +369,11 @@ func (cph *Cipher) TargetLimit(ctx context.Context, plan *record.Plan, field, op if err != nil { return Limit{}, err } - encodedStats, err := vcffi.Marshal(stats.wire()) + encodedStats, err := frame.Marshal(stats.wire()) if err != nil { return Limit{}, fmt.Errorf("%w: %v", ErrEncoding, err) } - encodedPlan, err := vcffi.Marshal(p.Wire()) + encodedPlan, err := frame.Marshal(p.Wire()) if err != nil { return Limit{}, fmt.Errorf("%w: %v", ErrEncoding, err) } diff --git a/languages/golang/encrypt/query_test.go b/languages/golang/encrypt/query_test.go index 345fdafcc..a2c5ca7c7 100644 --- a/languages/golang/encrypt/query_test.go +++ b/languages/golang/encrypt/query_test.go @@ -19,8 +19,8 @@ import ( "github.com/cipherstash/stack/languages/golang/encrypt" "github.com/cipherstash/stack/languages/golang/encrypt/internal/testusers" + "github.com/cipherstash/stack/languages/golang/encrypt/value" "github.com/cipherstash/stack/languages/golang/internal/record" - "github.com/cipherstash/vitaminc/bindings/go/vcvalue" ) // The query fixture holds the guest's query exports to the Rust results: @@ -96,7 +96,7 @@ func readQueryFixture(t *testing.T) queryFixture { // objects as maps, lists as []any. func wireJSON(v any) any { switch v := v.(type) { - case vcvalue.Object: + case value.Object: out := make(map[string]any, len(v)) for _, f := range v { out[f.Key] = wireJSON(f.Value) diff --git a/languages/golang/encrypt/read_conformance_test.go b/languages/golang/encrypt/read_conformance_test.go index 4244446bc..5772dbd5c 100644 --- a/languages/golang/encrypt/read_conformance_test.go +++ b/languages/golang/encrypt/read_conformance_test.go @@ -11,8 +11,8 @@ import ( "testing" "github.com/cipherstash/stack/languages/golang/encrypt" + "github.com/cipherstash/stack/languages/golang/encrypt/value" "github.com/cipherstash/stack/languages/golang/internal/record" - "github.com/cipherstash/vitaminc/bindings/go/vcvalue" ) type readDeclaration struct { @@ -55,10 +55,10 @@ func readTree(stored []record.Sealed, contextField bool, contextName string) []a for i, row := range stored { fields := map[string]any{} if contextField { - fields[contextName] = map[string]any{"passthrough": vcvalue.Plain{V: row[contextName].Context}} + fields[contextName] = map[string]any{"passthrough": value.Plain{V: row[contextName].Context}} } if field, ok := row["value"]; ok { - fields["value"] = map[string]any{"c": encrypt.Ciphertext(field.Ciphertext), "eq": vcvalue.Plain{V: field.Terms[record.Equality]}} + fields["value"] = map[string]any{"c": encrypt.Ciphertext(field.Ciphertext), "eq": value.Plain{V: field.Terms[record.Equality]}} } batch[i] = fields } @@ -80,7 +80,7 @@ func mutateRead(t *testing.T, batch []any, c readCase) { if i < 0 || i >= len(batch) { t.Fatal("mutation row out of range") } - plain := vcvalue.Plain{V: int32(34)} + plain := value.Plain{V: int32(34)} if c.Mutation.Kind == "row_plain" { batch[i] = plain return diff --git a/languages/golang/encrypt/records.go b/languages/golang/encrypt/records.go index 256137668..edea57acc 100644 --- a/languages/golang/encrypt/records.go +++ b/languages/golang/encrypt/records.go @@ -4,11 +4,12 @@ import ( "context" "errors" "fmt" + "reflect" + "github.com/cipherstash/stack/languages/golang/encrypt/frame" + "github.com/cipherstash/stack/languages/golang/encrypt/value" "github.com/cipherstash/stack/languages/golang/internal/guest" "github.com/cipherstash/stack/languages/golang/internal/record" - "github.com/cipherstash/vitaminc/bindings/go/vcffi" - "github.com/cipherstash/vitaminc/bindings/go/vcvalue" ) // The record path: what generated code calls through encrypt/gensupport. @@ -64,14 +65,14 @@ func (cph *Cipher) Seal(ctx context.Context, plan *record.Plan, rows []record.So } } } - encodedSource, err := vcffi.Marshal(source) + encodedSource, err := frame.Marshal(source) if err != nil { return nil, fmt.Errorf("%w: %v", ErrEncoding, err) } // The source is plaintext: its transport copy is wiped once it is in // the guest, and the guest wipes its own copy before it returns. defer wipe(encodedSource) - encodedPlan, err := vcffi.Marshal(p.Wire()) + encodedPlan, err := frame.Marshal(p.Wire()) if err != nil { return nil, fmt.Errorf("%w: %v", ErrEncoding, err) } @@ -158,14 +159,14 @@ func (cph *Cipher) derive(ctx context.Context, plan *record.Plan, field string, if !declared { return nil, fmt.Errorf("%w: field %q declares no %q index", ErrEncoding, field, output) } - encodedValue, err := vcffi.Marshal(value) + encodedValue, err := frame.Marshal(value) if err != nil { return nil, fmt.Errorf("%w: %v", ErrEncoding, err) } // The probe value is plaintext: its transport copy is wiped once it is // in the guest. defer wipe(encodedValue) - encodedContext, err := vcffi.Marshal(p.FieldContext(*f)) + encodedContext, err := frame.Marshal(p.FieldContext(*f)) if err != nil { return nil, fmt.Errorf("%w: %v", ErrEncoding, err) } @@ -297,7 +298,7 @@ func (cph *Cipher) plan(plan *record.Plan) (*record.Plan, error) { // the plan has one, then the plan's fields, in plan order, each with its // value. Unknown fields and missing required values are refused before anything // is sent; SQL-null fields may be omitted. -func sourceRow(p *record.Plan, row record.Source) (vcvalue.Object, error) { +func sourceRow(p *record.Plan, row record.Source) (value.Object, error) { expected := len(p.Fields) if p.ContextField != "" { expected++ @@ -308,7 +309,7 @@ func sourceRow(p *record.Plan, row record.Source) (vcvalue.Object, error) { return nil, sourceDiagnostic("unknown_field", name, fmt.Sprintf("the plan has no field %q", name)) } } - out := make(vcvalue.Object, 0, expected) + out := make(value.Object, 0, expected) if p.ContextField != "" { v, ok := row[p.ContextField] if !ok { @@ -317,7 +318,7 @@ func sourceRow(p *record.Plan, row record.Source) (vcvalue.Object, error) { if _, isString := v.(string); !isString { return nil, fmt.Errorf("the context field %q holds a %T, not a string", p.ContextField, v) } - out = append(out, vcvalue.Field{Key: p.ContextField, Value: v}) + out = append(out, value.Field{Key: p.ContextField, Value: v}) } for _, f := range p.Fields { v, ok := row[f.Name] @@ -328,11 +329,47 @@ func sourceRow(p *record.Plan, row record.Source) (vcvalue.Object, error) { if !ok { return nil, sourceDiagnostic("field_missing", f.Name, fmt.Sprintf("no value for field %q", f.Name)) } - out = append(out, vcvalue.Field{Key: f.Name, Value: v}) + if f.Kind == record.Untyped && nilEncryptable(v) { + // The codec writes a nil Encryptable as the null of one byte. + // The field declares no type, so the engine has no width to pad + // the null to. The length of the stored value would then show + // that it is a null. + return nil, sourceDiagnostic("field_type", f.Name, fmt.Sprintf("field %q has no declared type, so a nil %T would be stored shorter than a value; declare the field's type", f.Name, v)) + } + out = append(out, value.Field{Key: f.Name, Value: v}) } return out, nil } +// encryptableType is Encryptable's reflect.Type. +var encryptableType = reflect.TypeFor[Encryptable]() + +// nilEncryptable reports whether v is a nil pointer to a type that +// implements Encryptable, through any number of pointers. The codec writes +// such a pointer as the null of one byte, whatever the type writes for a +// value. +func nilEncryptable(v any) bool { + rv := reflect.ValueOf(v) + for depth := 0; rv.IsValid() && rv.Kind() == reflect.Pointer && depth < 128; depth++ { + if !rv.IsNil() { + rv = rv.Elem() + continue + } + t := rv.Type() + for range 128 { + if t.Implements(encryptableType) { + return true + } + if t.Kind() != reflect.Pointer { + return false + } + t = t.Elem() + } + return false + } + return false +} + // sealedOf lifts one decoded record node into the per-field outputs. func sealedOf(p *record.Plan, node any) (record.Sealed, error) { fields, ok := node.(map[string]any) @@ -355,7 +392,7 @@ func sealedOf(p *record.Plan, node any) (record.Sealed, error) { if len(om) != 1 { return nil, fmt.Errorf("the context field %q came back with %d outputs", name, len(om)) } - plain, ok := om[string(record.Passthrough)].(vcvalue.Plain) + plain, ok := om[string(record.Passthrough)].(value.Plain) if !ok { return nil, fmt.Errorf("the context field %q did not come back as a passthrough", name) } @@ -411,7 +448,7 @@ func sealedOf(p *record.Plan, node any) (record.Sealed, error) { // termBytes unwraps a term node: a passthrough carrying the term's bytes. func termBytes(node any) ([]byte, error) { - plain, ok := node.(vcvalue.Plain) + plain, ok := node.(value.Plain) if !ok { return nil, fmt.Errorf("term node is %T, not a passthrough", node) } @@ -447,7 +484,7 @@ func (c *Client) open(ctx context.Context, opts callOptions, p *record.Plan, rec if !ok || outputs.Context == "" { return nil, fmt.Errorf("%w: row %d, field %q", errNoContext, i, p.ContextField) } - tree[p.ContextField] = map[string]any{string(record.Passthrough): vcvalue.Plain{V: outputs.Context}} + tree[p.ContextField] = map[string]any{string(record.Passthrough): value.Plain{V: outputs.Context}} } for _, f := range p.Fields { if !f.HasCiphertext() { @@ -466,7 +503,7 @@ func (c *Client) open(ctx context.Context, opts callOptions, p *record.Plan, rec // The EQL value rides as a passthrough byte node, the shape // the engine stored it in; opening it runs the EQL type's own // decryption on the ciphertext inside the JSON. - tree[f.Name] = map[string]any{record.EQLKey: vcvalue.Plain{V: append([]byte(nil), outputs.EQL...)}} + tree[f.Name] = map[string]any{record.EQLKey: value.Plain{V: append([]byte(nil), outputs.EQL...)}} continue } if !ok || outputs.Ciphertext == nil { @@ -493,7 +530,7 @@ func (c *Client) openTree(ctx context.Context, opts callOptions, p *record.Plan, // encoder refuses a repeated key, so a test that needs one feeds this // directly, and the guest's decoder is what refuses it. func (c *Client) openEncoded(ctx context.Context, call callOptions, p *record.Plan, encodedTree []byte, rows int) ([]record.Source, error) { - encodedPlan, err := vcffi.Marshal(p.Wire()) + encodedPlan, err := frame.Marshal(p.Wire()) if err != nil { return nil, fmt.Errorf("%w: %v", ErrEncoding, err) } @@ -533,7 +570,7 @@ func (c *Client) openEncoded(ctx context.Context, call callOptions, p *record.Pl } sources := make([]record.Source, len(items)) for i, item := range items { - obj, ok := item.(vcvalue.Object) + obj, ok := item.(value.Object) if !ok { return nil, guest.BadAnswer("se_decrypt_record", fmt.Errorf("record %d is not a map of fields", i)) } diff --git a/languages/golang/encrypt/step.go b/languages/golang/encrypt/step.go index a37085c1e..857dc29c8 100644 --- a/languages/golang/encrypt/step.go +++ b/languages/golang/encrypt/step.go @@ -6,9 +6,9 @@ import ( "fmt" "sync" + "github.com/cipherstash/stack/languages/golang/encrypt/frame" + "github.com/cipherstash/stack/languages/golang/encrypt/value" "github.com/cipherstash/stack/languages/golang/internal/guest" - "github.com/cipherstash/vitaminc/bindings/go/vcffi" - "github.com/cipherstash/vitaminc/bindings/go/vcvalue" ) // The step loop. The guest never waits on the network: an export that @@ -92,11 +92,11 @@ func (inst *instance) takeIO(ctx context.Context) (*ioStep, error) { // "headers", "body"}, ...]}`. Every byte slice the decoder returns is its // own copy. func decodeStep(raw []byte) (*ioStep, error) { - decoded, err := vcffi.Unmarshal(raw) + decoded, err := frame.Unmarshal(raw) if err != nil { return nil, guest.BadAnswer("se_io", fmt.Errorf("%w: %w", errStepMalformed, err)) } - obj, ok := decoded.(vcvalue.Object) + obj, ok := decoded.(value.Object) if !ok { return nil, errMalformedStep } @@ -138,7 +138,7 @@ func decodeStep(raw []byte) (*ioStep, error) { } func decodeRequest(item any) (ioRequest, bool) { - obj, ok := item.(vcvalue.Object) + obj, ok := item.(value.Object) if !ok { return ioRequest{}, false } @@ -230,11 +230,11 @@ func (t *transport) performStep(ctx context.Context, step *ioStep) ([]byte, erro if body == nil { body = []byte{} } - responses = append(responses, vcvalue.Object{ + responses = append(responses, value.Object{ {Key: "status", Value: status}, {Key: "headers", Value: headers}, {Key: "body", Value: body}, }) } - return vcffi.Marshal(responses) + return frame.Marshal(responses) } diff --git a/languages/golang/encrypt/step_parallel_test.go b/languages/golang/encrypt/step_parallel_test.go index fb14462a4..4ca1b34cf 100644 --- a/languages/golang/encrypt/step_parallel_test.go +++ b/languages/golang/encrypt/step_parallel_test.go @@ -12,8 +12,8 @@ import ( "testing" "time" - "github.com/cipherstash/vitaminc/bindings/go/vcffi" - "github.com/cipherstash/vitaminc/bindings/go/vcvalue" + "github.com/cipherstash/stack/languages/golang/encrypt/frame" + "github.com/cipherstash/stack/languages/golang/encrypt/value" ) // A step's requests are performed at the same time, and their responses @@ -158,7 +158,7 @@ func okResponse(body string) *http.Response { // body, in order. func responseBodies(t *testing.T, encoded []byte) []string { t.Helper() - decoded, err := vcffi.Unmarshal(encoded) + decoded, err := frame.Unmarshal(encoded) if err != nil { t.Fatal(err) } @@ -168,7 +168,7 @@ func responseBodies(t *testing.T, encoded []byte) []string { } bodies := make([]string, len(list)) for i, item := range list { - obj, ok := item.(vcvalue.Object) + obj, ok := item.(value.Object) if !ok { t.Fatalf("response %d is %T, want an object", i, item) } diff --git a/languages/golang/encrypt/step_test.go b/languages/golang/encrypt/step_test.go index 867d50fb6..22656e015 100644 --- a/languages/golang/encrypt/step_test.go +++ b/languages/golang/encrypt/step_test.go @@ -17,9 +17,9 @@ import ( "testing" "time" + "github.com/cipherstash/stack/languages/golang/encrypt/frame" + "github.com/cipherstash/stack/languages/golang/encrypt/value" "github.com/cipherstash/stack/languages/golang/internal/guest" - "github.com/cipherstash/vitaminc/bindings/go/vcffi" - "github.com/cipherstash/vitaminc/bindings/go/vcvalue" ) // The step loop, driven hermetically: the guest's init pauses on its @@ -331,14 +331,14 @@ func TestARefusedRequestIsWiped(t *testing.T) { for _, missing := range []string{"method", "url"} { headers := []byte("authorization: Bearer stub-token") body := []byte("wrapped key") - var obj vcvalue.Object + var obj value.Object if missing != "method" { - obj = append(obj, vcvalue.Field{Key: "method", Value: "POST"}) + obj = append(obj, value.Field{Key: "method", Value: "POST"}) } if missing != "url" { - obj = append(obj, vcvalue.Field{Key: "url", Value: "https://zerokms.example/keys"}) + obj = append(obj, value.Field{Key: "url", Value: "https://zerokms.example/keys"}) } - obj = append(obj, vcvalue.Field{Key: "headers", Value: headers}, vcvalue.Field{Key: "body", Value: body}) + obj = append(obj, value.Field{Key: "headers", Value: headers}, value.Field{Key: "body", Value: body}) if _, ok := decodeRequest(obj); ok { t.Fatalf("a request with no %s was accepted", missing) } @@ -352,7 +352,7 @@ func TestARefusedRequestIsWiped(t *testing.T) { func marshalStep(t *testing.T, v any) []byte { t.Helper() - b, err := vcffi.Marshal(v) + b, err := frame.Marshal(v) if err != nil { t.Fatal(err) } diff --git a/languages/golang/encrypt/targets_test.go b/languages/golang/encrypt/targets_test.go index e0a35a4d5..7fef1db91 100644 --- a/languages/golang/encrypt/targets_test.go +++ b/languages/golang/encrypt/targets_test.go @@ -6,37 +6,37 @@ import ( "strings" "testing" + "github.com/cipherstash/stack/languages/golang/encrypt/frame" + "github.com/cipherstash/stack/languages/golang/encrypt/value" "github.com/cipherstash/stack/languages/golang/internal/guest" "github.com/cipherstash/stack/languages/golang/internal/record" - "github.com/cipherstash/vitaminc/bindings/go/vcffi" - "github.com/cipherstash/vitaminc/bindings/go/vcvalue" ) // The se_targets entry shape is shared with eql-bindings' serialiser; this // reader is strict about it, so the next build's entries are read whole or // refused, never half-read. func TestParseTargetsReadsEachEntry(t *testing.T) { - entry := func(fields ...vcvalue.Field) vcvalue.Object { return vcvalue.Object(fields) } + entry := func(fields ...value.Field) value.Object { return value.Object(fields) } textEq := entry( - vcvalue.Field{Key: "name", Value: "TextEq"}, vcvalue.Field{Key: "family", Value: "Text"}, vcvalue.Field{Key: "suffix", Value: "Eq"}, - vcvalue.Field{Key: "plaintext", Value: "string"}, vcvalue.Field{Key: "sql_domain", Value: "eql_v4_text_eq"}, - vcvalue.Field{Key: "indexes", Value: []any{"eq"}}, vcvalue.Field{Key: "query", Value: "TextEqQuery"}, - vcvalue.Field{Key: "query_sql_domain", Value: "eql_v4.query_text_eq"}, vcvalue.Field{Key: "producible", Value: true}, vcvalue.Field{Key: "reason", Value: nil}, - vcvalue.Field{Key: "operators", Value: []any{operator("eq", "exact", "one", "eq")}}, + value.Field{Key: "name", Value: "TextEq"}, value.Field{Key: "family", Value: "Text"}, value.Field{Key: "suffix", Value: "Eq"}, + value.Field{Key: "plaintext", Value: "string"}, value.Field{Key: "sql_domain", Value: "eql_v4_text_eq"}, + value.Field{Key: "indexes", Value: []any{"eq"}}, value.Field{Key: "query", Value: "TextEqQuery"}, + value.Field{Key: "query_sql_domain", Value: "eql_v4.query_text_eq"}, value.Field{Key: "producible", Value: true}, value.Field{Key: "reason", Value: nil}, + value.Field{Key: "operators", Value: []any{operator("eq", "exact", "one", "eq")}}, ) notYet := entry( - vcvalue.Field{Key: "name", Value: "JSON"}, vcvalue.Field{Key: "family", Value: "JSON"}, vcvalue.Field{Key: "suffix", Value: ""}, - vcvalue.Field{Key: "plaintext", Value: nil}, vcvalue.Field{Key: "sql_domain", Value: "eql_v4_json"}, - vcvalue.Field{Key: "indexes", Value: []any{"json"}}, vcvalue.Field{Key: "query", Value: nil}, vcvalue.Field{Key: "query_sql_domain", Value: nil}, - vcvalue.Field{Key: "producible", Value: false}, vcvalue.Field{Key: "reason", Value: "the JSON index is a new operation in the engine"}, - vcvalue.Field{Key: "operators", Value: []any{}}, + value.Field{Key: "name", Value: "JSON"}, value.Field{Key: "family", Value: "JSON"}, value.Field{Key: "suffix", Value: ""}, + value.Field{Key: "plaintext", Value: nil}, value.Field{Key: "sql_domain", Value: "eql_v4_json"}, + value.Field{Key: "indexes", Value: []any{"json"}}, value.Field{Key: "query", Value: nil}, value.Field{Key: "query_sql_domain", Value: nil}, + value.Field{Key: "producible", Value: false}, value.Field{Key: "reason", Value: "the JSON index is a new operation in the engine"}, + value.Field{Key: "operators", Value: []any{}}, ) ordered := entry( - vcvalue.Field{Key: "name", Value: "IntegerOrdOre"}, vcvalue.Field{Key: "plaintext", Value: "int64"}, - vcvalue.Field{Key: "indexes", Value: []any{"ore"}}, vcvalue.Field{Key: "producible", Value: true}, - vcvalue.Field{Key: "operators", Value: []any{operator("lt", "exact", "one", "ore"), operator("between", "exact", "pair", "ore"), operator("matches", "probabilistic", "one", "match")}}, + value.Field{Key: "name", Value: "IntegerOrdOre"}, value.Field{Key: "plaintext", Value: "int64"}, + value.Field{Key: "indexes", Value: []any{"ore"}}, value.Field{Key: "producible", Value: true}, + value.Field{Key: "operators", Value: []any{operator("lt", "exact", "one", "ore"), operator("between", "exact", "pair", "ore"), operator("matches", "probabilistic", "one", "match")}}, ) - got, err := parseTargets(vcvalue.Object{{Key: "targets", Value: []any{textEq, notYet, ordered}}}) + got, err := parseTargets(value.Object{{Key: "targets", Value: []any{textEq, notYet, ordered}}}) if err != nil { t.Fatal(err) } @@ -53,38 +53,38 @@ func TestParseTargetsReadsEachEntry(t *testing.T) { if !reflect.DeepEqual(got, want) { t.Fatalf("parseTargets =\n%+v\nwant\n%+v", got, want) } - empty, err := parseTargets(vcvalue.Object{{Key: "targets", Value: []any{}}}) + empty, err := parseTargets(value.Object{{Key: "targets", Value: []any{}}}) if err != nil || len(empty) != 0 { t.Fatalf("empty list: %v %v", empty, err) } for name, bad := range map[string]any{ "not an object": "targets", - "another key": vcvalue.Object{{Key: "types", Value: []any{}}}, - "list not a list": vcvalue.Object{{Key: "targets", Value: "x"}}, - "entry not object": vcvalue.Object{{Key: "targets", Value: []any{"TextEq"}}}, - "numeric plaintext": vcvalue.Object{{Key: "targets", Value: []any{entry(vcvalue.Field{Key: "name", Value: "TextEq"}, vcvalue.Field{Key: "plaintext", Value: int64(1)}, vcvalue.Field{Key: "indexes", Value: []any{}}, vcvalue.Field{Key: "producible", Value: true})}}}, - "misspelled kind": vcvalue.Object{{Key: "targets", Value: []any{entry(vcvalue.Field{Key: "name", Value: "TextEq"}, vcvalue.Field{Key: "plaintext", Value: "strng"}, vcvalue.Field{Key: "indexes", Value: []any{}}, vcvalue.Field{Key: "producible", Value: true})}}}, - "misspelled index": vcvalue.Object{{Key: "targets", Value: []any{entry(vcvalue.Field{Key: "name", Value: "TextEq"}, vcvalue.Field{Key: "indexes", Value: []any{"equality"}}, vcvalue.Field{Key: "producible", Value: true})}}}, - "unknown key": vcvalue.Object{{Key: "targets", Value: []any{entry(vcvalue.Field{Key: "name", Value: "TextEq"}, vcvalue.Field{Key: "kind", Value: "string"}, vcvalue.Field{Key: "indexes", Value: []any{}}, vcvalue.Field{Key: "producible", Value: true})}}}, - "no name": vcvalue.Object{{Key: "targets", Value: []any{entry(vcvalue.Field{Key: "indexes", Value: []any{}}, vcvalue.Field{Key: "producible", Value: true})}}}, - "no producible": vcvalue.Object{{Key: "targets", Value: []any{entry(vcvalue.Field{Key: "name", Value: "TextEq"}, vcvalue.Field{Key: "indexes", Value: []any{}})}}}, - "index not string": vcvalue.Object{{Key: "targets", Value: []any{entry(vcvalue.Field{Key: "name", Value: "TextEq"}, vcvalue.Field{Key: "indexes", Value: []any{int64(1)}}, vcvalue.Field{Key: "producible", Value: true})}}}, - "producible string": vcvalue.Object{{Key: "targets", Value: []any{entry(vcvalue.Field{Key: "name", Value: "TextEq"}, vcvalue.Field{Key: "indexes", Value: []any{}}, vcvalue.Field{Key: "producible", Value: "yes"})}}}, - "key twice": vcvalue.Object{{Key: "targets", Value: []any{entry(vcvalue.Field{Key: "name", Value: "A"}, vcvalue.Field{Key: "name", Value: "B"}, vcvalue.Field{Key: "indexes", Value: []any{}}, vcvalue.Field{Key: "producible", Value: true})}}}, - "no operators": vcvalue.Object{{Key: "targets", Value: []any{entry(vcvalue.Field{Key: "name", Value: "TextEq"}, vcvalue.Field{Key: "indexes", Value: []any{}}, vcvalue.Field{Key: "producible", Value: true})}}}, + "another key": value.Object{{Key: "types", Value: []any{}}}, + "list not a list": value.Object{{Key: "targets", Value: "x"}}, + "entry not object": value.Object{{Key: "targets", Value: []any{"TextEq"}}}, + "numeric plaintext": value.Object{{Key: "targets", Value: []any{entry(value.Field{Key: "name", Value: "TextEq"}, value.Field{Key: "plaintext", Value: int64(1)}, value.Field{Key: "indexes", Value: []any{}}, value.Field{Key: "producible", Value: true})}}}, + "misspelled kind": value.Object{{Key: "targets", Value: []any{entry(value.Field{Key: "name", Value: "TextEq"}, value.Field{Key: "plaintext", Value: "strng"}, value.Field{Key: "indexes", Value: []any{}}, value.Field{Key: "producible", Value: true})}}}, + "misspelled index": value.Object{{Key: "targets", Value: []any{entry(value.Field{Key: "name", Value: "TextEq"}, value.Field{Key: "indexes", Value: []any{"equality"}}, value.Field{Key: "producible", Value: true})}}}, + "unknown key": value.Object{{Key: "targets", Value: []any{entry(value.Field{Key: "name", Value: "TextEq"}, value.Field{Key: "kind", Value: "string"}, value.Field{Key: "indexes", Value: []any{}}, value.Field{Key: "producible", Value: true})}}}, + "no name": value.Object{{Key: "targets", Value: []any{entry(value.Field{Key: "indexes", Value: []any{}}, value.Field{Key: "producible", Value: true})}}}, + "no producible": value.Object{{Key: "targets", Value: []any{entry(value.Field{Key: "name", Value: "TextEq"}, value.Field{Key: "indexes", Value: []any{}})}}}, + "index not string": value.Object{{Key: "targets", Value: []any{entry(value.Field{Key: "name", Value: "TextEq"}, value.Field{Key: "indexes", Value: []any{int64(1)}}, value.Field{Key: "producible", Value: true})}}}, + "producible string": value.Object{{Key: "targets", Value: []any{entry(value.Field{Key: "name", Value: "TextEq"}, value.Field{Key: "indexes", Value: []any{}}, value.Field{Key: "producible", Value: "yes"})}}}, + "key twice": value.Object{{Key: "targets", Value: []any{entry(value.Field{Key: "name", Value: "A"}, value.Field{Key: "name", Value: "B"}, value.Field{Key: "indexes", Value: []any{}}, value.Field{Key: "producible", Value: true})}}}, + "no operators": value.Object{{Key: "targets", Value: []any{entry(value.Field{Key: "name", Value: "TextEq"}, value.Field{Key: "indexes", Value: []any{}}, value.Field{Key: "producible", Value: true})}}}, "operators not list": withOperators("eq"), "operator not object": withOperators([]any{"eq"}), "unknown fidelity": withOperators([]any{operator("eq", "approximate", "one", "eq")}), "unknown arity": withOperators([]any{operator("eq", "exact", "three", "eq")}), "unknown op index": withOperators([]any{operator("eq", "exact", "one", "equality")}), - "unknown op input": withOperators([]any{append(operator("eq", "exact", "one", "eq")[:4], vcvalue.Field{Key: "input", Value: "path_value"})}), + "unknown op input": withOperators([]any{append(operator("eq", "exact", "one", "eq")[:4], value.Field{Key: "input", Value: "path_value"})}), "no op name": withOperators([]any{operator("", "exact", "one", "eq")}), "unknown operator": withOperators([]any{operator("like", "exact", "one", "eq")}), "operator case": withOperators([]any{operator("Eq", "exact", "one", "eq")}), - "op key missing": withOperators([]any{vcvalue.Object{{Key: "operator", Value: "eq"}}}), - "op unknown key": withOperators([]any{append(operator("eq", "exact", "one", "eq"), vcvalue.Field{Key: "case", Value: "insensitive"})}), - "op key twice": withOperators([]any{append(operator("eq", "exact", "one", "eq"), vcvalue.Field{Key: "index", Value: "eq"})}), - "op value not text": withOperators([]any{vcvalue.Object{{Key: "operator", Value: int64(1)}, {Key: "fidelity", Value: "exact"}, {Key: "arity", Value: "one"}, {Key: "index", Value: "eq"}, {Key: "input", Value: "value"}}}), + "op key missing": withOperators([]any{value.Object{{Key: "operator", Value: "eq"}}}), + "op unknown key": withOperators([]any{append(operator("eq", "exact", "one", "eq"), value.Field{Key: "case", Value: "insensitive"})}), + "op key twice": withOperators([]any{append(operator("eq", "exact", "one", "eq"), value.Field{Key: "index", Value: "eq"})}), + "op value not text": withOperators([]any{value.Object{{Key: "operator", Value: int64(1)}, {Key: "fidelity", Value: "exact"}, {Key: "arity", Value: "one"}, {Key: "index", Value: "eq"}, {Key: "input", Value: "value"}}}), } { _, err := parseTargets(bad) if !errors.Is(err, ErrInternal) { @@ -102,8 +102,8 @@ func TestParseTargetsReadsEachEntry(t *testing.T) { want string }{ {"secret", "it is a string, not an object"}, - {vcvalue.Object{{Key: "targets", Value: "secret"}}, "targets is a string, not a list"}, - {vcvalue.Object{{Key: "targets", Value: []any{"secret"}}}, "target 0 is a string, not an object"}, + {value.Object{{Key: "targets", Value: "secret"}}, "targets is a string, not a list"}, + {value.Object{{Key: "targets", Value: []any{"secret"}}}, "target 0 is a string, not an object"}, {withOperators([]any{"secret"}), "target 0: operator 0 is a string, not an object"}, } { _, err := parseTargets(tc.answer) @@ -114,18 +114,18 @@ func TestParseTargetsReadsEachEntry(t *testing.T) { } // operator is one se_targets operators entry. -func operator(name, fidelity, arity, index string) vcvalue.Object { +func operator(name, fidelity, arity, index string) value.Object { input := "value" if arity == "pair" { input = "pair" } - return vcvalue.Object{{Key: "operator", Value: name}, {Key: "fidelity", Value: fidelity}, {Key: "arity", Value: arity}, {Key: "index", Value: index}, {Key: "input", Value: input}} + return value.Object{{Key: "operator", Value: name}, {Key: "fidelity", Value: fidelity}, {Key: "arity", Value: arity}, {Key: "index", Value: index}, {Key: "input", Value: input}} } // withOperators is a well-formed TextEq entry whose operators are value. -func withOperators(value any) vcvalue.Object { - return vcvalue.Object{{Key: "targets", Value: []any{vcvalue.Object{ - {Key: "name", Value: "TextEq"}, {Key: "indexes", Value: []any{}}, {Key: "producible", Value: true}, {Key: "operators", Value: value}, +func withOperators(val any) value.Object { + return value.Object{{Key: "targets", Value: []any{value.Object{ + {Key: "name", Value: "TextEq"}, {Key: "indexes", Value: []any{}}, {Key: "producible", Value: true}, {Key: "operators", Value: val}, }}}} } @@ -133,8 +133,8 @@ func withOperators(value any) vcvalue.Object { // operator, fidelity or index the catalog would refuse is refused here too, // and every name the engine writes is read by both. func TestParseQueryTermTakesOnlyWhatTheEngineWrites(t *testing.T) { - term := func(operator, fidelity, index string) vcvalue.Object { - return vcvalue.Object{ + term := func(operator, fidelity, index string) value.Object { + return value.Object{ {Key: "operator", Value: operator}, {Key: "fidelity", Value: fidelity}, {Key: "index", Value: index}, {Key: "domain", Value: nil}, {Key: "encoding", Value: "bytes"}, {Key: "term", Value: []byte{1, 2}}, } @@ -165,7 +165,7 @@ func TestParseQueryTermTakesOnlyWhatTheEngineWrites(t *testing.T) { t.Errorf("parseQueryTerm(%T) = %v, want %q", tc.answer, err, tc.want) } } - for name, bad := range map[string]vcvalue.Object{ + for name, bad := range map[string]value.Object{ "unknown operator": term("like", "exact", "eq"), "operator case": term("Eq", "exact", "eq"), "unknown fidelity": term("eq", "approximate", "eq"), @@ -182,13 +182,13 @@ func TestParseQueryTermTakesOnlyWhatTheEngineWrites(t *testing.T) { // writes them; a term that mixes them is a wire bug, refused. func TestParseQueryTermRefusesAMixedShape(t *testing.T) { domain := "eql_v4.query_json" - shaped := func(encoding string, domain any, term any) vcvalue.Object { - return vcvalue.Object{ + shaped := func(encoding string, domain any, term any) value.Object { + return value.Object{ {Key: "operator", Value: "contains"}, {Key: "fidelity", Value: "exact"}, {Key: "index", Value: "json"}, {Key: "domain", Value: domain}, {Key: "encoding", Value: encoding}, {Key: "term", Value: term}, } } - for name, ok := range map[string]vcvalue.Object{ + for name, ok := range map[string]value.Object{ "bytes": shaped("bytes", nil, []byte{1}), "bytes range": shaped("bytes", nil, []any{[]byte{1}, []byte{2}}), "eql": shaped("eql", domain, []byte{1}), @@ -201,7 +201,7 @@ func TestParseQueryTermRefusesAMixedShape(t *testing.T) { t.Errorf("%s: %v", name, err) } } - for name, bad := range map[string]vcvalue.Object{ + for name, bad := range map[string]value.Object{ "text array as one string": shaped("text_array", "text[]", "dA=="), "text as a list": shaped("text", "text", []any{"dA=="}), "eql with no domain": shaped("eql", nil, []byte{1}), @@ -270,18 +270,18 @@ func TestVerifyAndLimitAnswersSayWhatTheyAre(t *testing.T) { // For an index, a producible flag, or a name of the wrong kind, the error // names the kind of value that it is. func TestATargetFieldOfTheWrongKindSaysWhatItIs(t *testing.T) { - entry := func(fields ...vcvalue.Field) vcvalue.Object { - return vcvalue.Object{{Key: "targets", Value: []any{vcvalue.Object(fields)}}} + entry := func(fields ...value.Field) value.Object { + return value.Object{{Key: "targets", Value: []any{value.Object(fields)}}} } - name := vcvalue.Field{Key: "name", Value: "TextEq"} + name := value.Field{Key: "name", Value: "TextEq"} for _, tc := range []struct { - answer vcvalue.Object + answer value.Object want string }{ - {entry(name, vcvalue.Field{Key: "indexes", Value: "secret"}, vcvalue.Field{Key: "producible", Value: true}), "indexes is a string, not a list"}, - {entry(name, vcvalue.Field{Key: "indexes", Value: []any{int64(1)}}, vcvalue.Field{Key: "producible", Value: true}), "an index is a number, not a string"}, - {entry(name, vcvalue.Field{Key: "indexes", Value: []any{}}, vcvalue.Field{Key: "producible", Value: "secret"}), "producible is a string, not a bool"}, - {entry(vcvalue.Field{Key: "name", Value: int64(1)}), "name is a number, not a string"}, + {entry(name, value.Field{Key: "indexes", Value: "secret"}, value.Field{Key: "producible", Value: true}), "indexes is a string, not a list"}, + {entry(name, value.Field{Key: "indexes", Value: []any{int64(1)}}, value.Field{Key: "producible", Value: true}), "an index is a number, not a string"}, + {entry(name, value.Field{Key: "indexes", Value: []any{}}, value.Field{Key: "producible", Value: "secret"}), "producible is a string, not a bool"}, + {entry(value.Field{Key: "name", Value: int64(1)}), "name is a number, not a string"}, } { _, err := parseTargets(tc.answer) if err == nil || !strings.Contains(err.Error(), tc.want) || strings.Contains(err.Error(), "secret") { @@ -293,7 +293,7 @@ func TestATargetFieldOfTheWrongKindSaysWhatItIs(t *testing.T) { // mustMarshal returns v as transport bytes. func mustMarshal(t *testing.T, v any) []byte { t.Helper() - out, err := vcffi.Marshal(v) + out, err := frame.Marshal(v) if err != nil { t.Fatal(err) } @@ -309,7 +309,7 @@ func TestAnOpenedChildOfTheWrongShapeNamesNoKind(t *testing.T) { want string }{ {"secret", `it is not an object with "json" and either "key" or "index"`}, - {vcvalue.Object{{Key: "key", Value: "k"}, {Key: "json", Value: int64(7)}}, `the value at "json" is not text, an integer, or bytes`}, + {value.Object{{Key: "key", Value: "k"}, {Key: "json", Value: int64(7)}}, `the value at "json" is not text, an integer, or bytes`}, } { _, err := jsonChildValue(tc.item) if err == nil || err.Error() != tc.want { diff --git a/languages/golang/encrypt/testclient.go b/languages/golang/encrypt/testclient.go index 7fa3a3696..621b0b8d5 100644 --- a/languages/golang/encrypt/testclient.go +++ b/languages/golang/encrypt/testclient.go @@ -4,9 +4,9 @@ import ( "context" "fmt" + "github.com/cipherstash/stack/languages/golang/encrypt/frame" "github.com/cipherstash/stack/languages/golang/encrypt/internal/testclient" "github.com/cipherstash/stack/languages/golang/internal/guest" - "github.com/cipherstash/vitaminc/bindings/go/vcffi" ) // Package encrypttest builds its clients through this constructor. It is @@ -36,7 +36,7 @@ func seededClient(ctx context.Context, wasm []byte, seed [32]byte) (*Client, err return nil, err } c := newClient(inst, tr) - encoded, err := vcffi.Marshal(seed[:]) + encoded, err := frame.Marshal(seed[:]) if err != nil { _ = c.Close() return nil, err diff --git a/languages/golang/encrypt/typed_nil_test.go b/languages/golang/encrypt/typed_nil_test.go index a1020c126..e3476bd11 100644 --- a/languages/golang/encrypt/typed_nil_test.go +++ b/languages/golang/encrypt/typed_nil_test.go @@ -5,24 +5,28 @@ import ( "context" "errors" "reflect" + "strings" "testing" "time" "github.com/cipherstash/stack/languages/golang/encrypt" + "github.com/cipherstash/stack/languages/golang/encrypt/frame" "github.com/cipherstash/stack/languages/golang/internal/record" - "github.com/cipherstash/vitaminc/bindings/go/vcffi" ) -// A typed nil pointer on the two raw paths. Generated code passes a nil -// pointer through gensupport.Deref, which gives an untyped nil; the two -// paths that take a caller's value as it is are Cipher.Seal with a -// hand-built record.Source and Cipher.QueryTerm's input. There a -// (*int64)(nil) is not == nil, so it is sent, and vcffi, from vitaminc -// e9c3837b on (on main, in no Go tag yet), writes it as a typed null, -// padded to the width of an int64, where it wrote a one-byte null. These -// tests pin what the engine does with it: a typed null is a null to the -// engine, so each path answers a typed nil as it answers an untyped one, on -// a field of every null mode. +// These tests cover a typed nil pointer on the two paths that take a +// caller's value unchanged. Generated code passes a nil pointer through +// gensupport.Deref, and Deref returns an untyped nil. The two other paths +// are Cipher.Seal with a record.Source built by hand, and the input of +// Cipher.QueryTerm. +// +// On those two paths, a (*int64)(nil) is not equal to nil, so it is sent. +// The codec writes it as a typed null, padded to the width of an int64. An +// untyped nil is written as the null of one byte. +// +// The tests check what the engine does with a typed null. The engine treats +// a typed null as a null. Each path therefore handles a typed nil as it +// handles an untyped nil, for a field of every null mode. // typedNilPlan has one int64 field in each null mode and a timestamp field // that seals its nulls, so both encodings meet every answer the engine has. @@ -33,12 +37,14 @@ var typedNilPlan = &record.Plan{Context: []string{"typed_nil"}, Fields: []record {Name: "when", Kind: record.Timestamp, Outputs: []record.Output{record.Ciphertext, record.Equality}, Null: record.SealedNull}, }} -// The pinned vcffi behaviour itself, so the engine tests below are read -// against the bytes that reach it: a nil pointer to a fixed-width type is a -// typed null (tag 0x15, then the type, padded to the type's width), not the -// one-byte null an untyped nil is, and it decodes as nil like every null. +// This test checks the codec itself, so that the engine tests below can be +// read with the bytes that reach the engine in mind. A nil pointer to a +// fixed-width type is written as a typed null. The bytes are the tag 0x15, +// then the type, then padding to the width of the type. An untyped nil is +// written as the null of one byte. A typed null decodes as nil, as every +// null does. func TestANilFixedWidthPointerMarshalsAsATypedNull(t *testing.T) { - untyped, err := vcffi.Marshal(nil) + untyped, err := frame.Marshal(nil) if err != nil || !bytes.Equal(untyped, []byte{0x00}) { t.Fatalf("an untyped nil marshals as %x, %v; want the one-byte null", untyped, err) } @@ -50,21 +56,21 @@ func TestANilFixedWidthPointerMarshalsAsATypedNull(t *testing.T) { "*float64": {(*float64)(nil), 1.5}, "*time.Time": {(*time.Time)(nil), time.Unix(1_700_000_000, 0).UTC()}, } { - got, err := vcffi.Marshal(tc.nilPointer) + got, err := frame.Marshal(tc.nilPointer) if err != nil { t.Fatalf("%s: %v", name, err) } if bytes.Equal(got, untyped) || got[0] != 0x15 { t.Fatalf("%s: a nil pointer marshals as %x; want a typed null (tag 0x15)", name, got) } - value, err := vcffi.Marshal(tc.present) + value, err := frame.Marshal(tc.present) if err != nil { t.Fatal(err) } if len(got) != len(value) { t.Fatalf("%s: the typed null is %d bytes, a value %d; want them as long", name, len(got), len(value)) } - back, err := vcffi.Unmarshal(got) + back, err := frame.Unmarshal(got) if err != nil || back != nil { t.Fatalf("%s: the typed null decodes as %#v, %v; want nil", name, back, err) } @@ -204,3 +210,61 @@ func TestQueryTermReadsATypedNilAsANull(t *testing.T) { } } } + +// cents writes itself as an int64 count of cents: a value nine bytes long. +type cents int64 + +func (c cents) EncryptValue(enc encrypt.Encoder) error { + enc.Int64(int64(c)) + return nil +} + +// A nil pointer to an Encryptable is written as the null of one byte. A +// field with no declared type gives the engine no width to pad that null to. +// Seal therefore refuses a nil Encryptable for such a field, before anything +// is sent. Otherwise the stored null would be shorter than every value. +// +// Seal does not refuse the three other cases: +// +// - A field that declares its type pads the null. +// - A nil pointer to a built-in fixed-width type is written as a typed +// null. +// - A value that is present is written as itself. +func TestSealRefusesANilEncryptableOnAFieldWithNoType(t *testing.T) { + c := deterministicClient(t) + ctx := context.Background() + cipher := c.DefaultKeyset() + untyped := &record.Plan{Context: []string{"typed_nil"}, Fields: []record.Field{ + {Name: "v", Outputs: []record.Output{record.Ciphertext}}, + }} + for name, v := range map[string]any{ + "*cents": (*cents)(nil), + "**cents": (**cents)(nil), + "&nil": func() any { var p *cents; return &p }(), + } { + _, err := cipher.Seal(ctx, untyped, []record.Source{{"v": v}}) + if !errors.Is(err, encrypt.ErrEncoding) || !strings.Contains(err.Error(), "no declared type") { + t.Errorf("%s: Seal returned %v; want ErrEncoding for a nil Encryptable with no type", name, err) + } + } + for name, v := range map[string]any{ + "a value": cents(150), + "a pointer to one": func() any { c := cents(150); return &c }(), + "a nil *int64": (*int64)(nil), + "nil": nil, + } { + if _, err := cipher.Seal(ctx, untyped, []record.Source{{"v": v}}); err != nil && strings.Contains(err.Error(), "no declared type") { + t.Errorf("%s: refused as a nil Encryptable: %v", name, err) + } + } + typed := &record.Plan{Context: []string{"typed_nil"}, Fields: []record.Field{ + {Name: "v", Kind: record.Int64, Outputs: []record.Output{record.Ciphertext}, Null: record.SealedNull}, + }} + sealed, err := cipher.Seal(ctx, typed, []record.Source{{"v": (*cents)(nil)}, {"v": cents(150)}}) + if err != nil { + t.Fatalf("a nil Encryptable on a typed field: %v", err) + } + if len(sealed[0]["v"].Ciphertext) != len(sealed[1]["v"].Ciphertext) { + t.Fatalf("on a typed field a nil Encryptable seals to %d bytes, a value to %d", len(sealed[0]["v"].Ciphertext), len(sealed[1]["v"].Ciphertext)) + } +} diff --git a/languages/golang/encrypt/unit_test.go b/languages/golang/encrypt/unit_test.go index 021b81785..dd30bdebf 100644 --- a/languages/golang/encrypt/unit_test.go +++ b/languages/golang/encrypt/unit_test.go @@ -14,8 +14,8 @@ import ( "github.com/cipherstash/stack/languages/golang/internal/guest" - "github.com/cipherstash/vitaminc/bindings/go/vcffi" - "github.com/cipherstash/vitaminc/bindings/go/vcvalue" + "github.com/cipherstash/stack/languages/golang/encrypt/frame" + "github.com/cipherstash/stack/languages/golang/encrypt/value" ) // Pure Go: no guest needed. @@ -150,9 +150,9 @@ func TestTermsAndLeavesScanAndValue(t *testing.T) { func TestLeafSetKeepsStackEncryptLeavesDistinct(t *testing.T) { ct := map[string]any{ "a": Ciphertext{1}, - "c": otherLeaf{kind: vcffi.LeafEmptySeq, bytes: []byte{3}}, - "d": otherLeaf{kind: vcffi.LeafEmptyMap, bytes: []byte{4}}, - "p": vcvalue.Plain{V: "clear"}, + "c": otherLeaf{kind: frame.LeafEmptySeq, bytes: []byte{3}}, + "d": otherLeaf{kind: frame.LeafEmptyMap, bytes: []byte{4}}, + "p": value.Plain{V: "clear"}, } encoded, err := marshalCipherText(ct) if err != nil { @@ -165,13 +165,6 @@ func TestLeafSetKeepsStackEncryptLeavesDistinct(t *testing.T) { if !reflect.DeepEqual(back, ct) { t.Fatalf("round trip %#v", back) } - // A vitaminc leaf is not a stack-encrypt node. - if _, err := marshalCipherText(map[string]any{"a": vcvalue.Sealed{1}}); err == nil { - t.Fatal("vcvalue.Sealed accepted as a stack-encrypt leaf") - } - if _, err := vcffi.MarshalCipherText(vcffi.VCValueLeaves(), Ciphertext{1}); err == nil { - t.Fatal("encrypt.Ciphertext accepted as a vitaminc leaf") - } } // This package's sentinels are the shared table's: a packed status decodes diff --git a/languages/golang/encrypt/value/LICENSE b/languages/golang/encrypt/value/LICENSE new file mode 100644 index 000000000..2212a9966 --- /dev/null +++ b/languages/golang/encrypt/value/LICENSE @@ -0,0 +1,25 @@ +Copyright (c) 2024-2026 CipherStash Inc + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/languages/golang/encrypt/value/doc.go b/languages/golang/encrypt/value/doc.go new file mode 100644 index 000000000..704da829b --- /dev/null +++ b/languages/golang/encrypt/value/doc.go @@ -0,0 +1,19 @@ +// Package value declares the values that the Stack Encrypt Go SDK reads and +// writes, beside Go's own types: +// +// - The value types [Date], [Decimal], [Int128], [Uint128], [UUID], and +// [Timestamp], with their parse functions. +// - [Tagged], for a value of a logical type that this version does not +// know. +// - [Object] and [Field], for a decoded map. The fields are in the order +// they were encoded. +// - [Plain], for a passthrough value. A passthrough value is neither +// encrypted nor authenticated. +// +// Package encrypt names the value types too: encrypt.Date is the same type +// as value.Date. Package frame, the codec, reads and writes these types. +// +// The package imports nothing outside the standard library. It was vitaminc's +// Go package vcvalue (github.com/cipherstash/vitaminc/bindings/go/vcvalue), +// and keeps its MIT licence. +package value diff --git a/languages/golang/encrypt/value/model.go b/languages/golang/encrypt/value/model.go new file mode 100644 index 000000000..cb006c35d --- /dev/null +++ b/languages/golang/encrypt/value/model.go @@ -0,0 +1,30 @@ +package value + +// Plain marks a passthrough value. A passthrough value is neither encrypted +// nor authenticated, so use Plain only for a value that is not secret. +// +// To make a value passthrough, wrap it, as in Plain{V: id}. The encoder then +// writes the value through frame.Encoder.Passthrough and does not seal it. The +// codec never makes a value passthrough by itself. Only a Plain, or a direct +// call to frame.Encoder.Passthrough, does that. +// +// A passthrough value decodes as Plain{V: v}, where v is the decoded value. +// The caller can therefore tell which values were not encrypted. A decoded +// Plain encodes as a passthrough value again. +type Plain struct { + V any +} + +// Object is what a map decodes as: the map's fields, in the order they were +// encoded. The decoders return an Object and not a Go map, because a Go map +// has no order. Two decodes of the same bytes therefore give equal Objects. +// +// To encode a map, pass a struct or a Go map. Encode also accepts an Object +// that a decoder returned. +type Object []Field + +// Field is one entry of a decoded Object. +type Field struct { + Key string + Value any +} diff --git a/languages/golang/encrypt/value/scalars.go b/languages/golang/encrypt/value/scalars.go new file mode 100644 index 000000000..f275e2e84 --- /dev/null +++ b/languages/golang/encrypt/value/scalars.go @@ -0,0 +1,339 @@ +package value + +import ( + "errors" + "math/big" + "strings" + "time" +) + +var ( + ErrIntegerRange = errors.New("value: integer is outside its 128-bit range") + ErrInvalidDate = errors.New("value: invalid date") + ErrInvalidTimestamp = errors.New("value: invalid timestamp") + ErrInvalidDecimal = errors.New("value: invalid or out-of-range decimal") + ErrNonFiniteDecimal = errors.New("value: decimal must be finite") + ErrInvalidUUID = errors.New("value: invalid UUID") + ErrInvalidTagged = errors.New("value: a tagged value must be a physical scalar with a logical id that this version does not know") +) + +// Int128 is a signed 128-bit integer in two's complement, in little-endian +// byte order. +type Int128 [16]byte + +// Uint128 is an unsigned 128-bit integer in little-endian byte order. +type Uint128 [16]byte + +func littleInteger(value *big.Int) [16]byte { + var out [16]byte + bytes := value.Bytes() + for i, b := range bytes { + out[len(bytes)-1-i] = b + } + return out +} + +func ParseInt128(s string) (Int128, error) { + value, ok := new(big.Int).SetString(s, 10) + if !ok { + return Int128{}, ErrIntegerRange + } + limit := new(big.Int).Lsh(big.NewInt(1), 127) + if value.Cmp(new(big.Int).Neg(new(big.Int).Set(limit))) < 0 || value.Cmp(limit) >= 0 { + return Int128{}, ErrIntegerRange + } + if value.Sign() < 0 { + value.Add(value, new(big.Int).Lsh(big.NewInt(1), 128)) + } + return Int128(littleInteger(value)), nil +} + +func ParseUint128(s string) (Uint128, error) { + value, ok := new(big.Int).SetString(s, 10) + if !ok || value.Sign() < 0 || value.BitLen() > 128 { + return Uint128{}, ErrIntegerRange + } + return Uint128(littleInteger(value)), nil +} + +func bigInteger(value [16]byte) *big.Int { + var be [16]byte + for i, b := range value { + be[15-i] = b + } + return new(big.Int).SetBytes(be[:]) +} +func (v Uint128) String() string { return bigInteger([16]byte(v)).String() } +func (v Int128) String() string { + value := bigInteger([16]byte(v)) + if v[15]&0x80 != 0 { + value.Sub(value, new(big.Int).Lsh(big.NewInt(1), 128)) + } + return value.String() +} + +// These constants are the range of dates and instants that the encoding +// accepts: +// +// - A date has a year from -9999 through 9999. +// - An instant is from -009999-01-02T01:59:59Z through +// 9999-12-30T22:00:00.999999999Z. +// +// The range is the one that jiff accepts. jiff is the date and time library +// that the Rust code uses. Every language uses the same range. A value that +// one language seals can therefore be opened in every other language. +const ( + minDateYear = -9999 + maxDateYear = 9999 + minTimestampSeconds = -377705023201 // -009999-01-02T01:59:59Z + maxTimestampSeconds = 253402207200 // 9999-12-30T22:00:00Z +) + +// Date is a date in the proleptic Gregorian calendar, with no time and no +// time zone. The year is from -9999 through 9999. Year zero and the years +// before it are valid. +type Date struct { + Year int + Month time.Month + Day int +} + +func (d Date) Validate() error { + if d.Year < minDateYear || d.Year > maxDateYear || d.Month < 1 || d.Month > 12 || d.Day < 1 || d.Day > 31 { + return ErrInvalidDate + } + t := time.Date(d.Year, d.Month, d.Day, 0, 0, 0, 0, time.UTC) + if t.Year() != d.Year || t.Month() != d.Month || t.Day() != d.Day { + return ErrInvalidDate + } + return nil +} + +// DaysFromCE returns the day number that the encoding stores for d. Day 1 is +// 1 January of year 1. The numbering never changes. +func (d Date) DaysFromCE() (int32, error) { + if err := d.Validate(); err != nil { + return 0, err + } + return int32(time.Date(d.Year, d.Month, d.Day, 0, 0, 0, 0, time.UTC).Unix()/86400 + 719163), nil +} + +func DateFromDaysCE(days int32) (Date, error) { + t := time.Unix((int64(days)-719163)*86400, 0).UTC() + d := Date{Year: t.Year(), Month: t.Month(), Day: t.Day()} + return d, d.Validate() +} + +// Timestamp is an instant, as seconds and nanoseconds since the Unix epoch. +// Use it when the caller has those two numbers and no time.Time. The codec +// only encodes a Timestamp. A timestamp decodes as a time.Time. +// +// Validate refuses two kinds of Timestamp: +// +// - One whose Nanoseconds is one billion or more. Such a value is a leap +// second. A leap second has no count since the epoch. The rest of the +// codec refuses a leap second too. +// - An instant outside the range that the encoding accepts. +type Timestamp struct { + Seconds int64 + Nanoseconds uint32 +} + +func (t Timestamp) Validate() error { + if t.Seconds < minTimestampSeconds || t.Seconds > maxTimestampSeconds || t.Nanoseconds >= 1000000000 { + return ErrInvalidTimestamp + } + return nil +} + +// UUID is the sixteen bytes of a UUID. [ParseUUID] reads the hyphenated +// hexadecimal form. [UUID.String] writes that form in lower case. +// +// The codec writes a UUID as bytes with the logical type Uuid. A logical +// type is a meaning that the encoding records for a scalar. Uuid has no tag +// byte of its own. The codec therefore writes a UUID in the envelope. The +// envelope starts with the tag byte 0xF3. +// +// To the codec, any other UUID type is a [16]byte, so the codec writes it as +// bytes. One such type is github.com/google/uuid.UUID. Convert a value of +// that type first, with UUID(id). Rust and Node then read it as a UUID. +type UUID [16]byte + +// ParseUUID reads a UUID in its hyphenated form: groups of 8, 4, 4, 4, and +// 12 hexadecimal digits. The digits can be in upper or lower case. ParseUUID +// returns [ErrInvalidUUID] for any other text. +func ParseUUID(s string) (UUID, error) { + var u UUID + if len(s) != 36 || s[8] != '-' || s[13] != '-' || s[18] != '-' || s[23] != '-' { + return UUID{}, ErrInvalidUUID + } + hexDigits := strings.ReplaceAll(s, "-", "") + if len(hexDigits) != 32 { + return UUID{}, ErrInvalidUUID + } + for i := range u { + hi, ok1 := hexDigit(hexDigits[2*i]) + lo, ok2 := hexDigit(hexDigits[2*i+1]) + if !ok1 || !ok2 { + return UUID{}, ErrInvalidUUID + } + u[i] = hi<<4 | lo + } + return u, nil +} + +func hexDigit(c byte) (byte, bool) { + switch { + case c >= '0' && c <= '9': + return c - '0', true + case c >= 'a' && c <= 'f': + return c - 'a' + 10, true + case c >= 'A' && c <= 'F': + return c - 'A' + 10, true + } + return 0, false +} + +// String returns u in its hyphenated form, in lower case. +func (u UUID) String() string { + const digits = "0123456789abcdef" + var out [36]byte + j := 0 + for i, b := range u { + if i == 4 || i == 6 || i == 8 || i == 10 { + out[j] = '-' + j++ + } + out[j] = digits[b>>4] + out[j+1] = digits[b&0x0f] + j += 2 + } + return string(out[:]) +} + +// Tagged is a scalar with a logical type that this version of the codec does +// not know. A newer client can write such a value. The codec decodes it as a +// Tagged, and encodes a Tagged as the same bytes. So the codec neither loses +// the value nor treats it as a plain scalar. +// +// ID and Param are the id and the parameter of the logical type, as the +// envelope records them. ID must be greater than every id this version +// knows. V is the scalar, as the Go type that the codec decodes it as. V +// must be one of these: +// +// - nil +// - a bool +// - an integer or a float of any width +// - an Int128 or a Uint128 +// - a string +// - a []byte +// +// The codec writes an int as an Int64 and a uint as a Uint64, as it does for +// every value. A V of type int therefore decodes as an int64, and a V of +// type uint decodes as a uint64. +type Tagged struct { + ID uint8 + Param uint8 + V any +} + +// Decimal is a finite base-10 number. The value is Coefficient times 10 to +// the power of -Scale. The value is negative when Negative is set. +// +// Coefficient is an unsigned 96-bit integer in little-endian byte order. +// Scale is at most 28. That is the limit of the Rust crate rust_decimal. The +// codec keeps Scale as given, so it keeps trailing zeroes. +// +// A zero has no sign. The text "-0.00" parses as 0.00, and a negative zero +// encodes and decodes as zero. Each of these keeps the scale. +type Decimal struct { + Coefficient [12]byte + Scale uint8 + Negative bool +} + +func (d Decimal) Validate() error { + if d.Scale > 28 { + return ErrInvalidDecimal + } + return nil +} + +// ParseDecimal reads a number written in fixed-point decimal form, and never +// rounds. ParseDecimal returns [ErrInvalidDecimal] for text that is not such +// a number. ParseDecimal returns the same error for a number that a Decimal +// cannot represent exactly. ParseDecimal returns [ErrNonFiniteDecimal] for +// NaN and for an infinity. A caller can therefore tell those two cases apart +// from other bad text. +func ParseDecimal(s string) (Decimal, error) { + switch strings.ToLower(s) { + case "nan", "+nan", "-nan", "inf", "+inf", "-inf", "infinity", "+infinity", "-infinity": + return Decimal{}, ErrNonFiniteDecimal + } + var d Decimal + if strings.HasPrefix(s, "-") { + d.Negative = true + s = s[1:] + } else if strings.HasPrefix(s, "+") { + s = s[1:] + } + parts := strings.Split(s, ".") + if len(parts) > 2 || len(parts[0]) == 0 { + return Decimal{}, ErrInvalidDecimal + } + if len(parts) == 2 { + if len(parts[1]) == 0 || len(parts[1]) > 28 { + return Decimal{}, ErrInvalidDecimal + } + d.Scale = uint8(len(parts[1])) + } + digits := strings.Join(parts, "") + for _, c := range digits { + if c < '0' || c > '9' { + return Decimal{}, ErrInvalidDecimal + } + } + if len(strings.TrimLeft(digits, "0")) > 29 { + return Decimal{}, ErrInvalidDecimal + } + coefficient, ok := new(big.Int).SetString(digits, 10) + if !ok || coefficient.BitLen() > 96 { + return Decimal{}, ErrInvalidDecimal + } + raw := littleInteger(coefficient) + copy(d.Coefficient[:], raw[:12]) + if coefficient.Sign() == 0 { + d.Negative = false + } + return d, nil +} + +// IsZero reports whether the coefficient is zero, whatever the scale. +func (d Decimal) IsZero() bool { + return d.Coefficient == [12]byte{} +} + +// Normalized returns d, with Negative cleared when d is zero. +func (d Decimal) Normalized() Decimal { + if d.IsZero() { + d.Negative = false + } + return d +} + +func (d Decimal) String() string { + var raw [16]byte + copy(raw[:12], d.Coefficient[:]) + digits := bigInteger(raw).String() + scale := int(d.Scale) + if scale > 0 { + if len(digits) <= scale { + digits = strings.Repeat("0", scale+1-len(digits)) + digits + } + digits = digits[:len(digits)-scale] + "." + digits[len(digits)-scale:] + } + if d.Negative { + digits = "-" + digits + } + return digits +} diff --git a/languages/golang/encrypt/value/scalars_test.go b/languages/golang/encrypt/value/scalars_test.go new file mode 100644 index 000000000..f3bc97a96 --- /dev/null +++ b/languages/golang/encrypt/value/scalars_test.go @@ -0,0 +1,123 @@ +package value + +import ( + "errors" + "testing" + "time" +) + +func TestInteger128Boundaries(t *testing.T) { + for _, text := range []string{"0", "-1", "170141183460469231731687303715884105727", "-170141183460469231731687303715884105728"} { + v, err := ParseInt128(text) + if err != nil || v.String() != text { + t.Fatalf("%s: %v %s", text, err, v.String()) + } + } + for _, text := range []string{"0", "1", "340282366920938463463374607431768211455"} { + v, err := ParseUint128(text) + if err != nil || v.String() != text { + t.Fatalf("%s: %v %s", text, err, v.String()) + } + } + for _, text := range []string{"bad", "170141183460469231731687303715884105728", "-170141183460469231731687303715884105729"} { + if _, err := ParseInt128(text); !errors.Is(err, ErrIntegerRange) { + t.Fatalf("accepted %s", text) + } + } + for _, text := range []string{"bad", "-1", "340282366920938463463374607431768211456"} { + if _, err := ParseUint128(text); !errors.Is(err, ErrIntegerRange) { + t.Fatalf("accepted %s", text) + } + } +} + +func TestDecimalExactness(t *testing.T) { + for _, text := range []string{"0", "1.50", "-79228162514264337593543950335", "0.0000000000000000000000000001"} { + v, err := ParseDecimal(text) + if err != nil || v.String() != text { + t.Fatalf("%s: %v %s", text, err, v.String()) + } + } + // A zero has no sign. The parser keeps the scale and drops the sign. + for _, text := range []string{"-0", "-0.00", "+0.0"} { + v, err := ParseDecimal(text) + if err != nil || v.Negative || !v.IsZero() { + t.Fatalf("%s: %v %#v", text, err, v) + } + } + if v, _ := ParseDecimal("-0.00"); v.String() != "0.00" { + t.Fatalf("negative zero prints as %s", v.String()) + } + if n := (Decimal{Negative: true, Scale: 2}).Normalized(); n.Negative { + t.Fatal("Normalized kept the sign of a zero") + } + if n := (Decimal{Negative: true, Scale: 2, Coefficient: [12]byte{1}}).Normalized(); !n.Negative { + t.Fatal("Normalized dropped the sign of a nonzero") + } + for _, text := range []string{"NaN", "+nan", "-NaN", "inf", "+Infinity", "-Infinity"} { + if _, err := ParseDecimal(text); !errors.Is(err, ErrNonFiniteDecimal) { + t.Fatalf("%s: %v", text, err) + } + } + for _, text := range []string{"", ".1", "1.", "1.2.3", "1e2", "1_0", " 1", "a", "0.00000000000000000000000000001", "79228162514264337593543950336"} { + if _, err := ParseDecimal(text); !errors.Is(err, ErrInvalidDecimal) { + t.Fatalf("accepted %s", text) + } + } +} + +func TestDatesAndTimestampBounds(t *testing.T) { + for _, d := range []Date{{1, 1, 1}, {0, 1, 1}, {2024, 2, 29}, {-9999, 1, 1}, {9999, 12, 31}} { + days, err := d.DaysFromCE() + if err != nil { + t.Fatal(err) + } + got, err := DateFromDaysCE(days) + if err != nil || got != d { + t.Fatalf("%v: %v %v", d, got, err) + } + } + for _, d := range []Date{{2023, 2, 29}, {2024, 0, 1}, {2024, 13, 1}, {2024, 1, 0}, {2024, 1, 32}, {-10000, 12, 31}, {10000, 1, 1}} { + if d.Validate() == nil { + t.Fatalf("accepted %v", d) + } + } + // The two ends of the range that the encoding accepts. The range is that + // of jiff. + first := time.Date(-9999, 1, 2, 1, 59, 59, 0, time.UTC).Unix() + last := time.Date(9999, 12, 30, 22, 0, 0, 0, time.UTC).Unix() + for _, ts := range []Timestamp{{0, 0}, {-1, 999999999}, {59, 123456789}, {first, 0}, {last, 999999999}} { + if ts.Validate() != nil { + t.Fatalf("rejected %v", ts) + } + } + // A leap second has no count since the epoch, so Validate refuses it. + // Validate also refuses an instant outside either end of the range. + for _, ts := range []Timestamp{{0, 1000000000}, {59, 1123456789}, {59, 2000000000}, {first - 1, 999999999}, {last + 1, 0}, {time.Date(12000, 1, 1, 0, 0, 0, 0, time.UTC).Unix(), 0}, {1<<63 - 1, 0}} { + if ts.Validate() == nil { + t.Fatalf("accepted %v", ts) + } + } +} + +func TestUUIDSpelling(t *testing.T) { + text := "123e4567-e89b-12d3-a456-426614174000" + u, err := ParseUUID(text) + if err != nil || u.String() != text { + t.Fatalf("%s: %v %s", text, err, u.String()) + } + if u[0] != 0x12 || u[15] != 0x00 || u[4] != 0xe8 { + t.Fatalf("bytes %x", u[:]) + } + if upper, err := ParseUUID("123E4567-E89B-12D3-A456-426614174000"); err != nil || upper != u { + t.Fatalf("upper case: %v", err) + } + for _, bad := range []string{"", "123e4567e89b12d3a456426614174000", "{123e4567-e89b-12d3-a456-426614174000}", "123e4567-e89b-12d3-a456-42661417400g", "123e4567-e89b-12d3-a456-4266141740000", + "123e4567-e89b-12d3-a456-42661417400-", // a fifth hyphen at the end + "123e4567-e89b-12d3-a456-4266-4174000", // a fifth hyphen inside the last group + } { + if _, err := ParseUUID(bad); !errors.Is(err, ErrInvalidUUID) { + t.Fatalf("accepted %q", bad) + } + } +} diff --git a/languages/golang/encrypt/value_conformance_test.go b/languages/golang/encrypt/value_conformance_test.go index 5f500be04..4c11feaf6 100644 --- a/languages/golang/encrypt/value_conformance_test.go +++ b/languages/golang/encrypt/value_conformance_test.go @@ -12,8 +12,8 @@ import ( "time" "github.com/cipherstash/stack/languages/golang/encrypt" + "github.com/cipherstash/stack/languages/golang/encrypt/frame" "github.com/cipherstash/stack/languages/golang/internal/record" - "github.com/cipherstash/vitaminc/bindings/go/vcffi" ) type valueCase struct { @@ -143,7 +143,7 @@ func TestValueConformance(t *testing.T) { plan := &record.Plan{Context: []string{"conformance"}, Fields: []record.Field{{Name: "value", Kind: record.Kind(c.Kind), Null: record.Null(c.Null), Outputs: outputs}}} input := conformanceValue(t, c.Input) if c.Frame != nil { - encoded, err := vcffi.Marshal(input) + encoded, err := frame.Marshal(input) if err != nil { t.Fatal(err) } diff --git a/languages/golang/encrypt/value_kinds_test.go b/languages/golang/encrypt/value_kinds_test.go index 1b734daba..393b0494b 100644 --- a/languages/golang/encrypt/value_kinds_test.go +++ b/languages/golang/encrypt/value_kinds_test.go @@ -14,8 +14,8 @@ import ( "time" "github.com/cipherstash/stack/languages/golang/encrypt" + "github.com/cipherstash/stack/languages/golang/encrypt/frame" "github.com/cipherstash/stack/languages/golang/encrypt/internal/testusers" - "github.com/cipherstash/vitaminc/bindings/go/vcffi" ) // The value-kinds fixture is the cross-language proof for the kinds #1144 @@ -127,11 +127,11 @@ func TestGeneratedCodeOpensTheRustValueKindsFixture(t *testing.T) { for _, v := range f.Values { value := parseKind(t, v.Field, v.Text) values[v.Field] = value - frame, err := vcffi.Marshal(value) + encoded, err := frame.Marshal(value) if err != nil { t.Fatalf("%s: %v", v.Field, err) } - if got := hex.EncodeToString(frame); got != v.Frame { + if got := hex.EncodeToString(encoded); got != v.Frame { t.Errorf("%s (%s): Go writes the frame %s, Rust wrote %s", v.Field, v.Type, got, v.Frame) } } @@ -233,9 +233,9 @@ func TestGeneratedCodeOpensTheRustValueKindsFixture(t *testing.T) { t.Fatalf("the fixture has a %s query the test does not know", q.Operator) } value := parseKind(t, q.Field, q.Text) - frame, err := vcffi.Marshal(value) - if err != nil || hex.EncodeToString(frame) != q.Frame { - t.Errorf("%s query %q: Go writes the frame %x (%v), Rust wrote %s", q.Field, q.Text, frame, err, q.Frame) + encoded, err := frame.Marshal(value) + if err != nil || hex.EncodeToString(encoded) != q.Frame { + t.Errorf("%s query %q: Go writes the frame %x (%v), Rust wrote %s", q.Field, q.Text, encoded, err, q.Frame) } var term encrypt.EqualityTerm var order []byte diff --git a/languages/golang/encrypt/values.go b/languages/golang/encrypt/values.go index 93b2fd5a5..525ef2bc8 100644 --- a/languages/golang/encrypt/values.go +++ b/languages/golang/encrypt/values.go @@ -3,14 +3,17 @@ package encrypt import ( "time" - "github.com/cipherstash/vitaminc/bindings/go/vcvalue" + "github.com/cipherstash/stack/languages/golang/encrypt/value" ) -// The value types a struct field can hold beside Go's own, each sealed as -// vitaminc's leaf of that kind (ADR-0002). They are vitaminc's Go value -// types (module vcvalue), not copies: the transport codec writes each one as -// its leaf byte for byte, and an opened value comes back as the same type, so -// a field of one of these types needs no conversion either way. +// The types below are the value types that a struct field can have, in +// addition to Go's own types. Each value is sealed as the leaf of its kind. +// A leaf is one encrypted value. An opened value has the same type, so a +// field of one of these types needs no conversion in either direction. +// +// Each type is declared in package value, the package of the values that the +// codec reads and writes. The names here are aliases, so encrypt.Date and +// value.Date are the same type. // // A time.Time field is a timestamp: it seals the instant to the nanosecond, // in UTC, and opens as a time.Time in UTC. Its location and monotonic @@ -26,7 +29,7 @@ import ( // ErrEncoding, naming the field. An optional date is a *Date field: nil is // stored as a sealed null as long as a date, or, with the tag's null=sql, as // SQL NULL (see stashgen's README, "Optional fields"). -type Date = vcvalue.Date +type Date = value.Date // DateOf is the calendar day t falls on in its own location: what t.Date() // returns. A local midnight east of UTC is that day, not the UTC day before @@ -38,34 +41,55 @@ func DateOf(t time.Time) Date { // Int128 is a signed 128-bit integer, two's complement, little-endian. // ParseInt128 reads one from its decimal text, and String writes it. -type Int128 = vcvalue.Int128 +type Int128 = value.Int128 // Uint128 is an unsigned 128-bit integer, little-endian. ParseUint128 reads // one from its decimal text, and String writes it. -type Uint128 = vcvalue.Uint128 +type Uint128 = value.Uint128 // ParseInt128 reads a signed 128-bit integer from decimal text, refusing a // value outside its range. -func ParseInt128(s string) (Int128, error) { return vcvalue.ParseInt128(s) } +func ParseInt128(s string) (Int128, error) { return value.ParseInt128(s) } // ParseUint128 reads an unsigned 128-bit integer from decimal text, refusing // a negative value or one outside its range. -func ParseUint128(s string) (Uint128, error) { return vcvalue.ParseUint128(s) } +func ParseUint128(s string) (Uint128, error) { return value.ParseUint128(s) } -// Decimal is a finite decimal number with its scale: "1.50" is not "1.5", -// and opens as it was sealed, except that a zero has no sign: -0.00 opens as -// 0.00, at the same scale. Its mantissa fits 96 bits and its scale is at -// most 28, rust_decimal's range. There is no NaN and no infinity: the type -// cannot hold one, and ParseDecimal refuses one. An equality term normalises -// the scale, so 1.5, 1.50 and 1.500 match each other. -type Decimal = vcvalue.Decimal +// Decimal is a finite decimal number that keeps its scale. "1.50" is not +// "1.5", and each opens as it was sealed. A zero is the exception, because a +// zero has no sign: -0.00 opens as 0.00, at the same scale. +// +// The value is Coefficient times 10 to the power of -Scale. The value is +// negative when Negative is set. Coefficient is an unsigned 96-bit integer +// in little-endian byte order. Scale is at most 28. That is the limit of the +// Rust crate rust_decimal. +// +// A Decimal cannot be NaN or an infinity, and [ParseDecimal] refuses both. +// An equality term normalises the scale, so 1.5, 1.50, and 1.500 match each +// other. +type Decimal = value.Decimal // ErrNonFiniteDecimal is the error ParseDecimal returns for NaN or an // infinity. -var ErrNonFiniteDecimal = vcvalue.ErrNonFiniteDecimal +var ErrNonFiniteDecimal = value.ErrNonFiniteDecimal // ParseDecimal reads a decimal from its fixed-point text ("-1234.5600"), // keeping its scale, without rounding. NaN and the infinities are // ErrNonFiniteDecimal; a value with more than 28 digits after the point or a // mantissa past 96 bits is refused too. -func ParseDecimal(s string) (Decimal, error) { return vcvalue.ParseDecimal(s) } +func ParseDecimal(s string) (Decimal, error) { return value.ParseDecimal(s) } + +// UUID is the sixteen bytes of a UUID. A UUID is sealed with the logical +// type UUID, so Rust and Node open it as a UUID. [ParseUUID] reads the +// hyphenated form, and String writes it. +// +// A field of the kind "uuid" (gensupport.UUID) also accepts a value of +// another type whose underlying type is [16]byte. One such type is +// github.com/google/uuid.UUID. The SDK converts that value to a UUID. +// Anywhere else, such a value is sealed as sixteen bytes. Convert it with +// UUID(id) first. +type UUID = value.UUID + +// ParseUUID reads a UUID in its hyphenated form: groups of 8, 4, 4, 4, and +// 12 hexadecimal digits. The digits can be in upper or lower case. +func ParseUUID(s string) (UUID, error) { return value.ParseUUID(s) } diff --git a/languages/golang/encrypt/values_test.go b/languages/golang/encrypt/values_test.go new file mode 100644 index 000000000..3f4381404 --- /dev/null +++ b/languages/golang/encrypt/values_test.go @@ -0,0 +1,241 @@ +package encrypt_test + +import ( + "bytes" + "errors" + "reflect" + "strings" + "testing" + "time" + + "github.com/cipherstash/stack/languages/golang/encrypt" + "github.com/cipherstash/stack/languages/golang/encrypt/frame" + "github.com/cipherstash/stack/languages/golang/internal/guest" +) + +// Each value type crosses the codec as itself: encrypt.Date is value.Date, +// so a decoded value has the type that was encoded. A field of one of these +// types therefore needs no conversion in either direction. +func TestTheValueTypesCrossTheCodecAsThemselves(t *testing.T) { + id, err := encrypt.ParseUUID("0190c6d2-3a4b-7c5d-8e9f-a0b1c2d3e4f5") + if err != nil { + t.Fatal(err) + } + big, err := encrypt.ParseInt128("-170141183460469231731687303715884105728") + if err != nil { + t.Fatal(err) + } + huge, err := encrypt.ParseUint128("340282366920938463463374607431768211455") + if err != nil { + t.Fatal(err) + } + amount, err := encrypt.ParseDecimal("-1234.5600") + if err != nil { + t.Fatal(err) + } + for _, v := range []any{ + encrypt.Date{Year: -44, Month: time.March, Day: 15}, + big, + huge, + amount, + id, + } { + got, err := frame.Marshal(v) + if err != nil { + t.Fatal(err) + } + back, err := frame.Unmarshal(got) + if err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(back, v) { + t.Fatalf("%x decodes as %#v (%T), want %#v", got, back, back, v) + } + } +} + +func TestTheValueTypesSpellThemselves(t *testing.T) { + for _, c := range []struct{ got, want string }{ + {mustParse(t, encrypt.ParseInt128, "-17").String(), "-17"}, + {mustParse(t, encrypt.ParseUint128, "17").String(), "17"}, + {mustParse(t, encrypt.ParseDecimal, "-0.50").String(), "-0.50"}, + {mustParse(t, encrypt.ParseUUID, "0190C6D2-3A4B-7C5D-8E9F-A0B1C2D3E4F5").String(), "0190c6d2-3a4b-7c5d-8e9f-a0b1c2d3e4f5"}, + } { + if c.got != c.want { + t.Errorf("got %q, want %q", c.got, c.want) + } + } + if _, err := encrypt.ParseDecimal("NaN"); !errors.Is(err, encrypt.ErrNonFiniteDecimal) { + t.Errorf("ParseDecimal(NaN): %v", err) + } + if !mustParse(t, encrypt.ParseDecimal, "0.000").IsZero() { + t.Error("0.000 is not zero") + } + if (encrypt.Decimal{Scale: 29}).Validate() == nil { + t.Error("a scale of 29 is valid") + } + if (encrypt.Date{Year: 2023, Month: time.February, Day: 29}).Validate() == nil { + t.Error("2023-02-29 is valid") + } + for _, bad := range []string{"", "0190c6d2-3a4b-7c5d-8e9f", "0190c6d2x3a4b-7c5d-8e9f-a0b1c2d3e4f5"} { + if _, err := encrypt.ParseUUID(bad); err == nil { + t.Errorf("ParseUUID(%q) succeeded", bad) + } + } +} + +func mustParse[T any](t *testing.T, parse func(string) (T, error), s string) T { + t.Helper() + v, err := parse(s) + if err != nil { + t.Fatalf("%q: %v", s, err) + } + return v +} + +// writesWith is an Encryptable that writes itself with one Encoder method. +type writesWith func(encrypt.Encoder) + +func (w writesWith) EncryptValue(enc encrypt.Encoder) error { + w(enc) + return nil +} + +// Each Encoder method writes what the codec writes for a value of its type. +func TestEachEncoderMethodWritesItsType(t *testing.T) { + when := time.Unix(1_700_000_000, 5).UTC() + for _, c := range []struct { + write writesWith + want any + }{ + {func(e encrypt.Encoder) { e.Null() }, nil}, + {func(e encrypt.Encoder) { e.Bool(true) }, true}, + {func(e encrypt.Encoder) { e.Int8(-8) }, int8(-8)}, + {func(e encrypt.Encoder) { e.Int16(-16) }, int16(-16)}, + {func(e encrypt.Encoder) { e.Int32(-32) }, int32(-32)}, + {func(e encrypt.Encoder) { e.Int64(-64) }, int64(-64)}, + {func(e encrypt.Encoder) { e.Int128(encrypt.Int128{1}) }, encrypt.Int128{1}}, + {func(e encrypt.Encoder) { e.Uint8(8) }, uint8(8)}, + {func(e encrypt.Encoder) { e.Uint16(16) }, uint16(16)}, + {func(e encrypt.Encoder) { e.Uint32(32) }, uint32(32)}, + {func(e encrypt.Encoder) { e.Uint64(64) }, uint64(64)}, + {func(e encrypt.Encoder) { e.Uint128(encrypt.Uint128{1}) }, encrypt.Uint128{1}}, + {func(e encrypt.Encoder) { e.Float32(1.5) }, float32(1.5)}, + {func(e encrypt.Encoder) { e.Float64(2.5) }, 2.5}, + {func(e encrypt.Encoder) { e.String("text") }, "text"}, + {func(e encrypt.Encoder) { e.Bytes([]byte{1, 2}) }, []byte{1, 2}}, + {func(e encrypt.Encoder) { e.Date(encrypt.Date{Year: 2000, Month: 1, Day: 2}) }, encrypt.Date{Year: 2000, Month: 1, Day: 2}}, + {func(e encrypt.Encoder) { e.Timestamp(when) }, when}, + {func(e encrypt.Encoder) { e.Decimal(encrypt.Decimal{Scale: 1, Coefficient: [12]byte{15}}) }, encrypt.Decimal{Scale: 1, Coefficient: [12]byte{15}}}, + {func(e encrypt.Encoder) { e.UUID(encrypt.UUID{1}) }, encrypt.UUID{1}}, + } { + got, err := frame.Marshal(c.write) + if err != nil { + t.Fatalf("%T: %v", c.want, err) + } + want, err := frame.Marshal(c.want) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(got, want) { + t.Errorf("%T: the Encoder writes %x, the value %x", c.want, got, want) + } + } + // EncryptValue must write exactly one value. The encode fails for no + // value, for two values, and for a value that the codec refuses. + for name, write := range map[string]writesWith{ + "no value": func(encrypt.Encoder) {}, + "two values": func(e encrypt.Encoder) { e.Bool(true); e.Bool(false) }, + "bad UTF-8": func(e encrypt.Encoder) { e.String(string([]byte{0xff})) }, + "no date": func(e encrypt.Encoder) { e.Date(encrypt.Date{}) }, + } { + if _, err := frame.Marshal(write); err == nil { + t.Errorf("%s: the encode succeeded", name) + } + } + // A nil pointer to an Encryptable is written as a null. The codec does + // not call its method. + if got, err := frame.Marshal((*writesWith)(nil)); err != nil || !bytes.Equal(got, []byte{0}) { + t.Errorf("a nil Encryptable writes %x, %v", got, err) + } +} + +// A date or a decimal has no storage form. The error names the type. +func TestADateOrADecimalHasNoStorageForm(t *testing.T) { + for _, c := range []struct { + v any + name string + }{ + {encrypt.Decimal{Scale: 2}, "value.Decimal"}, + {struct{ When encrypt.Date }{}, "value.Date"}, + } { + _, err := frame.MarshalStorage(c.v) + if !errors.Is(err, frame.ErrUnwritable) || !strings.Contains(err.Error(), c.name+" has no storage form") { + t.Errorf("%T: %v; want a refusal naming %s", c.v, err, c.name) + } + } +} + +// An error about a guest answer names each value type by its kind. The +// error does not call a UUID bytes. The error does not call a date a struct. +func TestAnErrorNamesEachValueTypeByItsKind(t *testing.T) { + for _, tc := range []struct { + value any + want string + }{ + {encrypt.Int128{}, "a number"}, + {encrypt.Uint128{}, "a number"}, + {encrypt.Date{}, "a date"}, + {encrypt.Decimal{}, "a decimal"}, + {encrypt.UUID{}, "a UUID"}, + } { + if got := guest.KindOf(tc.value); got != tc.want { + t.Errorf("KindOf(%T) = %q, want %q", tc.value, got, tc.want) + } + } +} + +// The zero Encoder does not panic: it keeps nothing, and its Err says so. +func TestTheZeroEncoderKeepsNothing(t *testing.T) { + var zero encrypt.Encoder + zero.Null() + zero.Bool(true) + zero.Int8(1) + zero.Int16(1) + zero.Int32(1) + zero.Int64(1) + zero.Int128(encrypt.Int128{}) + zero.Uint8(1) + zero.Uint16(1) + zero.Uint32(1) + zero.Uint64(1) + zero.Uint128(encrypt.Uint128{}) + zero.Float32(1) + zero.Float64(1) + zero.String("s") + zero.Bytes(nil) + zero.Date(encrypt.Date{Year: 2000, Month: 1, Day: 1}) + zero.Timestamp(time.Now()) + zero.Decimal(encrypt.Decimal{}) + zero.UUID(encrypt.UUID{}) + if zero.Err() == nil { + t.Fatal("the zero Encoder's Err is nil") + } + // A type's own unit test can call EncryptValue with one. + if err := writesWith(func(e encrypt.Encoder) { e.Int64(1) }).EncryptValue(encrypt.Encoder{}); err != nil { + t.Fatal(err) + } + // The Encoder the codec hands out has no error until one is written. + var before, after error + write := writesWith(func(e encrypt.Encoder) { + before = e.Err() + e.String(string([]byte{0xff})) + after = e.Err() + }) + if _, err := frame.Marshal(write); err == nil { + t.Fatal("a string that is not UTF-8 was written") + } + if before != nil || after == nil { + t.Fatalf("Err before a refusal %v, after %v", before, after) + } +} diff --git a/languages/golang/examples/s3/go.mod b/languages/golang/examples/s3/go.mod index 8c7bec1f1..a71cb2d24 100644 --- a/languages/golang/examples/s3/go.mod +++ b/languages/golang/examples/s3/go.mod @@ -32,8 +32,6 @@ require ( github.com/aws/aws-sdk-go-v2/service/ssooidc v1.44.7 // indirect github.com/aws/aws-sdk-go-v2/service/sts v1.53.2 // indirect github.com/aws/smithy-go v1.28.11 // indirect - github.com/cipherstash/vitaminc/bindings/go/vcffi v0.0.0-20261119095843-f1fc9ae74882 // indirect - github.com/cipherstash/vitaminc/bindings/go/vcvalue v0.0.0-20261119095843-f1fc9ae74882 // indirect github.com/tetratelabs/wazero v1.12.0 // indirect golang.org/x/oauth2 v0.37.0 // indirect golang.org/x/sys v0.49.0 // indirect diff --git a/languages/golang/examples/s3/go.sum b/languages/golang/examples/s3/go.sum index 33e266c84..b5348bbfa 100644 --- a/languages/golang/examples/s3/go.sum +++ b/languages/golang/examples/s3/go.sum @@ -34,10 +34,6 @@ github.com/aws/aws-sdk-go-v2/service/sts v1.53.2 h1:nLsYkVhvseSf0aBwvXwEjoYn9vN3 github.com/aws/aws-sdk-go-v2/service/sts v1.53.2/go.mod h1:7f/XsI45+GK2yL0Gg0gojsNXVlXx9+qtCSYk2HdE308= github.com/aws/smithy-go v1.28.11 h1:2aArhkXe0dFld6IFMlaVy47SbSdU/ZGbDaE7X2DjZkI= github.com/aws/smithy-go v1.28.11/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc= -github.com/cipherstash/vitaminc/bindings/go/vcffi v0.0.0-20261119095843-f1fc9ae74882 h1:T3GexX/bqkB3KS9mbz8TJxEIP/RdUyFgcMH6VQDnRR8= -github.com/cipherstash/vitaminc/bindings/go/vcffi v0.0.0-20261119095843-f1fc9ae74882/go.mod h1:7hPdj2tN3YpcPZYdZ+Fe7+Fsc7dnSyH5bsL9y+LbRuM= -github.com/cipherstash/vitaminc/bindings/go/vcvalue v0.0.0-20261119095843-f1fc9ae74882 h1:5joeyPbldjXj9vRemilG7wYwmICFPZSPBMXiXGsgg7Q= -github.com/cipherstash/vitaminc/bindings/go/vcvalue v0.0.0-20261119095843-f1fc9ae74882/go.mod h1:RJODA1DCSm4H+1pbmCzDdT2pAIkxhinwIu6ewjh5sPs= github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo= diff --git a/languages/golang/go.mod b/languages/golang/go.mod index a8252af97..defc1ef16 100644 --- a/languages/golang/go.mod +++ b/languages/golang/go.mod @@ -2,16 +2,7 @@ module github.com/cipherstash/stack/languages/golang go 1.26.10 -// TEMPORARY: vcffi and vcvalue at vitaminc f1fc9ae74, the commit vitaminc -// 0.10.0 was released from, so the host checks dates and timestamps against -// the range the guests' vitaminc 0.10.0 does (years -9999 to 9999), and -// writes the storage profile (vcffi.MarshalStorage) and the transport the -// guests read. vitaminc's Go bindings have no tags, so the commit is the pin. -// The pin moves to a tag when vitaminc provides one; until then -// scripts/go-release-version.mjs refuses a final version of this module. require ( - github.com/cipherstash/vitaminc/bindings/go/vcffi v0.0.0-20261119095843-f1fc9ae74882 - github.com/cipherstash/vitaminc/bindings/go/vcvalue v0.0.0-20261119095843-f1fc9ae74882 github.com/tetratelabs/wazero v1.12.0 golang.org/x/oauth2 v0.37.0 ) diff --git a/languages/golang/go.sum b/languages/golang/go.sum index b1d677278..c4c1e0189 100644 --- a/languages/golang/go.sum +++ b/languages/golang/go.sum @@ -1,7 +1,3 @@ -github.com/cipherstash/vitaminc/bindings/go/vcffi v0.0.0-20261119095843-f1fc9ae74882 h1:T3GexX/bqkB3KS9mbz8TJxEIP/RdUyFgcMH6VQDnRR8= -github.com/cipherstash/vitaminc/bindings/go/vcffi v0.0.0-20261119095843-f1fc9ae74882/go.mod h1:7hPdj2tN3YpcPZYdZ+Fe7+Fsc7dnSyH5bsL9y+LbRuM= -github.com/cipherstash/vitaminc/bindings/go/vcvalue v0.0.0-20261119095843-f1fc9ae74882 h1:5joeyPbldjXj9vRemilG7wYwmICFPZSPBMXiXGsgg7Q= -github.com/cipherstash/vitaminc/bindings/go/vcvalue v0.0.0-20261119095843-f1fc9ae74882/go.mod h1:RJODA1DCSm4H+1pbmCzDdT2pAIkxhinwIu6ewjh5sPs= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= diff --git a/languages/golang/internal/guest/answer.go b/languages/golang/internal/guest/answer.go index c4bc3c1db..d7cfd8d89 100644 --- a/languages/golang/internal/guest/answer.go +++ b/languages/golang/internal/guest/answer.go @@ -4,8 +4,8 @@ import ( "fmt" "reflect" - "github.com/cipherstash/vitaminc/bindings/go/vcffi" - "github.com/cipherstash/vitaminc/bindings/go/vcvalue" + "github.com/cipherstash/stack/languages/golang/encrypt/frame" + "github.com/cipherstash/stack/languages/golang/encrypt/value" ) // KindOf returns a phrase that names the kind of a decoded value, such as @@ -16,38 +16,32 @@ import ( // of the kind that it takes. So a program can log the error without // leaking the value. // -// KindOf checks the vcvalue types first, so that it does not report a -// sealed value as bytes. KindOf names any other Go value by its -// reflect.Kind. +// KindOf checks the types of package value first, so that it does not +// report a date as a struct, or a UUID as bytes. KindOf names any other Go +// value by its reflect.Kind. func KindOf(v any) string { switch v.(type) { - case nil, vcvalue.TypedNull: + case nil: return "null" - case vcvalue.Object: + case value.Object: return "an object" - case vcvalue.Sealed: - return "an encrypted value" - case vcvalue.SealedEmptySeq: - return "an encrypted empty list" - case vcvalue.SealedEmptyMap: - return "an encrypted empty map" - case vcvalue.Plain: + case value.Plain: return "a passthrough value" - case vcvalue.Tagged: + case value.Tagged: return "a value of a type this build does not define" - case vcvalue.Int128, vcvalue.Uint128: + case value.Int128, value.Uint128: return "a number" - case vcvalue.Date: + case value.Date: return "a date" - case vcvalue.Timestamp: + case value.Timestamp: return "a timestamp" - case vcvalue.Decimal: + case value.Decimal: return "a decimal" - case vcvalue.UUID: + case value.UUID: return "a UUID" } - value := reflect.ValueOf(v) - switch value.Kind() { + rv := reflect.ValueOf(v) + switch rv.Kind() { case reflect.Bool: return "a boolean" case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, @@ -57,7 +51,7 @@ func KindOf(v any) string { case reflect.String: return "a string" case reflect.Slice, reflect.Array: - if value.Type().Elem().Kind() == reflect.Uint8 { + if rv.Type().Elem().Kind() == reflect.Uint8 { return "bytes" } return "a list" @@ -92,7 +86,7 @@ func BadAnswer(export string, problem error) error { // [BadAnswer]. That error names the export and wraps the error from the // decoder. func DecodeAnswer(export string, out []byte) (any, error) { - decoded, err := vcffi.Unmarshal(out) + decoded, err := frame.Unmarshal(out) if err != nil { return nil, BadAnswer(export, err) } diff --git a/languages/golang/internal/guest/answer_test.go b/languages/golang/internal/guest/answer_test.go index 64959455f..4b7443dae 100644 --- a/languages/golang/internal/guest/answer_test.go +++ b/languages/golang/internal/guest/answer_test.go @@ -5,25 +5,24 @@ import ( "strings" "testing" + "github.com/cipherstash/stack/languages/golang/encrypt/frame" + "github.com/cipherstash/stack/languages/golang/encrypt/value" "github.com/cipherstash/stack/languages/golang/internal/guest" - "github.com/cipherstash/vitaminc/bindings/go/vcffi" - "github.com/cipherstash/vitaminc/bindings/go/vcvalue" ) // named is a defined Go type whose underlying type is string. type named string // KindOf names the kind of a decoded value, and never the value. KindOf -// names a vcvalue type by what the type is, and any other Go value by its -// reflect.Kind. +// names a value type of package frame by what the type is, and any other Go +// value by its reflect.Kind. func TestKindOfNamesAValueByItsKind(t *testing.T) { for _, tc := range []struct { value any want string }{ {nil, "null"}, - {vcvalue.TypedNull{}, "null"}, - {vcvalue.Object{{Key: "secret", Value: "secret"}}, "an object"}, + {value.Object{{Key: "secret", Value: "secret"}}, "an object"}, {[]any{"secret"}, "a list"}, {"secret", "a string"}, {[]byte("secret"), "bytes"}, @@ -36,19 +35,16 @@ func TestKindOfNamesAValueByItsKind(t *testing.T) { {uint16(1), "a number"}, {uint32(1), "a number"}, {uint64(1), "a number"}, - {vcvalue.Int128{}, "a number"}, - {vcvalue.Uint128{}, "a number"}, + {value.Int128{}, "a number"}, + {value.Uint128{}, "a number"}, {float32(1), "a number"}, {float64(1), "a number"}, - {vcvalue.Date{}, "a date"}, - {vcvalue.Timestamp{}, "a timestamp"}, - {vcvalue.Decimal{}, "a decimal"}, - {vcvalue.UUID{}, "a UUID"}, - {vcvalue.Sealed("secret"), "an encrypted value"}, - {vcvalue.SealedEmptySeq("secret"), "an encrypted empty list"}, - {vcvalue.SealedEmptyMap("secret"), "an encrypted empty map"}, - {vcvalue.Plain{V: "secret"}, "a passthrough value"}, - {vcvalue.Tagged{ID: 200, V: "secret"}, "a value of a type this build does not define"}, + {value.Date{}, "a date"}, + {value.Timestamp{}, "a timestamp"}, + {value.Decimal{}, "a decimal"}, + {value.UUID{}, "a UUID"}, + {value.Plain{V: "secret"}, "a passthrough value"}, + {value.Tagged{ID: 200, V: "secret"}, "a value of a type this build does not define"}, {int(1), "a number"}, {uint(1), "a number"}, {uintptr(1), "a number"}, @@ -96,7 +92,7 @@ func TestBadAnswerIsInternalAndNamesTheExport(t *testing.T) { // DecodeAnswer returns an ErrInternal error that names the export and wraps // the error from the decoder. func TestDecodeAnswerNamesTheExport(t *testing.T) { - encoded, err := vcffi.Marshal("users / email") + encoded, err := frame.Marshal("users / email") if err != nil { t.Fatal(err) } diff --git a/languages/golang/internal/guest/diagnostic.go b/languages/golang/internal/guest/diagnostic.go index 973aa98ef..5ab6ced2a 100644 --- a/languages/golang/internal/guest/diagnostic.go +++ b/languages/golang/internal/guest/diagnostic.go @@ -6,8 +6,8 @@ import ( "fmt" "math" - "github.com/cipherstash/vitaminc/bindings/go/vcffi" - "github.com/cipherstash/vitaminc/bindings/go/vcvalue" + "github.com/cipherstash/stack/languages/golang/encrypt/frame" + "github.com/cipherstash/stack/languages/golang/encrypt/value" "github.com/tetratelabs/wazero/api" ) @@ -330,11 +330,11 @@ func LastErrorExport(m api.Module) api.Function { // help, url, severity, fields and causes. An error with no message is not // one: ok is false, and the caller falls back to the sentinel. func decodeDiagnostic(raw []byte) (*Diagnostic, bool) { - value, err := vcffi.Unmarshal(raw) + decoded, err := frame.Unmarshal(raw) if err != nil { return nil, false } - object, ok := value.(vcvalue.Object) + object, ok := decoded.(value.Object) if !ok { return nil, false } @@ -355,7 +355,7 @@ func decodeDiagnostic(raw []byte) (*Diagnostic, bool) { } switch entry.Key { case "fields": - if fields, isObject := entry.Value.(vcvalue.Object); isObject { + if fields, isObject := entry.Value.(value.Object); isObject { d.Fields = objectMap(fields) } case "causes": @@ -369,11 +369,11 @@ func decodeDiagnostic(raw []byte) (*Diagnostic, bool) { } // causes reads a list of {code?, message} objects, skipping anything else. -func causes(value any) []Cause { - items, _ := value.([]any) +func causes(v any) []Cause { + items, _ := v.([]any) var out []Cause for _, item := range items { - entry, ok := item.(vcvalue.Object) + entry, ok := item.(value.Object) if !ok { continue } @@ -387,7 +387,7 @@ func causes(value any) []Cause { // objectMap turns a decoded object into a map, and every object or list // inside it likewise, so Fields holds only plain Go values. -func objectMap(object vcvalue.Object) map[string]any { +func objectMap(object value.Object) map[string]any { out := make(map[string]any, len(object)) for _, entry := range object { out[entry.Key] = plain(entry.Value) @@ -395,9 +395,9 @@ func objectMap(object vcvalue.Object) map[string]any { return out } -func plain(value any) any { - switch v := value.(type) { - case vcvalue.Object: +func plain(x any) any { + switch v := x.(type) { + case value.Object: return objectMap(v) case []any: out := make([]any, len(v)) diff --git a/languages/golang/internal/guest/diagnostic_test.go b/languages/golang/internal/guest/diagnostic_test.go index 614db9227..f2ee9598b 100644 --- a/languages/golang/internal/guest/diagnostic_test.go +++ b/languages/golang/internal/guest/diagnostic_test.go @@ -9,8 +9,8 @@ import ( "strings" "testing" + "github.com/cipherstash/stack/languages/golang/encrypt/frame" "github.com/cipherstash/stack/languages/golang/internal/guest" - "github.com/cipherstash/vitaminc/bindings/go/vcffi" "github.com/tetratelabs/wazero" "github.com/tetratelabs/wazero/experimental" ) @@ -186,7 +186,7 @@ func callStub(t *testing.T, status uint32, detail []byte, mode lastErrorMode) ([ func encode(t *testing.T, v any) []byte { t.Helper() - raw, err := vcffi.Marshal(v) + raw, err := frame.Marshal(v) if err != nil { t.Fatal(err) } diff --git a/languages/golang/internal/guest/wipe.go b/languages/golang/internal/guest/wipe.go index bbafa00f0..8fece4f01 100644 --- a/languages/golang/internal/guest/wipe.go +++ b/languages/golang/internal/guest/wipe.go @@ -1,14 +1,18 @@ package guest -import "github.com/cipherstash/vitaminc/bindings/go/vcvalue" +import "github.com/cipherstash/stack/languages/golang/encrypt/value" -// WipeDecoded zeroes every []byte in a value vcffi.Unmarshal returned: the -// bytes at its top level, in a list ([]any) and in an object -// (vcvalue.Object), at any depth. Unmarshal gives every bytes leaf its own -// copy, so a decoder that refuses a frame calls it on the whole decoded -// value before it returns: what it had not read yet, or had read and then -// refused, can hold a credential too. Text and numbers are left as they are: -// a Go string cannot be wiped. +// WipeDecoded sets to zero every []byte in a value that frame.Unmarshal +// returned. That covers bytes at the top level, in a list ([]any), and in an +// object (value.Object), at any depth. +// +// Unmarshal gives every bytes value a copy of its own. A decoder that +// refuses a frame therefore calls WipeDecoded on the whole decoded value +// before it returns. The parts that the decoder had not read yet can contain +// a credential. So can the parts that it read and then refused. +// +// WipeDecoded leaves text and numbers unchanged, because a Go string cannot +// be wiped. func WipeDecoded(v any) { switch v := v.(type) { case []byte: @@ -17,7 +21,7 @@ func WipeDecoded(v any) { for _, item := range v { WipeDecoded(item) } - case vcvalue.Object: + case value.Object: for _, f := range v { WipeDecoded(f.Value) } diff --git a/languages/golang/internal/guest/wipe_test.go b/languages/golang/internal/guest/wipe_test.go index 1b2bc3faa..e94a8b689 100644 --- a/languages/golang/internal/guest/wipe_test.go +++ b/languages/golang/internal/guest/wipe_test.go @@ -4,27 +4,27 @@ import ( "bytes" "testing" + "github.com/cipherstash/stack/languages/golang/encrypt/frame" + "github.com/cipherstash/stack/languages/golang/encrypt/value" "github.com/cipherstash/stack/languages/golang/internal/guest" - "github.com/cipherstash/vitaminc/bindings/go/vcffi" - "github.com/cipherstash/vitaminc/bindings/go/vcvalue" ) func TestWipeDecodedZeroesEveryBytesLeafAtAnyDepth(t *testing.T) { secret := func() []byte { return []byte("secret") } - raw, err := vcffi.Marshal(vcvalue.Object{ + raw, err := frame.Marshal(value.Object{ {Key: "top", Value: secret()}, {Key: "text", Value: "kept"}, {Key: "n", Value: uint64(7)}, {Key: "list", Value: []any{secret(), "kept", []any{secret()}}}, - {Key: "object", Value: vcvalue.Object{ + {Key: "object", Value: value.Object{ {Key: "inner", Value: secret()}, - {Key: "deeper", Value: vcvalue.Object{{Key: "leaf", Value: secret()}}}, + {Key: "deeper", Value: value.Object{{Key: "leaf", Value: secret()}}}, }}, }) if err != nil { t.Fatal(err) } - decoded, err := vcffi.Unmarshal(raw) + decoded, err := frame.Unmarshal(raw) if err != nil { t.Fatal(err) } @@ -38,7 +38,7 @@ func TestWipeDecodedZeroesEveryBytesLeafAtAnyDepth(t *testing.T) { for _, item := range v { collect(item) } - case vcvalue.Object: + case value.Object: for _, f := range v { collect(f.Value) } @@ -54,14 +54,14 @@ func TestWipeDecodedZeroesEveryBytesLeafAtAnyDepth(t *testing.T) { t.Errorf("bytes leaf %d was not wiped", i) } } - obj := decoded.(vcvalue.Object) + obj := decoded.(value.Object) if obj[1].Value != "kept" || obj[2].Value != uint64(7) { t.Error("a value that is not bytes changed") } } func TestWipeDecodedTakesAnyValue(t *testing.T) { - for _, v := range []any{nil, "text", uint64(1), true, []byte{}, []any{}, vcvalue.Object{}} { + for _, v := range []any{nil, "text", uint64(1), true, []byte{}, []any{}, value.Object{}} { guest.WipeDecoded(v) } b := []byte("secret") diff --git a/languages/golang/internal/record/record.go b/languages/golang/internal/record/record.go index 6e5d71037..7095580b5 100644 --- a/languages/golang/internal/record/record.go +++ b/languages/golang/internal/record/record.go @@ -30,7 +30,7 @@ import ( "strings" "unicode" - "github.com/cipherstash/vitaminc/bindings/go/vcvalue" + "github.com/cipherstash/stack/languages/golang/encrypt/value" ) // Kind is a plan field's declared type: the data form of the Rust chain's @@ -195,17 +195,17 @@ func (o *TargetOptions) ElementArrays() []ElementArray { } // wire is the options object as the plan spells it: only the options set. -func (o *TargetOptions) wire() vcvalue.Object { - out := vcvalue.Object{} +func (o *TargetOptions) wire() value.Object { + out := value.Object{} if o.SealedRoot != nil { - out = append(out, vcvalue.Field{Key: "sealed_root", Value: *o.SealedRoot}) + out = append(out, value.Field{Key: "sealed_root", Value: *o.SealedRoot}) } if o.Ordered != nil { paths := make([]any, len(o.Ordered)) for i, p := range o.Ordered { paths[i] = p } - out = append(out, vcvalue.Field{Key: "ordered", Value: paths}) + out = append(out, value.Field{Key: "ordered", Value: paths}) } return out } @@ -511,19 +511,19 @@ func (p *Plan) Field(name string) *Field { // (the label, extended), its outputs or its target, and its type; with a // context field, the plan-level "context_field" key and that field's own // entry, a passthrough of type string. Validate first. -func (p *Plan) Wire() vcvalue.Object { - out := make(vcvalue.Object, 0, len(p.Fields)+3) +func (p *Plan) Wire() value.Object { + out := make(value.Object, 0, len(p.Fields)+3) if len(p.Bind) != 0 { parts := make([]any, len(p.Bind)) for i, part := range p.Bind { parts[i] = ownPart(part) } - out = append(out, vcvalue.Field{Key: "bind", Value: parts}) + out = append(out, value.Field{Key: "bind", Value: parts}) } if p.ContextField != "" { out = append(out, - vcvalue.Field{Key: "context_field", Value: p.ContextField}, - vcvalue.Field{Key: p.ContextField, Value: vcvalue.Object{ + value.Field{Key: "context_field", Value: p.ContextField}, + value.Field{Key: p.ContextField, Value: value.Object{ {Key: "context", Value: p.FieldContext(Field{Name: p.ContextField})}, {Key: "outputs", Value: []any{string(Passthrough)}}, {Key: "type", Value: string(String)}, @@ -531,29 +531,29 @@ func (p *Plan) Wire() vcvalue.Object { ) } for _, f := range p.Fields { - spec := vcvalue.Object{{Key: "context", Value: p.FieldContext(f)}} + spec := value.Object{{Key: "context", Value: p.FieldContext(f)}} switch { case f.IsTarget() && f.TargetOptions != nil: - spec = append(spec, vcvalue.Field{Key: "target", Value: vcvalue.Object{ + spec = append(spec, value.Field{Key: "target", Value: value.Object{ {Key: "name", Value: f.Target}, {Key: "options", Value: f.TargetOptions.wire()}, }}) case f.IsTarget(): - spec = append(spec, vcvalue.Field{Key: "target", Value: f.Target}) + spec = append(spec, value.Field{Key: "target", Value: f.Target}) default: outputs := make([]any, len(f.Outputs)) for i, o := range f.Outputs { outputs[i] = string(o) } - spec = append(spec, vcvalue.Field{Key: "outputs", Value: outputs}) + spec = append(spec, value.Field{Key: "outputs", Value: outputs}) } if f.Kind != Untyped { - spec = append(spec, vcvalue.Field{Key: "type", Value: string(f.Kind)}) + spec = append(spec, value.Field{Key: "type", Value: string(f.Kind)}) } if f.Null != NotNull { - spec = append(spec, vcvalue.Field{Key: "null", Value: string(f.Null)}) + spec = append(spec, value.Field{Key: "null", Value: string(f.Null)}) } - out = append(out, vcvalue.Field{Key: f.Name, Value: spec}) + out = append(out, value.Field{Key: f.Name, Value: spec}) } return out } diff --git a/languages/golang/internal/record/record_test.go b/languages/golang/internal/record/record_test.go index 29dd1edc9..adc414c61 100644 --- a/languages/golang/internal/record/record_test.go +++ b/languages/golang/internal/record/record_test.go @@ -5,8 +5,8 @@ import ( "strings" "testing" - "github.com/cipherstash/vitaminc/bindings/go/vcffi" - "github.com/cipherstash/vitaminc/bindings/go/vcvalue" + "github.com/cipherstash/stack/languages/golang/encrypt/frame" + "github.com/cipherstash/stack/languages/golang/encrypt/value" ) func users() *Plan { @@ -23,18 +23,18 @@ func TestWireIsTheFixturesPlan(t *testing.T) { t.Fatal(err) } wire := p.Wire() - want := vcvalue.Object{ - {Key: "age", Value: vcvalue.Object{ + want := value.Object{ + {Key: "age", Value: value.Object{ {Key: "context", Value: []any{"users", "age"}}, {Key: "outputs", Value: []any{"c", "eq", "ore"}}, {Key: "type", Value: "uint32"}, }}, - {Key: "email", Value: vcvalue.Object{ + {Key: "email", Value: value.Object{ {Key: "context", Value: []any{"users", "email"}}, {Key: "outputs", Value: []any{"c", "eq", "match"}}, {Key: "type", Value: "string"}, }}, - {Key: "notes", Value: vcvalue.Object{ + {Key: "notes", Value: value.Object{ {Key: "context", Value: []any{"users", "notes"}}, {Key: "outputs", Value: []any{"c"}}, {Key: "type", Value: "string"}, @@ -43,7 +43,7 @@ func TestWireIsTheFixturesPlan(t *testing.T) { if !reflect.DeepEqual(wire, want) { t.Fatalf("Wire = %#v", wire) } - if _, err := vcffi.Marshal(wire); err != nil { + if _, err := frame.Marshal(wire); err != nil { t.Fatal(err) } } @@ -62,7 +62,7 @@ func TestExtensionNestsToTheLeftAndIdentityReplacesTheName(t *testing.T) { t.Fatalf("Descriptor = %q", p.Descriptor(p.Fields[0])) } // An untyped field carries no "type" key. - if spec := p.Wire()[0].Value.(vcvalue.Object); len(spec) != 2 { + if spec := p.Wire()[0].Value.(value.Object); len(spec) != 2 { t.Fatalf("untyped field spec = %#v", spec) } // A byte part is copied. @@ -86,13 +86,13 @@ func TestTargetFieldWiresItsTypeInsteadOfOutputs(t *testing.T) { if !p.Fields[0].IsTarget() || !p.Fields[0].HasCiphertext() || p.Fields[1].IsTarget() { t.Fatal("a target field is one, and is opened; a sealed field is not a target") } - want := vcvalue.Object{ - {Key: "email", Value: vcvalue.Object{ + want := value.Object{ + {Key: "email", Value: value.Object{ {Key: "context", Value: []any{"users", "email"}}, {Key: "target", Value: "TextEq"}, {Key: "type", Value: "string"}, }}, - {Key: "notes", Value: vcvalue.Object{ + {Key: "notes", Value: value.Object{ {Key: "context", Value: []any{"users", "notes"}}, {Key: "outputs", Value: []any{"c"}}, {Key: "type", Value: "string"}, @@ -199,20 +199,20 @@ func TestWireGivesATargetItsOptions(t *testing.T) { t.Fatal(err) } wire := p.Wire() - target := func(i int) any { return wire[i].Value.(vcvalue.Object)[1].Value } - want := vcvalue.Object{{Key: "name", Value: "JsonSearch"}, {Key: "options", Value: vcvalue.Object{ + target := func(i int) any { return wire[i].Value.(value.Object)[1].Value } + want := value.Object{{Key: "name", Value: "JsonSearch"}, {Key: "options", Value: value.Object{ {Key: "sealed_root", Value: false}, {Key: "ordered", Value: []any{"$.age"}}, }}} if !reflect.DeepEqual(target(0), want) { t.Fatalf("target = %#v", target(0)) } - if !reflect.DeepEqual(target(1), vcvalue.Object{{Key: "name", Value: "JsonSearch"}, {Key: "options", Value: vcvalue.Object{}}}) { + if !reflect.DeepEqual(target(1), value.Object{{Key: "name", Value: "JsonSearch"}, {Key: "options", Value: value.Object{}}}) { t.Fatalf("empty options = %#v", target(1)) } if target(2) != "JsonSearch" { t.Fatalf("no options = %#v", target(2)) } - if typ := wire[0].Value.(vcvalue.Object)[2]; typ.Key != "type" || typ.Value != "json" { + if typ := wire[0].Value.(value.Object)[2]; typ.Key != "type" || typ.Value != "json" { t.Fatalf("type = %#v", typ) } bad := &Plan{Context: []string{"users"}, Fields: []Field{{Name: "a", Kind: String, Outputs: []Output{Ciphertext}, TargetOptions: &TargetOptions{}}}} diff --git a/languages/golang/stashgen/read.go b/languages/golang/stashgen/read.go index 8b6131628..113c65863 100644 --- a/languages/golang/stashgen/read.go +++ b/languages/golang/stashgen/read.go @@ -17,6 +17,7 @@ const ( encryptPath = "github.com/cipherstash/stack/languages/golang/encrypt" eqlPath = encryptPath + "/eql" gensupportPath = encryptPath + "/gensupport" + valuePath = encryptPath + "/value" ) // genFile is everything the emitter needs for one generated file. The reader @@ -975,16 +976,14 @@ func classify(t types.Type, typeExpr func(types.Type) string, seen map[types.Typ return g } -// vcvaluePath is vitaminc's Go value module, whose types encrypt's value -// types alias. -const vcvaluePath = "github.com/cipherstash/vitaminc/bindings/go/vcvalue" - -// valueKind is the kind of a value type the generator knows by name: -// time.Time, json.RawMessage, and encrypt's Date, Int128, Uint128 and -// Decimal, whether the field names the alias in encrypt or the vcvalue type -// it stands for, or an alias of any of them. A type defined over one of -// them is not one: the codec writes these by their exact type, so it is -// classified by its underlying type and refused as a struct or array. +// valueKind returns the kind of a value type that the generator recognises +// by name. Those types are time.Time, json.RawMessage, and Date, Int128, +// Uint128, and Decimal, by their names in package encrypt or package value. +// An alias of any of them is recognised too. +// +// A type defined over one of them is not a value type, because the codec +// matches these types exactly. The generator classifies such a type by its +// underlying type, and refuses it as a struct or an array. func valueKind(t types.Type) (Kind, bool) { named := func(t types.Type) (string, string, bool) { switch t := t.(type) { @@ -1010,7 +1009,7 @@ func valueKind(t types.Type) (Kind, bool) { if path == "encoding/json" && name == "RawMessage" { return KindJSON, true } - if path != encryptPath && path != vcvaluePath { + if path != encryptPath && path != valuePath { continue } switch name { @@ -1156,28 +1155,50 @@ func itOrEach(fields []string) string { return "each" } -// notCarried says why an opaque struct's field type cannot be carried both -// ways by the two codecs every such field must satisfy, as a reason from -// each, or "" from one that carries it. encoding/json: a row an earlier -// release sealed holds the struct as one JSON document, which comes back -// by decoding it into the generated shape struct. The storage profile -// (vcffi.MarshalStorage and UnmarshalStorage): the struct is sealed as a -// storage blob now. One walk asks both rules of every type it reaches, so -// a case one rule covers and the other does not cannot fall between two -// walkers; byJSON and byStorage say which rules still apply, and each stops -// below a type that carries itself (a MarshalJSON and UnmarshalJSON pair -// for JSON, a MarshalText and UnmarshalText pair for storage). +// notCarried reports why the field type of an opaque struct cannot be +// encoded and decoded by both codecs that every such field must work with. +// The function returns one reason for each codec, or "" for a codec that +// accepts the type. The two codecs are these: +// +// - encoding/json. A row that an earlier release sealed has the struct as +// one JSON document. That document is decoded into the generated shape +// struct. +// - The storage profile, frame.MarshalStorage and frame.UnmarshalStorage. +// A struct that this release seals is a storage blob. +// +// One traversal applies both rules to every type that it reaches. With two +// separate traversals, a case that one rule covers and the other does not +// could be missed. The arguments byJSON and byStorage say which rules still +// apply. +// +// Each rule stops below a type that encodes itself. For JSON, that is a type +// with MarshalJSON and UnmarshalJSON. For storage, that is a type with +// MarshalText and UnmarshalText. +// +// The JSON rule accepts these types: +// +// - a scalar +// - a slice or an array of an accepted type +// - a map with string or integer keys +// - a pointer +// - a struct whose fields are all exported and accepted +// +// A struct with an unexported field would come back without that field. An +// interface or a channel would not come back at all. // -// The JSON rule: a scalar, a slice or array of a carried type, a map with -// string or integer keys, a pointer, or a struct whose every field is -// exported and carried; a struct with an unexported field would come back -// without it, an interface or a channel not at all. The storage rule, -// vcffi's own: a scalar by its kind; a slice, array or pointer by its -// element; a map whose key is an integer, a string, bytes or text, by its -// value; a struct by its exported fields; no logical value type -// (encrypt.Decimal, encrypt.Date, which have no storage form); and no type -// with only half of the text pair. It knows nothing of MarshalJSON, so a -// type that carries itself through JSON alone is walked like any other. +// The storage rule is the rule of the codec: +// +// - For a scalar, the rule checks its kind. +// - For a slice, an array, or a pointer, the rule checks its element. +// - For a map, the rule checks its value. The key must be an integer, a +// string, bytes, or text. +// - For a struct, the rule checks its exported fields. +// - The logical value types encrypt.Decimal and encrypt.Date are refused, +// because they have no storage form. +// - A type with only one method of the text pair is refused. +// +// The storage rule ignores MarshalJSON. A type that encodes itself only +// through JSON is therefore checked like any other type. func notCarried(t types.Type, seen map[types.Type]bool, byJSON, byStorage bool) (asJSON, asBlob string) { if seen[t] || (!byJSON && !byStorage) { return "", "" @@ -1228,10 +1249,10 @@ func notCarried(t types.Type, seen map[types.Type]bool, byJSON, byStorage bool) } return notCarried(u.Elem(), seen, byJSON, byStorage) case *types.Struct: - // Both write a struct by its exported fields and drop the rest: - // vcffi refuses a struct that has unexported fields only, and a - // struct with none at all (struct{}) is an empty object to both, - // read back as itself. + // Both codecs write a struct by its exported fields and leave out + // the other fields. The storage codec refuses a struct that has only + // unexported fields. Both codecs write a struct with no fields, + // struct{}, as an empty object, and read it back as itself. for i := range u.NumFields() { fld := u.Field(i) if !fld.Exported() { @@ -1474,24 +1495,19 @@ func methodOf(t types.Type, name string) (*types.Selection, bool) { return nil, false } -// noStorageForm refuses vitaminc's logical value types, which the -// transport carries and the storage profile does not: encrypt.Date and -// encrypt.Decimal (vcvalue.Date and vcvalue.Decimal), and vcvalue's other -// logical types. Its 128-bit integers and Object have a storage form. +// noStorageForm returns the reason that t has no storage form, when t is a +// logical value type: encrypt.Date or encrypt.Decimal. The transport +// encoding has a form for those types. The storage profile has none. The +// 128-bit integers have a storage form. So does encrypt.UUID, as its sixteen +// bytes. func noStorageForm(t types.Type) string { switch kind, _ := valueKind(t); kind { case KindDate: return "is a date, which has no storage form (store it as text, or by its parts)" case KindDecimal: return "is a decimal, which has no storage form (store it as text, or by its parts)" - case KindInt128, KindUint128: - return "" } - named, ok := types.Unalias(t).(*types.Named) - if !ok || named.Obj().Pkg() == nil || named.Obj().Pkg().Path() != vcvaluePath || named.Obj().Name() == "Object" { - return "" - } - return "is vcvalue." + named.Obj().Name() + ", which has no storage form" + return "" } // textForm reports whether t is written as its text, and why not when it @@ -1519,10 +1535,14 @@ func textForm(t types.Type) (bool, string) { return false, "" } -// notStorableKey says why a map key has no storage form: vcffi takes an -// integer, a string, bytes (a byte array, a 128-bit integer; a slice is -// not comparable, so Go never keys a map by one) or a type with MarshalText -// and UnmarshalText. +// notStorableKey returns the reason that the map key type k has no storage +// form, or "" when k has one. The codec accepts four kinds of key: +// +// - an integer +// - a string +// - a byte array, including a 128-bit integer. A byte slice is not +// comparable, so Go never uses one as a map key. +// - a type with both MarshalText and UnmarshalText func notStorableKey(k types.Type) string { if kind, _ := valueKind(k); kind == KindInt128 || kind == KindUint128 { return "" diff --git a/languages/golang/stashgen/refusal_test.go b/languages/golang/stashgen/refusal_test.go index d25d712e4..baada7842 100644 --- a/languages/golang/stashgen/refusal_test.go +++ b/languages/golang/stashgen/refusal_test.go @@ -50,6 +50,11 @@ func user(fields string) string { return "package users\n\nimport (\n\t\"time\"\n\n\t\"example.com/app/crm\"\n\t\"github.com/cipherstash/stack/languages/golang/encrypt\"\n\t\"gorm.io/gorm\"\n)\n\nvar (\n\t_ time.Time\n\t_ crm.Contact\n\t_ encrypt.Cipher\n\t_ gorm.Model\n)\n\ntype User struct {\n" + fields + "\n}\n" } +// userWithValue is user, with package value imported too. +func userWithValue(fields string) string { + return strings.Replace(user(fields), "\t\"github.com/cipherstash/stack/languages/golang/encrypt\"\n", "\t\"github.com/cipherstash/stack/languages/golang/encrypt\"\n\t\"github.com/cipherstash/stack/languages/golang/encrypt/value\"\n", 1) + "\nvar _ value.Date\n" +} + const ctx = "\t_ struct{} `stash:\"context=users\"`\n" // TestRefusals covers every entry of the refusal list in the plan's stashgen @@ -107,6 +112,7 @@ func TestRefusals(t *testing.T) { {"an opaque struct with a type that writes itself only as JSON", user("\t_ struct{} `stash:\"context=users,opaque\"`\n\tTx jsonOnly") + "\ntype jsonOnly struct {\n\tA int\n\tb int\n}\n\nfunc (j jsonOnly) MarshalJSON() ([]byte, error) { return nil, nil }\n\nfunc (j *jsonOnly) UnmarshalJSON([]byte) error { return nil }\n", stashgen.Request{Type: "User"}, "Tx", "a storage blob would drop"}, {"an opaque struct with a decimal", user("\t_ struct{} `stash:\"context=users,opaque\"`\n\tAmount encrypt.Decimal"), stashgen.Request{Type: "User"}, "Amount", "has no storage form"}, {"an opaque struct with a date in a slice", user("\t_ struct{} `stash:\"context=users,opaque\"`\n\tDays []encrypt.Date"), stashgen.Request{Type: "User"}, "Days", "has no storage form"}, + {"an opaque struct with a date of package value", userWithValue("\t_ struct{} `stash:\"context=users,opaque\"`\n\tDays []value.Date"), stashgen.Request{Type: "User"}, "Days", "has no storage form"}, {"an opaque struct with a type that writes text it cannot read", user("\t_ struct{} `stash:\"context=users,opaque\"`\n\tL level") + "\ntype level int\n\nfunc (l level) MarshalText() ([]byte, error) { return nil, nil }\n", stashgen.Request{Type: "User"}, "L", "MarshalText but no UnmarshalText"}, {"an opaque struct with a pointer to a type that writes text it cannot read", user("\t_ struct{} `stash:\"context=users,opaque\"`\n\tL *level") + "\ntype level int\n\nfunc (l level) MarshalText() ([]byte, error) { return nil, nil }\n", stashgen.Request{Type: "User"}, "L", "MarshalText but no UnmarshalText"}, {"an opaque struct with a type that reads text it does not write", user("\t_ struct{} `stash:\"context=users,opaque\"`\n\tL level") + "\ntype level int\n\nfunc (l *level) UnmarshalText([]byte) error { return nil }\n", stashgen.Request{Type: "User"}, "L", "UnmarshalText but no MarshalText"}, diff --git a/languages/golang/stashgen/testdata/stubsdk/encrypt/encrypt.go b/languages/golang/stashgen/testdata/stubsdk/encrypt/encrypt.go index e15eb2e04..5d3d53295 100644 --- a/languages/golang/stashgen/testdata/stubsdk/encrypt/encrypt.go +++ b/languages/golang/stashgen/testdata/stubsdk/encrypt/encrypt.go @@ -9,7 +9,8 @@ package encrypt import ( "context" "encoding/json" - "time" + + "github.com/cipherstash/stack/languages/golang/encrypt/value" ) // Cipher is a keyset with any extension of the context. @@ -103,22 +104,14 @@ type clientOptions struct{} // Close closes the client. func (*Client) Close() error { return nil } -// The value types a field can hold beside Go's own. The real ones are -// aliases of vitaminc's vcvalue types; the generator recognises them by -// their name in this package. +// The value types that a field can have, in addition to Go's own types. As +// in the SDK, each is declared in package value, and named here by an alias. +// The generator recognises them by their names in either package. type ( - Date struct { - Year int - Month time.Month - Day int - } - Int128 [16]byte - Uint128 [16]byte - Decimal struct { - Coefficient [12]byte - Scale uint8 - Negative bool - } + Date = value.Date + Int128 = value.Int128 + Uint128 = value.Uint128 + Decimal = value.Decimal ) // JSONSelector is the selector `col -> $1::text` binds. diff --git a/languages/golang/stashgen/testdata/stubsdk/encrypt/value/value.go b/languages/golang/stashgen/testdata/stubsdk/encrypt/value/value.go new file mode 100644 index 000000000..16ee7c197 --- /dev/null +++ b/languages/golang/stashgen/testdata/stubsdk/encrypt/value/value.go @@ -0,0 +1,21 @@ +// Package value is a stand-in for the SDK's package value: the value types +// that a field can have, in addition to Go's own types. Package encrypt names +// them with aliases, as the SDK does. +package value + +import "time" + +type ( + Date struct { + Year int + Month time.Month + Day int + } + Int128 [16]byte + Uint128 [16]byte + Decimal struct { + Coefficient [12]byte + Scale uint8 + Negative bool + } +) diff --git a/mise.toml b/mise.toml index 8a592e922..5b4c2fdbb 100644 --- a/mise.toml +++ b/mise.toml @@ -399,7 +399,7 @@ description = "Format check, vet and test the Go module (languages/golang: encry run = "scripts/go-binding-test.sh languages/golang" [tasks."go:fuzz"] -description = "Fuzz the guests' ABI from Go: run every Fuzz* target in languages/golang for GO_FUZZTIME each (default 60s), or only the target GO_FUZZ names; needs `wasm:guest:build:deterministic` and `wasm:auth-guest:build` first" +description = "Fuzz the guests' ABI and the frame codec from Go: run every Fuzz* target in languages/golang for GO_FUZZTIME each (default 60s), or only the target GO_FUZZ names; the encrypt and auth targets need `wasm:guest:build:deterministic` and `wasm:auth-guest:build` first, and the frame codec's need no guest" dir = "languages/golang" shell = "bash -c" # `go test -fuzz` takes one target in one package at a time, so the targets diff --git a/packages/recipher-frame/STORAGE.md b/packages/recipher-frame/STORAGE.md index 09f2daec8..6c3397af2 100644 --- a/packages/recipher-frame/STORAGE.md +++ b/packages/recipher-frame/STORAGE.md @@ -115,8 +115,9 @@ Stable, and covered by this specification: and `storage::MAP`; - `storage::ErrorKind`, the class of a refusal. -The Go module `bindings/go/vcffi` implements the same format -(`MarshalStorage`, `UnmarshalStorage`). +The frame codec of the Go SDK, in `languages/golang/encrypt/frame`, +implements the same format with `MarshalStorage` and `UnmarshalStorage`. +The tests of that codec read the same corpus. Not stable, and not covered: everything else in `recipher-frame`. The transport frame (`Frame`, `FrameWriter`, `to_frame`), the transport @@ -326,8 +327,8 @@ write different bytes (`1u8` and `1u32`), NaN payloads are kept, and a reader accepts the extra forms listed above. Compare values, not blobs, unless the type is one whose bytes are fixed. -Writers in other languages make the same choice. Go's `vcffi` writes a -non-nil pointer as its value, unmarked, as `encoding/json` does, where Rust +Writers in other languages make the same choice. The Go codec writes a +non-nil pointer as its value, with no marker, as `encoding/json` does. Rust writes `Some(x)` as `some`, then `x`. So `&int32(5)` in Go and `Some(5i32)` in Rust are different blobs. Both readers read both forms, as the same value. diff --git a/packages/recipher-frame/tests/serde.rs b/packages/recipher-frame/tests/serde.rs index de969eec0..ba092176c 100644 --- a/packages/recipher-frame/tests/serde.rs +++ b/packages/recipher-frame/tests/serde.rs @@ -42,9 +42,10 @@ enum Keyset { Id(#[serde(with = "serde_bytes")] Vec), } -/// The bytes the Go SDK's codec (`vcffi.Marshal`) writes for -/// `{"keyset": {"name": "acme"}, "context": "tenants/acme"}`: Go orders an -/// object's keys, so `context` comes first. +/// The bytes that the frame codec of the Go SDK writes for `{"keyset": +/// {"name": "acme"}, "context": "tenants/acme"}`. The codec is in +/// `languages/golang/encrypt/frame`. Go sorts the keys of an object, so +/// `context` comes first. const GO_OPTIONS: &str = "f10200000007000000636f6e746578740a0c00000074656e616e74732f61636d65060000006b6579736574f101000000040000006e616d650a0400000061636d65"; /// `{"keyset": {"default": {}}}`, as Go writes it. diff --git a/packages/stack-encrypt/Cargo.toml b/packages/stack-encrypt/Cargo.toml index 4f617651a..1174ee062 100644 --- a/packages/stack-encrypt/Cargo.toml +++ b/packages/stack-encrypt/Cargo.toml @@ -67,11 +67,15 @@ rand = { version = "0.10.1", default-features = false } # credential loads the default keyset, so callers arriving together make # one load between them. futures = { version = "0.3.25", default-features = false, features = ["std"] } -# Two things: the storage profile (`storage`, behind `serde`) that -# `OpaqueBlob` encodes a whole value with before sealing it as one leaf, -# the same versioned bytes the Go SDK writes through `vcffi.MarshalStorage`; -# and, for `dynamic`, serde over the transport frame, which reads a binding's -# control data (statistics, options, a plan) into typed messages. +# This crate uses recipher-frame for two things: +# +# - The storage profile, `storage`, behind the `serde` feature. `OpaqueBlob` +# encodes a whole value with it, then seals the value as one leaf. The frame +# codec of the Go SDK writes the same versioned bytes for an opaque struct. +# That codec is in `languages/golang/encrypt/frame`. +# - For the `dynamic` feature, serde over the transport frame. That code reads +# the control data of a binding into typed messages. Control data is +# statistics, options, or a plan. recipher-frame = { workspace = true, features = ["serde"] } serde = { workspace = true } # `deserialize_in_place`: `#[derive(Deserialize)]` also writes diff --git a/packages/stack-encrypt/src/blob.rs b/packages/stack-encrypt/src/blob.rs index c3977a49e..dad9fd92c 100644 --- a/packages/stack-encrypt/src/blob.rs +++ b/packages/stack-encrypt/src/blob.rs @@ -97,11 +97,12 @@ //! - map keys that keep their kind //! - a promise that a version's bytes never change meaning //! -//! The specification is `STORAGE.md` in the `recipher-frame` crate. -//! Every implementation must pass its golden corpus of test vectors. The Go -//! SDK writes and reads the same profile through `vcffi`, so a Go opaque -//! struct and a Rust `OpaqueBlob` are one stored format. See [Go](#go) -//! for the type rules. +//! The specification is `STORAGE.md` in the `recipher-frame` crate. Every +//! implementation must pass its golden corpus of test vectors. The Go SDK +//! writes and reads the same profile with its frame codec, in +//! `languages/golang/encrypt/frame`. A Go opaque struct and a Rust +//! `OpaqueBlob` therefore have one stored format. See [Go](#go) for the +//! type rules. //! //! Every blob starts with [`HEADER`]: the ASCII bytes `VCS`, then the //! version byte, [`VERSION`]. The header is part of the plaintext, so it is diff --git a/packages/stack-encrypt/tests/opaque_blob.rs b/packages/stack-encrypt/tests/opaque_blob.rs index deac81eb4..c31b2f541 100644 --- a/packages/stack-encrypt/tests/opaque_blob.rs +++ b/packages/stack-encrypt/tests/opaque_blob.rs @@ -263,12 +263,14 @@ impl Zeroize for WitnessThenMore { /// reads the same hex: Rust writes, Go reads. const RUST_BLOB: &str = "56435301f104000000040000006e616d650a0c000000416461204c6f76656c6163650300000061676506240000000400000074616773f0020000000a050000006d617468730a07000000656e67696e6573080000006e69636b6e616d65f50a03000000616461"; -/// `ada()` as the Go SDK writes it, through `vcffi.MarshalStorage`, from a -/// struct with the tags `vc:"name"`, `vc:"age"`, `vc:"tags"` and -/// `vc:"nickname"`, where the nickname is a non-nil `*string`. Go writes a -/// non-nil pointer as the bare value, and Rust writes `Some` with a marker -/// byte, so this is one byte shorter than [`RUST_BLOB`]. The Go test -/// `TestOpaqueReadsARustWrittenBlob` pins the same hex. +/// The blob that the Go SDK writes for `ada()`, with the storage profile of +/// its frame codec in `languages/golang/encrypt/frame`. The Go struct has +/// the tags `vc:"name"`, `vc:"age"`, `vc:"tags"`, and `vc:"nickname"`. The +/// nickname is a non-nil `*string`. +/// +/// Go writes a non-nil pointer as the value alone. Rust writes `Some` with a +/// marker byte, so this blob is one byte shorter than [`RUST_BLOB`]. The Go +/// test `TestOpaqueReadsARustWrittenBlob` checks the same hex. const GO_BLOB_SOME: &str = "56435301f104000000040000006e616d650a0c000000416461204c6f76656c6163650300000061676506240000000400000074616773f0020000000a050000006d617468730a07000000656e67696e6573080000006e69636b6e616d650a03000000616461"; /// [`GO_BLOB_SOME`] with the nickname a nil pointer, which Go writes as null. diff --git a/packages/stack-encrypt/tests/value_bytes.rs b/packages/stack-encrypt/tests/value_bytes.rs index 57967889e..f7638a332 100644 --- a/packages/stack-encrypt/tests/value_bytes.rs +++ b/packages/stack-encrypt/tests/value_bytes.rs @@ -525,9 +525,9 @@ async fn host_section(cipher: &StackCipher, keys: &Kept) -> Json { Json::Object(out) } -/// A typed null a host sends (Go's `vcvalue.TypedNull`, or a nil pointer to -/// a fixed-width type), against each null policy of a typed field, an -/// untyped field, and inside an untyped value. +/// Checks a typed null that a host sends, for each null policy of a typed +/// field, for an untyped field, and inside an untyped value. Go writes a +/// typed null for a nil pointer to a fixed-width type. async fn typed_null_section(cipher: &StackCipher, keys: &Kept) -> Json { let int32 = typed_null(FixedType::new(None, Width::I32).expect("a fixed type")); let int64 = typed_null(FixedType::new(None, Width::I64).expect("a fixed type")); diff --git a/packages/stack-guest-abi/Cargo.toml b/packages/stack-guest-abi/Cargo.toml index 2d51d9115..ecfdff38f 100644 --- a/packages/stack-guest-abi/Cargo.toml +++ b/packages/stack-guest-abi/Cargo.toml @@ -9,8 +9,8 @@ homepage.workspace = true keywords.workspace = true categories.workspace = true license-file = "LICENSE" -# Internal plumbing for the guests under bindings/go, never a release of its -# own; also keeps release-plz from picking it up. +# This crate is internal to the guests under languages/golang, so it is never +# published. The setting also stops release-plz from releasing it. publish = false [dependencies] diff --git a/packages/stack-guest-abi/src/buffers.rs b/packages/stack-guest-abi/src/buffers.rs index 109b56e9f..e50f3e5a0 100644 --- a/packages/stack-guest-abi/src/buffers.rs +++ b/packages/stack-guest-abi/src/buffers.rs @@ -1,7 +1,6 @@ -//! The guest-owned buffer registry behind `se_alloc` / `se_dealloc`, -//! following the vitaminc guest's conventions (see `vcencrypt/guest/src/ -//! abi.rs`). Shared by every guest under `bindings/go`, so the registry -//! discipline is written once: +//! The registry of buffers that the guest owns, used by `se_alloc` and +//! `se_dealloc`. Every guest under `languages/golang` shares this module, so +//! the rules of the registry are written once: //! //! - Every buffer the guest hands out — from [`alloc`] and from packed //! results — is recorded here keyed by start address, holding the true diff --git a/packages/stack-guest-abi/src/value.rs b/packages/stack-guest-abi/src/value.rs index 67d9b8134..bc551b6bf 100644 --- a/packages/stack-guest-abi/src/value.rs +++ b/packages/stack-guest-abi/src/value.rs @@ -1,13 +1,16 @@ //! [`HostValue`]: a value a guest hands its host, and how it crosses the //! boundary. //! -//! Every structured output a guest returns (a list of workspace ids, the -//! fields of a token, the last error) crosses as one transport frame, the -//! encoding vitaminc's `Frame` and `FrameWriter` define and the Go module -//! reads with `vcffi`. A `HostValue` describes itself to vitaminc's -//! [`Encrypt`] model, so [`encode`](HostValue::encode) is vitaminc's own -//! frame writer, and [`decode`](HostValue::decode) reads a frame back -//! through a [`Sink`], for the tests that check what a host is given. +//! Every structured output that a guest returns crosses to the host as one +//! transport frame. Examples are a list of workspace ids, the fields of a +//! token, and the last error. `Frame` and `FrameWriter` in `recipher-frame` +//! define the encoding. The Go module reads it with its frame codec, in +//! `languages/golang/encrypt/frame`. +//! +//! A `HostValue` implements the [`Encrypt`] model of `vitaminc-aead`. +//! [`encode`](HostValue::encode) therefore uses the frame writer of +//! `recipher-frame`. [`decode`](HostValue::decode) reads a frame back +//! through a [`Sink`]. The tests use `decode` to check what a host is given. use recipher_frame::{to_frame, Frame, FrameError, FrameWriteError}; use vitaminc_aead::plaintext::{ diff --git a/scripts/__tests__/go-release-version.test.mjs b/scripts/__tests__/go-release-version.test.mjs index ed2639573..09c4ed3ff 100644 --- a/scripts/__tests__/go-release-version.test.mjs +++ b/scripts/__tests__/go-release-version.test.mjs @@ -6,7 +6,6 @@ import { allowedMajors, goReleaseVersionErrors, modulePathOf, - vitamincPseudoVersions, } from '../go-release-version.mjs' import { REPO_ROOT } from './lib/repo-root.mjs' import { readWorkflow } from './lib/workflows.mjs' @@ -20,26 +19,8 @@ const MODULE = 'github.com/cipherstash/stack/languages/golang' const MAIN = 'refs/heads/main' const BRANCH = 'refs/heads/ci/golang-release' -const errorsFor = (version, ref = MAIN, modulePath = MODULE, goMod = '') => - goReleaseVersionErrors(version, { modulePath, ref, goMod }) - -const VCFFI = 'github.com/cipherstash/vitaminc/bindings/go/vcffi' -const VCVALUE = 'github.com/cipherstash/vitaminc/bindings/go/vcvalue' -const PSEUDO = 'v0.0.0-20261026030854-d7de535c4288' - -// A go.mod whose vitaminc modules are at `version`, with the TEMPORARY -// comment the real one carries when that is a pseudo-version. -const goModPinning = (version) => `module ${MODULE} - -go 1.26.10 - -// TEMPORARY: vcffi and vcvalue at vitaminc d7de535c4 (v0.0.0-20261026030854-d7de535c4288). -require ( - ${VCFFI} ${version} - ${VCVALUE} ${version} - github.com/tetratelabs/wazero v1.12.0 -) -` +const errorsFor = (version, ref = MAIN, modulePath = MODULE) => + goReleaseVersionErrors(version, { modulePath, ref }) describe('goReleaseVersionErrors', () => { it.each([ @@ -99,62 +80,6 @@ describe('goReleaseVersionErrors', () => { }) }) -describe('a TEMPORARY vitaminc pin', () => { - const temporary = goModPinning(PSEUDO) - const released = goModPinning('v0.9.0') - - it('is every vitaminc module go.mod names at a pseudo-version', () => { - expect(vitamincPseudoVersions(temporary)).toEqual([ - `${VCFFI} ${PSEUDO}`, - `${VCVALUE} ${PSEUDO}`, - ]) - // The three pseudo-version forms, and a replace directive, count too. - expect( - vitamincPseudoVersions( - `require ${VCFFI} v0.8.1-0.20261026030854-d7de535c4288\n` + - `replace ${VCVALUE} v0.9.0 => ${VCVALUE} v0.9.1-alpha.1.0.20261026030854-d7de535c4288\n`, - ), - ).toEqual([ - `${VCFFI} v0.8.1-0.20261026030854-d7de535c4288`, - `${VCVALUE} v0.9.1-alpha.1.0.20261026030854-d7de535c4288`, - ]) - }) - - it('is not a tag, a pseudo-version quoted in a comment, or another module', () => { - expect(vitamincPseudoVersions(released)).toEqual([]) - expect( - vitamincPseudoVersions( - `// ${VCFFI} ${PSEUDO}\nrequire github.com/tetratelabs/wazero ${PSEUDO}\n`, - ), - ).toEqual([]) - expect(vitamincPseudoVersions('')).toEqual([]) - }) - - it('refuses a final version, naming the pins', () => { - const errors = errorsFor('0.1.0', MAIN, MODULE, temporary) - expect(errors).toHaveLength(1) - expect(errors[0]).toContain('pseudo-version') - expect(errors[0]).toContain(`${VCFFI} ${PSEUDO}`) - expect(errors[0]).toContain(`${VCVALUE} ${PSEUDO}`) - expect(errors[0]).toContain('0.1.0-alpha.1') - }) - - it('lets a pre-release through, from main or a branch', () => { - expect(errorsFor('0.1.0-alpha.1', MAIN, MODULE, temporary)).toEqual([]) - expect(errorsFor('0.1.0-rc.1', BRANCH, MODULE, temporary)).toEqual([]) - }) - - it('does not hold a final version once the pin is a tag', () => { - expect(errorsFor('0.1.0', MAIN, MODULE, released)).toEqual([]) - }) - - it('is reported alongside the other reasons, not instead of them', () => { - const errors = errorsFor('0.1.0', BRANCH, MODULE, temporary).join('\n') - expect(errors).toContain('released from main only') - expect(errors).toContain('pseudo-version') - }) -}) - describe('allowedMajors', () => { it('reads the /vN suffix and nothing else', () => { expect(allowedMajors(MODULE)).toEqual([0, 1]) @@ -200,19 +125,10 @@ describe('the script as the workflow runs it', () => { expect(out).toContain('::error::') }) - it("reads the tree's go.mod, so a final version is refused while it carries a TEMPORARY vitaminc pin", () => { - const goMod = readFileSync( - join(REPO_ROOT, 'languages/golang/go.mod'), - 'utf8', - ) - const pins = vitamincPseudoVersions(goMod) + it("reads the module path from the tree's go.mod", () => { const { status, out } = run('0.1.0', MAIN) - if (pins.length > 0) { - expect(status).toBe(1) - for (const pin of pins) expect(out).toContain(pin) - } else { - expect(status).toBe(0) - } + expect(status).toBe(0) + expect(out).toContain(`${MODULE} v0.1.0 may be released`) }) it('is what release-golang.yml checks the version with, before any build', () => { diff --git a/scripts/go-binding-test.sh b/scripts/go-binding-test.sh index 8ca97837f..2b4c7c457 100755 --- a/scripts/go-binding-test.sh +++ b/scripts/go-binding-test.sh @@ -63,10 +63,11 @@ if [[ -n "${STACK_CONFORMANCE_OUTPUT:-}" ]]; then fi CGO_ENABLED=0 go test "$@" ./... -# The transport codec's u32-bound guards are load-bearing where int is 32 -# bits (vitaminc's vcffi runs this sweep too); the binding's own reflection -# and buffer arithmetic must hold there as well. Linux hosts execute 386 -# natively; elsewhere the binary cannot run, so only vet. +# The frame codec in encrypt/frame checks that each length and count fits 32 +# bits. Those checks are needed where an int is 32 bits. The reflection and +# the buffer arithmetic of the Go module must be correct there too. A Linux +# host runs a 386 binary natively, so the tests run. On any other host the +# binary cannot run, so only vet runs. if [ "$(uname -s)" = "Linux" ]; then CGO_ENABLED=0 GOOS=linux GOARCH=386 go test "$@" ./... else diff --git a/scripts/go-release-version.mjs b/scripts/go-release-version.mjs index 780339ff7..3ec3569d8 100644 --- a/scripts/go-release-version.mjs +++ b/scripts/go-release-version.mjs @@ -9,7 +9,7 @@ // pushed, rather than by the proxy check at the end of the run, after the tag // exists and the version number is spent. // -// Five rules: +// Four rules: // // 1. CANONICAL SEMVER. Go accepts only `vMAJOR.MINOR.PATCH[-PRERELEASE]` with // no leading zeros in a numeric part or a numeric pre-release identifier, @@ -29,14 +29,6 @@ // the dispatcher picks. A pre-release (a version with a `-suffix`) may be // cut from a branch, which is how a partner alpha is built from an // unmerged stack; a final version may not. -// 5. A FINAL VERSION SHIPS NO TEMPORARY VITAMINC PIN. vitaminc's Go bindings -// (`github.com/cipherstash/vitaminc/bindings/go/…`) have no tags, so -// `go.mod` names them by pseudo-version, and from time to time that is an -// unreleased commit taken ahead of a vitaminc release, marked TEMPORARY in -// `go.mod` and promised in the CHANGELOG to be gone before the module is -// tagged. `release-golang.yml` tags whatever `go.mod` names, so the promise -// is held here: a final version is refused while any vitaminc module is -// pinned to a pseudo-version; a pre-release may carry one. import { readFileSync } from 'node:fs' import { join, resolve } from 'node:path' @@ -51,9 +43,6 @@ const NUMERIC = /^(0|[1-9][0-9]*)$/ const PSEUDO_VERSION = /^v[0-9]+\.(0\.0-|\d+\.\d+-([^+]*\.)?0\.)\d{14}-[A-Za-z0-9]+$/ const IDENTIFIER = /^[0-9A-Za-z-]+$/ -// A module of vitaminc's Go bindings and the version it is required or -// replaced at, in a go.mod stripped of its comments. -const VITAMINC_MODULE = /github\.com\/cipherstash\/vitaminc(?:\/\S+)?\s+(v\S+)/g /** The `module` line of a go.mod. */ export function modulePathOf(goMod) { @@ -62,20 +51,6 @@ export function modulePathOf(goMod) { return match[1] } -/** - * Every `github.com/cipherstash/vitaminc/…` module a go.mod names at a - * pseudo-version, as `path version` strings. Comments are dropped first, so - * the TEMPORARY note explaining a pin does not count as one. - */ -export function vitamincPseudoVersions(goMod) { - const code = goMod.replace(/\/\/[^\n]*/g, '') - const pins = [] - for (const match of code.matchAll(VITAMINC_MODULE)) { - if (PSEUDO_VERSION.test(match[1])) pins.push(match[0].trim()) - } - return pins -} - /** The major version a module path may publish: `/vN` gives N, otherwise 0 or 1. */ export function allowedMajors(modulePath) { const suffix = modulePath.match(/\/v([2-9]|[1-9][0-9]+)$/) @@ -84,12 +59,9 @@ export function allowedMajors(modulePath) { /** * Every reason `version` may not be released from `ref` for the module at - * `modulePath`, whose go.mod text is `goMod`. Empty when it may. + * `modulePath`. Empty when it may. */ -export function goReleaseVersionErrors( - version, - { modulePath, ref, goMod = '' }, -) { +export function goReleaseVersionErrors(version, { modulePath, ref }) { const errors = [] if (version.startsWith('v')) { @@ -153,13 +125,6 @@ export function goReleaseVersionErrors( ) } - const pins = vitamincPseudoVersions(goMod) - if (pre === null && pins.length > 0) { - errors.push( - `a final version cannot ship vitaminc's Go bindings at a pseudo-version (go.mod names ${pins.join(', ')}); pin a vitaminc tag or a commit on vitaminc main that a release carries first, or give a pre-release version such as ${core}-alpha.1`, - ) - } - return errors } @@ -171,7 +136,7 @@ function main() { } const goMod = readFileSync(GO_MOD, 'utf8') const modulePath = modulePathOf(goMod) - const errors = goReleaseVersionErrors(version, { modulePath, ref, goMod }) + const errors = goReleaseVersionErrors(version, { modulePath, ref }) for (const error of errors) console.log(`::error::${error}`) if (errors.length > 0) process.exit(1) console.log(`${modulePath} v${version} may be released from ${ref}`)