From f9afec8132a28d96a2559d9ea906b4d7df28983d Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Wed, 2 Dec 2026 17:08:39 +1100 Subject: [PATCH 1/6] refactor(go): copy vitaminc's Go packages vcffi and vcvalue into the module The Go SDK encodes every value that it sends to the guest with vitaminc's Go packages vcffi and vcvalue. go.mod pins them at an untagged commit, so the Go half of the frame codec moves separately from the Rust half (recipher-frame, already in this repository). A final release of the module is refused while that pin stands. This commit copies both packages in unchanged, so the move can be compared with the source file by file: vcffi -> languages/golang/encrypt/frame vcvalue -> languages/golang/encrypt/value Both stay public, as they were in vitaminc, and stay two packages: value holds the value types and imports nothing outside the standard library; frame is the codec and the storage profile. Source: github.com/cipherstash/vitaminc bindings/go/vcffi and bindings/go/vcvalue at commit f1fc9ae74882 (pseudo-version v0.0.0-20261119095843-f1fc9ae74882), the version that go.mod pins, taken from the Go module cache. Each package's go.mod is left out, so the two directories are packages of this module. Each package's MIT LICENSE file comes with it. Nothing imports the copies yet. Their package clauses, their import of vcvalue and the corpus paths of their tests are still vitaminc's; the next commit makes them the module's own. --- languages/golang/encrypt/frame/LICENSE | 25 + languages/golang/encrypt/frame/README.md | 265 +++++ languages/golang/encrypt/frame/ciphertext.go | 348 ++++++ languages/golang/encrypt/frame/codec_test.go | 1040 +++++++++++++++++ .../golang/encrypt/frame/conformance_test.go | 269 +++++ languages/golang/encrypt/frame/decode.go | 317 +++++ languages/golang/encrypt/frame/doc.go | 55 + languages/golang/encrypt/frame/encoder.go | 853 ++++++++++++++ languages/golang/encrypt/frame/fuzz_test.go | 376 ++++++ languages/golang/encrypt/frame/scalars.go | 339 ++++++ .../golang/encrypt/frame/scalars_test.go | 216 ++++ languages/golang/encrypt/frame/storage.go | 688 +++++++++++ .../golang/encrypt/frame/storage_decode.go | 500 ++++++++ .../golang/encrypt/frame/storage_test.go | 963 +++++++++++++++ .../fuzz/FuzzUnmarshal/505ffa2ed15a4b90 | 2 + .../FuzzUnmarshalCipherText/27336d1f7f4edceb | 2 + .../FuzzUnmarshalCipherText/27dc9fccff066f08 | 2 + .../FuzzUnmarshalCipherText/b69fb6cf28e5d74f | 2 + languages/golang/encrypt/frame/transport.go | 208 ++++ .../encrypt/frame/transport_internal_test.go | 28 + .../golang/encrypt/frame/typed_null_test.go | 410 +++++++ languages/golang/encrypt/value/LICENSE | 25 + languages/golang/encrypt/value/README.md | 126 ++ languages/golang/encrypt/value/doc.go | 43 + languages/golang/encrypt/value/model.go | 27 + languages/golang/encrypt/value/model_test.go | 132 +++ languages/golang/encrypt/value/null.go | 48 + languages/golang/encrypt/value/scalars.go | 303 +++++ .../golang/encrypt/value/scalars_test.go | 122 ++ languages/golang/encrypt/value/sealed.go | 125 ++ 30 files changed, 7859 insertions(+) create mode 100644 languages/golang/encrypt/frame/LICENSE create mode 100644 languages/golang/encrypt/frame/README.md create mode 100644 languages/golang/encrypt/frame/ciphertext.go create mode 100644 languages/golang/encrypt/frame/codec_test.go create mode 100644 languages/golang/encrypt/frame/conformance_test.go create mode 100644 languages/golang/encrypt/frame/decode.go create mode 100644 languages/golang/encrypt/frame/doc.go create mode 100644 languages/golang/encrypt/frame/encoder.go create mode 100644 languages/golang/encrypt/frame/fuzz_test.go create mode 100644 languages/golang/encrypt/frame/scalars.go create mode 100644 languages/golang/encrypt/frame/scalars_test.go create mode 100644 languages/golang/encrypt/frame/storage.go create mode 100644 languages/golang/encrypt/frame/storage_decode.go create mode 100644 languages/golang/encrypt/frame/storage_test.go create mode 100644 languages/golang/encrypt/frame/testdata/fuzz/FuzzUnmarshal/505ffa2ed15a4b90 create mode 100644 languages/golang/encrypt/frame/testdata/fuzz/FuzzUnmarshalCipherText/27336d1f7f4edceb create mode 100644 languages/golang/encrypt/frame/testdata/fuzz/FuzzUnmarshalCipherText/27dc9fccff066f08 create mode 100644 languages/golang/encrypt/frame/testdata/fuzz/FuzzUnmarshalCipherText/b69fb6cf28e5d74f create mode 100644 languages/golang/encrypt/frame/transport.go create mode 100644 languages/golang/encrypt/frame/transport_internal_test.go create mode 100644 languages/golang/encrypt/frame/typed_null_test.go create mode 100644 languages/golang/encrypt/value/LICENSE create mode 100644 languages/golang/encrypt/value/README.md create mode 100644 languages/golang/encrypt/value/doc.go create mode 100644 languages/golang/encrypt/value/model.go create mode 100644 languages/golang/encrypt/value/model_test.go create mode 100644 languages/golang/encrypt/value/null.go create mode 100644 languages/golang/encrypt/value/scalars.go create mode 100644 languages/golang/encrypt/value/scalars_test.go create mode 100644 languages/golang/encrypt/value/sealed.go 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/README.md b/languages/golang/encrypt/frame/README.md new file mode 100644 index 000000000..b0e5398a0 --- /dev/null +++ b/languages/golang/encrypt/frame/README.md @@ -0,0 +1,265 @@ +# vcffi — the shared FFI transport codec + +`vcffi` is the wire encoding that carries a **value tree** into a wasm guest +and a **ciphertext tree** back out, plus the `Encryptable`/`Encoder` +extension point for types that control their own encoding. It exists as its +own module so every binding that owns a wasm boundary speaks the same bytes +from one implementation — one codec, one hostile-input test suite, one fuzz +corpus. Consumers: [`vcencrypt`](../vcencrypt) (the `vitaminc-encrypt` +reference binding) and the stack-encrypt Go SDK. + +``` +import "github.com/cipherstash/vitaminc/bindings/go/vcffi" +``` + +Depends only on the sibling [`vcvalue`](../vcvalue) module (the value model — +`Plain`, `Object`, the sealed leaf family), via a local `replace` directive. +No wazero, no crypto. + +## Transport, and one storage profile + +The transport bytes are an FFI detail with **no compatibility commitment**: +nothing `Marshal`, `Encode` or `MarshalCipherText` writes should ever be +persisted. The one exception is the **storage profile**, `MarshalStorage` and +`UnmarshalStorage`, which write and read a value as a versioned blob for bytes +that are kept. Its format is shared with the Rust module +`vitaminc_aead_frame::storage`, specified in +[`packages/aead-frame/STORAGE.md`](../../../packages/aead-frame/STORAGE.md), +frozen at version 1, and pinned by the golden corpus +[`storage-v1.json`](../../../packages/aead-frame/testdata/storage-v1.json), +which `storage_test.go` reads row by row. The other frozen format is the +sealed leaf inside the AEAD envelope (see `vcvalue.Sealed` and the Rust crate +`vitaminc-aead`'s leaf codec). + +```go +blob, err := vcffi.MarshalStorage(record) // "VCS", version 1, then the value +var back Record +err = vcffi.UnmarshalStorage(blob, &back) // errors.Is(err, vcffi.ErrUnsupportedVersion) … +``` + +A Go struct is an object (field names from `vc` tags, as in the transport), a +map is a map whose keys keep their kind, `[]byte` and `[N]byte` are bytes, and +an `encoding.TextMarshaler` such as `time.Time` is text. A pointer is written +as `encoding/json` writes it: nil is null, and anything else is its value, so +Rust reads it into an `Option` or a plain `T` alike. Only a pointer to a +value that is itself written as null or marked present (a nil pointer, or a +pointer to one) is marked present, so every level reads back. Reading +follows Rust's rules: an integer reads into any integer type it fits, a +pointer reads a value marked present or not, unknown keys are ignored, and a +missing field is refused unless it is a pointer or tagged `vc:"name,default"`, +which reads it as its zero value, as Rust's `#[serde(default)]` does. +`default` is the only tag option: any other is refused, in a blob and in the +transport, so a misspelt one is not quietly ignored. A pointer costs no depth +unless it is marked, so Go nests as deep as the blob does. Go's `[]uint8` is `[]byte`, so it is always +bytes; a Rust type sharing a value with Go keeps its `Vec` as bytes with +`serde_bytes`. Go has no enums and no unit type, so the corpus rows that read +those are not run here. `FuzzUnmarshalStorage` holds the reader to the +hostile-input contract below, and requires every blob it reads to write back +byte for byte. + +## The `LeafSet` parameter + +The ciphertext codec's structural nodes (`[]any`, `map[string]any`, +`vcvalue.Plain`) are common to every binding, but the sealed-leaf marker +types are deliberately **not**: each binding hands the codec a `LeafSet` +mapping its own leaf types onto the framing. A stack-encrypt leaf is not +decryptable by `vitaminc-encrypt`, and keeping the Go types distinct means +one can never scan or marshal where the other belongs. `VCValueLeaves` is +the set for the `vcvalue` model types. + +The seam stops at the leaves. The structural nodes — including +`vcvalue.Plain` and the `vcvalue.Object` decode shape — are shared and **not** +parameterised: a binding brings its own leaves, not its own model. That is +deliberate. `Plain` is cleartext with no key binding, so none of the "a leaf +sealed by one cipher must never be mistaken for another's" reasoning applies +to it, and a second model would fork the wire encoding this module exists to +keep single. + +## Hostile input + +`Unmarshal` and `UnmarshalCipherText` treat their input as untrusted: +recursion depth, length prefixes and item counts are bounded, strings are +UTF-8 validated, duplicate map keys are rejected, and every malformed input +fails with `ErrMalformed` rather than panicking or over-allocating. The fuzz +targets in this package pin that contract, and also require anything accepted +to re-encode to the same bytes (Undefined becoming Null is the one allowed +difference). PR CI runs them over their seeds, which include every shared +corpus vector, and the whole suite on 32-bit GOARCH, where the u32-bound +guards are load-bearing. `.github/workflows/fuzz.yml` fuzzes them nightly +and records a failure on an open issue labelled `fuzz`; commit the failing +input attached to that run under `testdata/fuzz` as a regression seed. +vcencrypt's differential fuzz targets check the same decoders against the +Rust ones in its wasm guest (see its README). + +`ErrMalformed` covers hostile bytes, not caller mistakes: a `LeafSet` that is +partially wired, or that does not materialize a kind the buffer carries, +fails with its own attributable error. So `errors.Is(err, ErrMalformed)` is a +test for bad input, not a total branch over decode failures. Encode-side +depth exhaustion has its own sentinel, `ErrTooDeep`. + +## Usage + +### Value tree in, ciphertext tree out + +`Marshal` encodes a Go value into the bytes a wasm guest expects; +`UnmarshalCipherText` decodes what comes back, materializing sealed leaves +through the caller's `LeafSet`. + +```go +type User struct { + Email string `vc:"email"` + Age int `vc:"age"` + Notes string `vc:"-"` // never leaves the process +} + +buf, err := vcffi.Marshal(User{Email: "a@example.com", Age: 42}) +if err != nil { + return err +} + +// ... hand buf to the guest, get ciphertext bytes back ... + +ct, err := vcffi.UnmarshalCipherText(vcffi.VCValueLeaves(), ctBytes) +if err != nil { + return err // errors.Is(err, vcffi.ErrMalformed) for hostile input +} +sealed := ct.(map[string]any)["email"].(vcvalue.Sealed) +``` + +The reverse pair is `MarshalCipherText` (ciphertext tree to bytes, for the +decrypt call) and `Unmarshal` (guest response to a plaintext tree). + +### A type that controls its own encoding + +Implement `Encryptable` when reflection is not the encoding you want. The +`Encoder` writes exactly one value: one terminal channel, or one container +closed with `End`. + +```go +type Money struct { + Cents int64 + Currency string +} + +func (m Money) EncryptValue(enc vcffi.Encoder) error { + mp := enc.Map() + mp.Field("cents").Int64(m.Cents) + // Currency is not a secret — mark it so it travels in the clear. + mp.Field("currency").Passthrough().String(m.Currency) + return mp.End() +} +``` + +Errors accumulate on the encoder, so writes chain without a check after each +one; `End` (or `Marshal`) surfaces the first failure. A zero-value +`vcffi.Encoder` is unusable — usable ones only ever arrive as the argument to +`EncryptValue` or from `Passthrough`, `Elem` and `Field`. + +### A binding's own leaf types + +A second binding defines its own sealed-leaf types and maps them onto the +framing, so its leaves can never be mistaken for another cipher's. + +```go +type stackSealed []byte + +var stackLeaves = vcffi.LeafSet{ + Classify: func(v any) (vcffi.LeafKind, []byte, bool) { + if s, ok := v.(stackSealed); ok { + return vcffi.LeafSingle, s, true + } + return 0, nil, false // not ours — the codec handles the rest + }, + Make: func(kind vcffi.LeafKind, b []byte) any { + if kind == vcffi.LeafSingle { + return stackSealed(b) + } + return nil // an unwired kind is an error, never a nil node + }, +} +``` + +`Classify` is offered only non-structural values, so it cannot claim `[]any`, +`map[string]any` or `vcvalue.Plain`. A real binding covers all four kinds +(`LeafSingle`, `LeafEmptySeq`, `LeafEmptyMap`); returning nil for +a kind the wire carries fails the decode attributably rather than injecting an +untyped nil. + +## Scalar mappings and shared vectors + +Fixed integer widths remain exact (`int8`→Int8, `uint16`→UInt16, and so on). +`vcvalue.Int128`, `Uint128`, `Date`, `Decimal`, `UUID` and `Tagged` are +intercepted before reflection, including inside structs, pointers and +containers. `time.Time` encodes a nanosecond Timestamp; a timestamp that +arrives in the `0xF3` envelope in seconds, milliseconds or microseconds +decodes to `time.Time` too, and so re-encodes in the nanosecond form. A leap +second is refused in both directions, and a decimal negative zero reads back +as zero (ADR 0001). `UUID` and `Tagged` travel in the `0xF3` envelope. +Another UUID type, such as `github.com/google/uuid.UUID`, is a plain +`[16]byte` and is written as bytes: convert it with `vcvalue.UUID(id)` first +so that Rust and Node read it as a UUID. +Matching explicit Encoder channels are available for custom `Encryptable` +implementations. + +### Absent values + +AES-GCM keeps the plaintext's length, so a one-byte null sealed in place of a +date would show which rows have no date. A nil pointer to a fixed-width type +(`*int32`, `*float64`, `*time.Time`, `*vcvalue.Date`, `*vcvalue.Decimal`, +`*vcvalue.UUID`, and so on, and a named int or float type such as +`type Age int32`) is therefore +written as a **typed null**, padded to the length of a value of that type, as +Rust writes an `Option`'s `None` (vitaminc#493): + +```go +type Person struct { + Name string + Born *vcvalue.Date // nil seals as long as a date +} +``` + +A nil with no fixed-width type to go by is the plain null: a nil interface, a +nil `*bool` (a bool is already as short as a null), a nil `*string` or +`*[]byte` (variable width), a nil pointer to an `Encryptable`, whose +encoding is its own, and a named type over a `vcvalue` or `time` type (`type +Birthday vcvalue.Date`), which reflection writes field by field, not as a +date. Where the Go type cannot say what is missing (a nil in a +`map[string]any`), write `vcvalue.TypedNull{Type: vcvalue.TypeDate}`, or call +`Encoder.TypedNull` from an `Encryptable`. + +An `Encryptable` whose `EncryptValue` always writes one value of one +fixed-width type can say so by implementing `FixedWidth`, the Go side of +Rust's `Encrypt::FIXED`. A nil pointer to it is then a typed null of that +type: + +```go +type Money struct{ cents int64 } + +func (m Money) EncryptValue(enc vcffi.Encoder) error { enc.Int64(m.cents); return nil } +func (Money) FixedType() vcvalue.FixedType { return vcvalue.TypeInt64 } + +type Order struct { + Refund *Money // nil seals as long as a Money +} +``` + +`FixedType` is called once per type, on a pointer to a zero value, so it must +answer from the type alone. A type that returns an invalid `FixedType` fails +the encode with `vcvalue.ErrInvalidFixedType` rather than write the plain +null in its place. + +A typed null decodes as `nil`, like every null. Out of the seal the padding +means nothing, and Rust's frame writer writes it back as the plain null, so +Go does too. A decrypted value therefore no longer says what type an absent +field was: hold optional fields in a typed struct (`Born *vcvalue.Date`) +before encrypting again. A value re-encrypted from `any` or `vcvalue.Object` +seals its nils as the plain null, and its absent values show by length. + +Reading a typed null takes a guest built from the vitaminc release that adds +it (vitaminc#493); an older one refuses the frame. A binding that ships its +own guest must update it together with this module. + +The codec reads `testdata/value-conformance.json` from the repo root directly, +as do Rust and Node. Invalid scalar widths, date ranges, nanoseconds, decimal +flags and scales return `ErrMalformed`. Value construction errors retain the +typed `vcvalue` errors. The broader #332 guest-object corpus remains separate. diff --git a/languages/golang/encrypt/frame/ciphertext.go b/languages/golang/encrypt/frame/ciphertext.go new file mode 100644 index 000000000..fc3260beb --- /dev/null +++ b/languages/golang/encrypt/frame/ciphertext.go @@ -0,0 +1,348 @@ +package vcffi + +import ( + "errors" + "fmt" + "slices" + + "github.com/cipherstash/vitaminc/bindings/go/vcvalue" +) + +// A ciphertext is made of ordinary Go values — the same dynamic shape as +// decoded plaintext — with marker types distinguishing what is sealed from +// what travels in the clear: +// +// - a sealed-leaf marker (one of the binding's [LeafSet] types, e.g. +// vcvalue.Sealed): one encrypted leaf, an authenticated absent marker, +// or an authenticated empty-composite marker +// - vcvalue.Plain{V: ...}: a passthrough field, readable without the key +// - []any: a sequence of ciphertext nodes +// - map[string]any: a record of named nodes. Keys travel in the clear but +// each is cryptographically bound to its sealed value — renaming or +// swapping keys fails decryption. Entry order is not authenticated +// (encoding sorts keys for determinism), and there is no whole-map seal: +// any subset of entries decrypts independently. +// +// There is deliberately no dedicated tree type and no conversion step: a +// map-shaped ciphertext binds directly as database named parameters (the leaf +// types and vcvalue.Plain implement driver.Valuer), and leaves loaded back +// from columns go into a map[string]any for decryption. Only the sealed leaf +// bytes are a frozen format; the transport encoding crossing the FFI boundary +// is an implementation detail. +// +// Which concrete leaf types appear in the tree is the one thing this codec +// does not decide: each binding supplies a [LeafSet] so its leaves stay a +// distinct Go type. A stack-encrypt sealed leaf is not decryptable by +// vitaminc-encrypt, and keeping the types distinct means one can never scan +// or marshal where the other belongs. + +// Ciphertext node tags in the transport encoding (mirrors the Rust codec). +// 0x02 was the absent marker, retired by ADR 0001 (a None is a null leaf): +// never written, and refused when read like any unknown tag. +const ( + ctSingle byte = 0x01 + ctSeq byte = 0x03 + ctMap byte = 0x04 + ctPassthrough byte = 0x05 + ctEmptySeq byte = 0x06 + ctEmptyMap byte = 0x07 +) + +// LeafKind names the three sealed-leaf node kinds of the ciphertext framing. +// The stored bytes do not record the kind — it is authenticated through +// domain-separated AAD — so the framing carries it on the wire. +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 maps a binding's sealed-leaf marker types onto the ciphertext +// framing, in both directions. Each binding defines its own leaf types (so a +// leaf sealed by one cipher can never be mistaken for another's) and hands +// the codec this pair of translations: +// +// - Classify reports whether v is one of the binding's leaf values, +// returning its kind and bytes. The codec's structural node types +// ([]any, map[string]any, vcvalue.Plain) are never offered to Classify, +// so a LeafSet cannot claim a subtree; values Classify does not claim +// fall through to the bare-plaintext rejection. +// - Make constructs the binding's leaf value for a kind decoded off the +// wire. The bytes slice is freshly allocated and owned by the callee. +// Returning nil rejects the kind: the decoder turns it into an error, so +// a LeafSet that materializes only some kinds fails loudly instead of +// injecting nil nodes into the decoded tree. +// +// [VCValueLeaves] is the set for the vcvalue model types. +type LeafSet struct { + Classify func(v any) (LeafKind, []byte, bool) + Make func(kind LeafKind, bytes []byte) any +} + +// VCValueLeaves returns the [LeafSet] of the vcvalue model: vcvalue.Sealed, +// vcvalue.SealedEmptySeq and vcvalue.SealedEmptyMap. +// These are the leaf types the vitaminc-encrypt binding materializes; other +// bindings define their own set so their leaves stay a distinct Go type. A +// function rather than an exported var, so no importer can reassign the set +// out from under every other consumer in the process. +func VCValueLeaves() LeafSet { + return vcValueLeaves +} + +var vcValueLeaves = LeafSet{ + Classify: func(v any) (LeafKind, []byte, bool) { + switch n := v.(type) { + case vcvalue.Sealed: + return LeafSingle, n, true + case vcvalue.SealedEmptySeq: + return LeafEmptySeq, n, true + case vcvalue.SealedEmptyMap: + return LeafEmptyMap, n, true + default: + return 0, nil, false + } + }, + Make: func(kind LeafKind, bytes []byte) any { + switch kind { + case LeafSingle: + return vcvalue.Sealed(bytes) + case LeafEmptySeq: + return vcvalue.SealedEmptySeq(bytes) + case LeafEmptyMap: + return vcvalue.SealedEmptyMap(bytes) + default: + // An unlisted kind is rejected (nil), mirroring leafTag on the + // encode side — a future fourth kind must not silently mint Sealed. + return nil + } + }, +} + +// check rejects a partially wired LeafSet up front, where the mistake is +// attributable, instead of as a nil-function panic mid-tree. +func (l LeafSet) check() error { + if l.Classify == nil || l.Make == nil { + return errors.New("vcffi: LeafSet must define both Classify and Make") + } + return nil +} + +// leafTags is the single source of truth for the LeafKind ↔ wire-tag +// correspondence; leafTag and leafKind are its two directions, so a new leaf +// kind cannot be wired into one direction and missed in the other. +// +// No ciphertext tag is 0x00, so a zero entry means "this kind is not wired to +// the wire format" — a hole left by a LeafKind constant that skips a value, +// or an index past the end. Both directions refuse it, so a kind can never +// round-trip inside Go under a tag the Rust codec has never heard of. +var leafTags = [...]byte{ + LeafSingle: ctSingle, + LeafEmptySeq: ctEmptySeq, + LeafEmptyMap: ctEmptyMap, +} + +// leafTag maps a classified kind to its wire tag. +func leafTag(kind LeafKind) (byte, error) { + if int(kind) >= len(leafTags) || leafTags[kind] == 0 { + return 0, fmt.Errorf("vcffi: LeafSet classified an unknown LeafKind %d", kind) + } + return leafTags[kind], nil +} + +// leafKind maps a wire tag back to its leaf kind — the decode direction. +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 value into transport bytes; leaves +// recognizes the binding's sealed-leaf types. Bare plaintext values are +// rejected — a passthrough must be marked with vcvalue.Plain, so a value can +// never end up travelling 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 a transport-encoded ciphertext into the dynamic +// shape above — leaf nodes constructed through leaves — requiring the whole +// buffer to be consumed. +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 structural arms come first: the codec's own node types are never + // offered to Classify, so a LeafSet cannot claim a whole subtree as one + // leaf chunk — only non-structural values reach it (in the default arm). + 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 vcvalue.Plain: + // The payload node sits one level deeper; reject it here because the + // value encoder's scalar channels never re-check depth, and emitting + // bytes the decoder is guaranteed to reject (decodeValue enforces the + // same bound) would be an asymmetric round trip. + if depth+1 > maxDepth { + return nil, ErrTooDeep + } + out = append(out, ctPassthrough) + // Encode the plaintext payload as one value node, sharing the + // recursion budget with the surrounding ciphertext (depth+1), + // mirroring the Rust CT_PASSTHROUGH framing. + 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("vcffi: passthrough payload must complete exactly one value, completed %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("vcffi: %T is not a ciphertext node — wrap passthrough values in vcvalue.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 does not materialize this kind is a wiring + // mistake in the binding, not malformed input — name it, instead + // of injecting a nil node the caller only trips over later. + return nil, fmt.Errorf("vcffi: 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: + // One embedded plaintext value node, decoded one level deeper. + v, err := decodeValue(r, depth+1) + if err != nil { + return nil, err + } + return vcvalue.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..6b2600653 --- /dev/null +++ b/languages/golang/encrypt/frame/codec_test.go @@ -0,0 +1,1040 @@ +package vcffi + +import ( + "bytes" + "encoding/binary" + "errors" + "math" + "reflect" + "strings" + "testing" + + "github.com/cipherstash/vitaminc/bindings/go/vcvalue" +) + +// marshalUnmarshal is the round trip every case below shares: encode v to +// transport bytes, decode back to the natives shape. +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)}, // int → 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)}, // bare uint → UInt64 (no fit-check) + {"uint64-small", uint64(7), uint64(7)}, // uint64 → UInt64 + {"uint64-max", uint64(math.MaxUint64), uint64(math.MaxUint64)}, + {"float32", float32(1.5), float32(1.5)}, // Float32, exact width + {"float", 1.5, 1.5}, // float64 → 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 := vcvalue.Object{ + {Key: "name", Value: "x"}, + {Key: "Nested", Value: vcvalue.Object{{Key: "a", Value: int64(1)}}}, + } + if !reflect.DeepEqual(got, want) { + t.Fatalf("got %#v, want %#v", got, want) + } +} + +func TestReflectMapSortsKeys(t *testing.T) { + // Map iteration is randomized; the encoder must sort keys so the + // structure is deterministic. Decode preserves that sorted order. + got := marshalUnmarshal(t, map[string]int64{"c": 3, "a": 1, "b": 2}) + want := vcvalue.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 uses the Encryptable extension point. +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 := vcvalue.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 confirms an Encryptable is honored when reached +// through reflection (as a struct field), not only at the top level. +func TestEncryptableNested(t *testing.T) { + type shape struct { + Origin point + } + got := marshalUnmarshal(t, shape{Origin: point{X: 3, Y: 4}}) + want := vcvalue.Object{ + {Key: "Origin", Value: vcvalue.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) { + // Drive the raw Encoder channels 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") + } + // Trailing bytes after a complete value. + if _, err := Unmarshal([]byte{0x00, 0x00}); err == nil { + t.Fatal("trailing bytes must be rejected") + } +} + +// TestPlainPassthroughRoundTrip: the reflection opt-in marker Plain seals a +// value as passthrough, and it decodes back as Plain{V:...} — the marking +// round-trips so a caller can tell the field travelled in the clear. +func TestPlainPassthroughRoundTrip(t *testing.T) { + got := marshalUnmarshal(t, map[string]any{ + "id": vcvalue.Plain{V: int64(42)}, + "email": "ada@example.com", + }) + want := vcvalue.Object{ + {Key: "email", Value: "ada@example.com"}, + {Key: "id", Value: vcvalue.Plain{V: int64(42)}}, + } + if !reflect.DeepEqual(got, want) { + t.Fatalf("got %#v, want %#v", got, want) + } +} + +// A Plain wrapping a whole subtree makes the entire subtree passthrough. +func TestPlainPassthroughSubtree(t *testing.T) { + got := marshalUnmarshal(t, vcvalue.Plain{V: []any{int64(1), "two", true}}) + want := vcvalue.Plain{V: []any{int64(1), "two", true}} + if !reflect.DeepEqual(got, want) { + t.Fatalf("got %#v, want %#v", got, want) + } +} + +// The raw Encoder.Passthrough() channel, at root/seq/map positions. +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{vcvalue.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 marker (0xF2) with no value node behind it. + if _, err := Unmarshal([]byte{0xF2}); err == nil { + t.Fatal("truncated passthrough node must be rejected") + } +} + +func TestUnmarshalRejectsPassthroughDepthBomb(t *testing.T) { + // Nesting exclusively through passthrough markers must hit the depth bound. + 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 ciphertext node carries its readable value across the +// transport and back, marked Plain so it cannot be mistaken for a +// ciphertext map or sequence on the way back in. +func TestCipherTextPassthroughTransportRoundTrip(t *testing.T) { + ct := map[string]any{ + "id": vcvalue.Plain{V: int64(42)}, + "email": vcvalue.Sealed{9, 9, 9}, + } + buf, err := MarshalCipherText(VCValueLeaves(), ct) + if err != nil { + t.Fatalf("MarshalCipherText: %v", err) + } + got, err := UnmarshalCipherText(VCValueLeaves(), 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": vcvalue.Sealed{9, 9, 9}, + "b": []any{vcvalue.Sealed{1}, vcvalue.SealedEmptySeq{2}}, + } + buf, err := MarshalCipherText(VCValueLeaves(), ct) + if err != nil { + t.Fatalf("MarshalCipherText: %v", err) + } + got, err := UnmarshalCipherText(VCValueLeaves(), buf) + if err != nil { + t.Fatalf("UnmarshalCipherText: %v", err) + } + if !reflect.DeepEqual(got, ct) { + t.Fatalf("got %#v, want %#v", got, ct) + } +} + +// A bare plaintext value in ciphertext position is rejected: passthrough must +// be explicit (Plain), so nothing travels unencrypted by accident. +func TestCipherTextRejectsBarePlaintext(t *testing.T) { + if _, err := MarshalCipherText(VCValueLeaves(), map[string]any{"x": "oops"}); err == nil { + t.Fatal("bare plaintext in ciphertext position must be rejected") + } + if _, err := MarshalCipherText(VCValueLeaves(), []byte{1, 2, 3}); err == nil { + t.Fatal("bare []byte must be rejected (use Sealed or Plain)") + } +} + +// A struct with zero exported fields (time.Time is the canonical case) must +// be rejected, not silently sealed as an empty map that destroys the payload. +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") + } + // An all-vc:"-" struct asked for the empty encoding explicitly and stays + // allowed, as does the empty struct. + 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 (the decode result for maps) must re-encode with object framing so +// a decrypt-then-re-encrypt flow preserves the record's structure — both at +// the root and nested inside other values. +func TestObjectReencodesWithObjectFraming(t *testing.T) { + o := vcvalue.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) + } +} + +// A Plain-wrapped Object inside a ciphertext must survive the passthrough +// round trip shape-intact (PR review P1). +func TestCipherTextPassthroughObjectRoundTrip(t *testing.T) { + o := vcvalue.Object{{Key: "id", Value: int64(42)}} + buf, err := MarshalCipherText(VCValueLeaves(), vcvalue.Plain{V: o}) + if err != nil { + t.Fatalf("MarshalCipherText: %v", err) + } + got, err := UnmarshalCipherText(VCValueLeaves(), buf) + if err != nil { + t.Fatalf("UnmarshalCipherText: %v", err) + } + if !reflect.DeepEqual(got, vcvalue.Plain{V: o}) { + t.Fatalf("got %#v, want Plain{V: %#v}", got, o) + } +} + +// [N]byte must take the same single-Bytes-leaf path as []byte — element-wise +// encoding would produce a ciphertext shape no other producer emits. +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 := vcvalue.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 through a nil receiver — +// the behaviour typed-nil detection must prevent. +type nilEncryptable struct{ n int } + +func (e *nilEncryptable) EncryptValue(enc Encoder) error { + enc.Int64(int64(e.n)) // dereferences e + return nil +} + +// A typed nil pointer satisfying Encryptable must encode as Null, not invoke +// the method on a nil receiver (PR review P2). +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, not recurse to stack overflow +// (PR review P2). +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 reject a passthrough whose payload sits beyond the +// depth budget instead of emitting bytes UnmarshalCipherText is guaranteed +// to reject (PR review P2). +func TestMarshalCipherTextRejectsPassthroughBeyondDepthBudget(t *testing.T) { + // 129 nested []any push the Plain payload past maxDepth (128). + var deep any = vcvalue.Plain{V: int64(1)} + for range 129 { + deep = []any{deep} + } + if _, err := MarshalCipherText(VCValueLeaves(), deep); !errors.Is(err, ErrTooDeep) { + t.Fatalf("over-deep passthrough must be rejected with ErrTooDeep at encode time, got %v", err) + } + + // One level shallower still round-trips — the bound is exact. + var ok any = vcvalue.Plain{V: int64(1)} + for range 127 { + ok = []any{ok} + } + buf, err := MarshalCipherText(VCValueLeaves(), ok) + if err != nil { + t.Fatalf("MarshalCipherText at the bound: %v", err) + } + if _, err := UnmarshalCipherText(VCValueLeaves(), buf); err != nil { + t.Fatalf("UnmarshalCipherText at the bound: %v", err) + } +} + +// --- Malformed-input coverage for the two decoders (PR #257 review gaps). +// Raw transport bytes are hand-built here because no Go encoder produces +// these shapes — that unreachability is exactly why the branches were +// untested. + +func u32le(n int) []byte { + b := make([]byte, 4) + binary.LittleEndian.PutUint32(b, uint32(n)) + return b +} + +// ctEntry frames one ciphertext map entry: key chunk + a 1-byte ctSingle leaf. +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 rejects a duplicate map key — a branch only reachable +// from hand-crafted or cross-language transport bytes (a Go map cannot +// produce duplicates). +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(VCValueLeaves(), dup); err == nil { + t.Fatal("duplicate ciphertext map key must be rejected") + } + + // Positive control: the same framing with distinct keys decodes. + ok := []byte{0x04} + ok = append(ok, u32le(2)...) + ok = append(ok, ctEntry("a")...) + ok = append(ok, ctEntry("b")...) + if _, err := UnmarshalCipherText(VCValueLeaves(), ok); err != nil { + t.Fatalf("distinct keys should decode: %v", err) + } +} + +// Unmarshal's recursion bound and hostile-count guard on the array/object +// routes — the Rust codec tests all three; only the passthrough depth bomb +// was covered on the Go side. +func TestUnmarshalRejectsArrayAndObjectBombs(t *testing.T) { + // Depth bomb: 130 nested single-element arrays (> 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") + } + + // Object nesting: 130 nested one-entry objects. + 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") + } + + // Hostile count: an array claiming max-u32 items with no bytes behind it. + if _, err := Unmarshal([]byte{0xF0, 0xFF, 0xFF, 0xFF, 0xFF}); err == nil { + t.Fatal("hostile array count must be rejected") + } +} + +// UnmarshalCipherText's own recursion bound, hostile-count guard, and +// trailing-byte rejection — a separate recursion from the value decoder, +// previously untested. +func TestUnmarshalCipherTextRejectsMalformed(t *testing.T) { + // Depth bomb: 130 nested one-element ctSeq. + 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(VCValueLeaves(), deep); err == nil { + t.Fatal("ciphertext depth bomb must be rejected") + } + + // Hostile count. + if _, err := UnmarshalCipherText(VCValueLeaves(), []byte{0x03, 0xFF, 0xFF, 0xFF, 0xFF}); err == nil { + t.Fatal("hostile ciphertext count must be rejected") + } + + // Trailing bytes after a complete node. + leaf := append([]byte{0x01}, u32le(1)...) + leaf = append(leaf, 0xAB, 0xFF) // one extra byte + if _, err := UnmarshalCipherText(VCValueLeaves(), leaf); err == nil { + t.Fatal("trailing bytes must be rejected") + } + + // Unknown tag. + if _, err := UnmarshalCipherText(VCValueLeaves(), []byte{0x7F}); err == nil { + t.Fatal("unknown ciphertext tag must be rejected") + } +} + +// The encodeReflect default arm: kinds with no encoding (chan/func/complex) +// error instead of panicking or emitting garbage. +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 rejects non-string map keys — the transport frames keys as +// UTF-8 chunks, so there is nothing sound to write for other key types. +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 encode-side recursion guard: an over-deep Go value fails the encode. +// The decode side has depth-bomb coverage; this drives the same bound from +// the writing end. +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 wire bytes must be rejected exactly as the +// ciphertext decoder rejects a duplicate ctMap key: an Object carrying +// duplicates cannot survive re-encoding through a Go map without silently +// dropping an entry. Only hand-built transport bytes can reach this branch — +// the encoder sorts unique map keys. +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") + } + + // Positive control: the same shape with distinct keys decodes. + 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 claims an element) and never writes the value — +// the contract violation Field/Elem must now catch at encode time, where it +// previously surfaced only as an opaque 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 exercises the End-side check: the final entry's value is +// the one skipped, so no later Field/Elem call can catch 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 completes a terminal *inside* a nested container but never +// Ends the container — the slot itself is incomplete even though a descendant +// value finished, so a per-slot (not global) completion check is required. +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 pushes two terminals through one element/entry Encoder, +// producing an extra value node the container's count doesn't account for. +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 zero or several values at the root slot. +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 leaves the root container un-Ended. +type unclosedRoot struct{} + +func (unclosedRoot) EncryptValue(enc Encoder) error { + enc.Seq().Elem().Int64(1) // End() never called + return nil +} + +// The passthrough payload path in encodeCipherText applies the same +// exactly-one rule as Marshal's root slot; without this, a malformed payload +// would emit wire bytes that UnmarshalCipherText only rejects later as an +// opaque ErrMalformed. +func TestMarshalCipherTextRejectsPayloadMiscount(t *testing.T) { + for _, v := range []any{ + vcvalue.Plain{V: rootMiscount{writes: 0}}, + vcvalue.Plain{V: rootMiscount{writes: 2}}, + vcvalue.Plain{V: unclosedRoot{}}, + } { + if _, err := MarshalCipherText(VCValueLeaves(), v); err == nil { + t.Fatalf("malformed passthrough payload %#v must fail the encode", v) + } + } +} + +// missingPassthroughPayload writes a Passthrough marker into a sequence slot +// but never the wrapped value — the passthrough-specific skipped-value case. +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 is the reflection route to a duplicate wire key: a vc tag +// resolving to another field's effective name. Without encode-time rejection +// this marshals happily and only fails inside the ciphertext decoder — after +// the plaintext crossed the FFI boundary — as an ErrMalformed that names +// neither the struct nor the key. +type collidingTag struct { + Name string + Alias string `vc:"Name"` +} + +// duplicateFieldKey is the Encryptable route to the same collision. +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 // substring the diagnostic must carry + }{ + {"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 pins the End() error contract: End returns the +// first error of the whole encode, not one scoped to its own container, so +// an outer End reports a failure that happened inside a sibling 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 binding-specific LeafSet round-trips its own distinct leaf types — the +// reason the ciphertext codec is parameterised at all: a stack-encrypt leaf +// must come back as a stack-encrypt type, never as vcvalue.Sealed. +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) + } + + // The wire bytes are identical across LeafSets — only the Go types + // differ — so the same buffer decodes to vcvalue types under + // VCValueLeaves. This pins that a LeafSet changes materialization, not + // the encoding. + asVC, err := UnmarshalCipherText(VCValueLeaves(), buf) + if err != nil { + t.Fatalf("UnmarshalCipherText(VCValueLeaves): %v", err) + } + want := map[string]any{"email": vcvalue.Sealed{9, 9, 9}} + if !reflect.DeepEqual(asVC, want) { + t.Fatalf("got %#v, want %#v", asVC, want) + } + + // And a foreign leaf type is a bare plaintext to a LeafSet that does not + // claim it — rejected, not silently passed through. + if _, err := MarshalCipherText(VCValueLeaves(), 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 materializes only LeafSingle. Wire bytes carrying the + // authenticated absent marker must fail attributably — never decode to a + // nil node the caller only trips over later. + 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 vcvalue set likewise rejects an unlisted kind instead of minting a + // Sealed for it — mirroring leafTag's refusal on the encode side. + if got := VCValueLeaves().Make(LeafKind(9), []byte{1}); got != nil { + t.Fatalf("an unknown LeafKind must not materialize, got %#v", got) + } +} + +func TestMarshalCipherTextRejectsOutOfRangeLeafKind(t *testing.T) { + // The encode-side half of the pair above: a Classify that claims a leaf + // under a kind outside the wire table is refused before any tag is + // emitted, so a future fifth kind can never reach the wire unnamed. + 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) { + // Every kind in the wire table, so no Classify or Make arm goes + // unexercised: a swapped arm (an empty-map marker materialized where an + // empty-seq belongs) fails here rather than at some later decrypt. + ct := map[string]any{ + "single": vcvalue.Sealed{9, 9, 9}, + "emptySeq": vcvalue.SealedEmptySeq{7}, + "emptyMap": vcvalue.SealedEmptyMap{8}, + } + buf, err := MarshalCipherText(VCValueLeaves(), ct) + if err != nil { + t.Fatalf("MarshalCipherText: %v", err) + } + got, err := UnmarshalCipherText(VCValueLeaves(), 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 hole in + // leafTags. Without the zero guard, leafTag would emit tag 0x00 with no + // error and leafKind would map it straight back — a clean round trip + // inside Go under a tag the Rust codec does not define. Both directions + // refuse zero, and the table itself must have no holes to refuse. + 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(VCValueLeaves(), []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}}, + {vcvalue.Object{}, []byte{0xF1, 0, 0, 0, 0}}, + {vcvalue.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 on the way to +// the encoder would set the quiet bit (found by FuzzUnmarshal). +// namedFloat32 has no Encryptable method, so it reaches the reflect path. +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..bc89b21ec --- /dev/null +++ b/languages/golang/encrypt/frame/conformance_test.go @@ -0,0 +1,269 @@ +package vcffi + +import ( + "encoding/hex" + "encoding/json" + "fmt" + "os" + "reflect" + "regexp" + "strconv" + "testing" + "time" + + "github.com/cipherstash/vitaminc/bindings/go/vcvalue" +) + +// isoDate and rfc3339ish match the corpus date and timestamp spellings, +// including a negative year as a sign and six digits, which time.Parse +// cannot read. +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 a vector's kind and value fields describe, +// without the transport decoder, so a bug that decodes and encodes +// symmetrically wrong cannot pass. +func expected(kind string, raw json.RawMessage) (any, error) { + if kind == "unknown" { + // A logical id this build does not know: the id, the parameter and + // the physical scalar, which round-trips as a vcvalue.Tagged. + 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 vcvalue.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 vcvalue.ParseInt128(text) + case "uint128": + return vcvalue.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 vcvalue.Date{Year: n[0], Month: time.Month(n[1]), Day: n[2]}, nil + case "timestamp": + return timestamp(text) + case "decimal": + return vcvalue.ParseDecimal(text) + case "uuid": + return vcvalue.ParseUUID(text) + case "array": + if string(raw) == "[]" { + return []any{}, nil + } + case "object": + if string(raw) == "{}" { + return vcvalue.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, err := os.ReadFile("../../../testdata/value-conformance.json") + if err != nil { + t.Fatal(err) + } + 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(VCValueLeaves(), raw); err != ErrMalformed { + t.Fatalf("got %v, want ErrMalformed", err) + } + }) + } +} diff --git a/languages/golang/encrypt/frame/decode.go b/languages/golang/encrypt/frame/decode.go new file mode 100644 index 000000000..27ca62812 --- /dev/null +++ b/languages/golang/encrypt/frame/decode.go @@ -0,0 +1,317 @@ +package vcffi + +import ( + "encoding/binary" + "math" + "math/big" + "time" + + "github.com/cipherstash/vitaminc/bindings/go/vcvalue" +) + +// Unmarshal decodes value transport bytes into Go natives: +// +// - Null and Undefined → nil (Go has no undefined analog); +// - a typed null → nil: an absent value is absent whatever its type +// once it is out of the seal, so it re-encodes as the plain null; +// - Bool → bool; +// - Int32 → int32; +// - Int64 → int64; +// - UInt32 → uint32; +// - UInt64 → uint64; +// - Float32 → float32; +// - Float64 → float64; +// - String → string; +// - Bytes → []byte; +// - Array → []any; +// - vcvalue.Object → vcvalue.Object (ordered []Field); +// - Passthrough → vcvalue.Plain{V: } (the clear-field marker); +// - the 0xF3 envelope → time.Time for a timestamp in seconds, milliseconds +// or microseconds, vcvalue.UUID for a UUID, and vcvalue.Tagged for a +// logical id this build does not know, which re-encodes unchanged. +// +// Go maps exactly in both directions — the 32-bit tags decode to int32 / +// uint32 / float32, not widened to 64-bit. JavaScript decodes integer tags +// as BigInt and widens Float32 to a number. +// +// This self-describing shape is deliberately spike-scoped. A reflection-based +// unmarshal into caller structs (the mirror of Encode) is future work. +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 the node whose tag has just been read. +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(vcvalue.Object, 0, eagerCap(n)) + // Duplicate keys are rejected as on the ciphertext decode path (and + // both Rust decoders): an vcvalue.Object with duplicates cannot survive a + // re-encode through a Go map without silently dropping an entry. + 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{}{} + value, err := decodeValue(r, depth+1) + if err != nil { + return nil, err + } + fields = append(fields, vcvalue.Field{Key: key, Value: value}) + } + return fields, nil + case tagPassthrough: + // A passthrough value surfaces as vcvalue.Plain{V: }, the + // mirror of the Encoder's vcvalue.Plain opt-in, so a caller can tell the + // field travelled in the clear. + inner, err := decodeValue(r, depth+1) + if err != nil { + return nil, err + } + return vcvalue.Plain{V: inner}, nil + case tagEnvelope: + return decodeEnvelope(r) + case tagTypedNull: + return decodeTypedNull(r) + default: + return nil, ErrMalformed + } +} + +// physicalTag reports whether tag is a physical scalar: one the envelope +// may carry. The logical shorthand tags (Undefined, Date, Timestamp, +// Decimal) and the containers are not. +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 the 0xF3 envelope after its tag: a logical id, a +// parameter, and a physical scalar. There is one encoding per value, so an +// envelope over a type with a shorthand tag, an id of zero, or a known id +// with a parameter it cannot take is malformed (ADR 0001 section 3). +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 vcvalue.UUID + copy(u[:], b) + return u, nil + default: + return vcvalue.Tagged{ID: id, Param: param, V: physical}, nil + } +} + +// envelopeTimestamp is a count of seconds, milliseconds or microseconds +// since the epoch as a time.Time, in the wire's range (jiff's, about years +// -9999 to 9999; see vcvalue.Timestamp). The nanosecond unit has +// the shorthand Timestamp tag and is refused in the envelope. +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 vcvalue.Timestamp + if count, ok := smallIntegerOf(physical); ok { + // Most counts fit an int64, among them every Date that Node writes, + // so they skip math/big. The count splits into whole seconds and a + // remainder that is never negative, as DivMod does below. + perSecond := 1_000_000_000 / per + seconds, rem := count/perSecond, count%perSecond + if rem < 0 { + seconds, rem = seconds-1, rem+perSecond + } + t = vcvalue.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 = vcvalue.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 is the value of a decoded int that fits an int64. +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 is the value of a decoded int that smallIntegerOf does not +// take: 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 vcvalue.Int128: + value, ok := new(big.Int).SetString(x.String(), 10) + return value, ok + case vcvalue.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..649f8573b --- /dev/null +++ b/languages/golang/encrypt/frame/doc.go @@ -0,0 +1,55 @@ +// Package vcffi is the shared FFI transport codec of the vitaminc Go +// bindings: the wire encoding that carries a value tree into a wasm guest +// and a ciphertext tree back out, together with the Encryptable/Encoder +// extension point for types that control their own encoding. +// +// It exists as its own module so every binding that owns a wasm boundary +// speaks the same bytes from one implementation — vcencrypt (the +// vitaminc-encrypt reference binding) and the stack-encrypt Go SDK are the +// intended consumers. Forking the codec per binding is exactly the failure +// mode this module prevents: one codec, one hostile-input test suite, one +// fuzz corpus. +// +// # Transport, and one storage profile +// +// The transport bytes are an FFI detail with no compatibility commitment: +// nothing [Marshal], [Encode] or [MarshalCipherText] writes should ever be +// persisted. The one exception is the storage profile, [MarshalStorage] and +// [UnmarshalStorage], which write and read a value as a versioned blob for +// bytes that are kept. Its format is shared with the Rust module +// vitaminc_aead_frame::storage, specified in packages/aead-frame/STORAGE.md, +// frozen at version 1, and pinned by the golden corpus in +// packages/aead-frame/testdata/storage-v1.json, which this package's tests +// read. Use it, and only it, for bytes that outlive the process that wrote +// them. The other frozen format is the sealed leaf inside the AEAD envelope +// (see vcvalue.Sealed and the Rust crate vitaminc-aead's leaf codec). +// +// # Values and ciphertexts +// +// [Marshal] and [Unmarshal] carry the plaintext value model (Go natives, +// vcvalue.Object for maps, vcvalue.Plain for passthrough): Marshal walks +// ordinary Go values with encoding/json-style rules, consulting +// [Encryptable] first so a user type can drive the [Encoder] channels +// itself. +// +// [MarshalCipherText] and [UnmarshalCipherText] carry the ciphertext tree. +// Its structural nodes ([]any, map[string]any, vcvalue.Plain) are common to +// every binding, but the sealed-leaf marker types are deliberately not: each +// binding supplies a [LeafSet] mapping its own leaf types onto the framing, +// so a leaf sealed by one cipher is a distinct Go type from a leaf sealed by +// another and can never scan or marshal where the other belongs. +// [VCValueLeaves] is the set for the vcvalue model types. +// +// # Hostile input +// +// The decoders treat their input as untrusted: recursion depth, length +// prefixes and item counts are bounded, strings are UTF-8 validated, +// duplicate map keys are rejected, and every malformed input fails with +// [ErrMalformed] rather than panicking or over-allocating. The fuzz targets +// in this package pin that contract. +// +// [ErrMalformed] covers hostile bytes, not caller mistakes: a [LeafSet] that +// is partially wired, or that does not materialize a kind the buffer carries, +// fails with its own attributable error, so errors.Is(err, [ErrMalformed]) is +// a test for bad input rather than a total branch over decode failures. +package vcffi diff --git a/languages/golang/encrypt/frame/encoder.go b/languages/golang/encrypt/frame/encoder.go new file mode 100644 index 000000000..8e2aa070c --- /dev/null +++ b/languages/golang/encrypt/frame/encoder.go @@ -0,0 +1,853 @@ +package vcffi + +import ( + "encoding/binary" + "errors" + "fmt" + "math" + "reflect" + "slices" + "strings" + "sync" + "time" + "unicode/utf8" + + "github.com/cipherstash/vitaminc/bindings/go/vcvalue" +) + +// Encryptable is the extension point for user types: a type implements it to +// control how it is sealed, the way a Rust type implements `Encrypt`. Because +// Go has no orphan impls, this interface (rather than reflection) is how a +// type opts into a bespoke encoding. Encode and Marshal consult it before +// falling back to reflection. +type Encryptable interface { + // EncryptValue records this value into enc. Implementations write + // exactly one value: one terminal channel (String, Int, …) or one + // container (Seq, Map). Returning an error aborts the whole encode. + EncryptValue(enc Encoder) error +} + +// FixedWidth is the Go side of Rust's `Encrypt::FIXED`: an Encryptable whose +// EncryptValue always writes one value of one fixed-width type (a money type +// that writes its cents with Int64, say). A nil pointer to such a type is +// written as a typed null of that type, so a sealed absence is as long as a +// sealed value. A nil pointer to an Encryptable that does not implement it +// is the plain null, since its encoding is its own. +// +// FixedType is called once per type, on a pointer to a zero value, so it +// must answer from the type alone. A type that returns an invalid FixedType +// fails the encode with vcvalue.ErrInvalidFixedType rather than write the +// plain null in its place. +type FixedWidth interface { + Encryptable + FixedType() vcvalue.FixedType +} + +// encState is the buffer and first-error shared by an Encoder and every +// sub-encoder it hands out. Errors accumulate: once one is recorded, further +// channel calls are no-ops, so consumer code can chain writes without +// checking after every call and still surface the first failure from +// End/Marshal. +type encState struct { + buf []byte + err error +} + +func (s *encState) fail(err error) { + if s.err == nil { + s.err = err + } +} + +// Encoder records a single value in transport form. It mirrors the Rust +// Cipher channels — it is a recorder that writes the transport bytes, not a +// live cipher handle. Exactly one channel must be used per Encoder: a +// terminal (Null, Undefined, Bool, Int32, Int64, UInt32, UInt64, Float32, +// Float64, String, Bytes) or a container (Seq, Map). +// +// Encoder is passed and stored by value; all instances handed out for one +// encode share the same underlying buffer and first-error via a pointer, so +// copying an Encoder is cheap and safe. The zero Encoder is not usable and +// its methods panic: usable Encoders are only the one handed to +// [Encryptable.EncryptValue] and those returned by Passthrough, Elem and +// Field. +type Encoder struct { + st *encState + depth int + // done points at the completion counter for the slot this Encoder writes + // into (a container's current element/entry, or the root). Terminals and + // container Ends increment it; the slot's owner then verifies exactly one + // completion. This is per-slot on purpose: a global counter would let a + // completed *descendant* (e.g. a terminal inside an un-Ended nested + // container) stand in for the slot's own value, shifting the wire and + // surfacing only as an opaque ErrMalformed at decode. + done *int +} + +func (e Encoder) push(b ...byte) { + e.st.buf = append(e.st.buf, b...) +} + +// complete records that this Encoder's slot received one full value. +func (e Encoder) complete() { + if e.done != nil { + *e.done++ + } +} + +// Null records the cross-language null (Go nil, JS null, Python None). +func (e Encoder) Null() { + if e.st.err == nil { + e.push(tagNull) + e.complete() + } +} + +// Undefined records JavaScript's undefined. Go has no analog, so Go code +// rarely writes it; the channel exists so a value round-tripped from JS can +// be re-encoded. On decode, Undefined collapses to nil like Null. +func (e Encoder) Undefined() { + if e.st.err == nil { + e.push(tagUndefined) + e.complete() + } +} + +// Bool records a boolean. +func (e Encoder) Bool(b bool) { + if e.st.err != nil { + return + } + if b { + e.push(tagTrue) + } else { + e.push(tagFalse) + } + e.complete() +} + +// Float64 records an IEEE-754 double. Distinct from the integer channels: it +// round-trips as a 64-bit float in every language. Round-trips by raw bit +// pattern, so NaN payloads and -0.0 survive. +func (e Encoder) Float64(f float64) { + if e.st.err != nil { + return + } + e.push(tagFloat64) + e.st.buf = binary.LittleEndian.AppendUint64(e.st.buf, math.Float64bits(f)) + e.complete() +} + +// Float32 records an IEEE-754 single. For schema fidelity with float4 at the +// EQL layer; round-trips by raw bit pattern. +func (e Encoder) Float32(f float32) { + if e.st.err != nil { + 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. For schema fidelity with int4 at +// the EQL layer; kept distinct from Int64. +func (e Encoder) Int32(i int32) { + if e.st.err != nil { + return + } + e.push(tagInt32) + e.st.buf = binary.LittleEndian.AppendUint32(e.st.buf, uint32(i)) + e.complete() +} + +// Int64 records a signed 64-bit integer. Kept distinct from Float64 so +// integer-typed languages round-trip integers as integers. +func (e Encoder) Int64(i int64) { + if e.st.err != nil { + return + } + e.push(tagInt64) + e.st.buf = binary.LittleEndian.AppendUint64(e.st.buf, uint64(i)) + e.complete() +} + +// UInt32 records an unsigned 32-bit integer. For schema fidelity with the +// EQL layer. +func (e Encoder) UInt32(u uint32) { + if e.st.err != nil { + 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.st.err != nil { + return + } + e.push(tagUint64) + e.st.buf = binary.LittleEndian.AppendUint64(e.st.buf, u) + e.complete() +} + +// String records a UTF-8 string. Invalid UTF-8 fails the encode. +func (e Encoder) String(s string) { + if e.st.err != nil { + return + } + if !utf8.ValidString(s) { + e.st.fail(errors.New("vcffi: 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 raw binary data. +func (e Encoder) Bytes(b []byte) { + if e.st.err != nil { + 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 (unencrypted, +// unauthenticated) and returns an Encoder for it — the same channel set, so +// the wrapped value is written exactly as any other: +// +// 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 (terminal or container) through the returned +// Encoder. Non-sensitive data only — the wrapped value is not sealed. +func (e Encoder) Passthrough() Encoder { + if e.st.err == nil { + if e.depth+1 > maxDepth { + e.st.fail(ErrTooDeep) + } else { + e.push(tagPassthrough) + } + } + // The passthrough marker and its wrapped value form ONE value in this + // Encoder's slot, so the wrapped value completes the same counter. + return Encoder{st: e.st, depth: e.depth + 1, done: e.done} +} + +// Seq begins a sequence. Call Elem once per element and End when done. +func (e Encoder) Seq() *SeqEncoder { + s := &SeqEncoder{st: e.st, depth: e.depth + 1, done: e.done} + if e.st.err != nil { + 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) // length back-patched by End + return s +} + +// Map begins a string-keyed map. Call Field once per entry and End when +// done. Keys preserve insertion order and are UTF-8 validated. +func (e Encoder) Map() *MapEncoder { + m := &MapEncoder{st: e.st, depth: e.depth + 1, done: e.done} + if e.st.err != nil { + 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) // length back-patched by End + return m +} + +// SeqEncoder records the elements of a sequence. The element count is +// back-patched into the reserved length slot at End. +type SeqEncoder struct { + st *encState + depth int + lenOff int + count int + // done is the enclosing slot's completion counter (see Encoder.done); + // End increments it — the sequence is one value in its parent's slot. + done *int + // childDone counts completions of this sequence's own element slots. + // Elem and End verify childDone == count, so a skipped element, an + // un-Ended nested container, or a doubly-written element fails here at + // encode time instead of as ErrMalformed at decode. + childDone int +} + +// checkPrev verifies the previous element slot completed exactly once. +func (s *SeqEncoder) checkPrev() { + if s.childDone > s.count { + s.st.fail(fmt.Errorf("vcffi: 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("vcffi: sequence element %d was never completed", s.count-1)) + } +} + +// Elem returns an Encoder for the next element. Write the element fully +// (one channel, containers Ended) before calling Elem again. +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 finalizes the sequence, writing its element count. +// +// Error contract (deliberate, frozen): End returns the first error recorded +// anywhere in the whole encode so far — not one scoped to this sequence. A +// nested container's End can therefore surface an error caused elsewhere in +// the tree. Errors are sticky (later channel calls no-op), so an +// EncryptValue implementation may chain writes without checking and return +// the outermost End; inspecting intermediate errors for *which* slot failed +// is not part of the contract — the error text names the slot instead. +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 itself is one completed value in the enclosing slot. + if s.done != nil { + *s.done++ + } + } + return err +} + +// MapEncoder records the entries of a map. The entry count is back-patched +// into the reserved length slot at End. +type MapEncoder struct { + st *encState + depth int + lenOff int + count int + // done is the enclosing slot's completion counter (see Encoder.done); + // End increments it — the map is one value in its parent's slot. + done *int + // childDone mirrors SeqEncoder.childDone: completions of this map's own + // entry slots. Field and End verify childDone == count, so a key whose + // value was skipped, left as an un-Ended container, or written twice + // fails at encode time — otherwise the wire shifts and the next key + // parses as the missing value, surfacing only as ErrMalformed at decode. + childDone int + // lastKey is the most recent Field key, kept so contract violations name + // the key whose value slot misbehaved. + lastKey string + // seen rejects duplicate keys at encode time. Reflection over a Go map + // cannot produce duplicates, but encodeStruct can (a vc tag colliding + // with another field's effective name) and a hand-written Encryptable + // can; without this check the collision only surfaces after the + // plaintext has crossed the FFI boundary, as the ciphertext decoder's + // opaque ErrMalformed naming neither the struct nor the key. + seen map[string]struct{} +} + +// checkPrev verifies the previous entry's value slot completed exactly once. +func (m *MapEncoder) checkPrev() { + if m.childDone > m.count { + m.st.fail(fmt.Errorf("vcffi: 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("vcffi: value for key %q was never completed", m.lastKey)) + } +} + +// Field writes an entry key and returns an Encoder for its value. Write the +// value fully (one channel, containers Ended) before calling Field again. +// Keys are UTF-8 validated; insertion order is preserved on the wire. +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("vcffi: object key is not valid UTF-8")) + } else if _, dup := m.seen[key]; dup { + m.st.fail(fmt.Errorf("vcffi: duplicate key %q in map encoding", 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 finalizes the map, writing its entry count. Same error contract as +// SeqEncoder.End: the first error of the whole encode, not one scoped 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 itself is one completed value in the enclosing slot. + 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("vcffi: 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 into the value transport form a wasm guest expects: the +// encode counterpart of [Unmarshal], and the path a binding's Encrypt takes. +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 paths always write exactly one value; only an + // Encryptable can leave the root empty (or an un-Ended container) or + // write more than once. + if root != 1 { + return nil, fmt.Errorf("vcffi: encode must complete exactly one root value, completed %d", root) + } + return st.buf, nil +} + +// Encode records v into enc following encoding/json-style rules, but +// consulting the Encryptable interface first: +// +// - a value implementing Encryptable uses its EncryptValue; +// - nil → Null; +// - bool → Bool; +// - int8/int16/int32 → Int8/Int16/Int32; +// - int/int64 → Int64; +// - uint8/uint16/uint32 → UInt8/UInt16/UInt32; +// - uint/uint64/uintptr → UInt64; +// - float32 → Float32; +// - float64 → Float64; +// - string → String; +// - []byte → Bytes; +// - slices/arrays → Seq; +// - map[string]T → Map, keys SORTED for determinism; +// - structs → Map by field name, honoring `vc:"name"` +// tags (`vc:"-"` skips a field; options after a comma, such as the +// storage profile's `,default`, do not change the name), in +// declaration order; +// - pointers → dereferenced; a nil pointer → a typed +// null if its element type is fixed width (see [fixedTypeOf]), Null +// otherwise; +// - vcvalue.TypedNull → a typed null of its type. +// +// Map keys are sorted because Go map iteration order is randomized; +// sorting makes the encrypted structure deterministic. Struct fields keep +// declaration order. +// +// Encode returns the first error recorded while writing enc, so it composes: +// an Encryptable can delegate a sub-value with vcffi.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 handles the marker types both dispatchers (encodeAny for +// interface values, encodeReflect for values reached through reflection) +// must special-case before any reflection sees them. Returns true when v was +// fully handled. +// +// - vcvalue.Plain is the explicit passthrough opt-in; checked before Encryptable +// and the struct arm so it is never mistaken for a plain struct. +// - vcvalue.Object is decode-only in spirit, but a decrypt-then-re-encrypt flow +// legitimately feeds it back in; without interception the reflect slice +// arm would encode it as a SEQ of {Key,Value} structs, silently changing +// the record's structure. +// - Encryptable hands control to the user type — except a typed nil +// pointer, which still satisfies the assertion but would dereference nil +// in typical implementations; it encodes as Null like every other nil, +// or as a typed null when the type declares its width (FixedWidth). +func interceptMarkers(enc Encoder, v any) bool { + if m, ok := markers[reflect.TypeOf(v)]; ok { + m.encode(enc, v) + return true + } + if e, ok := v.(Encryptable); ok { + if ev := reflect.ValueOf(e); ev.Kind() == reflect.Pointer && ev.IsNil() { + if t, ok := fixedTypeOf(ev.Type()); ok { + enc.TypedNull(t) + } else { + enc.Null() + } + return true + } + if err := e.EncryptValue(enc); err != nil { + enc.st.fail(err) + } + return true + } + return false +} + +// encodeObject re-encodes a decoded vcvalue.Object with object framing, preserving +// its field order (vcvalue.Object exists precisely to preserve wire order). +func encodeObject(enc Encoder, o vcvalue.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 + } + // Re-check the explicit markers for values reached through reflection + // (struct fields, slice elements, map values). vcvalue.Plain is itself a struct, + // so it must be intercepted before the reflect.Struct arm 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 { + // Byte arrays are one Bytes leaf, matching the slice arm above + // and Rust's single-leaf [u8; N] — element-wise encoding would + // seal N separate leaves and produce a ciphertext shape no other + // producer emits. + 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 its element type, so an absent + // fixed-width value is padded like Rust's Option. A nil + // interface has no type to go by. + if rv.Kind() != reflect.Pointer { + enc.Null() + } else if t, ok := fixedTypeOf(rv.Type()); ok { + enc.TypedNull(t) + } else { + enc.Null() + } + return + } + // Charge the dereference against the shared depth budget: it writes + // no container framing, so without this a pointer cycle (x = &x) + // would recurse to stack overflow instead of failing cleanly. + if enc.depth+1 > maxDepth { + enc.st.fail(ErrTooDeep) + return + } + // Same slot: the dereferenced value completes the pointer's counter. + encodeReflect(Encoder{st: enc.st, depth: enc.depth + 1, done: enc.done}, rv.Elem()) + default: + enc.st.fail(fmt.Errorf("vcffi: 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("vcffi: map keys must be strings, got %s", rv.Type().Key())) + return + } + keys := rv.MapKeys() + // Sort keys: Go map iteration is randomized; sorting makes the encrypted + // structure deterministic across encodes of an equal map. + 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() + // Named as the storage profile names them: `vc:"name"`, options after + // a comma, `vc:"-"` skipped, an unknown option 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++ + } + // A struct whose every field is unexported (time.Time is the canonical + // case) would seal as an empty map and the payload would be gone with no + // error at either end — the exact hazard the NAPI layer's + // ensure_plain_object guards. An all-`vc:"-"` struct is left alone: the + // caller asked for the empty encoding explicitly. + if encoded == 0 && unexported > 0 { + enc.st.fail(fmt.Errorf( + "vcffi: struct %s has no exported fields to encode — implement Encryptable to control its sealing", t)) + return + } + _ = m.End() +} + +// marker is how interceptMarkers writes a type it handles by exact type, +// and the fixed-width type of its typed null, if it has one (zero if not). +// One table for both, so a new marker type cannot be written one way and +// padded, or not, another. +type marker struct { + fixed vcvalue.FixedType + encode func(Encoder, any) +} + +// numeric is how encodeReflect writes an int, uint or float kind, and the +// fixed-width type of its typed null: the same one-table rule as marker. +type numeric struct { + fixed vcvalue.FixedType + encode func(Encoder, reflect.Value) +} + +var ( + encryptableType = reflect.TypeOf((*Encryptable)(nil)).Elem() + fixedWidthType = reflect.TypeOf((*FixedWidth)(nil)).Elem() + float32Type = reflect.TypeOf(float32(0)) + + // markers is filled in init: Plain and Object encode by calling back + // into encodeAny, which reads the table. + markers map[reflect.Type]marker + + numericKinds = map[reflect.Kind]numeric{ + reflect.Int8: {vcvalue.TypeInt8, func(e Encoder, rv reflect.Value) { e.Int8(int8(rv.Int())) }}, + reflect.Int16: {vcvalue.TypeInt16, func(e Encoder, rv reflect.Value) { e.Int16(int16(rv.Int())) }}, + reflect.Int32: {vcvalue.TypeInt32, func(e Encoder, rv reflect.Value) { e.Int32(int32(rv.Int())) }}, + reflect.Int: {vcvalue.TypeInt64, func(e Encoder, rv reflect.Value) { e.Int64(rv.Int()) }}, + reflect.Int64: {vcvalue.TypeInt64, func(e Encoder, rv reflect.Value) { e.Int64(rv.Int()) }}, + reflect.Uint8: {vcvalue.TypeUint8, func(e Encoder, rv reflect.Value) { e.UInt8(uint8(rv.Uint())) }}, + reflect.Uint16: {vcvalue.TypeUint16, func(e Encoder, rv reflect.Value) { + e.UInt16(uint16(rv.Uint())) + }}, + reflect.Uint32: {vcvalue.TypeUint32, func(e Encoder, rv reflect.Value) { + e.UInt32(uint32(rv.Uint())) + }}, + // Every unsigned word-or-wider kind keeps its unsigned identity as + // UInt64 (no fit-check: a bare uint always maps to UINT64). + reflect.Uint: {vcvalue.TypeUint64, func(e Encoder, rv reflect.Value) { e.UInt64(rv.Uint()) }}, + reflect.Uint64: {vcvalue.TypeUint64, func(e Encoder, rv reflect.Value) { e.UInt64(rv.Uint()) }}, + reflect.Uintptr: {vcvalue.TypeUint64, func(e Encoder, rv reflect.Value) { e.UInt64(rv.Uint()) }}, + reflect.Float32: {vcvalue.TypeFloat32, func(e Encoder, rv reflect.Value) { + // rv.Float() widens to float64, and the hardware widening sets + // the quiet bit of a signaling NaN. Converting to the built-in + // float32 instead copies the bits (reflect special-cases float32 + // to float32, Go issue 36400), so a named float32 type keeps + // them too. Only a value that cannot be read as an interface + // falls back to widening. + if f, ok := interfaceOf(rv.Convert(float32Type)).(float32); ok { + e.Float32(f) + } else { + e.Float32(float32(rv.Float())) + } + }}, + reflect.Float64: {vcvalue.TypeFloat64, func(e Encoder, rv reflect.Value) { e.Float64(rv.Float()) }}, + } + + // fixedTypes caches fixedTypeOf by pointer type: every nil pointer of a + // record type would otherwise pay its reflection again. + fixedTypes sync.Map +) + +func init() { + markers = map[reflect.Type]marker{ + reflect.TypeOf(vcvalue.Int128{}): {vcvalue.TypeInt128, func(e Encoder, v any) { + e.Int128(v.(vcvalue.Int128)) + }}, + reflect.TypeOf(vcvalue.Uint128{}): {vcvalue.TypeUint128, func(e Encoder, v any) { + e.UInt128(v.(vcvalue.Uint128)) + }}, + reflect.TypeOf(vcvalue.Date{}): {vcvalue.TypeDate, func(e Encoder, v any) { + e.Date(v.(vcvalue.Date)) + }}, + reflect.TypeOf(time.Time{}): {vcvalue.TypeTimestamp, func(e Encoder, v any) { + e.Timestamp(v.(time.Time)) + }}, + reflect.TypeOf(vcvalue.Timestamp{}): {vcvalue.TypeTimestamp, func(e Encoder, v any) { + e.TimestampParts(v.(vcvalue.Timestamp)) + }}, + reflect.TypeOf(vcvalue.Decimal{}): {vcvalue.TypeDecimal, func(e Encoder, v any) { + e.Decimal(v.(vcvalue.Decimal)) + }}, + reflect.TypeOf(vcvalue.UUID{}): {vcvalue.TypeUUID, func(e Encoder, v any) { + e.UUID(v.(vcvalue.UUID)) + }}, + // A tagged value's physical type is in the value, not the type. + reflect.TypeOf(vcvalue.Tagged{}): {0, func(e Encoder, v any) { e.Tagged(v.(vcvalue.Tagged)) }}, + reflect.TypeOf(vcvalue.TypedNull{}): {0, func(e Encoder, v any) { + e.TypedNull(v.(vcvalue.TypedNull).Type) + }}, + reflect.TypeOf(vcvalue.Plain{}): {0, func(e Encoder, v any) { + encodeAny(e.Passthrough(), v.(vcvalue.Plain).V) + }}, + reflect.TypeOf(vcvalue.Object{}): {0, func(e Encoder, v any) { + encodeObject(e, v.(vcvalue.Object)) + }}, + } +} + +// fixedAnswer is what fixedTypeOf caches: whether the type has a fixed-width +// type at all, and which. A type declared through FixedWidth is kept even +// when it is invalid, so that the encode fails instead of writing the plain +// null in its place. +type fixedAnswer struct { + ft vcvalue.FixedType + has bool +} + +// fixedTypeOf is the fixed-width type a pointer of type t points at, through +// any number of pointers, when encodeReflect writes every value of it with +// one fixed-width tag: the int, uint and float kinds (a named type over one +// included) and the fixed-width marker types, exactly (a named type over a +// marker is a struct to reflection, written field by field). A type that +// implements Encryptable chooses its own encoding, which may not be fixed +// width, so it has none unless it says so through FixedWidth. +func fixedTypeOf(t reflect.Type) (vcvalue.FixedType, bool) { + if cached, ok := fixedTypes.Load(t); ok { + a := cached.(fixedAnswer) + return a.ft, a.has + } + var a fixedAnswer + elem := t + // A pointer type that points at itself (type P *P) never reaches a + // non-pointer, so the walk is bounded by the same depth budget that + // bounds a value cycle. Past it the type has no fixed width. + for depth := 0; elem.Kind() == reflect.Pointer && !elem.Implements(encryptableType); depth++ { + if depth == maxDepth { + fixedTypes.Store(t, a) + return 0, false + } + elem = elem.Elem() + } + switch { + case elem.Implements(fixedWidthType): + a = fixedAnswer{zeroValueOf(elem).Interface().(FixedWidth).FixedType(), true} + case elem.Implements(encryptableType): + // Its encoding is its own. + default: + if m, ok := markers[elem]; ok { + a.ft = m.fixed + } else { + a.ft = numericKinds[elem.Kind()].fixed + } + a.has = a.ft != 0 + } + fixedTypes.Store(t, a) + return a.ft, a.has +} + +// zeroValueOf is a zero value of t that a method can be called on: for a +// pointer type, a pointer to a zero value rather than nil, so a method with +// a value receiver does not dereference nil. +func zeroValueOf(t reflect.Type) reflect.Value { + if t.Kind() == reflect.Pointer { + return reflect.New(t.Elem()) + } + return reflect.Zero(t) +} + +// interfaceOf is rv.Interface(), or nil where reflection forbids it +// (values reached through unexported fields). +func interfaceOf(rv reflect.Value) any { + if !rv.CanInterface() { + return nil + } + return rv.Interface() +} diff --git a/languages/golang/encrypt/frame/fuzz_test.go b/languages/golang/encrypt/frame/fuzz_test.go new file mode 100644 index 000000000..e3f71620a --- /dev/null +++ b/languages/golang/encrypt/frame/fuzz_test.go @@ -0,0 +1,376 @@ +package vcffi + +import ( + "bytes" + "cmp" + "encoding/binary" + "encoding/hex" + "encoding/json" + "math/big" + "os" + "slices" + "testing" +) + +// Unmarshal and UnmarshalCipherText are the package's entire hostile-input +// surface: arbitrary bytes from the wasm boundary or a database column. The +// fuzz targets assert the decoders never panic, and that anything they accept +// re-encodes to the same bytes (see requireCanonical) — errors are fine, +// crashes and drift are not. Run in CI as ordinary tests over the seed corpus, +// nightly as real fuzzing (.github/workflows/fuzz.yml), and with +// `go test -fuzz` locally for exploration. + +// addCorpusSeeds seeds a fuzz target with every valid and malformed vector in +// the shared value corpus, so the fuzzer starts from each scalar tag. +func addCorpusSeeds(f *testing.F, wrap func([]byte) []byte) { + data, err := os.ReadFile("../../../testdata/value-conformance.json") + if err != nil { + f.Fatal(err) + } + 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 transports are seeds as they are: the + // ciphertext targets must refuse them, and the value targets must not + // read them as a value either. + for _, row := range corpus.CiphertextMalformed { + raw, err := hex.DecodeString(row.Transport) + if err != nil { + f.Fatal(err) + } + f.Add(raw) + } +} + +// canonicalForm is what an accepted value encoding re-encodes as. Four +// things may legitimately change, and nothing else: an Undefined tag (0x01) +// comes back as Null (0x00), Go's documented projection; a typed null comes +// back as Null too, as Rust's frame writer writes it; a decimal negative +// zero comes back as zero with its scale kept (ADR 0001); and a timestamp in +// the 0xF3 envelope (seconds, milliseconds or microseconds) comes back in +// the shorthand nanosecond form, because Go reads it as a time.Time. The +// walker follows the transport format independently of the decoder, so a +// walk that falls out of step with it produces the wrong bytes and fails +// requireCanonical rather than passing. +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) + // flags(4) then the coefficient(12): a set sign bit over a zero + // coefficient is a negative zero, read 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, which fixes the padding; it all 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, booleans and the fixed-width extended scalars. + b, _ := r.take(fixedWidth(tag)) + *out = append(append(*out, tag), b...) + } +} + +// shorthandTimestamp reads the int the envelope carries and writes the +// instant as the shorthand Timestamp tag: i64 seconds then u32 nanoseconds. +// Follows the int encodings by width rather than 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, +// where a value can only appear inside passthrough nodes. One more thing +// may change here: the entries of a map come back sorted by key. Rust +// writes a map's entries in the order it holds them (a struct's field +// order, say), while Go reads a map into map[string]any, which keeps no +// order, and writes it back with the keys sorted. Entry order is not +// authenticated, so the decoder accepts either and the walker sorts. +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 walked onto out, then cut back off and kept + // aside, so 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 same order as encodeCipherText's slices.Sort over the keys. + 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) { + // Seeds: one of each node kind, plus known-hostile shapes. + 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 re-encoding is canonical, so it must be a fixed point. + 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}) // the retired ctNone: 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 clear 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(VCValueLeaves(), data) + if err != nil { + return + } + out, err := MarshalCipherText(VCValueLeaves(), v) + if err != nil { + t.Fatalf("accepted ciphertext decode failed to re-encode: %v (value %#v)", err, v) + } + requireCanonical(t, data, out, cipherCanonicalForm(data)) + }) +} + +// The walkers decide what may legitimately change, so pin that they rewrite +// nested Undefined tags, negative-zero signs, envelope timestamps and +// ciphertext map entry order and nothing else. +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/scalars.go b/languages/golang/encrypt/frame/scalars.go new file mode 100644 index 000000000..449cda13b --- /dev/null +++ b/languages/golang/encrypt/frame/scalars.go @@ -0,0 +1,339 @@ +package vcffi + +import ( + "encoding/binary" + "time" + + "github.com/cipherstash/vitaminc/bindings/go/vcvalue" +) + +func (e Encoder) scalar(tag byte, payload []byte) { + if e.st.err != nil { + 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 vcvalue.Int128) { e.scalar(tagInt128, v[:]) } +func (e Encoder) UInt128(v vcvalue.Uint128) { e.scalar(tagUint128, v[:]) } + +func (e Encoder) Date(v vcvalue.Date) { + if e.st.err != nil { + return + } + days, err := v.DaysFromCE() + if err != nil { + e.st.fail(err) + return + } + e.scalar(tagDate, binary.LittleEndian.AppendUint32(nil, uint32(days))) +} + +// Timestamp keeps the instant and nanoseconds, discarding location and monotonic metadata. +func (e Encoder) Timestamp(v time.Time) { + e.TimestampParts(vcvalue.Timestamp{Seconds: v.Unix(), Nanoseconds: uint32(v.Nanosecond())}) +} +func (e Encoder) TimestampParts(v vcvalue.Timestamp) { + if e.st.err != nil { + 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. A zero is written without a sign, +// whatever the sign of the value given (ADR 0001). +func (e Encoder) Decimal(v vcvalue.Decimal) { + if e.st.err != nil { + 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 sixteen bytes under the Uuid logical type, in the 0xF3 +// envelope over a bytes scalar. +func (e Encoder) UUID(u vcvalue.UUID) { + if e.st.err != nil { + return + } + e.push(uuidEnvelope[:]...) + e.Bytes(u[:]) +} + +// uuidEnvelope is the envelope header a UUID starts with, and the header of +// a UUID's typed null: the Uuid logical type, no parameter, over bytes. +var uuidEnvelope = [3]byte{tagEnvelope, logicalUUID, 0} + +// Tagged records a physical scalar under a logical id this build does not +// know, in the 0xF3 envelope: what Unmarshal produced for such a value, so +// it goes back out unchanged. An id this build knows, or a value that is +// not a physical scalar, is refused. +func (e Encoder) Tagged(t vcvalue.Tagged) { + if e.st.err != nil { + return + } + if t.ID <= logicalLastKnown { + e.st.fail(vcvalue.ErrInvalidTagged) + return + } + e.push(tagEnvelope, t.ID, t.Param) + if !e.physical(t.V) { + e.st.fail(vcvalue.ErrInvalidTagged) + } +} + +// physical writes v through its scalar channel, for the kinds the envelope +// may carry, and reports whether v was one of them. +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: + // As Encode writes int and uint everywhere else. + e.Int64(int64(x)) + case uint: + e.UInt64(uint64(x)) + case vcvalue.Int128: + e.Int128(x) + case vcvalue.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 vcvalue.Int128(b), nil + case tagUint128: + return vcvalue.Uint128(b), nil + case tagDate: + d, err := vcvalue.DateFromDaysCE(int32(binary.LittleEndian.Uint32(b))) + if err != nil { + return nil, ErrMalformed + } + return d, nil + case tagTimestamp: + // A leap second (nanoseconds of one billion or more) has no count + // since the epoch and is refused by Validate (ADR 0001). + t := vcvalue.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 := vcvalue.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 (ADR 0001). + return d.Normalized(), nil + default: + return nil, ErrMalformed + } +} + +// fixedWidth is the payload width of a fixed-width scalar tag, or zero for +// a tag whose payload is not fixed (or that has none). +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 a plain int or float: what a typed null +// in the envelope may ride on under a timestamp unit or an unknown id. +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 +} + +// fixedTags is the tag each FixedType is written with, all but the UUID, +// whose header is uuidEnvelope over tagBytes. +var fixedTags = map[vcvalue.FixedType]byte{ + vcvalue.TypeInt8: tagInt8, + vcvalue.TypeInt16: tagInt16, + vcvalue.TypeInt32: tagInt32, + vcvalue.TypeInt64: tagInt64, + vcvalue.TypeInt128: tagInt128, + vcvalue.TypeUint8: tagUint8, + vcvalue.TypeUint16: tagUint16, + vcvalue.TypeUint32: tagUint32, + vcvalue.TypeUint64: tagUint64, + vcvalue.TypeUint128: tagUint128, + vcvalue.TypeFloat32: tagFloat32, + vcvalue.TypeFloat64: tagFloat64, + vcvalue.TypeDate: tagDate, + vcvalue.TypeTimestamp: tagTimestamp, + vcvalue.TypeDecimal: tagDecimal, +} + +// TypedNull records an absent value of a fixed-width type: a null padded to +// the length of a value of t, so the two seal to the same length. Encode +// writes one for a nil pointer to a fixed-width type; this channel is for a +// caller that knows the type some other way. An invalid t fails the +// encode. +func (e Encoder) TypedNull(t vcvalue.FixedType) { + if e.st.err != nil { + return + } + if !t.Valid() { + e.st.fail(vcvalue.ErrInvalidFixedType) + return + } + var header []byte + var payload int + if t == vcvalue.TypeUUID { + header, payload = append(uuidEnvelope[:], tagBytes), len(vcvalue.UUID{}) + } else { + tag := fixedTags[t] + header, payload = []byte{tag}, fixedWidth(tag) + } + e.push(tagTypedNull) + e.push(header...) + // One byte of the value's length went to tagTypedNull. + e.push(make([]byte, payload-1)...) + e.complete() +} + +// decodeTypedNull reads a typed null after its tag, as strictly as the Rust +// codec does, so every absence has one encoding: a header a value of some +// fixed-width type starts with, then exactly the zero padding to that +// value's length. It decodes as nil. A frame is never sealed, so the padding +// means nothing once the value is out, and Rust's frame writer writes the +// plain null for it 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: + // The nanosecond unit has the shorthand Timestamp tag. + 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: + // A logical id this build does not know, over an int or 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..55d56f56f --- /dev/null +++ b/languages/golang/encrypt/frame/scalars_test.go @@ -0,0 +1,216 @@ +package vcffi + +import ( + "encoding/hex" + "errors" + "github.com/cipherstash/vitaminc/bindings/go/vcvalue" + "reflect" + "strings" + "testing" + "time" +) + +func TestScalarHostEncoding(t *testing.T) { + signed, err := vcvalue.ParseInt128("-170141183460469231731687303715884105728") + if err != nil { + t.Fatal(err) + } + unsigned, err := vcvalue.ParseUint128("340282366920938463463374607431768211455") + if err != nil { + t.Fatal(err) + } + decimal, err := vcvalue.ParseDecimal("1.50") + if err != nil { + t.Fatal(err) + } + uuid, err := vcvalue.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"}, + {vcvalue.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"}, + {vcvalue.Tagged{ID: 200, Param: 9, V: uint32(34)}, "f3c8090622000000"}, + {vcvalue.Tagged{ID: 255, Param: 0, V: nil}, "f3ff0000"}, + {vcvalue.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 intercept also 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 + }{ + {vcvalue.Date{Year: 2023, Month: 2, Day: 29}, vcvalue.ErrInvalidDate}, + {vcvalue.Timestamp{Seconds: 0, Nanoseconds: 1000000000}, vcvalue.ErrInvalidTimestamp}, + {time.Date(10000, 1, 1, 0, 0, 0, 0, time.UTC), vcvalue.ErrInvalidTimestamp}, + {time.Date(-9999, 1, 1, 0, 0, 0, 0, time.UTC), vcvalue.ErrInvalidTimestamp}, + {vcvalue.Decimal{Scale: 29}, vcvalue.ErrInvalidDecimal}, + // A tagged value must be a physical scalar under an unknown id. + {vcvalue.Tagged{ID: 5, V: []byte{1}}, vcvalue.ErrInvalidTagged}, + {vcvalue.Tagged{ID: 0, V: int8(1)}, vcvalue.ErrInvalidTagged}, + {vcvalue.Tagged{ID: 200, V: []any{int8(1)}}, vcvalue.ErrInvalidTagged}, + {vcvalue.Tagged{ID: 200, V: time.Unix(0, 0)}, vcvalue.ErrInvalidTagged}, + } + for _, tc := range cases { + if _, err := Marshal(tc.value); !errors.Is(err, tc.err) { + t.Fatalf("got %v, want %v", err, tc.err) + } + } +} + +// The envelope's timestamp units decode to time.Time; the nanosecond unit +// has the shorthand tag and is refused in the envelope, as is every other +// envelope the corpus does not already pin. +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 the wire admits, as an i64 + {"f30300051fb9060fa8ffffff", time.Unix(-377705023201, 0).UTC()}, // the first second the wire admits + } { + 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", // out of the wire's range + "f3030005" + "e1d3f2ff3a000000", // one second past the wire's 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 := vcvalue.ParseInt128("1") + if err != nil { + t.Fatal(err) + } + u128, err := vcvalue.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 (ADR 0001). +func TestDecimalNegativeZeroIsWrittenUnsigned(t *testing.T) { + encoded, err := Marshal(vcvalue.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 travels under an unknown id and reads back as the +// same Tagged value. +func TestTaggedRoundTripsEveryPhysicalScalar(t *testing.T) { + i128, err := vcvalue.ParseInt128("-1") + if err != nil { + t.Fatal(err) + } + u128, err := vcvalue.ParseUint128("1") + if err != nil { + t.Fatal(err) + } + for _, value := 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 := vcvalue.Tagged{ID: 200, Param: 9, V: value} + 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", value, got, err) + } + } +} + +// A Go int or uint in a Tagged value is written as Int64 or UInt64, as Encode +// writes it everywhere else, and 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(vcvalue.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 := (vcvalue.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..66c789ffa --- /dev/null +++ b/languages/golang/encrypt/frame/storage.go @@ -0,0 +1,688 @@ +package vcffi + +import ( + "cmp" + "encoding" + "encoding/binary" + "errors" + "fmt" + "math" + "reflect" + "slices" + "strings" + "unicode/utf8" + + "github.com/cipherstash/vitaminc/bindings/go/vcvalue" +) + +// The storage profile, version 1: a value as one versioned blob, for bytes +// that are kept. It is the Go side of the Rust module +// vitaminc_aead_frame::storage, specified in +// packages/aead-frame/STORAGE.md and pinned by the golden corpus in +// packages/aead-frame/testdata/storage-v1.json. Unlike the rest of this +// package, which is transport, the bytes [MarshalStorage] writes and +// [UnmarshalStorage] reads are a compatibility commitment, shared with Rust. + +// StorageVersion is the version this package writes, and the only one it +// reads. +const StorageVersion = 1 + +// StorageSome marks a present optional value: StorageSome, then the value. +// Rust writes it for every Some. Go writes it only for a pointer whose +// target is itself written as null, where leaving it out would read back as +// nil: a bare value reads as present into a pointer or a Rust Option, and as +// itself into a plain field, so a Go pointer is read alike in both +// languages, whatever the other side declares. +const StorageSome = 0xF5 + +// StorageMap starts a map whose keys are nodes: StorageMap, a u32 count, +// then a key and a value for each entry. A Go map is one; a struct is an +// object. +const StorageMap = 0xF6 + +// StorageHeader starts every blob: "VCS", then [StorageVersion]. +var StorageHeader = [4]byte{'V', 'C', 'S', StorageVersion} + +// The classes of a storage refusal, the Go side of Rust's +// storage::ErrorKind. Match them with errors.Is. A blob that breaks a rule +// of its version is [ErrMalformed], as transport bytes are. +var ( + // ErrNotABlob: shorter than the header, or not starting with "VCS". + ErrNotABlob = errors.New("vcffi: not a storage blob") + // ErrUnsupportedVersion: a blob of a version this package does not + // read. A later release may: the reader needs upgrading, and the blob + // is not corrupt. + ErrUnsupportedVersion = errors.New("vcffi: an unsupported storage version") + // ErrMismatch: a well-formed blob whose value the destination does not + // take: a string where a number was expected, a missing field. + ErrMismatch = errors.New("vcffi: the stored value does not fit the destination") + // ErrUnwritable: a value that cannot be written as a blob: nested too + // deep, a map key that is not an integer, text or bytes, a repeated + // key, a kind with no storage form. + ErrUnwritable = errors.New("vcffi: the value cannot be written as a storage blob") +) + +// Some is a present optional value, as a blob holds it, for a value read +// into an `any`. A pointer is the usual way to write one. +type Some struct { + V any +} + +// StorageEntries is a map as a blob holds it, for a value read into an +// `any`: its entries in the order they were written, each key an integer, +// a string or []byte. Written, it is a map in that 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: +// +// - nil, a nil interface → null; +// - bool → bool; +// - int8, int16, int32, int64 → that width; int → int64; +// - uint8 … uint64 → that width; uint, uintptr → uint64; +// - vcvalue.Int128, Uint128 → the 128-bit widths; +// - float32, float64 → that width, by its bits; +// - string → text (valid UTF-8 only); +// - []byte, [N]byte → bytes (so a UUID is its 16 bytes); +// - an encoding.TextMarshaler → text (time.Time as RFC 3339); +// - slices, arrays → array; a nil slice is an empty one; +// - map[K]V → map, keys sorted: integers by value, +// text and bytes by their bytes, as a Rust BTreeMap orders them; K is +// an integer, a string, a byte array or a TextMarshaler; +// - structs → object, by field name, honoring +// `vc:"name"` tags (`vc:"-"` skips a field), in declaration order; a +// `vc:"name,default"` field reads as its zero value when a blob does +// not have it; +// - pointers → nil is null, and a non-nil pointer is +// what it points at, as encoding/json writes it; a pointer to a value +// written starting with null or [StorageSome] (a nil pointer or +// interface, [Some], or a pointer to one) is [StorageSome] then that +// value, so every level reads back; +// - [Some], [StorageEntries], vcvalue.Object and []any → as they read. +// +// The transport's Encryptable, passthrough (vcvalue.Plain) and logical +// types (vcvalue.Date, Timestamp, Decimal, Tagged, TypedNull) have no +// storage form, and are refused. +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 model's own types, which [storageWriter.model] writes. Int128 and +// Uint128 are [16]byte too, so [byteArray] also leaves them out, for a +// value model cannot box and for the reader. +var ( + int128Type = reflect.TypeOf(vcvalue.Int128{}) + uint128Type = reflect.TypeOf(vcvalue.Uint128{}) + someType = reflect.TypeOf(Some{}) + objectType = reflect.TypeOf(vcvalue.Object{}) + entriesType = reflect.TypeOf(StorageEntries{}) + plainType = reflect.TypeOf(vcvalue.Plain{}) + dateType = reflect.TypeOf(vcvalue.Date{}) + timestampType = reflect.TypeOf(vcvalue.Timestamp{}) + decimalType = reflect.TypeOf(vcvalue.Decimal{}) + taggedType = reflect.TypeOf(vcvalue.Tagged{}) + typedNullType = reflect.TypeOf(vcvalue.TypedNull{}) +) + +// model writes rv if its type is one of the model's own, which have a form +// of their own rather than the one reflection would give them, and reports +// whether it was. Only those types are boxed 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().(vcvalue.Object), depth) + case entriesType: + return true, w.entries(rv.Interface().(StorageEntries), depth) + case int128Type: + x := rv.Interface().(vcvalue.Int128) + w.buf = append(append(w.buf, tagInt128), x[:]...) + return true, nil + case uint128Type: + x := rv.Interface().(vcvalue.Uint128) + w.buf = append(append(w.buf, tagUint128), x[:]...) + return true, nil + case plainType, dateType, timestampType, decimalType, taggedType, typedNullType: + 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 + } + // Checked by type, before a nil pointer is written as null, so a field + // of an Encryptable type is refused whether or not it is set. + 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("%s refused to write itself as text", rv.Type()) + } + return w.text(text) + } + if k, ok := numericKinds[rv.Kind()]; ok { + // The transport's numeric table writes each kind at the same width + // a blob does: only the framing differs, and there is none here. + 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 what the pointer or interface rv holds: null if it is +// nil, and otherwise what it points at, marked if that starts with null or +// a marker (see [startsOptional]). The marker is a node, and costs a level +// of depth as a reader counts it; a pointer or interface that writes +// nothing of its own costs none, since the blob is no deeper for it. A run +// of those is bounded on its own, so a cycle (p = &p) is refused rather +// than followed forever. +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 rv is written starting with null or +// [StorageSome]: a nil pointer or interface, [Some], or a pointer or +// interface to one of those. A pointer to such a value is marked, or a +// reader would take that null or marker for the pointer's own, and the +// value would read back one level shorter. A run of pointers longer than a +// blob may nest, a cycle say, is refused when it is written, so it is not +// followed further here. +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 [N]byte, a UUID say, written as bytes. +// Int128 and Uint128 are [16]byte too, and are integers. +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 it, implements +// Encryptable: its fields 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 is rv's MarshalText, if its type has one, through a pointer +// to a copy when the method needs one. +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 a container's tag and a count to be patched by close. +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 holds 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 vcvalue.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 an object's key, refusing one already written. +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++ + } + // As in the transport: a struct of only unexported fields (time.Time + // without its MarshalText, say) would be stored as an empty object, and + // its value lost with no error at either end. + if written == 0 && unexported > 0 { + return unwritable("struct %s has no exported fields", rv.Type()) + } + return w.close(at, written) +} + +// storageField is a struct field as a blob names it. +type storageField struct { + name string + index int + unexported bool + // defaulted fields read as their zero value when a blob lacks them. + defaulted bool +} + +// structFields are t's fields in declaration order, named by their `vc` +// tags, without the ones a `vc:"-"` tag skips. A tag is a name, then +// options after commas: `vc:"age,default"`, or `vc:",default"` to keep the +// field's own name. `default` is the only option; any other is refused, so +// a misspelt one is not quietly ignored. The transport names fields 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("vcffi: 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 written as a node, and what makes two keys the same: +// integers of equal value, whatever their widths, so 1 as a uint8 and 1 as +// an int64 are one key; text and bytes by their bytes, never equal to each +// other or to an integer. Its order is the one keys are written in: by +// kind, integers by value, text and bytes by their bytes. +type mapKey struct { + node []byte + id keyID +} + +// keyKind is a map key's kind, in the order keys of different kinds are +// written in. +type keyKind byte + +const ( + keyInteger keyKind = iota + keyText + keyBytes +) + +type keyID struct { + kind keyKind + // An integer as its sign and its two's-complement 128-bit word. + negative bool + hi, lo uint64 + // Text or 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 is the keyID of a 128-bit integer, from its little-endian word. +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 is the keyID of a key as the reader decodes it: a Go +// integer, Int128 or 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 vcvalue.Int128: + return wideKey(x[:], true), true + case vcvalue.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 writes a map key as its node. +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; its type's MarshalText, if it + // has one, 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("a map key of type %s refused to write itself as text", 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 that write the same key: two texts a + // TextMarshaler spells alike, say. + return unwritable("a key is repeated") + } + keys = append(keys, key) + values[key.id] = it.Value() + } + // Go map iteration is randomized; sorting makes 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..1c5dfe1d3 --- /dev/null +++ b/languages/golang/encrypt/frame/storage_decode.go @@ -0,0 +1,500 @@ +package vcffi + +import ( + "encoding" + "fmt" + "math/big" + "reflect" + "strconv" + + "github.com/cipherstash/vitaminc/bindings/go/vcvalue" +) + +// UnmarshalStorage reads a version 1 blob into the value v points at. +// +// The whole blob is checked first, so a blob of another version, bytes +// that are not a blob, or a malformed body is refused before anything is +// set: [ErrNotABlob], [ErrUnsupportedVersion] or [ErrMalformed]. Then the +// value is read into v by its type, as Rust's serde reads it, which the +// corpus's `reads` rows pin: +// +// - an integer reads into any integer type it fits; a float type reads a +// float or an integer; an integer type never reads a float; +// - a pointer reads null as nil, and any other value, marked present or +// not, as a pointer to that value: a Rust Some and a Go pointer alike; +// - a string reads only text, []byte and [N]byte only bytes (of length +// N), a slice or an array only an array; +// - a map reads a map or an object, each key 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, and a missing field is refused unless it is a +// pointer, which is left nil, or tagged `vc:"name,default"`, which is +// left its zero value, as Rust's #[serde(default)] reads it; +// - an encoding.TextUnmarshaler reads text; +// - an `any` reads the value as the blob holds it: nil, bool, the integer +// widths (vcvalue.Int128 and Uint128 for 128 bits), float32, float64, +// string, []byte, []any, vcvalue.Object for an object, +// [StorageEntries] for a map, and [Some] for an optional value. +// +// A value that does not fit is [ErrMismatch]. Its message names the kind +// found and where, never the value. +func UnmarshalStorage(blob []byte, v any) error { + rv := reflect.ValueOf(v) + if rv.Kind() != reflect.Pointer || rv.IsNil() { + return fmt.Errorf("vcffi: 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 as the value it holds, refusing any blob +// a version 1 reader refuses. +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 may start a map's key. +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(vcvalue.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{}{} + value, err := storageNode(r, depth+1) + if err != nil { + return nil, err + } + fields = append(fields, vcvalue.Field{Key: key, Value: value}) + } + 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 names what a model value is, for a refusal: never the value. +func kindOf(m any) string { + switch m.(type) { + case nil: + return "null" + case bool: + return "a boolean" + case int8, int16, int32, int64, vcvalue.Int128, uint8, uint16, uint32, uint64, vcvalue.Uint128: + return "an integer" + case float32, float64: + return "a float" + case string: + return "text" + case []byte: + return "bytes" + case []any: + return "an array" + case vcvalue.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 is a model integer's value. +func integerOf(m any) (*big.Int, bool) { + if small, ok := smallIntegerOf(m); ok { + return big.NewInt(small), true + } + return wideIntegerOf(m) +} + +// int128Of is v as the 16 little-endian bytes of a two's-complement word. +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: text %s does not take", 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(vcvalue.Int128(int128Of(v)))) + } + case t == uint128Type: + if fits = v.Sign() >= 0 && v.Cmp(maxUint128) <= 0; fits { + rv.Set(reflect.ValueOf(vcvalue.Uint128(int128Of(v)))) + } + 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: an integer that does not fit %s", ErrMismatch, orRoot(path), rv.Type()) + } + return nil +} + +func assignFloat(m any, rv reflect.Value, path string) error { + switch x := m.(type) { + case float32: + // Converted rather than widened, so a float32 keeps its bits + // (reflect copies float32 to float32, 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) + } + // Rounded once, to the destination's width, as Rust's `as` rounds. + 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 is an object's or a map's entries, whichever m is. +func entriesOf(m any) (StorageEntries, bool) { + switch x := m.(type) { + case StorageEntries: + return x, true + case vcvalue.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 read into an interface key is a []byte, which a Go + // map cannot hash: SetMapIndex would panic. + if !key.Comparable() { + return mismatch(at, "a key a Go map can hold", 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..df5245755 --- /dev/null +++ b/languages/golang/encrypt/frame/storage_test.go @@ -0,0 +1,963 @@ +package vcffi + +import ( + "bytes" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "math" + "os" + "reflect" + "strconv" + "strings" + "testing" + "time" + + "github.com/cipherstash/vitaminc/bindings/go/vcvalue" +) + +// The storage corpus is shared with Rust (packages/aead-frame), which pins +// version 1 byte for byte; this file holds Go to the same rows. +const storageCorpus = "../../../packages/aead-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"` +} + +func loadStorageCorpus(t testing.TB) storageCorpusFile { + t.Helper() + data, err := os.ReadFile(storageCorpus) + if err != nil { + t.Fatal(err) + } + var c storageCorpusFile + if err := json.Unmarshal(data, &c); err != nil { + t.Fatal(err) + } + // reads_as is null for a row that reads as null, so its presence is + // told apart from a refusal by the refusal field. + 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 a corpus value describes, without the +// storage reader, so a reader and writer wrong in the same way cannot pass. +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 := vcvalue.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 := vcvalue.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 := vcvalue.Object{} + for _, p := range pairs() { + var key string + _ = json.Unmarshal(p[0], &key) + out = append(out, vcvalue.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 = vcvalue.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 compares two models, floats by their bits so NaNs compare. +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 vcvalue.Object: + y, ok := b.(vcvalue.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 is refused by its class, whatever 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 is the Go type a corpus type describes, or why Go has none: Go has +// no enums and no unit type, and 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 them + // reads as one that does not, and its refusals 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 a row's type is itself a struct that +// denies unknown keys. UnmarshalStorage has no way to deny them, so a +// refused row of such a type that Go reads anyway is skipped. A row of +// that type that Go refuses is still checked for its error class. A +// struct that denies them nested in another type is not looked for: a row +// refused for that would fail below, rather than be skipped. +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 Go can express reads as it says, or is refused as a +// mismatch. What it reads as is compared as the blob it writes back to. +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 + } + // What the row reads as, written canonically, read by the same + // type: the Go value both blobs must read as. + 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()) + } + } + // Most rows are expressible; a new row Go cannot express is logged + // above, and this guards against a typo skipping them all. + 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 in lower case, so two keys can write as one. +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 vcvalue.UUID `vc:"id"` + Scores map[uint32]string `vc:"scores"` + When time.Time `vc:"when"` + Stamp stamp `vc:"stamp"` + Big vcvalue.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, _ := vcvalue.ParseInt128("-170141183460469231731687303715884105728") + in := record{ + Name: "ada", + Age: 36, + Pinned: &yes, + Nested: &np, + Absent: &nilInt, + Tags: []string{"x", "y"}, + Raw: []byte{1, 2}, + ID: vcvalue.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) + } + // The pieces whose bytes Rust must agree on. + var model any + if err := UnmarshalStorage(blob, &model); err != nil { + t.Fatal(err) + } + fields := model.(vcvalue.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 sort by value, as a Rust BTreeMap orders them, so the same +// map writes 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": vcvalue.Plain{V: 1}, + "a date": vcvalue.Date{}, + "a decimal": vcvalue.Decimal{}, + "a typed null": vcvalue.TypedNull{}, + "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": vcvalue.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 read into an interface key would be a []byte, which a Go map +// cannot hold: it is a mismatch, not a 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 became a pointer reads its old value; a missing pointer +// field is nil, and 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 tagged default reads a missing field as its zero value, and keeps + // its name, or the field's own with an empty 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.(vcvalue.Object)[1].Key, model.(vcvalue.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 bare, so a field that is not a pointer on the + // reading side reads it; Rust's marked Some 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(vcvalue.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 names a struct's fields by the same tags, options and all. +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.(vcvalue.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 holds the reader to its contract on hostile bytes: +// it never panics, a blob it reads writes back as exactly the same bytes +// (one encoding per value), and reading into a struct never panics either. +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 to a value +// that is itself written as null or marked present is marked, so its +// reader never takes the inner level's null or marker for its own. +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 blob Codex found: the innermost nil is two markers, 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 [Some] is marked too, so the Some keeps its own marker. + 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 is no map key. It is refused, never handed to its type's +// MarshalText, which would be called on 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 where a struct is +// written or read, in a blob or the transport, rather than ignored. +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 costs no depth, so a linked +// list is 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..cfed7f0d4 --- /dev/null +++ b/languages/golang/encrypt/frame/transport.go @@ -0,0 +1,208 @@ +package vcffi + +import ( + "encoding/binary" + "errors" + "fmt" + "unicode/utf8" +) + +// Transport framing tags. The scalar tags mirror vitaminc-aead's frozen +// sealed-leaf tag table so the two tables can't drift apart on +// meaning; the ARRAY/OBJECT container tags are transport-local (the sealed +// format has no container tags — container shape rides on the ciphertext +// tree). See the package doc: this transport encoding is NOT a storage +// format. +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 is an absent value of a fixed-width type, padded to that + // type's leaf length: the tag, the header a value of the type starts + // with, then zeros (vitaminc#493). + tagTypedNull = 0x15 + tagArray = 0xF0 + tagObject = 0xF1 + // tagPassthrough wraps one value node that travels in the clear + // (unencrypted, unauthenticated). Transport-local, like array/object. + tagPassthrough = 0xF2 + // tagEnvelope carries a logical type with no shorthand tag over a + // physical scalar: id, parameter, then the scalar (ADR 0001). 0xF4 is + // reserved for a longer envelope and is refused. + tagEnvelope = 0xF3 +) + +// Logical type ids, as the envelope spells them. Undefined, Date, Decimal +// and nanosecond Timestamp have shorthand tags of their own, so the +// envelope never carries them: there is one encoding per value. +const ( + logicalUndefined = 1 + logicalDate = 2 + logicalTimestamp = 3 + logicalDecimal = 4 + logicalUUID = 5 + // logicalLastKnown is the highest id this build knows. Any id above it + // is read and re-encoded unchanged as a vcvalue.Tagged. + logicalLastKnown = logicalUUID +) + +// Timestamp units, as the envelope's parameter spells them. Nanoseconds is +// the shorthand Timestamp tag, so only the coarser units use the envelope. +const ( + unitSeconds = 0 + unitMillis = 1 + unitMicros = 2 + unitNanos = 3 +) + +// maxUint32 bounds every length/count written or read (all are u32 LE). +// Typed uint64, not an untyped constant: an untyped 1<<32-1 compared against +// an int fails to compile on 32-bit GOARCH (constant overflows int), and the +// guard is load-bearing there — an oversized count coerced to a negative int +// would slip past the remaining-bytes check and panic in make instead of +// returning ErrMalformed. Comparisons convert the int operand to uint64 +// (always lossless for non-negative values, which the n < 0 guards ensure). +const maxUint32 = uint64(1<<32 - 1) + +// maxDepth mirrors the Rust transport codec's recursion bound, keeping a +// hostile nesting depth from overflowing the stack. +const maxDepth = 128 + +// maxEagerCapacity clamps the up-front reservation of a count-driven +// allocation. The reader's count guard bounds a single reservation against +// the bytes remaining, but not the sum of live reservations: a container +// nesting level costs 5-9 wire bytes while a reserved slot costs many times +// that, and up to maxDepth ancestor reservations are live at once — so ~1 MB +// of hostile bytes could otherwise pin gigabytes. Mirrors the Rust codecs' +// MAX_EAGER_CAPACITY. Slices still grow past the clamp on append; only the +// initial reservation is bounded. +const maxEagerCapacity = 1024 + +func eagerCap(n int) int { + // n < 0 is unreachable on 64-bit (u32 counts are non-negative in a 64-bit + // int) but load-bearing on 32-bit GOARCH, where a hostile prefix >= 2^31 + // coerces negative and min() would pass it through to make(). + if n < 0 { + return 0 + } + return min(n, maxEagerCapacity) +} + +// ErrMalformed is returned by the decoders for any transport buffer or +// storage blob that does not parse: truncated, over-deep, hostile counts, +// duplicate keys, unknown tags. Deliberately unspecific — the decoders treat their input as +// hostile and do not distinguish *how* it is malformed. It is returned bare, +// never wrapped, so errors.Is and == are equivalent today; prefer errors.Is. +// +// A misconfigured [LeafSet] is a different class of failure — the binding's +// own wiring, not hostile bytes — and [UnmarshalCipherText] reports it with a +// distinct, attributable error rather than folding it into ErrMalformed. +var ErrMalformed = errors.New("vcffi: malformed transport bytes or storage blob") + +// ErrTooDeep is returned by the encoders when a value or ciphertext tree +// exceeds the recursion bound (the decoders fold over-deep input into +// [ErrMalformed] — hostile bytes stay unspecific by design, but a too-deep +// value handed in by the caller's own code is worth matching on). +var ErrTooDeep = errors.New("vcffi: value is nested too deeply") + +func appendLen(out []byte, n int) ([]byte, error) { + if n < 0 || uint64(n) > maxUint32 { + return nil, fmt.Errorf("vcffi: 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 is a cursor over a transport buffer, tracking bytes consumed so a +// decode can insist the whole buffer was used. +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 u32 item count, rejecting counts that exceed the bytes +// remaining (every item costs at least one byte) so hostile input cannot +// drive a huge preallocation. The n < 0 guard matches take/appendLen: on +// 32-bit GOARCH a prefix >= 2^31 coerces to a negative int, which would slip +// past the remaining-bytes check and panic in make. +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 length-prefixed, UTF-8-validated string. +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..4ec4b2d35 --- /dev/null +++ b/languages/golang/encrypt/frame/transport_internal_test.go @@ -0,0 +1,28 @@ +package vcffi + +import "testing" + +// White-box pin for eagerCap, mirroring the Rust transport codec's +// eager_capacity test: the clamp is a capacity hint invisible to round-trip +// tests, so assert the function directly — identity below the threshold, +// flat at maxEagerCapacity above it, and zero for negative counts (a u32 +// prefix >= 2^31 coerced to int on 32-bit GOARCH, which must not reach +// make()). The constant itself is pinned so a silent bump shows up 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..8f902e6b4 --- /dev/null +++ b/languages/golang/encrypt/frame/typed_null_test.go @@ -0,0 +1,410 @@ +package vcffi + +import ( + "bytes" + "encoding/hex" + "errors" + "fmt" + "reflect" + "testing" + "time" + + "github.com/cipherstash/vitaminc/bindings/go/vcvalue" +) + +// typedNullAnswers pins each FixedType's typed null: the cross-language +// bytes the Rust codec writes for the same type (vitaminc-aead's leaf +// tests), beside a value of the type, which must be as long. +var typedNullAnswers = []struct { + t vcvalue.FixedType + hex string + present any +}{ + {vcvalue.TypeInt8, "150c", int8(-1)}, + {vcvalue.TypeInt16, "150e00", int16(-1)}, + {vcvalue.TypeInt32, "1504000000", int32(-1)}, + {vcvalue.TypeInt64, "1505" + zeros(7), int64(-1)}, + {vcvalue.TypeInt128, "1510" + zeros(15), vcvalue.Int128{1}}, + {vcvalue.TypeUint8, "150d", uint8(1)}, + {vcvalue.TypeUint16, "150f00", uint16(1)}, + {vcvalue.TypeUint32, "1506000000", uint32(1)}, + {vcvalue.TypeUint64, "1507" + zeros(7), uint64(1)}, + {vcvalue.TypeUint128, "1511" + zeros(15), vcvalue.Uint128{1}}, + {vcvalue.TypeFloat32, "1508000000", float32(1.5)}, + {vcvalue.TypeFloat64, "1509" + zeros(7), 1.5}, + {vcvalue.TypeDate, "1512000000", vcvalue.Date{Year: 1999, Month: 12, Day: 31}}, + {vcvalue.TypeTimestamp, "1513" + zeros(11), time.Unix(1_700_000_000, 5).UTC()}, + {vcvalue.TypeDecimal, "1514" + zeros(15), vcvalue.Decimal{Scale: 2, Coefficient: [12]byte{150}}}, + {vcvalue.TypeUUID, "15f305000b" + zeros(15), vcvalue.UUID{0xAB}}, +} + +func zeros(n int) string { return hex.EncodeToString(make([]byte, n)) } + +func TestTypedNullKnownAnswers(t *testing.T) { + for _, row := range typedNullAnswers { + t.Run(fmt.Sprint(row.t), func(t *testing.T) { + got, err := Marshal(vcvalue.TypedNull{Type: row.t}) + 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 gives bytes a length prefix; a typed null of a UUID + // has none, because its sealed leaf has none. + want := len(present) + if row.t == vcvalue.TypeUUID { + want -= 4 + } + if len(got) != want { + t.Fatalf("typed null is %d bytes, a value %d", len(got), want) + } + // It reads back as nil, like every null, and writes back as one. + v, err := Unmarshal(got) + if err != nil || v != nil { + t.Fatalf("decoded %#v, %v", v, err) + } + }) + } + if len(typedNullAnswers) != int(vcvalue.TypeUUID) { + t.Fatalf("pinned %d of %d types", len(typedNullAnswers), vcvalue.TypeUUID) + } +} + +func TestAnInvalidFixedTypeFailsTheEncode(t *testing.T) { + for _, ft := range []vcvalue.FixedType{0, vcvalue.TypeUUID + 1, 255} { + if _, err := Marshal(vcvalue.TypedNull{Type: ft}); !errors.Is(err, vcvalue.ErrInvalidFixedType) { + t.Fatalf("%v: got %v", ft, 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 a typed null, the Go side of +// Rust's Option; a nil with no fixed-width type to go by is the plain +// null. Each case is encoded twice, since the second encode reads the +// per-type cache. +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)}, + {"*vcvalue.Date", (*vcvalue.Date)(nil), "1512000000"}, + {"*vcvalue.Timestamp", (*vcvalue.Timestamp)(nil), "1513" + zeros(11)}, + {"*vcvalue.Decimal", (*vcvalue.Decimal)(nil), "1514" + zeros(15)}, + {"*vcvalue.UUID", (*vcvalue.UUID)(nil), "15f305000b" + zeros(15)}, + {"*vcvalue.Int128", (*vcvalue.Int128)(nil), "1510" + zeros(15)}, + {"*vcvalue.Uint128", (*vcvalue.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) + } + } + }) + } +} + +// An Encryptable that always writes one value of one fixed-width type: +// a FixedWidth, the Go side of Rust's Encrypt::FIXED. +type money struct{ cents int64 } + +func (m money) EncryptValue(enc Encoder) error { + enc.Int64(m.cents) + return nil +} + +func (money) FixedType() vcvalue.FixedType { return vcvalue.TypeInt64 } + +// The same, declared on the pointer. +type ptrMoney struct{ cents int64 } + +func (m *ptrMoney) EncryptValue(enc Encoder) error { + enc.Int64(m.cents) + return nil +} + +func (*ptrMoney) FixedType() vcvalue.FixedType { return vcvalue.TypeInt64 } + +// A FixedWidth that declares a type that is not one. +type badWidth struct{} + +func (badWidth) EncryptValue(enc Encoder) error { + enc.String("custom") + return nil +} + +func (badWidth) FixedType() vcvalue.FixedType { return 0 } + +func TestANilPointerToAFixedWidthEncryptableIsATypedNullOfItsType(t *testing.T) { + want := "1505" + zeros(7) + for _, c := range []struct { + name string + v any + }{ + {"*money", (*money)(nil)}, + {"**money", (**money)(nil)}, + {"*ptrMoney", (*ptrMoney)(nil)}, + {"**ptrMoney", (**ptrMoney)(nil)}, + } { + t.Run(c.name, func(t *testing.T) { + got, err := Marshal(c.v) + if err != nil { + t.Fatal(err) + } + if hex.EncodeToString(got) != want { + t.Fatalf("got %x, want %s", got, want) + } + }) + } + // A present value is as long, and still written by EncryptValue. + present, err := Marshal(&money{cents: 150}) + if err != nil { + t.Fatal(err) + } + if hex.EncodeToString(present) != "059600000000000000" { + t.Fatalf("present: got %x", present) + } + // Through a struct field, where a nil would otherwise show by length. + type order struct{ Refund *money } + absent, err := Marshal(order{}) + if err != nil { + t.Fatal(err) + } + if !bytes.HasSuffix(absent, []byte{tagTypedNull, tagInt64, 0, 0, 0, 0, 0, 0, 0}) { + t.Fatalf("absent: %x", absent) + } + // A declared type that is not a fixed-width type fails the encode, and + // never writes the plain null in its place. A present value is not + // asked. + if _, err := Marshal((*badWidth)(nil)); !errors.Is(err, vcvalue.ErrInvalidFixedType) { + t.Fatalf("invalid declared type: got %v", err) + } + if _, err := Marshal(badWidth{}); err != nil { + t.Fatalf("present: %v", err) + } +} + +func TestAStructsNilFieldsAreTypedNulls(t *testing.T) { + type person struct { + Name string + Born *vcvalue.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.(vcvalue.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 carry their padding; Any has no type to go by, and a nil + // slice is an empty sequence, as it always was. + 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) + } +} + +// The explicit channel, for an Encryptable that knows the type. +type maybeAge struct{ v *int32 } + +func (m maybeAge) EncryptValue(enc Encoder) error { + if m.v == nil { + enc.TypedNull(vcvalue.TypeInt32) + } 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) + } + // It completes exactly one slot, like every terminal. + enc := func(e Encoder) error { + s := e.Seq() + s.Elem().TypedNull(vcvalue.TypeUint8) + 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 absence has one encoding: the decoder refuses anything a writer +// does not write. The shared corpus pins the same refusals for every +// language; these are the Go-specific edges around them. +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) + } + } +} + +// Every fixed-width marker and kind writes its values with the header its +// typed null carries, so the one table cannot pad a type as something it is +// not. A marker added without a sample here fails the test. +func TestEveryFixedTypeIsWrittenWithItsTypedNullsHeader(t *testing.T) { + samples := map[reflect.Type]any{ + reflect.TypeOf(vcvalue.Int128{}): vcvalue.Int128{1}, + reflect.TypeOf(vcvalue.Uint128{}): vcvalue.Uint128{1}, + reflect.TypeOf(vcvalue.Date{}): vcvalue.Date{Year: 2000, Month: 1, Day: 1}, + reflect.TypeOf(time.Time{}): time.Unix(7, 0), + reflect.TypeOf(vcvalue.Timestamp{}): vcvalue.Timestamp{Seconds: 7}, + reflect.TypeOf(vcvalue.Decimal{}): vcvalue.Decimal{Scale: 1}, + reflect.TypeOf(vcvalue.UUID{}): vcvalue.UUID{1}, + } + check := func(name string, ft vcvalue.FixedType, sample any) { + null, err := Marshal(vcvalue.TypedNull{Type: ft}) + if err != nil { + t.Fatalf("%s: %v", name, err) + } + value, err := Marshal(sample) + if err != nil { + t.Fatalf("%s: %v", name, err) + } + // The typed null's header (after its tag) begins the value's. + 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 marker, so a marker that loses its + // fixed type is caught, not skipped. + for typ := range samples { + if markers[typ].fixed == 0 { + t.Fatalf("%v has a sample but no typed null", typ) + } + } + for typ, m := range markers { + if m.fixed == 0 { + continue + } + sample, ok := samples[typ] + if !ok { + t.Fatalf("no sample for the fixed-width marker %v", typ) + } + check(typ.String(), m.fixed, sample) + } + for kind, n := range numericKinds { + check(kind.String(), n.fixed, 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/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/README.md b/languages/golang/encrypt/value/README.md new file mode 100644 index 000000000..644872656 --- /dev/null +++ b/languages/golang/encrypt/value/README.md @@ -0,0 +1,126 @@ +# vcvalue — the durable value layer + +`vcvalue` is the Go materialization of vitaminc's **frozen data model**: the +value types application code holds and stores — `Plain`, the sealed leaf +family, and the ordered `Object` decode shape. + +It has **zero dependencies** — no wazero, no crypto, and (deliberately) no +wire format. It is the module a future stack-encrypt Go SDK is expected to +import. Keeping it dependency-free is the point: the wasm reference harness +(`vcencrypt`, next door) is just *one* consumer, and neither its +wazero/crypto dependencies nor its FFI wire encoding may leak into the layer +real applications depend on. + +``` +import "github.com/cipherstash/vitaminc/bindings/go/vcvalue" +``` + +## The model, not this package + +The cross-language contract is the frozen sealed-leaf tag table +(`[tag] ++ payload`, sealed **inside** the AEAD envelope, defined in the Rust +crate `vitaminc-aead`'s leaf codec) — not any language's types. This package's types +*implement* that model; they are not the contract. A new tag is added only +when a value class cannot be represented in the existing model, and needs a +defined decode mapping in every supported language before it ships. + +The transport codec — the wire encoding that hands a tree across an FFI +boundary in one copy — is **not part of this module**. It lives in the +sibling module `vcffi`, shared by the bindings that own such a boundary +(`vcencrypt` for the wasm harness, the stack-encrypt Go SDK), because it is +transport-only and carries no storage commitment: the only bytes an +application should ever persist are the sealed leaves. The +`Encryptable`/`Encoder` encoding extension point lives with the codec in +`vcffi` for the same reason. + +## Passthrough — fields in the clear + +Some fields are not secret and should travel unencrypted alongside the sealed +ones. The model carries them as **passthrough**: unencrypted *and* +unauthenticated, non-sensitive fields only. Passthrough never happens +implicitly — you opt in by wrapping the value in `Plain`: + +```go +value := map[string]any{ + "id": vcvalue.Plain{V: int64(42)}, // in the clear + "email": "ada@example.com", // sealed +} +``` + +On decode a passthrough field surfaces back as `Plain{V: }`, so +the marking round-trips and a caller can tell which fields were in the clear. +A passthrough field inside a *ciphertext* is likewise a `Plain` — legible with +no key. + +## Ciphertexts are ordinary Go values + +There is no ciphertext tree type and no conversion step. A ciphertext has the +same dynamic shape as decoded plaintext, with marker types naming what is +sealed: + +| value | meaning | +| ----------------- | -------------------------------------------------------------------- | +| `Sealed` | one encrypted leaf: `version(1) \|\| nonce \|\| ciphertext \|\| tag` | +| `SealedEmptySeq` | the authenticated marker for an empty sequence | +| `SealedEmptyMap` | the authenticated marker for an empty map | +| `Plain{V: ...}` | a passthrough field, readable without the key | +| `map[string]any` | a record of named nodes (clear keys, bound into AAD) | +| `[]any` | a sequence of nodes | + +Every leaf-shaped type starts with a one-byte wire version, which is also +authenticated into the leaf's AAD — a relabeled version byte fails the tag, +not just the parse. All four leaf types share that byte layout: the *kind* of +a leaf is authenticated through domain-separated AAD, not written into the +bytes, so a stored leaf's kind must be tracked by the schema (see the note on +the marker types' `Scan`). + +The `Sealed` family here is **vitaminc-encrypt's** materialization of the +model. Another binding — a stack-encrypt SDK, say — defines its own distinct +sealed-leaf types and wires them to the codec via `vcffi.LeafSet`, so its +leaves can never scan or marshal where these belong: a stack-encrypt leaf is +never a `vcvalue.Sealed`. + +The sealed leaf types and `Plain` implement `driver.Valuer`, and the sealed +types `sql.Scanner`, so a record-shaped ciphertext binds straight into a +database as named parameters and sealed columns scan straight back out — no +adapter layer. Because a record is a plain map, any subset of its fields can +be handed back for decryption: there is no whole-map seal, and each key is +bound into its own value's AAD. + +## Decoding + +Decryption (in `vcencrypt`) returns Go natives at the exact numeric widths +(`nil`, `bool`, `int8`, `int16`, `int32`, `int64`, `uint8`, `uint16`, `uint32`, `uint64`, `float32`, `float64`, +`string`, `[]byte`, `[]any`), this package's ordered `Object` for maps, and +`Plain` for passthrough. A reflection-based decode into caller structs (the +mirror of the reflection encode) is future work. + + +## Extended scalars + +`Int128` and `Uint128` are 16-byte little-endian values, with exact decimal +`ParseInt128` / `ParseUint128` constructors and `String` methods. Out-of-range +inputs return `ErrIntegerRange`. + +`Date{Year, Month, Day}` is a Gregorian calendar date in the wire's range, +years -9999 through 9999. `time.Time` maps to Timestamp with nanoseconds and +decodes in UTC, without its location or monotonic reading, from +-009999-01-02T01:59:59Z through 9999-12-30T22:00:00.999999999Z. These ranges +are jiff's, in every binding, so a value one binding seals, every binding +opens. `time.Time` itself reaches far wider, and a value outside the range is +refused. +`Timestamp{Seconds, Nanoseconds}` encodes an instant from its parts. A leap +second has no count since the epoch and is refused everywhere in the model +(ADR 0001). Invalid calendar/timestamp inputs return `ErrInvalidDate` or +`ErrInvalidTimestamp`. + +`UUID` is sixteen bytes under the Uuid logical type, spelled as hyphenated +hexadecimal by `ParseUUID` and `String`. `Tagged{ID, Param, V}` carries a +physical scalar under a logical id this build does not know, so a value +from a newer client is read and re-encoded unchanged rather than dropped. + +`ParseDecimal("1.50")` constructs a finite 96-bit coefficient with scale 0–28, +retaining trailing zeroes. A zero has no sign: `-0.00` is `0.00` with its +scale kept (ADR 0001). Exponents and rounding are not +accepted. NaN and infinities return `ErrNonFiniteDecimal`; malformed or +out-of-range text returns `ErrInvalidDecimal`. Match these with `errors.Is`. diff --git a/languages/golang/encrypt/value/doc.go b/languages/golang/encrypt/value/doc.go new file mode 100644 index 000000000..612b7f86a --- /dev/null +++ b/languages/golang/encrypt/value/doc.go @@ -0,0 +1,43 @@ +// Package vcvalue is the durable, dependency-free module of the vitaminc Go +// bindings: the value model — the types application code holds and stores — +// with no dependency on wazero, any crypto, or any wire format. A future +// stack-encrypt Go SDK is expected to import this module; the wasm reference +// harness (module vcencrypt) is one consumer of it. +// +// # The model +// +// - Plain{V: ...} marks (and surfaces) a field that travels in the clear — +// unencrypted and unauthenticated — beside the sealed ones. It is always +// an explicit opt-in, never inferred. +// - Sealed is one encrypted leaf (version || nonce || ciphertext || tag), +// the only frozen byte format in the model. SealedEmptySeq and +// SealedEmptyMap are its authenticated marker siblings for empty +// composites; an absent value is a sealed null leaf (ADR 0001), padded +// to the length of a value when its type is fixed width (TypedNull, +// and a nil pointer to such a type; vitaminc#493). This +// sealed family is vitaminc-encrypt's materialization of the model: another binding (a stack-encrypt SDK, +// say) defines its own distinct sealed-leaf types and wires them to the +// codec via vcffi's LeafSet — a stack-encrypt leaf is never a Sealed. +// - Object is the ordered map-decode shape (entry order preserved, so +// results compare deterministically); Field is one entry of it. +// +// All of the sealed leaf types and Plain implement driver.Valuer (and the +// leaves sql.Scanner), so a map-shaped ciphertext binds directly as database +// named parameters and sealed columns load back without conversion. +// +// # What is deliberately NOT here +// +// The transport codec — the wire encoding that carries a value tree across +// an FFI boundary — lives in the sibling module vcffi, shared by the +// bindings that own such a boundary (vcencrypt, the stack-encrypt Go SDK). +// It is not a storage format, so this module does not carry it: the only +// bytes an application should ever persist are the sealed leaves above. The +// Encryptable/Encoder extension point for custom encodings lives with the +// codec in vcffi for the same reason. +// +// The cross-language contract is the frozen tag table plus the sealed leaf +// encodings defined in the Rust crate vitaminc-aead's leaf codec — the +// model, not any package. A new tag is added only when a value class cannot be +// represented in the existing model, and requires a defined decode mapping +// for every supported language before it ships. +package vcvalue diff --git a/languages/golang/encrypt/value/model.go b/languages/golang/encrypt/value/model.go new file mode 100644 index 000000000..5e0382158 --- /dev/null +++ b/languages/golang/encrypt/value/model.go @@ -0,0 +1,27 @@ +package vcvalue + +// Plain marks a value that must travel through the cipher **unencrypted and +// unauthenticated** — the reflection-encode opt-in for passthrough. Wrap a +// non-secret value (Plain{V: id}) and the vcencrypt +// encoder records it via its Passthrough channel instead of sealing it. Passthrough never +// happens implicitly: only an explicit Plain (or a direct +// enc.Passthrough() call) produces it. +// +// A decoded passthrough field surfaces back as Plain{V: }, +// so the marking round-trips and a caller can tell which fields were in the +// clear. See the package docs — non-sensitive fields only. +type Plain struct { + V any +} + +// Object is the decode result for a map-mode value: an ordered list of +// fields mirroring the wire order. Decoding uses this (rather than a Go map) +// so entry order is preserved and results compare deterministically. Encode +// takes any/struct/map instead — this type is decode-only. +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/model_test.go b/languages/golang/encrypt/value/model_test.go new file mode 100644 index 000000000..abbd80740 --- /dev/null +++ b/languages/golang/encrypt/value/model_test.go @@ -0,0 +1,132 @@ +package vcvalue_test + +import ( + "database/sql" + "database/sql/driver" + "math" + "reflect" + "testing" + + "github.com/cipherstash/vitaminc/bindings/go/vcvalue" +) + +// Every sealed leaf type must survive the database column round trip: +// Value() then Scan() back into the same type. +func TestSealedLeafTypesScanValueRoundTrip(t *testing.T) { + roundTrip := func(t *testing.T, value driver.Valuer, scan sql.Scanner, got func() []byte, want []byte) { + t.Helper() + v, err := value.Value() + if err != nil { + t.Fatalf("Value: %v", err) + } + if err := scan.Scan(v); err != nil { + t.Fatalf("Scan: %v", err) + } + if !reflect.DeepEqual(got(), want) { + t.Fatalf("got %#v, want %#v", got(), want) + } + } + + leaf := []byte{1, 2, 3} + var s vcvalue.Sealed + roundTrip(t, vcvalue.Sealed(leaf), &s, func() []byte { return []byte(s) }, leaf) + var es vcvalue.SealedEmptySeq + roundTrip(t, vcvalue.SealedEmptySeq(leaf), &es, func() []byte { return []byte(es) }, leaf) + var em vcvalue.SealedEmptyMap + roundTrip(t, vcvalue.SealedEmptyMap(leaf), &em, func() []byte { return []byte(em) }, leaf) + + // Non-byte sources are rejected. + if err := (&es).Scan("not bytes"); err == nil { + t.Fatal("scanning a string into SealedEmptySeq must fail") + } +} + +// Every integer kind the encoder accepts must also bind through the driver: +// Plain{V: user.ID} with ID int encodes fine, so Value() must not reject it. +func TestPlainValueBindsEveryEncodableIntegerKind(t *testing.T) { + cases := []struct { + in any + want driver.Value + }{ + {int(7), int64(7)}, + {int8(-8), int64(-8)}, + {int16(-16), int64(-16)}, + {int32(-32), int64(-32)}, + {int64(-64), int64(-64)}, + {uint8(8), int64(8)}, + {uint16(16), int64(16)}, + {uint32(32), int64(32)}, + {uint(64), int64(64)}, + {uint64(64), int64(64)}, + } + for _, c := range cases { + got, err := vcvalue.Plain{V: c.in}.Value() + if err != nil { + t.Fatalf("Value(%T): %v", c.in, err) + } + if got != c.want { + t.Fatalf("Value(%T): got %#v, want %#v", c.in, got, c.want) + } + } + + // The unsigned kinds that can exceed int64 must fail closed. + if _, err := (vcvalue.Plain{V: uint64(math.MaxInt64) + 1}).Value(); err == nil { + t.Fatal("uint64 above MaxInt64 must not bind") + } + if uint64(math.MaxUint) > math.MaxInt64 { // uint is 32-bit on GOARCH=386 + if _, err := (vcvalue.Plain{V: uint(math.MaxUint)}).Value(); err == nil { + t.Fatal("uint above MaxInt64 must not bind") + } + } +} + +// Plain.Value's driver conversions: width-narrowing, the uint64 overflow +// error, and the container-has-no-column error. +func TestPlainValueConversions(t *testing.T) { + cases := []struct { + in any + want driver.Value + }{ + {nil, nil}, + {true, true}, + {int64(7), int64(7)}, + {"s", "s"}, + {[]byte{1}, []byte{1}}, + {int32(-3), int64(-3)}, + {uint32(9), int64(9)}, + {float32(0.5), float64(0.5)}, + {float64(1.5), float64(1.5)}, + {uint64(11), int64(11)}, + } + for _, c := range cases { + got, err := vcvalue.Plain{V: c.in}.Value() + if err != nil { + t.Fatalf("Value(%#v): %v", c.in, err) + } + if !reflect.DeepEqual(got, c.want) { + t.Fatalf("Value(%#v) = %#v, want %#v", c.in, got, c.want) + } + } + + if _, err := (vcvalue.Plain{V: uint64(math.MaxInt64) + 1}).Value(); err == nil { + t.Fatal("uint64 above MaxInt64 must not silently truncate") + } + if _, err := (vcvalue.Plain{V: []any{int64(1)}}).Value(); err == nil { + t.Fatal("a container passthrough has no single-column form") + } +} + +// The remaining Sealed.Scan arms: nil source and the non-byte error arm +// (the byte round trip is covered with the marker types above). +func TestSealedScanNilAndErrorArms(t *testing.T) { + s := vcvalue.Sealed{1, 2, 3} + if err := s.Scan(nil); err != nil { + t.Fatalf("Scan(nil): %v", err) + } + if s != nil { + t.Fatalf("Scan(nil) should clear the leaf, got %#v", s) + } + if err := s.Scan("not bytes"); err == nil { + t.Fatal("scanning a string into Sealed must fail") + } +} diff --git a/languages/golang/encrypt/value/null.go b/languages/golang/encrypt/value/null.go new file mode 100644 index 000000000..a9ebfd29c --- /dev/null +++ b/languages/golang/encrypt/value/null.go @@ -0,0 +1,48 @@ +package vcvalue + +// FixedType names a fixed-width type: one whose every value seals to a leaf +// of the same length. An absent value of such a type is written as a typed +// null, padded to that length, so a sealed absence cannot be told from a +// sealed value by its length, as a plain null (one byte) could be. +// +// bool is fixed width too, but its leaf is already as short as a null's, +// and text and bytes are variable width, so neither has a FixedType. A UUID's +// sixteen bytes are fixed by its type, so it has one. +type FixedType uint8 + +// The fixed-width types, each named for the Go type it is written from. +// TypeInt64 and TypeUint64 cover int and uint too, as the codec writes them. +const ( + TypeInt8 FixedType = iota + 1 + TypeInt16 + TypeInt32 + TypeInt64 + TypeInt128 + TypeUint8 + TypeUint16 + TypeUint32 + TypeUint64 + TypeUint128 + TypeFloat32 + TypeFloat64 + TypeDate + TypeTimestamp + TypeDecimal + TypeUUID +) + +// Valid reports whether t is one of the named fixed-width types. +func (t FixedType) Valid() bool { + return t >= TypeInt8 && t <= TypeUUID +} + +// TypedNull is an absent value of a fixed-width type, for a caller whose Go +// type cannot say what is missing: a nil in a map[string]any or an []any. +// A nil pointer to a fixed-width type (*int32, *time.Time, *Date, …) is +// written as a typed null without it. +// +// It only encodes. A typed null decodes as nil, like every null: once +// decrypted, an absent value is absent whatever its type. +type TypedNull struct { + Type FixedType +} diff --git a/languages/golang/encrypt/value/scalars.go b/languages/golang/encrypt/value/scalars.go new file mode 100644 index 000000000..614a7e759 --- /dev/null +++ b/languages/golang/encrypt/value/scalars.go @@ -0,0 +1,303 @@ +package vcvalue + +import ( + "errors" + "math/big" + "strings" + "time" +) + +var ( + ErrIntegerRange = errors.New("vcvalue: integer is outside its 128-bit range") + ErrInvalidDate = errors.New("vcvalue: invalid date") + ErrInvalidTimestamp = errors.New("vcvalue: invalid timestamp") + ErrInvalidDecimal = errors.New("vcvalue: invalid or out-of-range decimal") + ErrNonFiniteDecimal = errors.New("vcvalue: decimal must be finite") + ErrInvalidUUID = errors.New("vcvalue: invalid UUID") + ErrInvalidTagged = errors.New("vcvalue: a tagged value must hold a physical scalar under an unknown logical id") + ErrInvalidFixedType = errors.New("vcvalue: not a fixed-width type") +) + +// Int128 is a signed two's-complement integer in little-endian byte order. +type Int128 [16]byte + +// Uint128 is an unsigned 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() +} + +// The wire's range is jiff's in every binding (vitaminc#626), so a value +// one binding seals, every binding opens: dates in years -9999 through +// 9999, and instants from -009999-01-02T01:59:59Z through +// 9999-12-30T22:00:00.999999999Z. +const ( + minDateYear = -9999 + maxDateYear = 9999 + minTimestampSeconds = -377705023201 // -009999-01-02T01:59:59Z + maxTimestampSeconds = 253402207200 // 9999-12-30T22:00:00Z +) + +// Date is a proleptic Gregorian calendar date, without time or timezone. +// Its range is the wire's, years -9999 through 9999, including year zero +// and BCE dates. +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 frozen wire day count (0001-01-01 is day 1). +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 Unix seconds and nanoseconds, for a caller +// that holds the parts rather than a time.Time. Timestamps decode to +// time.Time; this type only encodes. A leap second (nanoseconds of one +// billion or more) has no count since the epoch and is refused, as it is +// everywhere in the model (ADR 0001), and so is an instant outside the +// wire's range. +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 sixteen bytes under the Uuid logical type: it travels in the +// 0xF3 envelope, since the type has no shorthand tag. ParseUUID reads the +// hyphenated hexadecimal spelling and String writes it in lower case. +// +// Another UUID type, such as github.com/google/uuid.UUID, is a plain +// [16]byte to the codec and is written as bytes. Convert it first, with +// vcvalue.UUID(id), so that Rust and Node read it as a UUID. +type UUID [16]byte + +// ParseUUID reads the hyphenated spelling, 8-4-4-4-12 hexadecimal digits in +// either case, and returns ErrInvalidUUID for anything else. +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 is the hyphenated spelling 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 carries a scalar under a logical type this build does not know: +// the envelope's id and parameter, and the physical value as the Go native +// of its kind. A value from a newer client is read and re-encoded unchanged +// rather than dropped or mistaken for its bare physical value. V must be a +// physical scalar (nil, bool, an integer or float width, Int128, Uint128, +// string or []byte); ID must be above the ids this build knows. An int or +// uint is written as Int64 or UInt64, as everywhere else in the codec, so +// it reads back as int64 or uint64. +type Tagged struct { + ID uint8 + Param uint8 + V any +} + +// Decimal is a finite base-10 value: sign * Coefficient * 10^-Scale. +// Coefficient is an unsigned 96-bit little-endian integer. Scale is retained, +// including trailing zeroes, and must be at most 28 (rust_decimal's range). +// A zero has no sign: "-0.00" parses, decodes and encodes as 0.00 with its +// scale kept (ADR 0001). +type Decimal struct { + Coefficient [12]byte + Scale uint8 + Negative bool +} + +func (d Decimal) Validate() error { + if d.Scale > 28 { + return ErrInvalidDecimal + } + return nil +} + +// ParseDecimal accepts exact fixed-point decimal text without rounding. +// NaN and infinities have their own error so callers can reject them by type. +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 is the decimal with the sign dropped from a 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..483684108 --- /dev/null +++ b/languages/golang/encrypt/value/scalars_test.go @@ -0,0 +1,122 @@ +package vcvalue + +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 scale is kept and the sign is dropped (ADR 0001). + 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 ends of the wire's range, which is jiff's. + 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 and is refused (ADR 0001). + // So is an instant past 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/sealed.go b/languages/golang/encrypt/value/sealed.go new file mode 100644 index 000000000..0579f4457 --- /dev/null +++ b/languages/golang/encrypt/value/sealed.go @@ -0,0 +1,125 @@ +package vcvalue + +import ( + "database/sql/driver" + "fmt" + "math" +) + +// Sealed is one encrypted leaf: version(1) || nonce || ciphertext || tag — +// the only frozen byte format in the model. The leading wire-version byte is +// itself authenticated into the leaf's AAD, so a relabeled version fails the +// tag rather than selecting different parsing rules. Sealed is a named type +// so sealed bytes can never be confused with a plaintext []byte value in the +// dynamic ciphertext shape. +// +// Sealed implements driver.Valuer and sql.Scanner, so it stores into and +// loads from a BLOB/BYTEA column with no conversion. +type Sealed []byte + +// Value implements driver.Valuer: a Sealed binds as raw bytes. +func (s Sealed) Value() (driver.Value, error) { + return []byte(s), nil +} + +// Scan implements sql.Scanner: a BLOB/BYTEA column loads as a Sealed. +func (s *Sealed) Scan(src any) error { + b, err := scanLeafBytes(src, "Sealed") + *s = Sealed(b) + return err +} + +// SealedEmptySeq is the authenticated marker for an empty sequence: with no +// element ciphertexts to bind the AAD, the cipher seals an empty plaintext +// under domain-separated AAD instead. Produced by encrypting an empty array; +// decrypts back to an empty array. +type SealedEmptySeq []byte + +// SealedEmptyMap is the authenticated marker for an empty map, the map-shaped +// counterpart of SealedEmptySeq. Produced by encrypting an empty object; +// decrypts back to an empty object. +type SealedEmptyMap []byte + +// The marker types implement driver.Valuer and sql.Scanner like Sealed, so a +// column holding one stores and loads without conversion. +// +// ⚠️ The stored bytes do NOT record which leaf kind they are — every leaf is +// the same `version || nonce || ciphertext || tag` shape, and the kind is +// authenticated through domain-separated AAD, not written into the bytes. A +// marker scanned back into the wrong type (e.g. a SealedEmptySeq loaded as +// Sealed) fails decryption with an authentication error and no further hint. +// A column that can hold both real values and empty-composite markers needs +// the schema (or the application) to record which kind it stored; scan into +// the type matching that record. + +// Value implements driver.Valuer: the marker binds as raw bytes. +func (s SealedEmptySeq) Value() (driver.Value, error) { return []byte(s), nil } + +// Scan implements sql.Scanner — see the leaf-kind caveat above. +func (s *SealedEmptySeq) Scan(src any) error { + b, err := scanLeafBytes(src, "SealedEmptySeq") + *s = SealedEmptySeq(b) + return err +} + +// Value implements driver.Valuer: the marker binds as raw bytes. +func (s SealedEmptyMap) Value() (driver.Value, error) { return []byte(s), nil } + +// Scan implements sql.Scanner — see the leaf-kind caveat above. +func (s *SealedEmptyMap) Scan(src any) error { + b, err := scanLeafBytes(src, "SealedEmptyMap") + *s = SealedEmptyMap(b) + return err +} + +func scanLeafBytes(src any, into string) ([]byte, error) { + switch b := src.(type) { + case nil: + return nil, nil + case []byte: + return append([]byte(nil), b...), nil + default: + return nil, fmt.Errorf("vcvalue: cannot scan %T into %s", src, into) + } +} + +// Value implements driver.Valuer for passthrough fields, so a map-shaped +// ciphertext binds directly as database named parameters. Only scalar +// natives convert; a container passthrough has no single-column form. +func (p Plain) Value() (driver.Value, error) { + // Every integer kind the encoder accepts must convert here too: a value + // that encodes must also bind, or `Plain{V: user.ID}` with `ID int` works + // until it reaches the database driver. + switch v := p.V.(type) { + case nil, bool, int64, float64, string, []byte: + return v, nil + case int: + return int64(v), nil + case int8: + return int64(v), nil + case int16: + return int64(v), nil + case int32: + return int64(v), nil + case uint8: + return int64(v), nil + case uint16: + return int64(v), nil + case uint32: + return int64(v), nil + case float32: + return float64(v), nil + case uint: + if uint64(v) > math.MaxInt64 { + return nil, fmt.Errorf("vcvalue: passthrough uint %d overflows the driver's int64", v) + } + return int64(v), nil + case uint64: + if v > math.MaxInt64 { + return nil, fmt.Errorf("vcvalue: passthrough uint64 %d overflows the driver's int64", v) + } + return int64(v), nil + default: + return nil, fmt.Errorf("vcvalue: passthrough %T has no single-column driver representation", p.V) + } +} From 6e8e9ee1f5e3614927594a0e6caab5af1140e6e2 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Wed, 2 Dec 2026 17:08:55 +1100 Subject: [PATCH 2/6] refactor(go): make encrypt/frame and encrypt/value the module's own The copies are still vitaminc's packages under new paths. This commit makes them packages of this module, and changes what the review of the move asked for. Nothing else in the module imports them yet. - Package clauses become frame and value, and frame imports encrypt/value in place of vitaminc's vcvalue. Error text starts with "frame: " or "value: ". - The tests read the value corpus (conformance/vitaminc-aead) and the storage corpus (packages/recipher-frame/testdata) from this repository, and skip, rather than fail, outside it. - What only vitaminc's own binding (vcencrypt) used is removed: the sealed leaves (Sealed, SealedEmptySeq, SealedEmptyMap), TypedNull, FixedType and ErrInvalidFixedType, Plain.Value, Encoder.TypedNull, FixedWidth and VCValueLeaves. The typed null for a nil pointer is built from the tag table, so the codec keeps no list of types. - The Encoder's unsigned methods are Uint8 to Uint128, as Go spells them, not UInt8 to UInt128. - The zero Encoder no longer panics. It keeps nothing, and Err reports that, so a unit test of a type can pass it to EncryptValue. Usable tells the two apart. - Encryptable is declared once, in frame, and the codec uses it directly. - A storage refusal names the program's own type. golangci-lint already allows gosec's G115 (integer width conversions) in the codec, which converts on purpose after checking each limit; the rule now names encrypt/frame and encrypt/value. --- languages/golang/.golangci.yaml | 8 + languages/golang/encrypt/frame/README.md | 265 ------ languages/golang/encrypt/frame/ciphertext.go | 222 +++-- languages/golang/encrypt/frame/codec_test.go | 418 +++++----- .../golang/encrypt/frame/conformance_test.go | 49 +- languages/golang/encrypt/frame/corpus_test.go | 62 ++ languages/golang/encrypt/frame/decode.go | 138 ++-- languages/golang/encrypt/frame/doc.go | 141 ++-- languages/golang/encrypt/frame/encoder.go | 761 ++++++++++-------- .../golang/encrypt/frame/encryptable_test.go | 119 +++ languages/golang/encrypt/frame/fuzz_test.go | 133 +-- languages/golang/encrypt/frame/leaves_test.go | 42 + languages/golang/encrypt/frame/scalars.go | 209 +++-- .../golang/encrypt/frame/scalars_test.go | 86 +- languages/golang/encrypt/frame/storage.go | 360 +++++---- .../golang/encrypt/frame/storage_decode.go | 114 +-- .../golang/encrypt/frame/storage_test.go | 183 +++-- languages/golang/encrypt/frame/transport.go | 170 ++-- .../encrypt/frame/transport_internal_test.go | 21 +- .../golang/encrypt/frame/typed_null_test.go | 244 ++---- languages/golang/encrypt/value/README.md | 126 --- languages/golang/encrypt/value/doc.go | 56 +- languages/golang/encrypt/value/model.go | 31 +- languages/golang/encrypt/value/model_test.go | 132 --- languages/golang/encrypt/value/null.go | 48 -- languages/golang/encrypt/value/scalars.go | 136 ++-- .../golang/encrypt/value/scalars_test.go | 11 +- languages/golang/encrypt/value/sealed.go | 125 --- 28 files changed, 2078 insertions(+), 2332 deletions(-) delete mode 100644 languages/golang/encrypt/frame/README.md create mode 100644 languages/golang/encrypt/frame/corpus_test.go create mode 100644 languages/golang/encrypt/frame/encryptable_test.go create mode 100644 languages/golang/encrypt/frame/leaves_test.go delete mode 100644 languages/golang/encrypt/value/README.md delete mode 100644 languages/golang/encrypt/value/model_test.go delete mode 100644 languages/golang/encrypt/value/null.go delete mode 100644 languages/golang/encrypt/value/sealed.go 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/encrypt/frame/README.md b/languages/golang/encrypt/frame/README.md deleted file mode 100644 index b0e5398a0..000000000 --- a/languages/golang/encrypt/frame/README.md +++ /dev/null @@ -1,265 +0,0 @@ -# vcffi — the shared FFI transport codec - -`vcffi` is the wire encoding that carries a **value tree** into a wasm guest -and a **ciphertext tree** back out, plus the `Encryptable`/`Encoder` -extension point for types that control their own encoding. It exists as its -own module so every binding that owns a wasm boundary speaks the same bytes -from one implementation — one codec, one hostile-input test suite, one fuzz -corpus. Consumers: [`vcencrypt`](../vcencrypt) (the `vitaminc-encrypt` -reference binding) and the stack-encrypt Go SDK. - -``` -import "github.com/cipherstash/vitaminc/bindings/go/vcffi" -``` - -Depends only on the sibling [`vcvalue`](../vcvalue) module (the value model — -`Plain`, `Object`, the sealed leaf family), via a local `replace` directive. -No wazero, no crypto. - -## Transport, and one storage profile - -The transport bytes are an FFI detail with **no compatibility commitment**: -nothing `Marshal`, `Encode` or `MarshalCipherText` writes should ever be -persisted. The one exception is the **storage profile**, `MarshalStorage` and -`UnmarshalStorage`, which write and read a value as a versioned blob for bytes -that are kept. Its format is shared with the Rust module -`vitaminc_aead_frame::storage`, specified in -[`packages/aead-frame/STORAGE.md`](../../../packages/aead-frame/STORAGE.md), -frozen at version 1, and pinned by the golden corpus -[`storage-v1.json`](../../../packages/aead-frame/testdata/storage-v1.json), -which `storage_test.go` reads row by row. The other frozen format is the -sealed leaf inside the AEAD envelope (see `vcvalue.Sealed` and the Rust crate -`vitaminc-aead`'s leaf codec). - -```go -blob, err := vcffi.MarshalStorage(record) // "VCS", version 1, then the value -var back Record -err = vcffi.UnmarshalStorage(blob, &back) // errors.Is(err, vcffi.ErrUnsupportedVersion) … -``` - -A Go struct is an object (field names from `vc` tags, as in the transport), a -map is a map whose keys keep their kind, `[]byte` and `[N]byte` are bytes, and -an `encoding.TextMarshaler` such as `time.Time` is text. A pointer is written -as `encoding/json` writes it: nil is null, and anything else is its value, so -Rust reads it into an `Option` or a plain `T` alike. Only a pointer to a -value that is itself written as null or marked present (a nil pointer, or a -pointer to one) is marked present, so every level reads back. Reading -follows Rust's rules: an integer reads into any integer type it fits, a -pointer reads a value marked present or not, unknown keys are ignored, and a -missing field is refused unless it is a pointer or tagged `vc:"name,default"`, -which reads it as its zero value, as Rust's `#[serde(default)]` does. -`default` is the only tag option: any other is refused, in a blob and in the -transport, so a misspelt one is not quietly ignored. A pointer costs no depth -unless it is marked, so Go nests as deep as the blob does. Go's `[]uint8` is `[]byte`, so it is always -bytes; a Rust type sharing a value with Go keeps its `Vec` as bytes with -`serde_bytes`. Go has no enums and no unit type, so the corpus rows that read -those are not run here. `FuzzUnmarshalStorage` holds the reader to the -hostile-input contract below, and requires every blob it reads to write back -byte for byte. - -## The `LeafSet` parameter - -The ciphertext codec's structural nodes (`[]any`, `map[string]any`, -`vcvalue.Plain`) are common to every binding, but the sealed-leaf marker -types are deliberately **not**: each binding hands the codec a `LeafSet` -mapping its own leaf types onto the framing. A stack-encrypt leaf is not -decryptable by `vitaminc-encrypt`, and keeping the Go types distinct means -one can never scan or marshal where the other belongs. `VCValueLeaves` is -the set for the `vcvalue` model types. - -The seam stops at the leaves. The structural nodes — including -`vcvalue.Plain` and the `vcvalue.Object` decode shape — are shared and **not** -parameterised: a binding brings its own leaves, not its own model. That is -deliberate. `Plain` is cleartext with no key binding, so none of the "a leaf -sealed by one cipher must never be mistaken for another's" reasoning applies -to it, and a second model would fork the wire encoding this module exists to -keep single. - -## Hostile input - -`Unmarshal` and `UnmarshalCipherText` treat their input as untrusted: -recursion depth, length prefixes and item counts are bounded, strings are -UTF-8 validated, duplicate map keys are rejected, and every malformed input -fails with `ErrMalformed` rather than panicking or over-allocating. The fuzz -targets in this package pin that contract, and also require anything accepted -to re-encode to the same bytes (Undefined becoming Null is the one allowed -difference). PR CI runs them over their seeds, which include every shared -corpus vector, and the whole suite on 32-bit GOARCH, where the u32-bound -guards are load-bearing. `.github/workflows/fuzz.yml` fuzzes them nightly -and records a failure on an open issue labelled `fuzz`; commit the failing -input attached to that run under `testdata/fuzz` as a regression seed. -vcencrypt's differential fuzz targets check the same decoders against the -Rust ones in its wasm guest (see its README). - -`ErrMalformed` covers hostile bytes, not caller mistakes: a `LeafSet` that is -partially wired, or that does not materialize a kind the buffer carries, -fails with its own attributable error. So `errors.Is(err, ErrMalformed)` is a -test for bad input, not a total branch over decode failures. Encode-side -depth exhaustion has its own sentinel, `ErrTooDeep`. - -## Usage - -### Value tree in, ciphertext tree out - -`Marshal` encodes a Go value into the bytes a wasm guest expects; -`UnmarshalCipherText` decodes what comes back, materializing sealed leaves -through the caller's `LeafSet`. - -```go -type User struct { - Email string `vc:"email"` - Age int `vc:"age"` - Notes string `vc:"-"` // never leaves the process -} - -buf, err := vcffi.Marshal(User{Email: "a@example.com", Age: 42}) -if err != nil { - return err -} - -// ... hand buf to the guest, get ciphertext bytes back ... - -ct, err := vcffi.UnmarshalCipherText(vcffi.VCValueLeaves(), ctBytes) -if err != nil { - return err // errors.Is(err, vcffi.ErrMalformed) for hostile input -} -sealed := ct.(map[string]any)["email"].(vcvalue.Sealed) -``` - -The reverse pair is `MarshalCipherText` (ciphertext tree to bytes, for the -decrypt call) and `Unmarshal` (guest response to a plaintext tree). - -### A type that controls its own encoding - -Implement `Encryptable` when reflection is not the encoding you want. The -`Encoder` writes exactly one value: one terminal channel, or one container -closed with `End`. - -```go -type Money struct { - Cents int64 - Currency string -} - -func (m Money) EncryptValue(enc vcffi.Encoder) error { - mp := enc.Map() - mp.Field("cents").Int64(m.Cents) - // Currency is not a secret — mark it so it travels in the clear. - mp.Field("currency").Passthrough().String(m.Currency) - return mp.End() -} -``` - -Errors accumulate on the encoder, so writes chain without a check after each -one; `End` (or `Marshal`) surfaces the first failure. A zero-value -`vcffi.Encoder` is unusable — usable ones only ever arrive as the argument to -`EncryptValue` or from `Passthrough`, `Elem` and `Field`. - -### A binding's own leaf types - -A second binding defines its own sealed-leaf types and maps them onto the -framing, so its leaves can never be mistaken for another cipher's. - -```go -type stackSealed []byte - -var stackLeaves = vcffi.LeafSet{ - Classify: func(v any) (vcffi.LeafKind, []byte, bool) { - if s, ok := v.(stackSealed); ok { - return vcffi.LeafSingle, s, true - } - return 0, nil, false // not ours — the codec handles the rest - }, - Make: func(kind vcffi.LeafKind, b []byte) any { - if kind == vcffi.LeafSingle { - return stackSealed(b) - } - return nil // an unwired kind is an error, never a nil node - }, -} -``` - -`Classify` is offered only non-structural values, so it cannot claim `[]any`, -`map[string]any` or `vcvalue.Plain`. A real binding covers all four kinds -(`LeafSingle`, `LeafEmptySeq`, `LeafEmptyMap`); returning nil for -a kind the wire carries fails the decode attributably rather than injecting an -untyped nil. - -## Scalar mappings and shared vectors - -Fixed integer widths remain exact (`int8`→Int8, `uint16`→UInt16, and so on). -`vcvalue.Int128`, `Uint128`, `Date`, `Decimal`, `UUID` and `Tagged` are -intercepted before reflection, including inside structs, pointers and -containers. `time.Time` encodes a nanosecond Timestamp; a timestamp that -arrives in the `0xF3` envelope in seconds, milliseconds or microseconds -decodes to `time.Time` too, and so re-encodes in the nanosecond form. A leap -second is refused in both directions, and a decimal negative zero reads back -as zero (ADR 0001). `UUID` and `Tagged` travel in the `0xF3` envelope. -Another UUID type, such as `github.com/google/uuid.UUID`, is a plain -`[16]byte` and is written as bytes: convert it with `vcvalue.UUID(id)` first -so that Rust and Node read it as a UUID. -Matching explicit Encoder channels are available for custom `Encryptable` -implementations. - -### Absent values - -AES-GCM keeps the plaintext's length, so a one-byte null sealed in place of a -date would show which rows have no date. A nil pointer to a fixed-width type -(`*int32`, `*float64`, `*time.Time`, `*vcvalue.Date`, `*vcvalue.Decimal`, -`*vcvalue.UUID`, and so on, and a named int or float type such as -`type Age int32`) is therefore -written as a **typed null**, padded to the length of a value of that type, as -Rust writes an `Option`'s `None` (vitaminc#493): - -```go -type Person struct { - Name string - Born *vcvalue.Date // nil seals as long as a date -} -``` - -A nil with no fixed-width type to go by is the plain null: a nil interface, a -nil `*bool` (a bool is already as short as a null), a nil `*string` or -`*[]byte` (variable width), a nil pointer to an `Encryptable`, whose -encoding is its own, and a named type over a `vcvalue` or `time` type (`type -Birthday vcvalue.Date`), which reflection writes field by field, not as a -date. Where the Go type cannot say what is missing (a nil in a -`map[string]any`), write `vcvalue.TypedNull{Type: vcvalue.TypeDate}`, or call -`Encoder.TypedNull` from an `Encryptable`. - -An `Encryptable` whose `EncryptValue` always writes one value of one -fixed-width type can say so by implementing `FixedWidth`, the Go side of -Rust's `Encrypt::FIXED`. A nil pointer to it is then a typed null of that -type: - -```go -type Money struct{ cents int64 } - -func (m Money) EncryptValue(enc vcffi.Encoder) error { enc.Int64(m.cents); return nil } -func (Money) FixedType() vcvalue.FixedType { return vcvalue.TypeInt64 } - -type Order struct { - Refund *Money // nil seals as long as a Money -} -``` - -`FixedType` is called once per type, on a pointer to a zero value, so it must -answer from the type alone. A type that returns an invalid `FixedType` fails -the encode with `vcvalue.ErrInvalidFixedType` rather than write the plain -null in its place. - -A typed null decodes as `nil`, like every null. Out of the seal the padding -means nothing, and Rust's frame writer writes it back as the plain null, so -Go does too. A decrypted value therefore no longer says what type an absent -field was: hold optional fields in a typed struct (`Born *vcvalue.Date`) -before encrypting again. A value re-encrypted from `any` or `vcvalue.Object` -seals its nils as the plain null, and its absent values show by length. - -Reading a typed null takes a guest built from the vitaminc release that adds -it (vitaminc#493); an older one refuses the frame. A binding that ships its -own guest must update it together with this module. - -The codec reads `testdata/value-conformance.json` from the repo root directly, -as do Rust and Node. Invalid scalar widths, date ranges, nanoseconds, decimal -flags and scales return `ErrMalformed`. Value construction errors retain the -typed `vcvalue` errors. The broader #332 guest-object corpus remains separate. diff --git a/languages/golang/encrypt/frame/ciphertext.go b/languages/golang/encrypt/frame/ciphertext.go index fc3260beb..cc0bbb5ae 100644 --- a/languages/golang/encrypt/frame/ciphertext.go +++ b/languages/golang/encrypt/frame/ciphertext.go @@ -1,44 +1,44 @@ -package vcffi +package frame import ( "errors" "fmt" "slices" - "github.com/cipherstash/vitaminc/bindings/go/vcvalue" + "github.com/cipherstash/stack/languages/golang/encrypt/value" ) -// A ciphertext is made of ordinary Go values — the same dynamic shape as -// decoded plaintext — with marker types distinguishing what is sealed from -// what travels in the clear: +// 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 marker (one of the binding's [LeafSet] types, e.g. -// vcvalue.Sealed): one encrypted leaf, an authenticated absent marker, -// or an authenticated empty-composite marker -// - vcvalue.Plain{V: ...}: a passthrough field, readable without the key -// - []any: a sequence of ciphertext nodes -// - map[string]any: a record of named nodes. Keys travel in the clear but -// each is cryptographically bound to its sealed value — renaming or -// swapping keys fails decryption. Entry order is not authenticated -// (encoding sorts keys for determinism), and there is no whole-map seal: -// any subset of entries decrypts independently. +// - 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. // -// There is deliberately no dedicated tree type and no conversion step: a -// map-shaped ciphertext binds directly as database named parameters (the leaf -// types and vcvalue.Plain implement driver.Valuer), and leaves loaded back -// from columns go into a map[string]any for decryption. Only the sealed leaf -// bytes are a frozen format; the transport encoding crossing the FFI boundary -// is an implementation detail. +// 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. // -// Which concrete leaf types appear in the tree is the one thing this codec -// does not decide: each binding supplies a [LeafSet] so its leaves stay a -// distinct Go type. A stack-encrypt sealed leaf is not decryptable by -// vitaminc-encrypt, and keeping the types distinct means one can never scan -// or marshal where the other belongs. +// 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. -// Ciphertext node tags in the transport encoding (mirrors the Rust codec). -// 0x02 was the absent marker, retired by ADR 0001 (a None is a null leaf): -// never written, and refused when read like any unknown tag. +// 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 @@ -48,9 +48,11 @@ const ( ctEmptyMap byte = 0x07 ) -// LeafKind names the three sealed-leaf node kinds of the ciphertext framing. -// The stored bytes do not record the kind — it is authenticated through -// domain-separated AAD — so the framing carries it on the wire. +// 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 ( @@ -62,99 +64,63 @@ const ( LeafEmptyMap ) -// LeafSet maps a binding's sealed-leaf marker types onto the ciphertext -// framing, in both directions. Each binding defines its own leaf types (so a -// leaf sealed by one cipher can never be mistaken for another's) and hands -// the codec this pair of translations: -// -// - Classify reports whether v is one of the binding's leaf values, -// returning its kind and bytes. The codec's structural node types -// ([]any, map[string]any, vcvalue.Plain) are never offered to Classify, -// so a LeafSet cannot claim a subtree; values Classify does not claim -// fall through to the bare-plaintext rejection. -// - Make constructs the binding's leaf value for a kind decoded off the -// wire. The bytes slice is freshly allocated and owned by the callee. -// Returning nil rejects the kind: the decoder turns it into an error, so -// a LeafSet that materializes only some kinds fails loudly instead of -// injecting nil nodes into the decoded tree. +// 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: // -// [VCValueLeaves] is the set for the vcvalue model types. +// - 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 } -// VCValueLeaves returns the [LeafSet] of the vcvalue model: vcvalue.Sealed, -// vcvalue.SealedEmptySeq and vcvalue.SealedEmptyMap. -// These are the leaf types the vitaminc-encrypt binding materializes; other -// bindings define their own set so their leaves stay a distinct Go type. A -// function rather than an exported var, so no importer can reassign the set -// out from under every other consumer in the process. -func VCValueLeaves() LeafSet { - return vcValueLeaves -} - -var vcValueLeaves = LeafSet{ - Classify: func(v any) (LeafKind, []byte, bool) { - switch n := v.(type) { - case vcvalue.Sealed: - return LeafSingle, n, true - case vcvalue.SealedEmptySeq: - return LeafEmptySeq, n, true - case vcvalue.SealedEmptyMap: - return LeafEmptyMap, n, true - default: - return 0, nil, false - } - }, - Make: func(kind LeafKind, bytes []byte) any { - switch kind { - case LeafSingle: - return vcvalue.Sealed(bytes) - case LeafEmptySeq: - return vcvalue.SealedEmptySeq(bytes) - case LeafEmptyMap: - return vcvalue.SealedEmptyMap(bytes) - default: - // An unlisted kind is rejected (nil), mirroring leafTag on the - // encode side — a future fourth kind must not silently mint Sealed. - return nil - } - }, -} - -// check rejects a partially wired LeafSet up front, where the mistake is -// attributable, instead of as a nil-function panic mid-tree. +// 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("vcffi: LeafSet must define both Classify and Make") + return errors.New("frame: LeafSet must define both Classify and Make") } return nil } -// leafTags is the single source of truth for the LeafKind ↔ wire-tag -// correspondence; leafTag and leafKind are its two directions, so a new leaf -// kind cannot be wired into one direction and missed in the other. +// 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 "this kind is not wired to -// the wire format" — a hole left by a LeafKind constant that skips a value, -// or an index past the end. Both directions refuse it, so a kind can never -// round-trip inside Go under a tag the Rust codec has never heard of. +// 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 maps a classified kind to its wire tag. +// 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("vcffi: LeafSet classified an unknown LeafKind %d", kind) + return 0, fmt.Errorf("frame: LeafSet.Classify returned an unknown LeafKind %d", kind) } return leafTags[kind], nil } -// leafKind maps a wire tag back to its leaf kind — the decode direction. +// 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 @@ -167,10 +133,10 @@ func leafKind(tag byte) (LeafKind, bool) { return 0, false } -// MarshalCipherText encodes a ciphertext value into transport bytes; leaves -// recognizes the binding's sealed-leaf types. Bare plaintext values are -// rejected — a passthrough must be marked with vcvalue.Plain, so a value can -// never end up travelling unencrypted by accident. +// 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 @@ -178,9 +144,10 @@ func MarshalCipherText(leaves LeafSet, v any) ([]byte, error) { return encodeCipherText(leaves, nil, v, 0) } -// UnmarshalCipherText decodes a transport-encoded ciphertext into the dynamic -// shape above — leaf nodes constructed through leaves — requiring the whole -// buffer to be consumed. +// 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 @@ -200,9 +167,9 @@ func encodeCipherText(leaves LeafSet, out []byte, v any, depth int) ([]byte, err if depth > maxDepth { return nil, ErrTooDeep } - // The structural arms come first: the codec's own node types are never - // offered to Classify, so a LeafSet cannot claim a whole subtree as one - // leaf chunk — only non-structural values reach it (in the default arm). + // 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) @@ -236,18 +203,19 @@ func encodeCipherText(leaves LeafSet, out []byte, v any, depth int) ([]byte, err } } return out, nil - case vcvalue.Plain: - // The payload node sits one level deeper; reject it here because the - // value encoder's scalar channels never re-check depth, and emitting - // bytes the decoder is guaranteed to reject (decodeValue enforces the - // same bound) would be an asymmetric round trip. + 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 payload as one value node, sharing the - // recursion budget with the surrounding ciphertext (depth+1), - // mirroring the Rust CT_PASSTHROUGH framing. + // 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) @@ -255,7 +223,7 @@ func encodeCipherText(leaves LeafSet, out []byte, v any, depth int) ([]byte, err return nil, st.err } if done != 1 { - return nil, fmt.Errorf("vcffi: passthrough payload must complete exactly one value, completed %d", done) + return nil, fmt.Errorf("frame: EncryptValue must write exactly one complete passthrough value, and wrote %d", done) } return st.buf, nil default: @@ -267,7 +235,7 @@ func encodeCipherText(leaves LeafSet, out []byte, v any, depth int) ([]byte, err out = append(out, tag) return appendChunk(out, bytes) } - return nil, fmt.Errorf("vcffi: %T is not a ciphertext node — wrap passthrough values in vcvalue.Plain", v) + return nil, fmt.Errorf("frame: %T is not a ciphertext node; wrap a passthrough value in Plain", v) } } @@ -292,10 +260,11 @@ func decodeCipherText(leaves LeafSet, r *reader, depth int) (any, error) { copy(leaf, s) node := leaves.Make(kind, leaf) if node == nil { - // A LeafSet that does not materialize this kind is a wiring - // mistake in the binding, not malformed input — name it, instead - // of injecting a nil node the caller only trips over later. - return nil, fmt.Errorf("vcffi: LeafSet.Make returned no value for LeafKind %d", kind) + // 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 } @@ -336,12 +305,13 @@ func decodeCipherText(leaves LeafSet, r *reader, depth int) (any, error) { } return fields, nil case ctPassthrough: - // One embedded plaintext value node, decoded one level deeper. + // 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 vcvalue.Plain{V: v}, nil + 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 index 6b2600653..ebcd9f225 100644 --- a/languages/golang/encrypt/frame/codec_test.go +++ b/languages/golang/encrypt/frame/codec_test.go @@ -1,4 +1,4 @@ -package vcffi +package frame import ( "bytes" @@ -9,11 +9,11 @@ import ( "strings" "testing" - "github.com/cipherstash/vitaminc/bindings/go/vcvalue" + "github.com/cipherstash/stack/languages/golang/encrypt/value" ) -// marshalUnmarshal is the round trip every case below shares: encode v to -// transport bytes, decode back to the natives shape. +// 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) @@ -35,19 +35,19 @@ func TestReflectNatives(t *testing.T) { }{ {"nil", nil, nil}, {"bool", true, true}, - {"int", 42, int64(42)}, // int → Int64 + {"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)}, // bare uint → UInt64 (no fit-check) - {"uint64-small", uint64(7), uint64(7)}, // uint64 → UInt64 + {"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}, // float64 → Float64 + {"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)}}, @@ -73,9 +73,9 @@ func TestReflectStructTags(t *testing.T) { Nested inner } got := marshalUnmarshal(t, outer{Name: "x", Skipped: "no", hidden: "no", Nested: inner{A: 1}}) - want := vcvalue.Object{ + want := value.Object{ {Key: "name", Value: "x"}, - {Key: "Nested", Value: vcvalue.Object{{Key: "a", Value: int64(1)}}}, + {Key: "Nested", Value: value.Object{{Key: "a", Value: int64(1)}}}, } if !reflect.DeepEqual(got, want) { t.Fatalf("got %#v, want %#v", got, want) @@ -83,10 +83,11 @@ func TestReflectStructTags(t *testing.T) { } func TestReflectMapSortsKeys(t *testing.T) { - // Map iteration is randomized; the encoder must sort keys so the - // structure is deterministic. Decode preserves that sorted order. + // 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 := vcvalue.Object{ + want := value.Object{ {Key: "a", Value: int64(1)}, {Key: "b", Value: int64(2)}, {Key: "c", Value: int64(3)}, @@ -107,7 +108,7 @@ func TestReflectPointerDeref(t *testing.T) { } } -// point uses the Encryptable extension point. +// point implements Encryptable, so it writes itself. type point struct{ X, Y int64 } func (p point) EncryptValue(enc Encoder) error { @@ -119,21 +120,22 @@ func (p point) EncryptValue(enc Encoder) error { func TestEncryptableImpl(t *testing.T) { got := marshalUnmarshal(t, point{X: 1, Y: 2}) - want := vcvalue.Object{{Key: "x", Value: int64(1)}, {Key: "y", Value: int64(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 confirms an Encryptable is honored when reached -// through reflection (as a struct field), not only at the top level. +// 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 := vcvalue.Object{ - {Key: "Origin", Value: vcvalue.Object{ + want := value.Object{ + {Key: "Origin", Value: value.Object{ {Key: "x", Value: int64(3)}, {Key: "y", Value: int64(4)}, }}, @@ -144,7 +146,7 @@ func TestEncryptableNested(t *testing.T) { } func TestEncoderChannels(t *testing.T) { - // Drive the raw Encoder channels directly, including a nested Seq. + // Call the Encoder methods directly, including a nested Seq. buf, err := Marshal(seqBuilder{}) if err != nil { t.Fatalf("Marshal: %v", err) @@ -175,8 +177,8 @@ func (seqBuilder) EncryptValue(enc Encoder) error { 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().Uint32(math.MaxUint32) + s.Elem().Uint64(math.MaxUint64) s.Elem().String("s") s.Elem().Bytes([]byte{9}) return s.End() @@ -192,39 +194,41 @@ func TestUnmarshalRejectsGarbage(t *testing.T) { if _, err := Unmarshal([]byte{0x7f}); err == nil { t.Fatal("unknown tag must be rejected") } - // Trailing bytes after a complete value. + // The input has bytes after a complete value. if _, err := Unmarshal([]byte{0x00, 0x00}); err == nil { t.Fatal("trailing bytes must be rejected") } } -// TestPlainPassthroughRoundTrip: the reflection opt-in marker Plain seals a -// value as passthrough, and it decodes back as Plain{V:...} — the marking -// round-trips so a caller can tell the field travelled in the clear. +// 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": vcvalue.Plain{V: int64(42)}, + "id": value.Plain{V: int64(42)}, "email": "ada@example.com", }) - want := vcvalue.Object{ + want := value.Object{ {Key: "email", Value: "ada@example.com"}, - {Key: "id", Value: vcvalue.Plain{V: int64(42)}}, + {Key: "id", Value: value.Plain{V: int64(42)}}, } if !reflect.DeepEqual(got, want) { t.Fatalf("got %#v, want %#v", got, want) } } -// A Plain wrapping a whole subtree makes the entire subtree passthrough. +// A Plain around a whole subtree makes every value in the subtree +// passthrough. func TestPlainPassthroughSubtree(t *testing.T) { - got := marshalUnmarshal(t, vcvalue.Plain{V: []any{int64(1), "two", true}}) - want := vcvalue.Plain{V: []any{int64(1), "two", true}} + 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) } } -// The raw Encoder.Passthrough() channel, at root/seq/map positions. +// 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 { @@ -236,21 +240,21 @@ func (passthroughBuilder) EncryptValue(enc Encoder) error { func TestEncoderPassthroughChannel(t *testing.T) { got := marshalUnmarshal(t, passthroughBuilder{}) - want := []any{vcvalue.Plain{V: int64(7)}, "sealed"} + 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 marker (0xF2) with no value node behind it. + // 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) { - // Nesting exclusively through passthrough markers must hit the depth bound. + // 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) @@ -261,19 +265,19 @@ func TestUnmarshalRejectsPassthroughDepthBomb(t *testing.T) { } } -// A passthrough ciphertext node carries its readable value across the -// transport and back, marked Plain so it cannot be mistaken for a -// ciphertext map or sequence on the way back in. +// 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": vcvalue.Plain{V: int64(42)}, - "email": vcvalue.Sealed{9, 9, 9}, + "id": value.Plain{V: int64(42)}, + "email": sealed{9, 9, 9}, } - buf, err := MarshalCipherText(VCValueLeaves(), ct) + buf, err := MarshalCipherText(testLeaves(), ct) if err != nil { t.Fatalf("MarshalCipherText: %v", err) } - got, err := UnmarshalCipherText(VCValueLeaves(), buf) + got, err := UnmarshalCipherText(testLeaves(), buf) if err != nil { t.Fatalf("UnmarshalCipherText: %v", err) } @@ -284,14 +288,14 @@ func TestCipherTextPassthroughTransportRoundTrip(t *testing.T) { func TestCipherTextTransportRoundTrip(t *testing.T) { ct := map[string]any{ - "a": vcvalue.Sealed{9, 9, 9}, - "b": []any{vcvalue.Sealed{1}, vcvalue.SealedEmptySeq{2}}, + "a": sealed{9, 9, 9}, + "b": []any{sealed{1}, sealedEmptySeq{2}}, } - buf, err := MarshalCipherText(VCValueLeaves(), ct) + buf, err := MarshalCipherText(testLeaves(), ct) if err != nil { t.Fatalf("MarshalCipherText: %v", err) } - got, err := UnmarshalCipherText(VCValueLeaves(), buf) + got, err := UnmarshalCipherText(testLeaves(), buf) if err != nil { t.Fatalf("UnmarshalCipherText: %v", err) } @@ -300,19 +304,21 @@ func TestCipherTextTransportRoundTrip(t *testing.T) { } } -// A bare plaintext value in ciphertext position is rejected: passthrough must -// be explicit (Plain), so nothing travels unencrypted by accident. +// 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(VCValueLeaves(), map[string]any{"x": "oops"}); err == nil { + if _, err := MarshalCipherText(testLeaves(), map[string]any{"x": "oops"}); err == nil { t.Fatal("bare plaintext in ciphertext position must be rejected") } - if _, err := MarshalCipherText(VCValueLeaves(), []byte{1, 2, 3}); err == nil { - t.Fatal("bare []byte must be rejected (use Sealed or Plain)") + 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 zero exported fields (time.Time is the canonical case) must -// be rejected, not silently sealed as an empty map that destroys the payload. +// 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 @@ -320,8 +326,8 @@ func TestMarshalRejectsZeroExportedFieldStruct(t *testing.T) { if _, err := Marshal(opaque{hidden: 1}); err == nil { t.Fatal("struct with no exported fields must be rejected") } - // An all-vc:"-" struct asked for the empty encoding explicitly and stays - // allowed, as does the empty struct. + // 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:"-"` } @@ -333,11 +339,11 @@ func TestMarshalRejectsZeroExportedFieldStruct(t *testing.T) { } } -// Object (the decode result for maps) must re-encode with object framing so -// a decrypt-then-re-encrypt flow preserves the record's structure — both at -// the root and nested inside other values. +// 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 := vcvalue.Object{ + o := value.Object{ {Key: "b", Value: int64(2)}, {Key: "a", Value: int64(1)}, } @@ -354,25 +360,26 @@ func TestObjectReencodesWithObjectFraming(t *testing.T) { } } -// A Plain-wrapped Object inside a ciphertext must survive the passthrough -// round trip shape-intact (PR review P1). +// 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 := vcvalue.Object{{Key: "id", Value: int64(42)}} - buf, err := MarshalCipherText(VCValueLeaves(), vcvalue.Plain{V: o}) + 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(VCValueLeaves(), buf) + got, err := UnmarshalCipherText(testLeaves(), buf) if err != nil { t.Fatalf("UnmarshalCipherText: %v", err) } - if !reflect.DeepEqual(got, vcvalue.Plain{V: o}) { + if !reflect.DeepEqual(got, value.Plain{V: o}) { t.Fatalf("got %#v, want Plain{V: %#v}", got, o) } } -// [N]byte must take the same single-Bytes-leaf path as []byte — element-wise -// encoding would produce a ciphertext shape no other producer emits. +// 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}) { @@ -382,14 +389,14 @@ func TestByteArrayEncodesAsBytes(t *testing.T) { Hash [4]byte } got = marshalUnmarshal(t, hashed{Hash: [4]byte{9, 8, 7, 6}}) - want := vcvalue.Object{{Key: "Hash", Value: []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 through a nil receiver — -// the behaviour typed-nil detection must prevent. +// 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 { @@ -397,8 +404,8 @@ func (e *nilEncryptable) EncryptValue(enc Encoder) error { return nil } -// A typed nil pointer satisfying Encryptable must encode as Null, not invoke -// the method on a nil receiver (PR review P2). +// 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 { @@ -410,8 +417,8 @@ func TestTypedNilEncryptableEncodesNull(t *testing.T) { } } -// A pointer cycle must fail with an error, not recurse to stack overflow -// (PR review P2). +// 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 @@ -420,37 +427,37 @@ func TestMarshalRejectsPointerCycle(t *testing.T) { } } -// MarshalCipherText must reject a passthrough whose payload sits beyond the -// depth budget instead of emitting bytes UnmarshalCipherText is guaranteed -// to reject (PR review P2). +// 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 push the Plain payload past maxDepth (128). - var deep any = vcvalue.Plain{V: int64(1)} + // 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(VCValueLeaves(), deep); !errors.Is(err, ErrTooDeep) { + 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) } - // One level shallower still round-trips — the bound is exact. - var ok any = vcvalue.Plain{V: int64(1)} + // 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(VCValueLeaves(), ok) + buf, err := MarshalCipherText(testLeaves(), ok) if err != nil { t.Fatalf("MarshalCipherText at the bound: %v", err) } - if _, err := UnmarshalCipherText(VCValueLeaves(), buf); err != nil { + if _, err := UnmarshalCipherText(testLeaves(), buf); err != nil { t.Fatalf("UnmarshalCipherText at the bound: %v", err) } } -// --- Malformed-input coverage for the two decoders (PR #257 review gaps). -// Raw transport bytes are hand-built here because no Go encoder produces -// these shapes — that unreachability is exactly why the branches were -// untested. +// 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) @@ -458,7 +465,8 @@ func u32le(n int) []byte { return b } -// ctEntry frames one ciphertext map entry: key chunk + a 1-byte ctSingle leaf. +// 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 @@ -466,33 +474,32 @@ func ctEntry(key string) []byte { return append(e, 0xAB) } -// decodeCipherText rejects a duplicate map key — a branch only reachable -// from hand-crafted or cross-language transport bytes (a Go map cannot -// produce duplicates). +// 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(VCValueLeaves(), dup); err == nil { + if _, err := UnmarshalCipherText(testLeaves(), dup); err == nil { t.Fatal("duplicate ciphertext map key must be rejected") } - // Positive control: the same framing with distinct keys decodes. + // 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(VCValueLeaves(), ok); err != nil { + if _, err := UnmarshalCipherText(testLeaves(), ok); err != nil { t.Fatalf("distinct keys should decode: %v", err) } } -// Unmarshal's recursion bound and hostile-count guard on the array/object -// routes — the Rust codec tests all three; only the passthrough depth bomb -// was covered on the Go side. +// 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) { - // Depth bomb: 130 nested single-element arrays (> maxDepth 128). + // Too deep: 130 nested arrays of one element each, more than maxDepth + // (128). var deep []byte for range 130 { deep = append(deep, 0xF0) // tagArray @@ -503,7 +510,7 @@ func TestUnmarshalRejectsArrayAndObjectBombs(t *testing.T) { t.Fatal("array depth bomb must be rejected") } - // Object nesting: 130 nested one-entry objects. + // Too deep: 130 nested objects of one entry each. var deepObj []byte for range 130 { deepObj = append(deepObj, 0xF1) // tagObject @@ -516,47 +523,49 @@ func TestUnmarshalRejectsArrayAndObjectBombs(t *testing.T) { t.Fatal("object depth bomb must be rejected") } - // Hostile count: an array claiming max-u32 items with no bytes behind it. + // 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's own recursion bound, hostile-count guard, and -// trailing-byte rejection — a separate recursion from the value decoder, -// previously untested. +// 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) { - // Depth bomb: 130 nested one-element ctSeq. + // 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(VCValueLeaves(), deep); err == nil { + if _, err := UnmarshalCipherText(testLeaves(), deep); err == nil { t.Fatal("ciphertext depth bomb must be rejected") } - // Hostile count. - if _, err := UnmarshalCipherText(VCValueLeaves(), []byte{0x03, 0xFF, 0xFF, 0xFF, 0xFF}); err == nil { + // A hostile count. + if _, err := UnmarshalCipherText(testLeaves(), []byte{0x03, 0xFF, 0xFF, 0xFF, 0xFF}); err == nil { t.Fatal("hostile ciphertext count must be rejected") } - // Trailing bytes after a complete node. + // Bytes after a complete node. leaf := append([]byte{0x01}, u32le(1)...) leaf = append(leaf, 0xAB, 0xFF) // one extra byte - if _, err := UnmarshalCipherText(VCValueLeaves(), leaf); err == nil { + if _, err := UnmarshalCipherText(testLeaves(), leaf); err == nil { t.Fatal("trailing bytes must be rejected") } - // Unknown tag. - if _, err := UnmarshalCipherText(VCValueLeaves(), []byte{0x7F}); err == nil { + // An unknown tag. + if _, err := UnmarshalCipherText(testLeaves(), []byte{0x7F}); err == nil { t.Fatal("unknown ciphertext tag must be rejected") } } -// The encodeReflect default arm: kinds with no encoding (chan/func/complex) -// error instead of panicking or emitting garbage. +// 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") @@ -569,17 +578,17 @@ func TestMarshalRejectsUnsupportedKind(t *testing.T) { } } -// encodeMap rejects non-string map keys — the transport frames keys as -// UTF-8 chunks, so there is nothing sound to write for other key types. +// 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 encode-side recursion guard: an over-deep Go value fails the encode. -// The decode side has depth-bomb coverage; this drives the same bound from -// the writing end. +// 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) @@ -590,11 +599,11 @@ func TestMarshalRejectsDepthBomb(t *testing.T) { } } -// A duplicate object key in the wire bytes must be rejected exactly as the -// ciphertext decoder rejects a duplicate ctMap key: an Object carrying -// duplicates cannot survive re-encoding through a Go map without silently -// dropping an entry. Only hand-built transport bytes can reach this branch — -// the encoder sorts unique map keys. +// 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 @@ -607,7 +616,7 @@ func TestUnmarshalRejectsDuplicateObjectKey(t *testing.T) { t.Fatal("an object with a duplicate key must be rejected") } - // Positive control: the same shape with distinct keys decodes. + // 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) @@ -617,9 +626,9 @@ func TestUnmarshalRejectsDuplicateObjectKey(t *testing.T) { } } -// skipsValue writes a key (or claims an element) and never writes the value — -// the contract violation Field/Elem must now catch at encode time, where it -// previously surfaced only as an opaque ErrMalformed at decode. +// 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 { @@ -635,8 +644,8 @@ func (s skipsValue) EncryptValue(enc Encoder) error { return m.End() } -// lastValueMissing exercises the End-side check: the final entry's value is -// the one skipped, so no later Field/Elem call can catch it. +// 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 { @@ -652,9 +661,10 @@ func (s lastValueMissing) EncryptValue(enc Encoder) error { return m.End() } -// unclosedNested completes a terminal *inside* a nested container but never -// Ends the container — the slot itself is incomplete even though a descendant -// value finished, so a per-slot (not global) completion check is required. +// 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 { @@ -672,8 +682,8 @@ func (u unclosedNested) EncryptValue(enc Encoder) error { return m.End() } -// doubleWrite pushes two terminals through one element/entry Encoder, -// producing an extra value node the container's count doesn't account for. +// 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 { @@ -691,7 +701,7 @@ func (d doubleWrite) EncryptValue(enc Encoder) error { return m.End() } -// rootMiscount writes zero or several values at the root slot. +// rootMiscount writes no value, or several values, at the root. type rootMiscount struct{ writes int } func (r rootMiscount) EncryptValue(enc Encoder) error { @@ -701,7 +711,7 @@ func (r rootMiscount) EncryptValue(enc Encoder) error { return nil } -// unclosedRoot leaves the root container un-Ended. +// unclosedRoot never calls End on the root container. type unclosedRoot struct{} func (unclosedRoot) EncryptValue(enc Encoder) error { @@ -709,24 +719,25 @@ func (unclosedRoot) EncryptValue(enc Encoder) error { return nil } -// The passthrough payload path in encodeCipherText applies the same -// exactly-one rule as Marshal's root slot; without this, a malformed payload -// would emit wire bytes that UnmarshalCipherText only rejects later as an -// opaque ErrMalformed. +// 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{ - vcvalue.Plain{V: rootMiscount{writes: 0}}, - vcvalue.Plain{V: rootMiscount{writes: 2}}, - vcvalue.Plain{V: unclosedRoot{}}, + value.Plain{V: rootMiscount{writes: 0}}, + value.Plain{V: rootMiscount{writes: 2}}, + value.Plain{V: unclosedRoot{}}, } { - if _, err := MarshalCipherText(VCValueLeaves(), v); err == nil { + if _, err := MarshalCipherText(testLeaves(), v); err == nil { t.Fatalf("malformed passthrough payload %#v must fail the encode", v) } } } -// missingPassthroughPayload writes a Passthrough marker into a sequence slot -// but never the wrapped value — the passthrough-specific skipped-value case. +// 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 { @@ -745,17 +756,17 @@ func TestEncoderPassthroughRequiresWrappedValue(t *testing.T) { } } -// collidingTag is the reflection route to a duplicate wire key: a vc tag -// resolving to another field's effective name. Without encode-time rejection -// this marshals happily and only fails inside the ciphertext decoder — after -// the plaintext crossed the FFI boundary — as an ErrMalformed that names -// neither the struct nor the key. +// 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 is the Encryptable route to the same collision. +// duplicateFieldKey produces the same duplicate key through an Encryptable. type duplicateFieldKey struct{} func (duplicateFieldKey) EncryptValue(enc Encoder) error { @@ -789,7 +800,7 @@ func TestEncoderCatchesSkippedValuesAtEncodeTime(t *testing.T) { for _, c := range []struct { name string v any - want string // substring the diagnostic must carry + want string // text that the error must contain }{ {"map middle", skipsValue{}, `key "a"`}, {"map last", lastValueMissing{}, `key "b"`}, @@ -815,9 +826,9 @@ func TestEncoderCatchesSkippedValuesAtEncodeTime(t *testing.T) { } } -// innerFailsOuterReports pins the End() error contract: End returns the -// first error of the whole encode, not one scoped to its own container, so -// an outer End reports a failure that happened inside a sibling subtree. +// 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 { @@ -839,9 +850,9 @@ func TestEndReturnsFirstEncodeErrorNotContainerScoped(t *testing.T) { } } -// A binding-specific LeafSet round-trips its own distinct leaf types — the -// reason the ciphertext codec is parameterised at all: a stack-encrypt leaf -// must come back as a stack-encrypt type, never as vcvalue.Sealed. +// 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{ @@ -873,22 +884,23 @@ func TestCipherTextLeafSetKeepsBindingTypesDistinct(t *testing.T) { t.Fatalf("got %#v, want %#v", got, ct) } - // The wire bytes are identical across LeafSets — only the Go types - // differ — so the same buffer decodes to vcvalue types under - // VCValueLeaves. This pins that a LeafSet changes materialization, not - // the encoding. - asVC, err := UnmarshalCipherText(VCValueLeaves(), buf) + // 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(VCValueLeaves): %v", err) + t.Fatalf("UnmarshalCipherText(testLeaves): %v", err) } - want := map[string]any{"email": vcvalue.Sealed{9, 9, 9}} + want := map[string]any{"email": sealed{9, 9, 9}} if !reflect.DeepEqual(asVC, want) { t.Fatalf("got %#v, want %#v", asVC, want) } - // And a foreign leaf type is a bare plaintext to a LeafSet that does not - // claim it — rejected, not silently passed through. - if _, err := MarshalCipherText(VCValueLeaves(), ct); err == nil { + // 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") } } @@ -909,25 +921,28 @@ func TestCipherTextRejectsPartialLeafSet(t *testing.T) { } func TestCipherTextMakeMustMaterializeDecodedKind(t *testing.T) { - // otherLeaves materializes only LeafSingle. Wire bytes carrying the - // authenticated absent marker must fail attributably — never decode to a - // nil node the caller only trips over later. + // 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 vcvalue set likewise rejects an unlisted kind instead of minting a - // Sealed for it — mirroring leafTag's refusal on the encode side. - if got := VCValueLeaves().Make(LeafKind(9), []byte{1}); got != nil { + // 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 encode-side half of the pair above: a Classify that claims a leaf - // under a kind outside the wire table is refused before any tag is - // emitted, so a future fifth kind can never reach the wire unnamed. + // 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 { @@ -943,19 +958,20 @@ func TestMarshalCipherTextRejectsOutOfRangeLeafKind(t *testing.T) { } func TestCipherTextRoundTripsAllLeafKinds(t *testing.T) { - // Every kind in the wire table, so no Classify or Make arm goes - // unexercised: a swapped arm (an empty-map marker materialized where an - // empty-seq belongs) fails here rather than at some later decrypt. + // 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": vcvalue.Sealed{9, 9, 9}, - "emptySeq": vcvalue.SealedEmptySeq{7}, - "emptyMap": vcvalue.SealedEmptyMap{8}, + "single": sealed{9, 9, 9}, + "emptySeq": sealedEmptySeq{7}, + "emptyMap": sealedEmptyMap{8}, } - buf, err := MarshalCipherText(VCValueLeaves(), ct) + buf, err := MarshalCipherText(testLeaves(), ct) if err != nil { t.Fatalf("MarshalCipherText: %v", err) } - got, err := UnmarshalCipherText(VCValueLeaves(), buf) + got, err := UnmarshalCipherText(testLeaves(), buf) if err != nil { t.Fatalf("UnmarshalCipherText: %v", err) } @@ -965,11 +981,13 @@ func TestCipherTextRoundTripsAllLeafKinds(t *testing.T) { } func TestLeafTagsHasNoUnwiredKinds(t *testing.T) { - // A LeafKind constant that skips a value would leave a zero hole in - // leafTags. Without the zero guard, leafTag would emit tag 0x00 with no - // error and leafKind would map it straight back — a clean round trip - // inside Go under a tag the Rust codec does not define. Both directions - // refuse zero, and the table itself must have no holes to refuse. + // 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) @@ -981,7 +999,7 @@ func TestLeafTagsHasNoUnwiredKinds(t *testing.T) { if _, ok := leafKind(0); ok { t.Fatal("tag 0x00 is not a ciphertext tag and must not map to a kind") } - if _, err := UnmarshalCipherText(VCValueLeaves(), []byte{0x00, 0, 0, 0, 0}); err == nil { + if _, err := UnmarshalCipherText(testLeaves(), []byte{0x00, 0, 0, 0, 0}); err == nil { t.Fatal("a 0x00 tag must be rejected on the wire") } } @@ -992,8 +1010,8 @@ func TestFramingTags(t *testing.T) { wire []byte }{ {[]any{}, []byte{0xF0, 0, 0, 0, 0}}, - {vcvalue.Object{}, []byte{0xF1, 0, 0, 0, 0}}, - {vcvalue.Plain{V: nil}, []byte{0xF2, 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) @@ -1011,9 +1029,9 @@ func TestFramingTags(t *testing.T) { } } -// A signaling NaN must keep its bits: widening it to float64 on the way to -// the encoder would set the quiet bit (found by FuzzUnmarshal). -// namedFloat32 has no Encryptable method, so it reaches the reflect path. +// 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) { diff --git a/languages/golang/encrypt/frame/conformance_test.go b/languages/golang/encrypt/frame/conformance_test.go index bc89b21ec..1575119bb 100644 --- a/languages/golang/encrypt/frame/conformance_test.go +++ b/languages/golang/encrypt/frame/conformance_test.go @@ -1,34 +1,39 @@ -package vcffi +package frame import ( "encoding/hex" "encoding/json" "fmt" - "os" "reflect" "regexp" "strconv" "testing" "time" - "github.com/cipherstash/vitaminc/bindings/go/vcvalue" + "github.com/cipherstash/stack/languages/golang/encrypt/value" ) -// isoDate and rfc3339ish match the corpus date and timestamp spellings, -// including a negative year as a sign and six digits, which time.Parse -// cannot read. +// 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 a vector's kind and value fields describe, -// without the transport decoder, so a bug that decodes and encodes -// symmetrically wrong cannot pass. +// 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 this build does not know: the id, the parameter and - // the physical scalar, which round-trips as a vcvalue.Tagged. + // 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 @@ -41,7 +46,7 @@ func expected(kind string, raw json.RawMessage) (any, error) { if err != nil { return nil, err } - return vcvalue.Tagged{ID: inner.ID, Param: inner.Param, V: v}, nil + return value.Tagged{ID: inner.ID, Param: inner.Param, V: v}, nil } var text string _ = json.Unmarshal(raw, &text) @@ -76,9 +81,9 @@ func expected(kind string, raw json.RawMessage) (any, error) { case "uint64": return natural(64) case "int128": - return vcvalue.ParseInt128(text) + return value.ParseInt128(text) case "uint128": - return vcvalue.ParseUint128(text) + return value.ParseUint128(text) case "float32": var v float32 return v, json.Unmarshal(raw, &v) @@ -102,20 +107,20 @@ func expected(kind string, raw json.RawMessage) (any, error) { } n[i] = v } - return vcvalue.Date{Year: n[0], Month: time.Month(n[1]), Day: n[2]}, nil + return value.Date{Year: n[0], Month: time.Month(n[1]), Day: n[2]}, nil case "timestamp": return timestamp(text) case "decimal": - return vcvalue.ParseDecimal(text) + return value.ParseDecimal(text) case "uuid": - return vcvalue.ParseUUID(text) + return value.ParseUUID(text) case "array": if string(raw) == "[]" { return []any{}, nil } case "object": if string(raw) == "{}" { - return vcvalue.Object{}, nil + return value.Object{}, nil } } return nil, fmt.Errorf("teach expected() the %s vector %s", kind, raw) @@ -150,9 +155,9 @@ func sameValue(got, want any) bool { } func TestSharedValueConformance(t *testing.T) { - data, err := os.ReadFile("../../../testdata/value-conformance.json") - if err != nil { - t.Fatal(err) + data, ok := readCorpus(t, valueCorpus) + if !ok { + t.Skip("no value corpus") } var corpus struct { Vectors []struct { @@ -261,7 +266,7 @@ func TestSharedValueConformance(t *testing.T) { if err != nil { t.Fatal(err) } - if _, err := UnmarshalCipherText(VCValueLeaves(), raw); err != ErrMalformed { + 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 index 27ca62812..f889ef398 100644 --- a/languages/golang/encrypt/frame/decode.go +++ b/languages/golang/encrypt/frame/decode.go @@ -1,4 +1,4 @@ -package vcffi +package frame import ( "encoding/binary" @@ -6,36 +6,40 @@ import ( "math/big" "time" - "github.com/cipherstash/vitaminc/bindings/go/vcvalue" + "github.com/cipherstash/stack/languages/golang/encrypt/value" ) -// Unmarshal decodes value transport bytes into Go natives: +// Unmarshal decodes the transport bytes of a value into Go values: // -// - Null and Undefined → nil (Go has no undefined analog); -// - a typed null → nil: an absent value is absent whatever its type -// once it is out of the seal, so it re-encodes as the plain null; -// - Bool → bool; -// - Int32 → int32; -// - Int64 → int64; -// - UInt32 → uint32; -// - UInt64 → uint64; -// - Float32 → float32; -// - Float64 → float64; -// - String → string; -// - Bytes → []byte; -// - Array → []any; -// - vcvalue.Object → vcvalue.Object (ordered []Field); -// - Passthrough → vcvalue.Plain{V: } (the clear-field marker); -// - the 0xF3 envelope → time.Time for a timestamp in seconds, milliseconds -// or microseconds, vcvalue.UUID for a UUID, and vcvalue.Tagged for a -// logical id this build does not know, which re-encodes unchanged. +// - 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 maps exactly in both directions — the 32-bit tags decode to int32 / -// uint32 / float32, not widened to 64-bit. JavaScript decodes integer tags -// as BigInt and widens Float32 to a number. -// -// This self-describing shape is deliberately spike-scoped. A reflection-based -// unmarshal into caller structs (the mirror of Encode) is future work. +// 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) @@ -59,7 +63,8 @@ func decodeValue(r *reader, depth int) (any, error) { return decodeTagged(r, tag, depth) } -// decodeTagged decodes the node whose tag has just been read. +// 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: @@ -139,10 +144,11 @@ func decodeTagged(r *reader, tag byte, depth int) (any, error) { if err != nil { return nil, err } - fields := make(vcvalue.Object, 0, eagerCap(n)) - // Duplicate keys are rejected as on the ciphertext decode path (and - // both Rust decoders): an vcvalue.Object with duplicates cannot survive a - // re-encode through a Go map without silently dropping an entry. + 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() @@ -153,22 +159,23 @@ func decodeTagged(r *reader, tag byte, depth int) (any, error) { return nil, ErrMalformed } seen[key] = struct{}{} - value, err := decodeValue(r, depth+1) + v, err := decodeValue(r, depth+1) if err != nil { return nil, err } - fields = append(fields, vcvalue.Field{Key: key, Value: value}) + fields = append(fields, value.Field{Key: key, Value: v}) } return fields, nil case tagPassthrough: - // A passthrough value surfaces as vcvalue.Plain{V: }, the - // mirror of the Encoder's vcvalue.Plain opt-in, so a caller can tell the - // field travelled in the clear. + // 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 vcvalue.Plain{V: inner}, nil + return value.Plain{V: inner}, nil case tagEnvelope: return decodeEnvelope(r) case tagTypedNull: @@ -178,9 +185,10 @@ func decodeTagged(r *reader, tag byte, depth int) (any, error) { } } -// physicalTag reports whether tag is a physical scalar: one the envelope -// may carry. The logical shorthand tags (Undefined, Date, Timestamp, -// Decimal) and the containers are not. +// 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, @@ -190,10 +198,13 @@ func physicalTag(tag byte) bool { return false } -// decodeEnvelope reads the 0xF3 envelope after its tag: a logical id, a -// parameter, and a physical scalar. There is one encoding per value, so an -// envelope over a type with a shorthand tag, an id of zero, or a known id -// with a parameter it cannot take is malformed (ADR 0001 section 3). +// 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 { @@ -224,18 +235,19 @@ func decodeEnvelope(r *reader) (any, error) { if param != 0 || !ok || len(b) != 16 { return nil, ErrMalformed } - var u vcvalue.UUID + var u value.UUID copy(u[:], b) return u, nil default: - return vcvalue.Tagged{ID: id, Param: param, V: physical}, nil + return value.Tagged{ID: id, Param: param, V: physical}, nil } } -// envelopeTimestamp is a count of seconds, milliseconds or microseconds -// since the epoch as a time.Time, in the wire's range (jiff's, about years -// -9999 to 9999; see vcvalue.Timestamp). The nanosecond unit has -// the shorthand Timestamp tag and is refused in the envelope. +// 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 { @@ -248,17 +260,18 @@ func envelopeTimestamp(unit byte, physical any) (any, error) { default: return nil, ErrMalformed } - var t vcvalue.Timestamp + var t value.Timestamp if count, ok := smallIntegerOf(physical); ok { - // Most counts fit an int64, among them every Date that Node writes, - // so they skip math/big. The count splits into whole seconds and a - // remainder that is never negative, as DivMod does below. + // 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 = vcvalue.Timestamp{Seconds: seconds, Nanoseconds: uint32(rem * per)} + t = value.Timestamp{Seconds: seconds, Nanoseconds: uint32(rem * per)} } else { count, ok := wideIntegerOf(physical) if !ok { @@ -269,7 +282,7 @@ func envelopeTimestamp(unit byte, physical any) (any, error) { if !seconds.IsInt64() { return nil, ErrMalformed } - t = vcvalue.Timestamp{Seconds: seconds.Int64(), Nanoseconds: uint32(sub.Int64())} + t = value.Timestamp{Seconds: seconds.Int64(), Nanoseconds: uint32(sub.Int64())} } if t.Validate() != nil { return nil, ErrMalformed @@ -277,7 +290,8 @@ func envelopeTimestamp(unit byte, physical any) (any, error) { return time.Unix(t.Seconds, int64(t.Nanoseconds)).UTC(), nil } -// smallIntegerOf is the value of a decoded int that fits an int64. +// 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: @@ -300,16 +314,16 @@ func smallIntegerOf(v any) (int64, bool) { return 0, false } -// wideIntegerOf is the value of a decoded int that smallIntegerOf does not -// take: a uint64 above math.MaxInt64, an Int128 or a Uint128. +// 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 vcvalue.Int128: + case value.Int128: value, ok := new(big.Int).SetString(x.String(), 10) return value, ok - case vcvalue.Uint128: + case value.Uint128: value, ok := new(big.Int).SetString(x.String(), 10) return value, ok } diff --git a/languages/golang/encrypt/frame/doc.go b/languages/golang/encrypt/frame/doc.go index 649f8573b..69c8e2b59 100644 --- a/languages/golang/encrypt/frame/doc.go +++ b/languages/golang/encrypt/frame/doc.go @@ -1,55 +1,100 @@ -// Package vcffi is the shared FFI transport codec of the vitaminc Go -// bindings: the wire encoding that carries a value tree into a wasm guest -// and a ciphertext tree back out, together with the Encryptable/Encoder -// extension point for types that control their own encoding. -// -// It exists as its own module so every binding that owns a wasm boundary -// speaks the same bytes from one implementation — vcencrypt (the -// vitaminc-encrypt reference binding) and the stack-encrypt Go SDK are the -// intended consumers. Forking the codec per binding is exactly the failure -// mode this module prevents: one codec, one hostile-input test suite, one -// fuzz corpus. -// -// # Transport, and one storage profile -// -// The transport bytes are an FFI detail with no compatibility commitment: -// nothing [Marshal], [Encode] or [MarshalCipherText] writes should ever be -// persisted. The one exception is the storage profile, [MarshalStorage] and -// [UnmarshalStorage], which write and read a value as a versioned blob for -// bytes that are kept. Its format is shared with the Rust module -// vitaminc_aead_frame::storage, specified in packages/aead-frame/STORAGE.md, -// frozen at version 1, and pinned by the golden corpus in -// packages/aead-frame/testdata/storage-v1.json, which this package's tests -// read. Use it, and only it, for bytes that outlive the process that wrote -// them. The other frozen format is the sealed leaf inside the AEAD envelope -// (see vcvalue.Sealed and the Rust crate vitaminc-aead's leaf codec). +// 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] carry the plaintext value model (Go natives, -// vcvalue.Object for maps, vcvalue.Plain for passthrough): Marshal walks -// ordinary Go values with encoding/json-style rules, consulting -// [Encryptable] first so a user type can drive the [Encoder] channels -// itself. +// [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 // -// [MarshalCipherText] and [UnmarshalCipherText] carry the ciphertext tree. -// Its structural nodes ([]any, map[string]any, vcvalue.Plain) are common to -// every binding, but the sealed-leaf marker types are deliberately not: each -// binding supplies a [LeafSet] mapping its own leaf types onto the framing, -// so a leaf sealed by one cipher is a distinct Go type from a leaf sealed by -// another and can never scan or marshal where the other belongs. -// [VCValueLeaves] is the set for the vcvalue model types. +// 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: recursion depth, length -// prefixes and item counts are bounded, strings are UTF-8 validated, -// duplicate map keys are rejected, and every malformed input fails with -// [ErrMalformed] rather than panicking or over-allocating. The fuzz targets -// in this package pin that contract. -// -// [ErrMalformed] covers hostile bytes, not caller mistakes: a [LeafSet] that -// is partially wired, or that does not materialize a kind the buffer carries, -// fails with its own attributable error, so errors.Is(err, [ErrMalformed]) is -// a test for bad input rather than a total branch over decode failures. -package vcffi +// 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 index 8e2aa070c..dfff12559 100644 --- a/languages/golang/encrypt/frame/encoder.go +++ b/languages/golang/encrypt/frame/encoder.go @@ -1,4 +1,4 @@ -package vcffi +package frame import ( "encoding/binary" @@ -12,42 +12,14 @@ import ( "time" "unicode/utf8" - "github.com/cipherstash/vitaminc/bindings/go/vcvalue" + "github.com/cipherstash/stack/languages/golang/encrypt/value" ) -// Encryptable is the extension point for user types: a type implements it to -// control how it is sealed, the way a Rust type implements `Encrypt`. Because -// Go has no orphan impls, this interface (rather than reflection) is how a -// type opts into a bespoke encoding. Encode and Marshal consult it before -// falling back to reflection. -type Encryptable interface { - // EncryptValue records this value into enc. Implementations write - // exactly one value: one terminal channel (String, Int, …) or one - // container (Seq, Map). Returning an error aborts the whole encode. - EncryptValue(enc Encoder) error -} - -// FixedWidth is the Go side of Rust's `Encrypt::FIXED`: an Encryptable whose -// EncryptValue always writes one value of one fixed-width type (a money type -// that writes its cents with Int64, say). A nil pointer to such a type is -// written as a typed null of that type, so a sealed absence is as long as a -// sealed value. A nil pointer to an Encryptable that does not implement it -// is the plain null, since its encoding is its own. -// -// FixedType is called once per type, on a pointer to a zero value, so it -// must answer from the type alone. A type that returns an invalid FixedType -// fails the encode with vcvalue.ErrInvalidFixedType rather than write the -// plain null in its place. -type FixedWidth interface { - Encryptable - FixedType() vcvalue.FixedType -} - -// encState is the buffer and first-error shared by an Encoder and every -// sub-encoder it hands out. Errors accumulate: once one is recorded, further -// channel calls are no-ops, so consumer code can chain writes without -// checking after every call and still surface the first failure from -// End/Marshal. +// 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 @@ -59,55 +31,121 @@ func (s *encState) fail(err error) { } } -// Encoder records a single value in transport form. It mirrors the Rust -// Cipher channels — it is a recorder that writes the transport bytes, not a -// live cipher handle. Exactly one channel must be used per Encoder: a -// terminal (Null, Undefined, Bool, Int32, Int64, UInt32, UInt64, Float32, -// Float64, String, Bytes) or a container (Seq, Map). +// 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. // -// Encoder is passed and stored by value; all instances handed out for one -// encode share the same underlying buffer and first-error via a pointer, so -// copying an Encoder is cheap and safe. The zero Encoder is not usable and -// its methods panic: usable Encoders are only the one handed to -// [Encryptable.EncryptValue] and those returned by Passthrough, Elem and -// Field. +// 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 completion counter for the slot this Encoder writes - // into (a container's current element/entry, or the root). Terminals and - // container Ends increment it; the slot's owner then verifies exactly one - // completion. This is per-slot on purpose: a global counter would let a - // completed *descendant* (e.g. a terminal inside an un-Ended nested - // container) stand in for the slot's own value, shifting the wire and - // surfacing only as an opaque ErrMalformed at decode. + // 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 this Encoder's slot received one full value. +// complete records that the slot of this Encoder received one complete +// value. func (e Encoder) complete() { if e.done != nil { *e.done++ } } -// Null records the cross-language null (Go nil, JS null, Python None). +// Null records a null. A null is nil in Go, null in JavaScript, and None in +// Python. func (e Encoder) Null() { - if e.st.err == nil { + if !e.dead() { e.push(tagNull) e.complete() } } -// Undefined records JavaScript's undefined. Go has no analog, so Go code -// rarely writes it; the channel exists so a value round-tripped from JS can -// be re-encoded. On decode, Undefined collapses to nil like Null. +// 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.st.err == nil { + if !e.dead() { e.push(tagUndefined) e.complete() } @@ -115,7 +153,7 @@ func (e Encoder) Undefined() { // Bool records a boolean. func (e Encoder) Bool(b bool) { - if e.st.err != nil { + if e.dead() { return } if b { @@ -126,11 +164,11 @@ func (e Encoder) Bool(b bool) { e.complete() } -// Float64 records an IEEE-754 double. Distinct from the integer channels: it -// round-trips as a 64-bit float in every language. Round-trips by raw bit -// pattern, so NaN payloads and -0.0 survive. +// 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.st.err != nil { + if e.dead() { return } e.push(tagFloat64) @@ -138,10 +176,11 @@ func (e Encoder) Float64(f float64) { e.complete() } -// Float32 records an IEEE-754 single. For schema fidelity with float4 at the -// EQL layer; round-trips by raw bit pattern. +// 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.st.err != nil { + if e.dead() { return } e.push(tagFloat32) @@ -149,10 +188,10 @@ func (e Encoder) Float32(f float32) { e.complete() } -// Int32 records a signed 32-bit integer. For schema fidelity with int4 at -// the EQL layer; kept distinct from Int64. +// 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.st.err != nil { + if e.dead() { return } e.push(tagInt32) @@ -160,10 +199,11 @@ func (e Encoder) Int32(i int32) { e.complete() } -// Int64 records a signed 64-bit integer. Kept distinct from Float64 so -// integer-typed languages round-trip integers as integers. +// 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.st.err != nil { + if e.dead() { return } e.push(tagInt64) @@ -171,10 +211,10 @@ func (e Encoder) Int64(i int64) { e.complete() } -// UInt32 records an unsigned 32-bit integer. For schema fidelity with the -// EQL layer. -func (e Encoder) UInt32(u uint32) { - if e.st.err != nil { +// 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) @@ -182,9 +222,9 @@ func (e Encoder) UInt32(u uint32) { e.complete() } -// UInt64 records an unsigned 64-bit integer without changing its width. -func (e Encoder) UInt64(u uint64) { - if e.st.err != nil { +// Uint64 records an unsigned 64-bit integer without changing its width. +func (e Encoder) Uint64(u uint64) { + if e.dead() { return } e.push(tagUint64) @@ -192,13 +232,13 @@ func (e Encoder) UInt64(u uint64) { e.complete() } -// String records a UTF-8 string. Invalid UTF-8 fails the encode. +// String records a string. The encode fails if s is not valid UTF-8. func (e Encoder) String(s string) { - if e.st.err != nil { + if e.dead() { return } if !utf8.ValidString(s) { - e.st.fail(errors.New("vcffi: string is not valid UTF-8")) + e.st.fail(errors.New("frame: string is not valid UTF-8")) return } e.push(tagString) @@ -210,9 +250,9 @@ func (e Encoder) String(s string) { } } -// Bytes records raw binary data. +// Bytes records binary data. func (e Encoder) Bytes(b []byte) { - if e.st.err != nil { + if e.dead() { return } e.push(tagBytes) @@ -224,33 +264,37 @@ func (e Encoder) Bytes(b []byte) { } } -// Passthrough marks the next value as passthrough (unencrypted, -// unauthenticated) and returns an Encoder for it — the same channel set, so -// the wrapped value is written exactly as any other: +// 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 (terminal or container) through the returned -// Encoder. Non-sensitive data only — the wrapped value is not sealed. +// Write exactly one value through the returned Encoder: a scalar or a +// container. func (e Encoder) Passthrough() Encoder { - if e.st.err == nil { + e = e.orDead() + if !e.dead() { if e.depth+1 > maxDepth { e.st.fail(ErrTooDeep) } else { e.push(tagPassthrough) } } - // The passthrough marker and its wrapped value form ONE value in this - // Encoder's slot, so the wrapped value completes the same counter. + // 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 begins a sequence. Call Elem once per element and End when 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.st.err != nil { + if e.dead() { return s } if e.depth+1 > maxDepth { @@ -259,15 +303,17 @@ func (e Encoder) Seq() *SeqEncoder { } e.push(tagArray) s.lenOff = len(e.st.buf) - e.push(0, 0, 0, 0) // length back-patched by End + e.push(0, 0, 0, 0) // End writes the count here return s } -// Map begins a string-keyed map. Call Field once per entry and End when -// done. Keys preserve insertion order and are UTF-8 validated. +// 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.st.err != nil { + if e.dead() { return m } if e.depth+1 > maxDepth { @@ -276,38 +322,42 @@ func (e Encoder) Map() *MapEncoder { } e.push(tagObject) m.lenOff = len(e.st.buf) - e.push(0, 0, 0, 0) // length back-patched by End + e.push(0, 0, 0, 0) // End writes the count here return m } -// SeqEncoder records the elements of a sequence. The element count is -// back-patched into the reserved length slot at End. +// 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 enclosing slot's completion counter (see Encoder.done); - // End increments it — the sequence is one value in its parent's slot. + // 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 completions of this sequence's own element slots. - // Elem and End verify childDone == count, so a skipped element, an - // un-Ended nested container, or a doubly-written element fails here at - // encode time instead of as ErrMalformed at decode. + // 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 verifies the previous element slot completed exactly once. +// 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("vcffi: more than one value was written for sequence element %d", s.count-1)) + 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("vcffi: sequence element %d was never completed", s.count-1)) + 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 element fully -// (one channel, containers Ended) before calling Elem again. +// 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() @@ -318,22 +368,25 @@ func (s *SeqEncoder) Elem() Encoder { return Encoder{st: s.st, depth: s.depth, done: &s.childDone} } -// End finalizes the sequence, writing its element count. +// 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. // -// Error contract (deliberate, frozen): End returns the first error recorded -// anywhere in the whole encode so far — not one scoped to this sequence. A -// nested container's End can therefore surface an error caused elsewhere in -// the tree. Errors are sticky (later channel calls no-op), so an -// EncryptValue implementation may chain writes without checking and return -// the outermost End; inspecting intermediate errors for *which* slot failed -// is not part of the contract — the error text names the slot instead. +// 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 itself is one completed value in the enclosing slot. + // The sequence is one complete value in the slot it was written + // into. if s.done != nil { *s.done++ } @@ -341,55 +394,66 @@ func (s *SeqEncoder) End() error { return err } -// MapEncoder records the entries of a map. The entry count is back-patched -// into the reserved length slot at End. +// 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 enclosing slot's completion counter (see Encoder.done); - // End increments it — the map is one value in its parent's slot. + // 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 mirrors SeqEncoder.childDone: completions of this map's own - // entry slots. Field and End verify childDone == count, so a key whose - // value was skipped, left as an un-Ended container, or written twice - // fails at encode time — otherwise the wire shifts and the next key - // parses as the missing value, surfacing only as ErrMalformed at decode. + // 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 most recent Field key, kept so contract violations name - // the key whose value slot misbehaved. + // 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 rejects duplicate keys at encode time. Reflection over a Go map - // cannot produce duplicates, but encodeStruct can (a vc tag colliding - // with another field's effective name) and a hand-written Encryptable - // can; without this check the collision only surfaces after the - // plaintext has crossed the FFI boundary, as the ciphertext decoder's - // opaque ErrMalformed naming neither the struct nor the key. + // 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 verifies the previous entry's value slot completed exactly once. +// 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("vcffi: more than one value was written for key %q", m.lastKey)) + 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("vcffi: value for key %q was never completed", m.lastKey)) + m.st.fail(fmt.Errorf("frame: no complete value was written for key %q", m.lastKey)) } } -// Field writes an entry key and returns an Encoder for its value. Write the -// value fully (one channel, containers Ended) before calling Field again. -// Keys are UTF-8 validated; insertion order is preserved on the wire. +// 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("vcffi: object key is not valid UTF-8")) + 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("vcffi: duplicate key %q in map encoding", key)) + 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 { @@ -405,16 +469,16 @@ func (m *MapEncoder) Field(key string) Encoder { return Encoder{st: m.st, depth: m.depth, done: &m.childDone} } -// End finalizes the map, writing its entry count. Same error contract as -// SeqEncoder.End: the first error of the whole encode, not one scoped to -// this map. +// 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 itself is one completed value in the enclosing slot. + // The map is one complete value in the slot it was written into. if m.done != nil { *m.done++ } @@ -427,61 +491,63 @@ func patchLen(st *encState, off, count int) error { return st.err } if count < 0 || uint64(count) > maxUint32 { - st.fail(fmt.Errorf("vcffi: item count %d out of range", count)) + 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 into the value transport form a wasm guest expects: the -// encode counterpart of [Unmarshal], and the path a binding's Encrypt takes. +// 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 paths always write exactly one value; only an - // Encryptable can leave the root empty (or an un-Ended container) or - // write more than once. + // 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("vcffi: encode must complete exactly one root value, completed %d", root) + 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 following encoding/json-style rules, but -// consulting the Encryptable interface first: +// 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: // -// - a value implementing Encryptable uses its EncryptValue; -// - nil → Null; -// - bool → Bool; -// - int8/int16/int32 → Int8/Int16/Int32; -// - int/int64 → Int64; -// - uint8/uint16/uint32 → UInt8/UInt16/UInt32; -// - uint/uint64/uintptr → UInt64; -// - float32 → Float32; -// - float64 → Float64; -// - string → String; -// - []byte → Bytes; -// - slices/arrays → Seq; -// - map[string]T → Map, keys SORTED for determinism; -// - structs → Map by field name, honoring `vc:"name"` -// tags (`vc:"-"` skips a field; options after a comma, such as the -// storage profile's `,default`, do not change the name), in -// declaration order; -// - pointers → dereferenced; a nil pointer → a typed -// null if its element type is fixed width (see [fixedTypeOf]), Null -// otherwise; -// - vcvalue.TypedNull → a typed null of its type. +// - 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]. // -// Map keys are sorted because Go map iteration order is randomized; -// sorting makes the encrypted structure deterministic. Struct fields keep -// declaration order. +// 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 writing enc, so it composes: -// an Encryptable can delegate a sub-value with vcffi.Encode(m.Field(k), x). +// 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 @@ -505,36 +571,37 @@ func encodeAny(enc Encoder, v any) { encodeReflect(enc, reflect.ValueOf(v)) } -// interceptMarkers handles the marker types both dispatchers (encodeAny for -// interface values, encodeReflect for values reached through reflection) -// must special-case before any reflection sees them. Returns true when v was -// fully handled. +// 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. // -// - vcvalue.Plain is the explicit passthrough opt-in; checked before Encryptable -// and the struct arm so it is never mistaken for a plain struct. -// - vcvalue.Object is decode-only in spirit, but a decrypt-then-re-encrypt flow -// legitimately feeds it back in; without interception the reflect slice -// arm would encode it as a SEQ of {Key,Value} structs, silently changing -// the record's structure. -// - Encryptable hands control to the user type — except a typed nil -// pointer, which still satisfies the assertion but would dereference nil -// in typical implementations; it encodes as Null like every other nil, -// or as a typed null when the type declares its width (FixedWidth). +// 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 e, ok := v.(Encryptable); ok { - if ev := reflect.ValueOf(e); ev.Kind() == reflect.Pointer && ev.IsNil() { - if t, ok := fixedTypeOf(ev.Type()); ok { - enc.TypedNull(t) - } else { - enc.Null() - } + if x, ok := v.(Encryptable); ok { + if ev := reflect.ValueOf(v); ev.Kind() == reflect.Pointer && ev.IsNil() { + enc.Null() return true } - if err := e.EncryptValue(enc); err != nil { + if err := x.EncryptValue(enc); err != nil { enc.st.fail(err) } return true @@ -542,9 +609,9 @@ func interceptMarkers(enc Encoder, v any) bool { return false } -// encodeObject re-encodes a decoded vcvalue.Object with object framing, preserving -// its field order (vcvalue.Object exists precisely to preserve wire order). -func encodeObject(enc Encoder, o vcvalue.Object) { +// 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) @@ -560,9 +627,10 @@ func encodeReflect(enc Encoder, rv reflect.Value) { enc.Null() return } - // Re-check the explicit markers for values reached through reflection - // (struct fields, slice elements, map values). vcvalue.Plain is itself a struct, - // so it must be intercepted before the reflect.Struct arm below. + // 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 } @@ -584,10 +652,10 @@ func encodeReflect(enc Encoder, rv reflect.Value) { encodeSeq(enc, rv) case reflect.Array: if rv.Type().Elem().Kind() == reflect.Uint8 { - // Byte arrays are one Bytes leaf, matching the slice arm above - // and Rust's single-leaf [u8; N] — element-wise encoding would - // seal N separate leaves and produce a ciphertext shape no other - // producer emits. + // 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) @@ -600,29 +668,32 @@ func encodeReflect(enc Encoder, rv reflect.Value) { encodeStruct(enc, rv) case reflect.Pointer, reflect.Interface: if rv.IsNil() { - // A nil pointer still has its element type, so an absent - // fixed-width value is padded like Rust's Option. A nil - // interface has no type to go by. + // 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 t, ok := fixedTypeOf(rv.Type()); ok { - enc.TypedNull(t) + } else if null := typedNullOf(rv.Type()); null != nil { + enc.typedNull(null) } else { enc.Null() } return } - // Charge the dereference against the shared depth budget: it writes - // no container framing, so without this a pointer cycle (x = &x) - // would recurse to stack overflow instead of failing cleanly. + // 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 } - // Same slot: the dereferenced value completes the pointer's counter. + // 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("vcffi: cannot encode value of kind %s", rv.Kind())) + enc.st.fail(fmt.Errorf("frame: cannot encode value of kind %s", rv.Kind())) } } @@ -636,12 +707,12 @@ func encodeSeq(enc Encoder, rv reflect.Value) { func encodeMap(enc Encoder, rv reflect.Value) { if rv.Type().Key().Kind() != reflect.String { - enc.st.fail(fmt.Errorf("vcffi: map keys must be strings, got %s", rv.Type().Key())) + enc.st.fail(fmt.Errorf("frame: map keys must be strings, got %s", rv.Type().Key())) return } keys := rv.MapKeys() - // Sort keys: Go map iteration is randomized; sorting makes the encrypted - // structure deterministic across encodes of an equal map. + // 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 { @@ -652,8 +723,9 @@ func encodeMap(enc Encoder, rv reflect.Value) { func encodeStruct(enc Encoder, rv reflect.Value) { t := rv.Type() - // Named as the storage profile names them: `vc:"name"`, options after - // a comma, `vc:"-"` skipped, an unknown option refused. + // 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) @@ -669,182 +741,169 @@ func encodeStruct(enc Encoder, rv reflect.Value) { encodeReflect(m.Field(f.name), rv.Field(f.index)) encoded++ } - // A struct whose every field is unexported (time.Time is the canonical - // case) would seal as an empty map and the payload would be gone with no - // error at either end — the exact hazard the NAPI layer's - // ensure_plain_object guards. An all-`vc:"-"` struct is left alone: the - // caller asked for the empty encoding explicitly. + // 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( - "vcffi: struct %s has no exported fields to encode — implement Encryptable to control its sealing", t)) + "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 how interceptMarkers writes a type it handles by exact type, -// and the fixed-width type of its typed null, if it has one (zero if not). -// One table for both, so a new marker type cannot be written one way and -// padded, or not, another. +// 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 { - fixed vcvalue.FixedType + null []byte encode func(Encoder, any) } -// numeric is how encodeReflect writes an int, uint or float kind, and the -// fixed-width type of its typed null: the same one-table rule as marker. +// 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 { - fixed vcvalue.FixedType + null []byte encode func(Encoder, reflect.Value) } var ( - encryptableType = reflect.TypeOf((*Encryptable)(nil)).Elem() - fixedWidthType = reflect.TypeOf((*FixedWidth)(nil)).Elem() - float32Type = reflect.TypeOf(float32(0)) + float32Type = reflect.TypeOf(float32(0)) - // markers is filled in init: Plain and Object encode by calling back - // into encodeAny, which reads the table. + // 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: {vcvalue.TypeInt8, func(e Encoder, rv reflect.Value) { e.Int8(int8(rv.Int())) }}, - reflect.Int16: {vcvalue.TypeInt16, func(e Encoder, rv reflect.Value) { e.Int16(int16(rv.Int())) }}, - reflect.Int32: {vcvalue.TypeInt32, func(e Encoder, rv reflect.Value) { e.Int32(int32(rv.Int())) }}, - reflect.Int: {vcvalue.TypeInt64, func(e Encoder, rv reflect.Value) { e.Int64(rv.Int()) }}, - reflect.Int64: {vcvalue.TypeInt64, func(e Encoder, rv reflect.Value) { e.Int64(rv.Int()) }}, - reflect.Uint8: {vcvalue.TypeUint8, func(e Encoder, rv reflect.Value) { e.UInt8(uint8(rv.Uint())) }}, - reflect.Uint16: {vcvalue.TypeUint16, func(e Encoder, rv reflect.Value) { - e.UInt16(uint16(rv.Uint())) + 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: {vcvalue.TypeUint32, func(e Encoder, rv reflect.Value) { - e.UInt32(uint32(rv.Uint())) + reflect.Uint32: {nullOf(tagUint32), func(e Encoder, rv reflect.Value) { + e.Uint32(uint32(rv.Uint())) }}, - // Every unsigned word-or-wider kind keeps its unsigned identity as - // UInt64 (no fit-check: a bare uint always maps to UINT64). - reflect.Uint: {vcvalue.TypeUint64, func(e Encoder, rv reflect.Value) { e.UInt64(rv.Uint()) }}, - reflect.Uint64: {vcvalue.TypeUint64, func(e Encoder, rv reflect.Value) { e.UInt64(rv.Uint()) }}, - reflect.Uintptr: {vcvalue.TypeUint64, func(e Encoder, rv reflect.Value) { e.UInt64(rv.Uint()) }}, - reflect.Float32: {vcvalue.TypeFloat32, func(e Encoder, rv reflect.Value) { - // rv.Float() widens to float64, and the hardware widening sets - // the quiet bit of a signaling NaN. Converting to the built-in - // float32 instead copies the bits (reflect special-cases float32 - // to float32, Go issue 36400), so a named float32 type keeps - // them too. Only a value that cannot be read as an interface - // falls back to widening. + // 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: {vcvalue.TypeFloat64, func(e Encoder, rv reflect.Value) { e.Float64(rv.Float()) }}, + reflect.Float64: {nullOf(tagFloat64), func(e Encoder, rv reflect.Value) { e.Float64(rv.Float()) }}, } - // fixedTypes caches fixedTypeOf by pointer type: every nil pointer of a - // record type would otherwise pay its reflection again. - fixedTypes sync.Map + // 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(vcvalue.Int128{}): {vcvalue.TypeInt128, func(e Encoder, v any) { - e.Int128(v.(vcvalue.Int128)) + reflect.TypeOf(value.Int128{}): {nullOf(tagInt128), func(e Encoder, v any) { + e.Int128(v.(value.Int128)) }}, - reflect.TypeOf(vcvalue.Uint128{}): {vcvalue.TypeUint128, func(e Encoder, v any) { - e.UInt128(v.(vcvalue.Uint128)) + reflect.TypeOf(value.Uint128{}): {nullOf(tagUint128), func(e Encoder, v any) { + e.Uint128(v.(value.Uint128)) }}, - reflect.TypeOf(vcvalue.Date{}): {vcvalue.TypeDate, func(e Encoder, v any) { - e.Date(v.(vcvalue.Date)) + reflect.TypeOf(value.Date{}): {nullOf(tagDate), func(e Encoder, v any) { + e.Date(v.(value.Date)) }}, - reflect.TypeOf(time.Time{}): {vcvalue.TypeTimestamp, func(e Encoder, v any) { + reflect.TypeOf(time.Time{}): {nullOf(tagTimestamp), func(e Encoder, v any) { e.Timestamp(v.(time.Time)) }}, - reflect.TypeOf(vcvalue.Timestamp{}): {vcvalue.TypeTimestamp, func(e Encoder, v any) { - e.TimestampParts(v.(vcvalue.Timestamp)) + reflect.TypeOf(value.Timestamp{}): {nullOf(tagTimestamp), func(e Encoder, v any) { + e.TimestampParts(v.(value.Timestamp)) }}, - reflect.TypeOf(vcvalue.Decimal{}): {vcvalue.TypeDecimal, func(e Encoder, v any) { - e.Decimal(v.(vcvalue.Decimal)) + reflect.TypeOf(value.Decimal{}): {nullOf(tagDecimal), func(e Encoder, v any) { + e.Decimal(v.(value.Decimal)) }}, - reflect.TypeOf(vcvalue.UUID{}): {vcvalue.TypeUUID, func(e Encoder, v any) { - e.UUID(v.(vcvalue.UUID)) + reflect.TypeOf(value.UUID{}): {uuidNull, func(e Encoder, v any) { + e.UUID(v.(value.UUID)) }}, - // A tagged value's physical type is in the value, not the type. - reflect.TypeOf(vcvalue.Tagged{}): {0, func(e Encoder, v any) { e.Tagged(v.(vcvalue.Tagged)) }}, - reflect.TypeOf(vcvalue.TypedNull{}): {0, func(e Encoder, v any) { - e.TypedNull(v.(vcvalue.TypedNull).Type) + // 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(vcvalue.Plain{}): {0, func(e Encoder, v any) { - encodeAny(e.Passthrough(), v.(vcvalue.Plain).V) - }}, - reflect.TypeOf(vcvalue.Object{}): {0, func(e Encoder, v any) { - encodeObject(e, v.(vcvalue.Object)) + reflect.TypeOf(value.Object{}): {nil, func(e Encoder, v any) { + encodeObject(e, v.(value.Object)) }}, } } -// fixedAnswer is what fixedTypeOf caches: whether the type has a fixed-width -// type at all, and which. A type declared through FixedWidth is kept even -// when it is invalid, so that the encode fails instead of writing the plain -// null in its place. -type fixedAnswer struct { - ft vcvalue.FixedType - has bool -} - -// fixedTypeOf is the fixed-width type a pointer of type t points at, through -// any number of pointers, when encodeReflect writes every value of it with -// one fixed-width tag: the int, uint and float kinds (a named type over one -// included) and the fixed-width marker types, exactly (a named type over a -// marker is a struct to reflection, written field by field). A type that -// implements Encryptable chooses its own encoding, which may not be fixed -// width, so it has none unless it says so through FixedWidth. -func fixedTypeOf(t reflect.Type) (vcvalue.FixedType, bool) { - if cached, ok := fixedTypes.Load(t); ok { - a := cached.(fixedAnswer) - return a.ft, a.has - } - var a fixedAnswer +// 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 that points at itself (type P *P) never reaches a - // non-pointer, so the walk is bounded by the same depth budget that - // bounds a value cycle. Past it the type has no fixed width. + // 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 { - fixedTypes.Store(t, a) - return 0, false + typedNulls.Store(t, null) + return nil } elem = elem.Elem() } - switch { - case elem.Implements(fixedWidthType): - a = fixedAnswer{zeroValueOf(elem).Interface().(FixedWidth).FixedType(), true} - case elem.Implements(encryptableType): - // Its encoding is its own. - default: + if !elem.Implements(encryptableType) { if m, ok := markers[elem]; ok { - a.ft = m.fixed + null = m.null } else { - a.ft = numericKinds[elem.Kind()].fixed + null = numericKinds[elem.Kind()].null } - a.has = a.ft != 0 - } - fixedTypes.Store(t, a) - return a.ft, a.has -} - -// zeroValueOf is a zero value of t that a method can be called on: for a -// pointer type, a pointer to a zero value rather than nil, so a method with -// a value receiver does not dereference nil. -func zeroValueOf(t reflect.Type) reflect.Value { - if t.Kind() == reflect.Pointer { - return reflect.New(t.Elem()) } - return reflect.Zero(t) + typedNulls.Store(t, null) + return null } -// interfaceOf is rv.Interface(), or nil where reflection forbids it -// (values reached through unexported fields). +// 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 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 index e3f71620a..2534bb845 100644 --- a/languages/golang/encrypt/frame/fuzz_test.go +++ b/languages/golang/encrypt/frame/fuzz_test.go @@ -1,4 +1,4 @@ -package vcffi +package frame import ( "bytes" @@ -7,25 +7,35 @@ import ( "encoding/hex" "encoding/json" "math/big" - "os" "slices" "testing" ) -// Unmarshal and UnmarshalCipherText are the package's entire hostile-input -// surface: arbitrary bytes from the wasm boundary or a database column. The -// fuzz targets assert the decoders never panic, and that anything they accept -// re-encodes to the same bytes (see requireCanonical) — errors are fine, -// crashes and drift are not. Run in CI as ordinary tests over the seed corpus, -// nightly as real fuzzing (.github/workflows/fuzz.yml), and with -// `go test -fuzz` locally for exploration. +// 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 seeds a fuzz target with every valid and malformed vector in -// the shared value corpus, so the fuzzer starts from each scalar tag. +// 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, err := os.ReadFile("../../../testdata/value-conformance.json") - if err != nil { - f.Fatal(err) + 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 } @@ -42,9 +52,9 @@ func addCorpusSeeds(f *testing.F, wrap func([]byte) []byte) { } f.Add(wrap(raw)) } - // The malformed ciphertext transports are seeds as they are: the - // ciphertext targets must refuse them, and the value targets must not - // read them as a value either. + // 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 { @@ -54,16 +64,20 @@ func addCorpusSeeds(f *testing.F, wrap func([]byte) []byte) { } } -// canonicalForm is what an accepted value encoding re-encodes as. Four -// things may legitimately change, and nothing else: an Undefined tag (0x01) -// comes back as Null (0x00), Go's documented projection; a typed null comes -// back as Null too, as Rust's frame writer writes it; a decimal negative -// zero comes back as zero with its scale kept (ADR 0001); and a timestamp in -// the 0xF3 envelope (seconds, milliseconds or microseconds) comes back in -// the shorthand nanosecond form, because Go reads it as a time.Time. The -// walker follows the transport format independently of the decoder, so a -// walk that falls out of step with it produces the wrong bytes and fails -// requireCanonical rather than passing. +// 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 @@ -86,8 +100,9 @@ func canonicalValue(r *reader, out *[]byte) { case tagDecimal: b, _ := r.take(16) b = bytes.Clone(b) - // flags(4) then the coefficient(12): a set sign bit over a zero - // coefficient is a negative zero, read back as zero. + // 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 } @@ -134,8 +149,8 @@ func canonicalValue(r *reader, out *[]byte) { *out = append(*out, tag) canonicalValue(r, out) case tagTypedNull: - // The header names the type, which fixes the padding; it all comes - // back as the plain null. + // 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 { @@ -150,15 +165,16 @@ func canonicalValue(r *reader, out *[]byte) { _, _ = r.take(width - 1) *out = append(*out, tagNull) default: - // Null, booleans and the fixed-width extended scalars. + // Null, the booleans, and the fixed-width extended scalars. b, _ := r.take(fixedWidth(tag)) *out = append(append(*out, tag), b...) } } -// shorthandTimestamp reads the int the envelope carries and writes the -// instant as the shorthand Timestamp tag: i64 seconds then u32 nanoseconds. -// Follows the int encodings by width rather than the decoder. +// 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 @@ -205,13 +221,15 @@ func signedLittle(b []byte) *big.Int { return v } -// cipherCanonicalForm is canonicalForm for an accepted ciphertext tree, -// where a value can only appear inside passthrough nodes. One more thing -// may change here: the entries of a map come back sorted by key. Rust -// writes a map's entries in the order it holds them (a struct's field -// order, say), while Go reads a map into map[string]any, which keeps no -// order, and writes it back with the keys sorted. Entry order is not -// authenticated, so the decoder accepts either and the walker sorts. +// 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 @@ -237,8 +255,9 @@ func cipherCanonicalForm(data []byte) []byte { start := r.pos n, _ := r.count() out = append(append(out, tag), r.buf[start:r.pos]...) - // Each entry is walked onto out, then cut back off and kept - // aside, so the entries can be written in key order. + // 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 @@ -253,7 +272,8 @@ func cipherCanonicalForm(data []byte) []byte { entries = append(entries, entry{key, bytes.Clone(out[mark:])}) out = out[:mark] } - // The same order as encodeCipherText's slices.Sort over the keys. + // 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...) @@ -268,7 +288,7 @@ func cipherCanonicalForm(data []byte) []byte { } func FuzzUnmarshal(f *testing.F) { - // Seeds: one of each node kind, plus known-hostile shapes. + // 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 @@ -292,7 +312,8 @@ func FuzzUnmarshal(f *testing.F) { t.Fatalf("accepted decode failed to re-encode: %v (value %#v)", err, v) } requireCanonical(t, data, out, canonicalForm(data)) - // The re-encoding is canonical, so it must be a fixed point. + // 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) @@ -305,22 +326,22 @@ func FuzzUnmarshal(f *testing.F) { 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}) // the retired ctNone: malformed + 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 clear passthrough nodes inside a ciphertext. + // 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(VCValueLeaves(), data) + v, err := UnmarshalCipherText(testLeaves(), data) if err != nil { return } - out, err := MarshalCipherText(VCValueLeaves(), v) + out, err := MarshalCipherText(testLeaves(), v) if err != nil { t.Fatalf("accepted ciphertext decode failed to re-encode: %v (value %#v)", err, v) } @@ -328,9 +349,13 @@ func FuzzUnmarshalCipherText(f *testing.F) { }) } -// The walkers decide what may legitimately change, so pin that they rewrite -// nested Undefined tags, negative-zero signs, envelope timestamps and -// ciphertext map entry order and nothing else. +// 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} 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 index 449cda13b..ad5e20ae1 100644 --- a/languages/golang/encrypt/frame/scalars.go +++ b/languages/golang/encrypt/frame/scalars.go @@ -1,14 +1,14 @@ -package vcffi +package frame import ( "encoding/binary" "time" - "github.com/cipherstash/vitaminc/bindings/go/vcvalue" + "github.com/cipherstash/stack/languages/golang/encrypt/value" ) func (e Encoder) scalar(tag byte, payload []byte) { - if e.st.err != nil { + if e.dead() { return } e.push(tag) @@ -16,15 +16,15 @@ func (e Encoder) scalar(tag byte, payload []byte) { 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 vcvalue.Int128) { e.scalar(tagInt128, v[:]) } -func (e Encoder) UInt128(v vcvalue.Uint128) { e.scalar(tagUint128, v[:]) } +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 vcvalue.Date) { - if e.st.err != nil { +func (e Encoder) Date(v value.Date) { + if e.dead() { return } days, err := v.DaysFromCE() @@ -35,12 +35,13 @@ func (e Encoder) Date(v vcvalue.Date) { e.scalar(tagDate, binary.LittleEndian.AppendUint32(nil, uint32(days))) } -// Timestamp keeps the instant and nanoseconds, discarding location and monotonic metadata. +// 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(vcvalue.Timestamp{Seconds: v.Unix(), Nanoseconds: uint32(v.Nanosecond())}) + e.TimestampParts(value.Timestamp{Seconds: v.Unix(), Nanoseconds: uint32(v.Nanosecond())}) } -func (e Encoder) TimestampParts(v vcvalue.Timestamp) { - if e.st.err != nil { +func (e Encoder) TimestampParts(v value.Timestamp) { + if e.dead() { return } if err := v.Validate(); err != nil { @@ -52,10 +53,10 @@ func (e Encoder) TimestampParts(v vcvalue.Timestamp) { e.scalar(tagTimestamp, b) } -// Decimal records a finite decimal. A zero is written without a sign, -// whatever the sign of the value given (ADR 0001). -func (e Encoder) Decimal(v vcvalue.Decimal) { - if e.st.err != nil { +// 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 { @@ -72,40 +73,45 @@ func (e Encoder) Decimal(v vcvalue.Decimal) { e.scalar(tagDecimal, b) } -// UUID records sixteen bytes under the Uuid logical type, in the 0xF3 -// envelope over a bytes scalar. -func (e Encoder) UUID(u vcvalue.UUID) { - if e.st.err != nil { +// 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 a UUID starts with, and the header of -// a UUID's typed null: the Uuid logical type, no parameter, over bytes. +// 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 under a logical id this build does not -// know, in the 0xF3 envelope: what Unmarshal produced for such a value, so -// it goes back out unchanged. An id this build knows, or a value that is -// not a physical scalar, is refused. -func (e Encoder) Tagged(t vcvalue.Tagged) { - if e.st.err != nil { +// 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(vcvalue.ErrInvalidTagged) + e.st.fail(value.ErrInvalidTagged) return } e.push(tagEnvelope, t.ID, t.Param) if !e.physical(t.V) { - e.st.fail(vcvalue.ErrInvalidTagged) + e.st.fail(value.ErrInvalidTagged) } } -// physical writes v through its scalar channel, for the kinds the envelope -// may carry, and reports whether v was one of them. +// 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: @@ -115,28 +121,28 @@ func (e Encoder) physical(v any) bool { case int8: e.Int8(x) case uint8: - e.UInt8(x) + e.Uint8(x) case int16: e.Int16(x) case uint16: - e.UInt16(x) + e.Uint16(x) case int32: e.Int32(x) case uint32: - e.UInt32(x) + e.Uint32(x) case int64: e.Int64(x) case uint64: - e.UInt64(x) + e.Uint64(x) case int: - // As Encode writes int and uint everywhere else. + // Encode writes an int and a uint the same way. e.Int64(int64(x)) case uint: - e.UInt64(uint64(x)) - case vcvalue.Int128: + e.Uint64(uint64(x)) + case value.Int128: e.Int128(x) - case vcvalue.Uint128: - e.UInt128(x) + case value.Uint128: + e.Uint128(x) case float32: e.Float32(x) case float64: @@ -166,19 +172,19 @@ func decodeScalar(r *reader, tag byte) (any, error) { case tagUint16: return binary.LittleEndian.Uint16(b), nil case tagInt128: - return vcvalue.Int128(b), nil + return value.Int128(b), nil case tagUint128: - return vcvalue.Uint128(b), nil + return value.Uint128(b), nil case tagDate: - d, err := vcvalue.DateFromDaysCE(int32(binary.LittleEndian.Uint32(b))) + d, err := value.DateFromDaysCE(int32(binary.LittleEndian.Uint32(b))) if err != nil { return nil, ErrMalformed } return d, nil case tagTimestamp: - // A leap second (nanoseconds of one billion or more) has no count - // since the epoch and is refused by Validate (ADR 0001). - t := vcvalue.Timestamp{Seconds: int64(binary.LittleEndian.Uint64(b)), Nanoseconds: binary.LittleEndian.Uint32(b[8:])} + // 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 } @@ -188,20 +194,21 @@ func decodeScalar(r *reader, tag byte) (any, error) { if flags&0x7f00ffff != 0 { return nil, ErrMalformed } - d := vcvalue.Decimal{Scale: uint8(flags >> 16), Negative: flags>>31 != 0} + 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 (ADR 0001). + // A negative zero reads as zero, with its scale kept. return d.Normalized(), nil default: return nil, ErrMalformed } } -// fixedWidth is the payload width of a fixed-width scalar tag, or zero for -// a tag whose payload is not fixed (or that has none). +// 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: @@ -220,8 +227,10 @@ func fixedWidth(tag byte) int { return 0 } -// numericTag reports whether tag is a plain int or float: what a typed null -// in the envelope may ride on under a timestamp unit or an unknown id. +// 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, @@ -233,60 +242,48 @@ func numericTag(tag byte, floats bool) bool { return false } -// fixedTags is the tag each FixedType is written with, all but the UUID, -// whose header is uuidEnvelope over tagBytes. -var fixedTags = map[vcvalue.FixedType]byte{ - vcvalue.TypeInt8: tagInt8, - vcvalue.TypeInt16: tagInt16, - vcvalue.TypeInt32: tagInt32, - vcvalue.TypeInt64: tagInt64, - vcvalue.TypeInt128: tagInt128, - vcvalue.TypeUint8: tagUint8, - vcvalue.TypeUint16: tagUint16, - vcvalue.TypeUint32: tagUint32, - vcvalue.TypeUint64: tagUint64, - vcvalue.TypeUint128: tagUint128, - vcvalue.TypeFloat32: tagFloat32, - vcvalue.TypeFloat64: tagFloat64, - vcvalue.TypeDate: tagDate, - vcvalue.TypeTimestamp: tagTimestamp, - vcvalue.TypeDecimal: tagDecimal, +// 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)) } -// TypedNull records an absent value of a fixed-width type: a null padded to -// the length of a value of t, so the two seal to the same length. Encode -// writes one for a nil pointer to a fixed-width type; this channel is for a -// caller that knows the type some other way. An invalid t fails the -// encode. -func (e Encoder) TypedNull(t vcvalue.FixedType) { - if e.st.err != nil { - return - } - if !t.Valid() { - e.st.fail(vcvalue.ErrInvalidFixedType) +// 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 } - var header []byte - var payload int - if t == vcvalue.TypeUUID { - header, payload = append(uuidEnvelope[:], tagBytes), len(vcvalue.UUID{}) - } else { - tag := fixedTags[t] - header, payload = []byte{tag}, fixedWidth(tag) - } - e.push(tagTypedNull) - e.push(header...) - // One byte of the value's length went to tagTypedNull. - e.push(make([]byte, payload-1)...) + e.push(null...) e.complete() } -// decodeTypedNull reads a typed null after its tag, as strictly as the Rust -// codec does, so every absence has one encoding: a header a value of some -// fixed-width type starts with, then exactly the zero padding to that -// value's length. It decodes as nil. A frame is never sealed, so the padding -// means nothing once the value is out, and Rust's frame writer writes the -// plain null for it too. +// 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 { @@ -302,7 +299,8 @@ func decodeTypedNull(r *reader) (any, error) { id, param, physical := h[0], h[1], h[2] switch id { case logicalTimestamp: - // The nanosecond unit has the shorthand Timestamp tag. + // A timestamp in nanoseconds uses tagTimestamp, so an envelope + // must not name that unit. if param > unitMicros || !numericTag(physical, false) { return nil, ErrMalformed } @@ -315,7 +313,8 @@ func decodeTypedNull(r *reader) (any, error) { case 0, logicalUndefined, logicalDate, logicalDecimal: return nil, ErrMalformed default: - // A logical id this build does not know, over an int or float. + // An id that this version does not know. The scalar must be an + // integer or a float. if !numericTag(physical, true) { return nil, ErrMalformed } diff --git a/languages/golang/encrypt/frame/scalars_test.go b/languages/golang/encrypt/frame/scalars_test.go index 55d56f56f..4f6aa4a66 100644 --- a/languages/golang/encrypt/frame/scalars_test.go +++ b/languages/golang/encrypt/frame/scalars_test.go @@ -1,29 +1,30 @@ -package vcffi +package frame import ( "encoding/hex" "errors" - "github.com/cipherstash/vitaminc/bindings/go/vcvalue" "reflect" "strings" "testing" "time" + + "github.com/cipherstash/stack/languages/golang/encrypt/value" ) func TestScalarHostEncoding(t *testing.T) { - signed, err := vcvalue.ParseInt128("-170141183460469231731687303715884105728") + signed, err := value.ParseInt128("-170141183460469231731687303715884105728") if err != nil { t.Fatal(err) } - unsigned, err := vcvalue.ParseUint128("340282366920938463463374607431768211455") + unsigned, err := value.ParseUint128("340282366920938463463374607431768211455") if err != nil { t.Fatal(err) } - decimal, err := vcvalue.ParseDecimal("1.50") + decimal, err := value.ParseDecimal("1.50") if err != nil { t.Fatal(err) } - uuid, err := vcvalue.ParseUUID("123e4567-e89b-12d3-a456-426614174000") + uuid, err := value.ParseUUID("123e4567-e89b-12d3-a456-426614174000") if err != nil { t.Fatal(err) } @@ -33,14 +34,14 @@ func TestScalarHostEncoding(t *testing.T) { }{ {int8(-128), "0c80"}, {uint8(255), "0dff"}, {int16(-32768), "0e0080"}, {uint16(65535), "0fffff"}, {signed, "1000000000000000000000000000000080"}, {unsigned, "11ffffffffffffffffffffffffffffffff"}, - {vcvalue.Date{Year: 1, Month: 1, Day: 1}, "1201000000"}, + {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"}, - {vcvalue.Tagged{ID: 200, Param: 9, V: uint32(34)}, "f3c8090622000000"}, - {vcvalue.Tagged{ID: 255, Param: 0, V: nil}, "f3ff0000"}, - {vcvalue.Tagged{ID: 6, Param: 1, V: "hi"}, "f306010a020000006869"}, + {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) @@ -54,7 +55,7 @@ func TestScalarHostEncoding(t *testing.T) { if err != nil || !reflect.DeepEqual(decoded, tc.value) { t.Fatalf("%T: got %#v: %v", tc.value, decoded, err) } - // The intercept also applies through pointers, fields and interfaces. + // 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) @@ -67,16 +68,16 @@ func TestInvalidScalarHostEncoding(t *testing.T) { value any err error }{ - {vcvalue.Date{Year: 2023, Month: 2, Day: 29}, vcvalue.ErrInvalidDate}, - {vcvalue.Timestamp{Seconds: 0, Nanoseconds: 1000000000}, vcvalue.ErrInvalidTimestamp}, - {time.Date(10000, 1, 1, 0, 0, 0, 0, time.UTC), vcvalue.ErrInvalidTimestamp}, - {time.Date(-9999, 1, 1, 0, 0, 0, 0, time.UTC), vcvalue.ErrInvalidTimestamp}, - {vcvalue.Decimal{Scale: 29}, vcvalue.ErrInvalidDecimal}, + {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. - {vcvalue.Tagged{ID: 5, V: []byte{1}}, vcvalue.ErrInvalidTagged}, - {vcvalue.Tagged{ID: 0, V: int8(1)}, vcvalue.ErrInvalidTagged}, - {vcvalue.Tagged{ID: 200, V: []any{int8(1)}}, vcvalue.ErrInvalidTagged}, - {vcvalue.Tagged{ID: 200, V: time.Unix(0, 0)}, vcvalue.ErrInvalidTagged}, + {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) { @@ -85,9 +86,10 @@ func TestInvalidScalarHostEncoding(t *testing.T) { } } -// The envelope's timestamp units decode to time.Time; the nanosecond unit -// has the shorthand tag and is refused in the envelope, as is every other -// envelope the corpus does not already pin. +// 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 @@ -97,8 +99,8 @@ func TestEnvelopeTimestampsDecodeToTime(t *testing.T) { {"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 the wire admits, as an i64 - {"f30300051fb9060fa8ffffff", time.Unix(-377705023201, 0).UTC()}, // the first second the wire admits + {"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, " ", "")) @@ -118,8 +120,8 @@ func TestEnvelopeTimestampsDecodeToTime(t *testing.T) { "f3030305" + "0000000000000000", // nanoseconds: the shorthand tag exists "f3030405" + "0000000000000000", // no such unit "f303010a" + "00000000", // a count that is not an int - "f3030010" + "0000000000000000000000000000ff7f", // out of the wire's range - "f3030005" + "e1d3f2ff3a000000", // one second past the wire's range, as an i64 + "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 } { @@ -137,11 +139,11 @@ func TestEnvelopeTimestampsDecodeToTime(t *testing.T) { // Every integer width is a valid count for an envelope timestamp. func TestEnvelopeTimestampAcceptsEveryIntegerWidth(t *testing.T) { - i128, err := vcvalue.ParseInt128("1") + i128, err := value.ParseInt128("1") if err != nil { t.Fatal(err) } - u128, err := vcvalue.ParseUint128("1") + u128, err := value.ParseUint128("1") if err != nil { t.Fatal(err) } @@ -155,9 +157,9 @@ func TestEnvelopeTimestampAcceptsEveryIntegerWidth(t *testing.T) { } // A decimal negative zero built as a struct literal is written without its -// sign: Go never writes the sign bit of a zero (ADR 0001). +// sign: Go never writes the sign bit of a zero. func TestDecimalNegativeZeroIsWrittenUnsigned(t *testing.T) { - encoded, err := Marshal(vcvalue.Decimal{Negative: true, Scale: 2}) + encoded, err := Marshal(value.Decimal{Negative: true, Scale: 2}) if err != nil { t.Fatal(err) } @@ -166,32 +168,32 @@ func TestDecimalNegativeZeroIsWrittenUnsigned(t *testing.T) { } } -// Every physical scalar travels under an unknown id and reads back as the -// same Tagged value. +// 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 := vcvalue.ParseInt128("-1") + i128, err := value.ParseInt128("-1") if err != nil { t.Fatal(err) } - u128, err := vcvalue.ParseUint128("1") + u128, err := value.ParseUint128("1") if err != nil { t.Fatal(err) } - for _, value := 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 := vcvalue.Tagged{ID: 200, Param: 9, V: value} + 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", value, got, err) + t.Errorf("%T: got %#v, err %v", v, got, err) } } } -// A Go int or uint in a Tagged value is written as Int64 or UInt64, as Encode -// writes it everywhere else, and reads back at that width. +// 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 @@ -201,7 +203,7 @@ func TestTaggedWritesIntAndUintAtSixtyFourBits(t *testing.T) { {-34, "f3c80905deffffffffffffff", int64(-34)}, {uint(34), "f3c809072200000000000000", uint64(34)}, } { - wire, err := Marshal(vcvalue.Tagged{ID: 200, Param: 9, V: tc.value}) + wire, err := Marshal(value.Tagged{ID: 200, Param: 9, V: tc.value}) if err != nil { t.Fatalf("%T: %v", tc.value, err) } @@ -209,7 +211,7 @@ func TestTaggedWritesIntAndUintAtSixtyFourBits(t *testing.T) { t.Errorf("%T: got %s, want %s", tc.value, got, tc.wire) } got, err := Unmarshal(wire) - if want := (vcvalue.Tagged{ID: 200, Param: 9, V: tc.back}); err != nil || !reflect.DeepEqual(got, want) { + 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 index 66c789ffa..d04551af0 100644 --- a/languages/golang/encrypt/frame/storage.go +++ b/languages/golang/encrypt/frame/storage.go @@ -1,4 +1,4 @@ -package vcffi +package frame import ( "cmp" @@ -12,65 +12,85 @@ import ( "strings" "unicode/utf8" - "github.com/cipherstash/vitaminc/bindings/go/vcvalue" + "github.com/cipherstash/stack/languages/golang/encrypt/value" ) -// The storage profile, version 1: a value as one versioned blob, for bytes -// that are kept. It is the Go side of the Rust module -// vitaminc_aead_frame::storage, specified in -// packages/aead-frame/STORAGE.md and pinned by the golden corpus in -// packages/aead-frame/testdata/storage-v1.json. Unlike the rest of this -// package, which is transport, the bytes [MarshalStorage] writes and -// [UnmarshalStorage] reads are a compatibility commitment, shared with Rust. +// 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 this package writes, and the only one it -// reads. +// StorageVersion is the version that this package writes. No other version +// is read. const StorageVersion = 1 -// StorageSome marks a present optional value: StorageSome, then the value. -// Rust writes it for every Some. Go writes it only for a pointer whose -// target is itself written as null, where leaving it out would read back as -// nil: a bare value reads as present into a pointer or a Rust Option, and as -// itself into a plain field, so a Go pointer is read alike in both -// languages, whatever the other side declares. +// 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 starts a map whose keys are nodes: StorageMap, a u32 count, -// then a key and a value for each entry. A Go map is one; a struct is an -// object. +// 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 starts every blob: "VCS", then [StorageVersion]. +// StorageHeader is the four bytes that start every blob: "VCS", then +// [StorageVersion]. var StorageHeader = [4]byte{'V', 'C', 'S', StorageVersion} -// The classes of a storage refusal, the Go side of Rust's -// storage::ErrorKind. Match them with errors.Is. A blob that breaks a rule -// of its version is [ErrMalformed], as transport bytes are. +// 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: shorter than the header, or not starting with "VCS". - ErrNotABlob = errors.New("vcffi: not a storage blob") - // ErrUnsupportedVersion: a blob of a version this package does not - // read. A later release may: the reader needs upgrading, and the blob - // is not corrupt. - ErrUnsupportedVersion = errors.New("vcffi: an unsupported storage version") - // ErrMismatch: a well-formed blob whose value the destination does not - // take: a string where a number was expected, a missing field. - ErrMismatch = errors.New("vcffi: the stored value does not fit the destination") - // ErrUnwritable: a value that cannot be written as a blob: nested too - // deep, a map key that is not an integer, text or bytes, a repeated - // key, a kind with no storage form. - ErrUnwritable = errors.New("vcffi: the value cannot be written as a storage blob") + // 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 a present optional value, as a blob holds it, for a value read -// into an `any`. A pointer is the usual way to write one. +// 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 holds it, for a value read into an -// `any`: its entries in the order they were written, each key an integer, -// a string or []byte. Written, it is a map in that order. +// 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]. @@ -83,35 +103,46 @@ func unwritable(format string, args ...any) error { return fmt.Errorf("%w: "+format, append([]any{ErrUnwritable}, args...)...) } -// MarshalStorage writes v as a version 1 blob: +// MarshalStorage writes v as a version 1 blob. The type of v decides how it +// is written: // -// - nil, a nil interface → null; -// - bool → bool; -// - int8, int16, int32, int64 → that width; int → int64; -// - uint8 … uint64 → that width; uint, uintptr → uint64; -// - vcvalue.Int128, Uint128 → the 128-bit widths; -// - float32, float64 → that width, by its bits; -// - string → text (valid UTF-8 only); -// - []byte, [N]byte → bytes (so a UUID is its 16 bytes); -// - an encoding.TextMarshaler → text (time.Time as RFC 3339); -// - slices, arrays → array; a nil slice is an empty one; -// - map[K]V → map, keys sorted: integers by value, -// text and bytes by their bytes, as a Rust BTreeMap orders them; K is -// an integer, a string, a byte array or a TextMarshaler; -// - structs → object, by field name, honoring -// `vc:"name"` tags (`vc:"-"` skips a field), in declaration order; a -// `vc:"name,default"` field reads as its zero value when a blob does -// not have it; -// - pointers → nil is null, and a non-nil pointer is -// what it points at, as encoding/json writes it; a pointer to a value -// written starting with null or [StorageSome] (a nil pointer or -// interface, [Some], or a pointer to one) is [StorageSome] then that -// value, so every level reads back; -// - [Some], [StorageEntries], vcvalue.Object and []any → as they read. +// - 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. // -// The transport's Encryptable, passthrough (vcvalue.Plain) and logical -// types (vcvalue.Date, Timestamp, Decimal, Tagged, TypedNull) have no -// storage form, and are refused. +// 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 { @@ -133,26 +164,27 @@ func (w *storageWriter) any(v any, depth int) error { return w.reflect(reflect.ValueOf(v), depth) } -// The model's own types, which [storageWriter.model] writes. Int128 and -// Uint128 are [16]byte too, so [byteArray] also leaves them out, for a -// value model cannot box and for the reader. +// 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(vcvalue.Int128{}) - uint128Type = reflect.TypeOf(vcvalue.Uint128{}) + int128Type = reflect.TypeOf(value.Int128{}) + uint128Type = reflect.TypeOf(value.Uint128{}) someType = reflect.TypeOf(Some{}) - objectType = reflect.TypeOf(vcvalue.Object{}) + objectType = reflect.TypeOf(value.Object{}) entriesType = reflect.TypeOf(StorageEntries{}) - plainType = reflect.TypeOf(vcvalue.Plain{}) - dateType = reflect.TypeOf(vcvalue.Date{}) - timestampType = reflect.TypeOf(vcvalue.Timestamp{}) - decimalType = reflect.TypeOf(vcvalue.Decimal{}) - taggedType = reflect.TypeOf(vcvalue.Tagged{}) - typedNullType = reflect.TypeOf(vcvalue.TypedNull{}) + 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 model's own, which have a form -// of their own rather than the one reflection would give them, and reports -// whether it was. Only those types are boxed to be written. +// 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 @@ -162,18 +194,18 @@ func (w *storageWriter) model(rv reflect.Value, depth int) (bool, error) { w.buf = append(w.buf, StorageSome) return true, w.any(rv.Interface().(Some).V, depth+1) case objectType: - return true, w.object(rv.Interface().(vcvalue.Object), depth) + return true, w.object(rv.Interface().(value.Object), depth) case entriesType: return true, w.entries(rv.Interface().(StorageEntries), depth) case int128Type: - x := rv.Interface().(vcvalue.Int128) + x := rv.Interface().(value.Int128) w.buf = append(append(w.buf, tagInt128), x[:]...) return true, nil case uint128Type: - x := rv.Interface().(vcvalue.Uint128) + x := rv.Interface().(value.Uint128) w.buf = append(append(w.buf, tagUint128), x[:]...) return true, nil - case plainType, dateType, timestampType, decimalType, taggedType, typedNullType: + case plainType, dateType, timestampType, decimalType, taggedType: return true, unwritable("%s has no storage form", rv.Type()) } return false, nil @@ -187,8 +219,9 @@ func (w *storageWriter) reflect(rv reflect.Value, depth int) error { w.buf = append(w.buf, tagNull) return nil } - // Checked by type, before a nil pointer is written as null, so a field - // of an Encryptable type is refused whether or not it is set. + // 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()) } @@ -204,13 +237,14 @@ func (w *storageWriter) reflect(rv reflect.Value, depth int) error { } if text, ok, err := marshalText(rv); ok { if err != nil { - return unwritable("%s refused to write itself as text", rv.Type()) + return unwritable("the MarshalText method of %s returned an error", rv.Type()) } return w.text(text) } if k, ok := numericKinds[rv.Kind()]; ok { - // The transport's numeric table writes each kind at the same width - // a blob does: only the framing differs, and there is none here. + // 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 @@ -241,13 +275,16 @@ func (w *storageWriter) reflect(rv reflect.Value, depth int) error { return unwritable("a value of kind %s has no storage form", rv.Kind()) } -// indirect writes what the pointer or interface rv holds: null if it is -// nil, and otherwise what it points at, marked if that starts with null or -// a marker (see [startsOptional]). The marker is a node, and costs a level -// of depth as a reader counts it; a pointer or interface that writes -// nothing of its own costs none, since the blob is no deeper for it. A run -// of those is bounded on its own, so a cycle (p = &p) is refused rather -// than followed forever. +// 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 { @@ -272,13 +309,16 @@ func (w *storageWriter) indirect(rv reflect.Value, depth int) error { } } -// startsOptional reports whether rv is written starting with null or -// [StorageSome]: a nil pointer or interface, [Some], or a pointer or -// interface to one of those. A pointer to such a value is marked, or a -// reader would take that null or marker for the pointer's own, and the -// value would read back one level shorter. A run of pointers longer than a -// blob may nest, a cycle say, is refused when it is written, so it is not -// followed further here. +// 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() { @@ -294,8 +334,9 @@ func startsOptional(rv reflect.Value) bool { return false } -// byteArray reports whether t is [N]byte, a UUID say, written as bytes. -// Int128 and Uint128 are [16]byte too, and are integers. +// 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 } @@ -306,15 +347,16 @@ func arrayBytes(rv reflect.Value) []byte { return b } -// encryptable reports whether t, or a pointer to it, implements -// Encryptable: its fields are not its value, so reflection must not write +// 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 is rv's MarshalText, if its type has one, through a pointer -// to a copy when the method needs one. +// 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() @@ -352,7 +394,9 @@ func (w *storageWriter) bytes(b []byte) error { return nil } -// open writes a container's tag and a count to be patched by close. +// 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 @@ -360,7 +404,7 @@ func (w *storageWriter) open(tag byte) int { func (w *storageWriter) close(at, count int) error { if uint64(count) > maxUint32 { - return unwritable("a container holds too many entries") + return unwritable("a container has too many entries") } binary.LittleEndian.PutUint32(w.buf[at:], uint32(count)) return nil @@ -376,7 +420,7 @@ func (w *storageWriter) array(rv reflect.Value, depth int) error { return w.close(at, rv.Len()) } -func (w *storageWriter) object(o vcvalue.Object, depth int) error { +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 { @@ -390,7 +434,8 @@ func (w *storageWriter) object(o vcvalue.Object, depth int) error { return w.close(at, len(o)) } -// field writes an object's key, refusing one already written. +// 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") @@ -428,30 +473,36 @@ func (w *storageWriter) goStruct(rv reflect.Value, depth int) error { } written++ } - // As in the transport: a struct of only unexported fields (time.Time - // without its MarshalText, say) would be stored as an empty object, and - // its value lost with no error at either end. + // 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 is a struct field as a blob names it. +// 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 fields read as their zero value when a blob lacks them. + // defaulted is true for a field that reads as its zero value when a blob + // does not have it. defaulted bool } -// structFields are t's fields in declaration order, named by their `vc` -// tags, without the ones a `vc:"-"` tag skips. A tag is a name, then -// options after commas: `vc:"age,default"`, or `vc:",default"` to keep the -// field's own name. `default` is the only option; any other is refused, so -// a misspelt one is not quietly ignored. The transport names fields the -// same way. +// 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() { @@ -477,7 +528,7 @@ func structFields(t reflect.Type) ([]storageField, error) { field.defaulted = true case "": default: - return nil, fmt.Errorf("vcffi: field %s of %s has an unknown vc tag option %q", f.Name, t, option) + return nil, fmt.Errorf("frame: field %s of %s has an unknown vc tag option %q", f.Name, t, option) } } } @@ -486,18 +537,25 @@ func structFields(t reflect.Type) ([]storageField, error) { return fields, nil } -// mapKey is a map key written as a node, and what makes two keys the same: -// integers of equal value, whatever their widths, so 1 as a uint8 and 1 as -// an int64 are one key; text and bytes by their bytes, never equal to each -// other or to an integer. Its order is the one keys are written in: by -// kind, integers by value, text and bytes by their bytes. +// 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 a map key's kind, in the order keys of different kinds are -// written in. +// 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 ( @@ -508,10 +566,10 @@ const ( type keyID struct { kind keyKind - // An integer as its sign and its two's-complement 128-bit word. + // For an integer: the sign, and the 128-bit word in two's complement. negative bool hi, lo uint64 - // Text or bytes. + // For text or bytes: the bytes. s string } @@ -528,7 +586,8 @@ func compareKeys(a, b keyID) int { return cmp.Or(cmp.Compare(a.hi, b.hi), cmp.Compare(a.lo, b.lo), cmp.Compare(a.s, b.s)) } -// wideKey is the keyID of a 128-bit integer, from its little-endian word. +// 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), @@ -537,8 +596,8 @@ func wideKey(word []byte, signed bool) keyID { } } -// decodedKeyID is the keyID of a key as the reader decodes it: a Go -// integer, Int128 or Uint128, a string, or bytes. +// 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: @@ -557,9 +616,9 @@ func decodedKeyID(k any) (keyID, bool) { return keyID{lo: uint64(x)}, true case uint64: return keyID{lo: x}, true - case vcvalue.Int128: + case value.Int128: return wideKey(x[:], true), true - case vcvalue.Uint128: + case value.Uint128: return wideKey(x[:], false), true case string: return keyID{kind: keyText, s: x}, true @@ -577,14 +636,14 @@ func signedKey(v int64) keyID { return id } -// keyOf writes a map key as its node. +// 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; its type's MarshalText, if it - // has one, would be called on nil. + // 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()) } @@ -610,7 +669,7 @@ func keyOf(k any) (mapKey, error) { default: if text, ok, err := marshalText(rv); ok { if err != nil { - return mapKey{}, unwritable("a map key of type %s refused to write itself as text", t) + 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 { @@ -648,14 +707,15 @@ func (w *storageWriter) goMap(rv reflect.Value, depth int) error { return err } if _, dup := values[key.id]; dup { - // Two Go keys that write the same key: two texts a - // TextMarshaler spells alike, say. + // 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 map iteration is randomized; sorting makes equal maps equal blobs. + // 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 { diff --git a/languages/golang/encrypt/frame/storage_decode.go b/languages/golang/encrypt/frame/storage_decode.go index 1c5dfe1d3..771a24c5e 100644 --- a/languages/golang/encrypt/frame/storage_decode.go +++ b/languages/golang/encrypt/frame/storage_decode.go @@ -1,4 +1,4 @@ -package vcffi +package frame import ( "encoding" @@ -7,41 +7,49 @@ import ( "reflect" "strconv" - "github.com/cipherstash/vitaminc/bindings/go/vcvalue" + "github.com/cipherstash/stack/languages/golang/encrypt/value" ) -// UnmarshalStorage reads a version 1 blob into the value v points at. +// UnmarshalStorage reads a version 1 blob into the value that v points at. // -// The whole blob is checked first, so a blob of another version, bytes -// that are not a blob, or a malformed body is refused before anything is -// set: [ErrNotABlob], [ErrUnsupportedVersion] or [ErrMalformed]. Then the -// value is read into v by its type, as Rust's serde reads it, which the -// corpus's `reads` rows pin: +// UnmarshalStorage checks the whole blob before it sets anything. The +// function returns one of three errors for a blob it cannot read: // -// - an integer reads into any integer type it fits; a float type reads a -// float or an integer; an integer type never reads a float; -// - a pointer reads null as nil, and any other value, marked present or -// not, as a pointer to that value: a Rust Some and a Go pointer alike; -// - a string reads only text, []byte and [N]byte only bytes (of length -// N), a slice or an array only an array; -// - a map reads a map or an object, each key 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, and a missing field is refused unless it is a -// pointer, which is left nil, or tagged `vc:"name,default"`, which is -// left its zero value, as Rust's #[serde(default)] reads it; -// - an encoding.TextUnmarshaler reads text; -// - an `any` reads the value as the blob holds it: nil, bool, the integer -// widths (vcvalue.Int128 and Uint128 for 128 bits), float32, float64, -// string, []byte, []any, vcvalue.Object for an object, -// [StorageEntries] for a map, and [Some] for an optional value. +// - [ErrNotABlob] for bytes that are not a blob +// - [ErrUnsupportedVersion] for a blob of another version +// - [ErrMalformed] for a blob with a malformed body // -// A value that does not fit is [ErrMismatch]. Its message names the kind -// found and where, never the value. +// 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("vcffi: UnmarshalStorage needs a non-nil pointer, not %T", v) + return fmt.Errorf("frame: UnmarshalStorage needs a non-nil pointer, not %T", v) } model, err := decodeStorage(blob) if err != nil { @@ -50,8 +58,8 @@ func UnmarshalStorage(blob []byte, v any) error { return assign(model, rv.Elem(), "") } -// decodeStorage reads a whole blob as the value it holds, refusing any blob -// a version 1 reader refuses. +// 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 @@ -79,7 +87,7 @@ func storageScalar(tag byte) bool { return storageKeyTag(tag) } -// storageKeyTag reports whether tag may start a map's key. +// storageKeyTag reports whether tag can start the key of a map. func storageKeyTag(tag byte) bool { switch tag { case tagInt8, tagInt16, tagInt32, tagInt64, tagInt128, @@ -123,7 +131,7 @@ func storageNode(r *reader, depth int) (any, error) { if err != nil { return nil, err } - fields := make(vcvalue.Object, 0, eagerCap(n)) + fields := make(value.Object, 0, eagerCap(n)) seen := make(map[string]struct{}, eagerCap(n)) for range n { key, err := r.str() @@ -134,11 +142,11 @@ func storageNode(r *reader, depth int) (any, error) { return nil, ErrMalformed } seen[key] = struct{}{} - value, err := storageNode(r, depth+1) + v, err := storageNode(r, depth+1) if err != nil { return nil, err } - fields = append(fields, vcvalue.Field{Key: key, Value: value}) + fields = append(fields, value.Field{Key: key, Value: v}) } return fields, nil case StorageMap: @@ -186,14 +194,15 @@ func storageNode(r *reader, depth int) (any, error) { // Reading into a Go value // ============================================================================= -// kindOf names what a model value is, for a refusal: never the 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, vcvalue.Int128, uint8, uint16, uint32, uint64, vcvalue.Uint128: + case int8, int16, int32, int64, value.Int128, uint8, uint16, uint32, uint64, value.Uint128: return "an integer" case float32, float64: return "a float" @@ -203,7 +212,7 @@ func kindOf(m any) string { return "bytes" case []any: return "an array" - case vcvalue.Object, StorageEntries: + case value.Object, StorageEntries: return "an object" case Some: return "an optional value" @@ -215,7 +224,7 @@ func mismatch(path, want string, found any) error { return fmt.Errorf("%w: %s: expected %s, found %s", ErrMismatch, orRoot(path), want, kindOf(found)) } -// integerOf is a model integer's value. +// 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 @@ -223,7 +232,8 @@ func integerOf(m any) (*big.Int, bool) { return wideIntegerOf(m) } -// int128Of is v as the 16 little-endian bytes of a two's-complement word. +// 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 { @@ -289,7 +299,7 @@ func assign(m any, rv reflect.Value, path string) error { return mismatch(path, "text", m) } if err := rv.Addr().Interface().(encoding.TextUnmarshaler).UnmarshalText([]byte(text)); err != nil { - return fmt.Errorf("%w: %s: text %s does not take", ErrMismatch, orRoot(path), t) + return fmt.Errorf("%w: %s: the UnmarshalText method of %s returned an error", ErrMismatch, orRoot(path), t) } return nil } @@ -367,11 +377,11 @@ func assignInteger(m any, rv reflect.Value, path string) error { switch t := rv.Type(); { case t == int128Type: if fits = v.Cmp(minInt128) >= 0 && v.Cmp(maxInt128) <= 0; fits { - rv.Set(reflect.ValueOf(vcvalue.Int128(int128Of(v)))) + 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(vcvalue.Uint128(int128Of(v)))) + rv.Set(reflect.ValueOf(value.Uint128(int128Of(v))).Convert(rv.Type())) } case rv.CanInt(): if fits = v.IsInt64() && !rv.OverflowInt(v.Int64()); fits { @@ -383,7 +393,7 @@ func assignInteger(m any, rv reflect.Value, path string) error { } } if !fits { - return fmt.Errorf("%w: %s: an integer that does not fit %s", ErrMismatch, orRoot(path), rv.Type()) + return fmt.Errorf("%w: %s: the integer is outside the range of %s", ErrMismatch, orRoot(path), rv.Type()) } return nil } @@ -391,8 +401,9 @@ func assignInteger(m any, rv reflect.Value, path string) error { func assignFloat(m any, rv reflect.Value, path string) error { switch x := m.(type) { case float32: - // Converted rather than widened, so a float32 keeps its bits - // (reflect copies float32 to float32, Go issue 36400). + // 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: @@ -403,7 +414,8 @@ func assignFloat(m any, rv reflect.Value, path string) error { if !ok { return mismatch(path, "a float", m) } - // Rounded once, to the destination's width, as Rust's `as` rounds. + // 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)) @@ -414,12 +426,12 @@ func assignFloat(m any, rv reflect.Value, path string) error { return nil } -// entriesOf is an object's or a map's entries, whichever m is. +// 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 vcvalue.Object: + case value.Object: entries := make(StorageEntries, len(x)) for i, f := range x { entries[i] = StorageEntry{Key: f.Key, Value: f.Value} @@ -441,10 +453,10 @@ func assignMap(m any, rv reflect.Value, path string) error { if err := assign(e.Key, key, at); err != nil { return err } - // A bytes key read into an interface key is a []byte, which a Go - // map cannot hash: SetMapIndex would panic. + // 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 a Go map can hold", e.Key) + 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 { diff --git a/languages/golang/encrypt/frame/storage_test.go b/languages/golang/encrypt/frame/storage_test.go index df5245755..112aea46b 100644 --- a/languages/golang/encrypt/frame/storage_test.go +++ b/languages/golang/encrypt/frame/storage_test.go @@ -1,4 +1,4 @@ -package vcffi +package frame import ( "bytes" @@ -7,19 +7,19 @@ import ( "errors" "fmt" "math" - "os" "reflect" "strconv" "strings" "testing" "time" - "github.com/cipherstash/vitaminc/bindings/go/vcvalue" + "github.com/cipherstash/stack/languages/golang/encrypt/value" ) -// The storage corpus is shared with Rust (packages/aead-frame), which pins -// version 1 byte for byte; this file holds Go to the same rows. -const storageCorpus = "../../../packages/aead-frame/testdata/storage-v1.json" +// 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"` @@ -39,18 +39,24 @@ type storageCorpusFile struct { 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, err := os.ReadFile(storageCorpus) - if err != nil { - t.Fatal(err) + 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) } - // reads_as is null for a row that reads as null, so its presence is - // told apart from a refusal by the refusal field. + // 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 == "" } @@ -66,8 +72,9 @@ func mustHex(t testing.TB, s string) []byte { return b } -// storageModel builds the Go value a corpus value describes, without the -// storage reader, so a reader and writer wrong in the same way cannot pass. +// 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" { @@ -115,7 +122,7 @@ func storageModel(t testing.TB, raw json.RawMessage) any { case "i64": return signed(64) case "i128": - n, err := vcvalue.ParseInt128(text) + n, err := value.ParseInt128(text) if err != nil { t.Fatal(err) } @@ -129,7 +136,7 @@ func storageModel(t testing.TB, raw json.RawMessage) any { case "u64": return unsigned(64) case "u128": - n, err := vcvalue.ParseUint128(text) + n, err := value.ParseUint128(text) if err != nil { t.Fatal(err) } @@ -155,11 +162,11 @@ func storageModel(t testing.TB, raw json.RawMessage) any { } return out case "object": - out := vcvalue.Object{} + out := value.Object{} for _, p := range pairs() { var key string _ = json.Unmarshal(p[0], &key) - out = append(out, vcvalue.Field{Key: key, Value: storageModel(t, p[1])}) + out = append(out, value.Field{Key: key, Value: storageModel(t, p[1])}) } return out case "map": @@ -181,7 +188,7 @@ func storageModel(t testing.TB, raw json.RawMessage) any { case "array": m = []any{m} case "object": - m = vcvalue.Object{{Key: "k", Value: m}} + m = value.Object{{Key: "k", Value: m}} case "some": m = Some{V: m} case "map": @@ -198,7 +205,8 @@ func storageModel(t testing.TB, raw json.RawMessage) any { return nil } -// sameModel compares two models, floats by their bits so NaNs compare. +// 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: @@ -221,8 +229,8 @@ func sameModel(a, b any) bool { } } return true - case vcvalue.Object: - y, ok := b.(vcvalue.Object) + case value.Object: + y, ok := b.(value.Object) if !ok || len(x) != len(y) { return false } @@ -296,7 +304,8 @@ func TestStorageCorpusVectors(t *testing.T) { } } -// Every refused row is refused by its class, whatever it is read into. +// 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 { @@ -316,8 +325,9 @@ func TestStorageCorpusRefused(t *testing.T) { } } -// goType is the Go type a corpus type describes, or why Go has none: Go has -// no enums and no unit type, and a []byte cannot be a map key. +// 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 @@ -374,8 +384,9 @@ func goType(t testing.TB, raw json.RawMessage) (reflect.Type, string) { return nil, why } return reflect.MapOf(key, value), "" - // UnmarshalStorage ignores unknown fields: a struct that denies them - // reads as one that does not, and its refusals are skipped below. + // 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": @@ -404,12 +415,14 @@ func goType(t testing.TB, raw json.RawMessage) (reflect.Type, string) { return nil, "" } -// deniesUnknown reports whether a row's type is itself a struct that -// denies unknown keys. UnmarshalStorage has no way to deny them, so a -// refused row of such a type that Go reads anyway is skipped. A row of -// that type that Go refuses is still checked for its error class. A -// struct that denies them nested in another type is not looked for: a row -// refused for that would fail below, rather than be skipped. +// 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 { @@ -419,8 +432,9 @@ func deniesUnknown(raw json.RawMessage) bool { return ok } -// Every reads row Go can express reads as it says, or is refused as a -// mismatch. What it reads as is compared as the blob it writes back to. +// 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 @@ -448,8 +462,8 @@ func TestStorageCorpusReads(t *testing.T) { t.Errorf("%s: %v", row.Name, err) continue } - // What the row reads as, written canonically, read by the same - // type: the Go value both blobs must read as. + // 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) @@ -462,8 +476,9 @@ func TestStorageCorpusReads(t *testing.T) { t.Errorf("%s: read as %#v, want %#v", row.Name, into.Elem().Interface(), want.Elem().Interface()) } } - // Most rows are expressible; a new row Go cannot express is logged - // above, and this guards against a typo skipping them all. + // 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)) } @@ -475,7 +490,8 @@ func TestStorageCorpusReads(t *testing.T) { type stamp struct{ at string } -// folded writes itself in lower case, so two keys can write as one. +// 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 } @@ -491,11 +507,11 @@ type record struct { Absent **int32 `vc:"absent"` Tags []string `vc:"tags"` Raw []byte `vc:"raw"` - ID vcvalue.UUID `vc:"id"` + ID value.UUID `vc:"id"` Scores map[uint32]string `vc:"scores"` When time.Time `vc:"when"` Stamp stamp `vc:"stamp"` - Big vcvalue.Int128 `vc:"big"` + Big value.Int128 `vc:"big"` Ratio float32 `vc:"ratio"` Skipped string `vc:"-"` Untyped any `vc:"untyped"` @@ -506,7 +522,7 @@ func TestStorageRecordRoundTrips(t *testing.T) { n := int32(-3) np := &n var nilInt *int32 - big, _ := vcvalue.ParseInt128("-170141183460469231731687303715884105728") + big, _ := value.ParseInt128("-170141183460469231731687303715884105728") in := record{ Name: "ada", Age: 36, @@ -515,7 +531,7 @@ func TestStorageRecordRoundTrips(t *testing.T) { Absent: &nilInt, Tags: []string{"x", "y"}, Raw: []byte{1, 2}, - ID: vcvalue.UUID{15: 1}, + 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"}, @@ -540,12 +556,12 @@ func TestStorageRecordRoundTrips(t *testing.T) { if !reflect.DeepEqual(out, in) { t.Fatalf("read %+v, want %+v", out, in) } - // The pieces whose bytes Rust must agree on. + // 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.(vcvalue.Object) + fields := model.(value.Object) for _, f := range fields { switch f.Key { case "pinned": @@ -587,8 +603,9 @@ func TestStorageRecordRoundTrips(t *testing.T) { } } -// Integer keys sort by value, as a Rust BTreeMap orders them, so the same -// map writes the same bytes in both languages. +// 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 @@ -645,16 +662,15 @@ func TestStorageRefusesWhatHasNoStorageForm(t *testing.T) { "a channel": make(chan int), "a function": func() {}, "a complex number": complex(1, 2), - "a passthrough": vcvalue.Plain{V: 1}, - "a date": vcvalue.Date{}, - "a decimal": vcvalue.Decimal{}, - "a typed null": vcvalue.TypedNull{}, + "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": vcvalue.Object{{Key: "k"}, {Key: "k"}}, + "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, @@ -688,8 +704,8 @@ func (s *sealedSecret) EncryptValue(enc Encoder) error { return nil } -// A bytes key read into an interface key would be a []byte, which a Go map -// cannot hold: it is a mismatch, not a panic. +// 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 { @@ -734,8 +750,9 @@ func TestStorageMismatchNamesWhereAndNotWhat(t *testing.T) { } } -// A field that became a pointer reads its old value; a missing pointer -// field is nil, and any other missing field is refused. +// 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"` @@ -756,8 +773,9 @@ func TestStorageOptionalFields(t *testing.T) { if err := UnmarshalStorage(blob, &stricter{}); !errors.Is(err, ErrMismatch) { t.Fatalf("a missing field: %v, want ErrMismatch", err) } - // A tagged default reads a missing field as its zero value, and keeps - // its name, or the field's own with an empty name. + // 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"` @@ -770,16 +788,17 @@ func TestStorageOptionalFields(t *testing.T) { full, _ := MarshalStorage(defaulted{N: 1, M: "m", K: []int8{2}}) var model any _ = UnmarshalStorage(full, &model) - if names := []string{model.(vcvalue.Object)[1].Key, model.(vcvalue.Object)[2].Key}; names[0] != "m" || names[1] != "K" { + 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 bare, so a field that is not a pointer on the - // reading side reads it; Rust's marked Some reads only into a pointer. + // 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(vcvalue.Object{{Key: "n", Value: Some{V: uint32(7)}}}) + 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) } @@ -788,7 +807,8 @@ func TestStorageOptionalFields(t *testing.T) { } } -// The transport names a struct's fields by the same tags, options and all. +// 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"` @@ -801,7 +821,7 @@ func TestTransportFieldNamesIgnoreTagOptions(t *testing.T) { if err != nil { t.Fatal(err) } - if got := v.(vcvalue.Object)[0].Key; got != "age" { + if got := v.(value.Object)[0].Key; got != "age" { t.Fatalf("the transport named the field %q", got) } } @@ -819,9 +839,12 @@ func addStorageSeeds(f *testing.F) { } } -// FuzzUnmarshalStorage holds the reader to its contract on hostile bytes: -// it never panics, a blob it reads writes back as exactly the same bytes -// (one encoding per value), and reading into a struct never panics either. +// 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) { @@ -840,9 +863,10 @@ func FuzzUnmarshalStorage(f *testing.F) { }) } -// Every level of a pointer to a pointer reads back: a pointer to a value -// that is itself written as null or marked present is marked, so its -// reader never takes the inner level's null or marker for its own. +// 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 @@ -869,7 +893,7 @@ func TestStoragePointerLevelsReadBack(t *testing.T) { } } - // The blob Codex found: the innermost nil is two markers, then null. + // The innermost nil is written as two StorageSome tags, then null. blob, err := MarshalStorage(&middle) if err != nil { t.Fatal(err) @@ -878,7 +902,8 @@ func TestStoragePointerLevelsReadBack(t *testing.T) { t.Errorf("%x, want %x", blob, want) } - // A pointer to [Some] is marked too, so the Some keeps its own marker. + // 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 { @@ -889,8 +914,9 @@ func TestStoragePointerLevelsReadBack(t *testing.T) { } } -// A nil pointer is no map key. It is refused, never handed to its type's -// MarshalText, which would be called on nil. +// 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}, @@ -903,8 +929,9 @@ func TestStorageRefusesANilPointerKey(t *testing.T) { } } -// A `vc` tag option other than `default` is refused where a struct is -// written or read, in a blob or the transport, rather than ignored. +// 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"` @@ -930,8 +957,8 @@ func TestUnknownTagOptionsAreRefused(t *testing.T) { } } -// A pointer that writes no node of its own costs no depth, so a linked -// list is as deep in Go as its blob is; a pointer cycle is still refused. +// 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"` diff --git a/languages/golang/encrypt/frame/transport.go b/languages/golang/encrypt/frame/transport.go index cfed7f0d4..ff0984831 100644 --- a/languages/golang/encrypt/frame/transport.go +++ b/languages/golang/encrypt/frame/transport.go @@ -1,4 +1,4 @@ -package vcffi +package frame import ( "encoding/binary" @@ -7,12 +7,17 @@ import ( "unicode/utf8" ) -// Transport framing tags. The scalar tags mirror vitaminc-aead's frozen -// sealed-leaf tag table so the two tables can't drift apart on -// meaning; the ARRAY/OBJECT container tags are transport-local (the sealed -// format has no container tags — container shape rides on the ciphertext -// tree). See the package doc: this transport encoding is NOT a storage -// format. +// 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 @@ -35,37 +40,46 @@ const ( tagDate = 0x12 tagTimestamp = 0x13 tagDecimal = 0x14 - // tagTypedNull is an absent value of a fixed-width type, padded to that - // type's leaf length: the tag, the header a value of the type starts - // with, then zeros (vitaminc#493). + // 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 wraps one value node that travels in the clear - // (unencrypted, unauthenticated). Transport-local, like array/object. + // 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 carries a logical type with no shorthand tag over a - // physical scalar: id, parameter, then the scalar (ADR 0001). 0xF4 is - // reserved for a longer envelope and is refused. + // 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 ) -// Logical type ids, as the envelope spells them. Undefined, Date, Decimal -// and nanosecond Timestamp have shorthand tags of their own, so the -// envelope never carries them: there is one encoding per value. +// 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 this build knows. Any id above it - // is read and re-encoded unchanged as a vcvalue.Tagged. + // 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 ) -// Timestamp units, as the envelope's parameter spells them. Nanoseconds is -// the shorthand Timestamp tag, so only the coarser units use the envelope. +// 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 @@ -73,59 +87,78 @@ const ( unitNanos = 3 ) -// maxUint32 bounds every length/count written or read (all are u32 LE). -// Typed uint64, not an untyped constant: an untyped 1<<32-1 compared against -// an int fails to compile on 32-bit GOARCH (constant overflows int), and the -// guard is load-bearing there — an oversized count coerced to a negative int -// would slip past the remaining-bytes check and panic in make instead of -// returning ErrMalformed. Comparisons convert the int operand to uint64 -// (always lossless for non-negative values, which the n < 0 guards ensure). +// 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 mirrors the Rust transport codec's recursion bound, keeping a -// hostile nesting depth from overflowing the stack. +// 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 clamps the up-front reservation of a count-driven -// allocation. The reader's count guard bounds a single reservation against -// the bytes remaining, but not the sum of live reservations: a container -// nesting level costs 5-9 wire bytes while a reserved slot costs many times -// that, and up to maxDepth ancestor reservations are live at once — so ~1 MB -// of hostile bytes could otherwise pin gigabytes. Mirrors the Rust codecs' -// MAX_EAGER_CAPACITY. Slices still grow past the clamp on append; only the -// initial reservation is bounded. +// 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 { - // n < 0 is unreachable on 64-bit (u32 counts are non-negative in a 64-bit - // int) but load-bearing on 32-bit GOARCH, where a hostile prefix >= 2^31 - // coerces negative and min() would pass it through to make(). + // 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 returned by the decoders for any transport buffer or -// storage blob that does not parse: truncated, over-deep, hostile counts, -// duplicate keys, unknown tags. Deliberately unspecific — the decoders treat their input as -// hostile and do not distinguish *how* it is malformed. It is returned bare, -// never wrapped, so errors.Is and == are equivalent today; prefer errors.Is. +// 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. // -// A misconfigured [LeafSet] is a different class of failure — the binding's -// own wiring, not hostile bytes — and [UnmarshalCipherText] reports it with a -// distinct, attributable error rather than folding it into ErrMalformed. -var ErrMalformed = errors.New("vcffi: malformed transport bytes or storage blob") - -// ErrTooDeep is returned by the encoders when a value or ciphertext tree -// exceeds the recursion bound (the decoders fold over-deep input into -// [ErrMalformed] — hostile bytes stay unspecific by design, but a too-deep -// value handed in by the caller's own code is worth matching on). -var ErrTooDeep = errors.New("vcffi: value is nested too deeply") +// 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("vcffi: length %d out of range", n) + return nil, fmt.Errorf("frame: length %d out of range", n) } return binary.LittleEndian.AppendUint32(out, uint32(n)), nil } @@ -138,8 +171,8 @@ func appendChunk(out, chunk []byte) ([]byte, error) { return append(out, chunk...), nil } -// reader is a cursor over a transport buffer, tracking bytes consumed so a -// decode can insist the whole buffer was used. +// 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 @@ -171,11 +204,15 @@ func (r *reader) u32() (int, error) { return int(binary.LittleEndian.Uint32(s)), nil } -// count reads a u32 item count, rejecting counts that exceed the bytes -// remaining (every item costs at least one byte) so hostile input cannot -// drive a huge preallocation. The n < 0 guard matches take/appendLen: on -// 32-bit GOARCH a prefix >= 2^31 coerces to a negative int, which would slip -// past the remaining-bytes check and panic in make. +// 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 { @@ -191,7 +228,8 @@ func (r *reader) finished() bool { return r.pos == len(r.buf) } -// str reads a length-prefixed, UTF-8-validated string. +// 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 { diff --git a/languages/golang/encrypt/frame/transport_internal_test.go b/languages/golang/encrypt/frame/transport_internal_test.go index 4ec4b2d35..d1aa55a24 100644 --- a/languages/golang/encrypt/frame/transport_internal_test.go +++ b/languages/golang/encrypt/frame/transport_internal_test.go @@ -1,13 +1,20 @@ -package vcffi +package frame import "testing" -// White-box pin for eagerCap, mirroring the Rust transport codec's -// eager_capacity test: the clamp is a capacity hint invisible to round-trip -// tests, so assert the function directly — identity below the threshold, -// flat at maxEagerCapacity above it, and zero for negative counts (a u32 -// prefix >= 2^31 coerced to int on 32-bit GOARCH, which must not reach -// make()). The constant itself is pinned so a silent bump shows up here. +// 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) diff --git a/languages/golang/encrypt/frame/typed_null_test.go b/languages/golang/encrypt/frame/typed_null_test.go index 8f902e6b4..4133210ba 100644 --- a/languages/golang/encrypt/frame/typed_null_test.go +++ b/languages/golang/encrypt/frame/typed_null_test.go @@ -1,49 +1,50 @@ -package vcffi +package frame import ( "bytes" "encoding/hex" - "errors" - "fmt" "reflect" "testing" "time" - "github.com/cipherstash/vitaminc/bindings/go/vcvalue" + "github.com/cipherstash/stack/languages/golang/encrypt/value" ) -// typedNullAnswers pins each FixedType's typed null: the cross-language -// bytes the Rust codec writes for the same type (vitaminc-aead's leaf -// tests), beside a value of the type, which must be as long. +// 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 { - t vcvalue.FixedType + name string + nilPtr any hex string present any }{ - {vcvalue.TypeInt8, "150c", int8(-1)}, - {vcvalue.TypeInt16, "150e00", int16(-1)}, - {vcvalue.TypeInt32, "1504000000", int32(-1)}, - {vcvalue.TypeInt64, "1505" + zeros(7), int64(-1)}, - {vcvalue.TypeInt128, "1510" + zeros(15), vcvalue.Int128{1}}, - {vcvalue.TypeUint8, "150d", uint8(1)}, - {vcvalue.TypeUint16, "150f00", uint16(1)}, - {vcvalue.TypeUint32, "1506000000", uint32(1)}, - {vcvalue.TypeUint64, "1507" + zeros(7), uint64(1)}, - {vcvalue.TypeUint128, "1511" + zeros(15), vcvalue.Uint128{1}}, - {vcvalue.TypeFloat32, "1508000000", float32(1.5)}, - {vcvalue.TypeFloat64, "1509" + zeros(7), 1.5}, - {vcvalue.TypeDate, "1512000000", vcvalue.Date{Year: 1999, Month: 12, Day: 31}}, - {vcvalue.TypeTimestamp, "1513" + zeros(11), time.Unix(1_700_000_000, 5).UTC()}, - {vcvalue.TypeDecimal, "1514" + zeros(15), vcvalue.Decimal{Scale: 2, Coefficient: [12]byte{150}}}, - {vcvalue.TypeUUID, "15f305000b" + zeros(15), vcvalue.UUID{0xAB}}, + {"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(fmt.Sprint(row.t), func(t *testing.T) { - got, err := Marshal(vcvalue.TypedNull{Type: row.t}) + t.Run(row.name, func(t *testing.T) { + got, err := Marshal(row.nilPtr) if err != nil { t.Fatal(err) } @@ -54,33 +55,24 @@ func TestTypedNullKnownAnswers(t *testing.T) { if err != nil { t.Fatal(err) } - // A frame gives bytes a length prefix; a typed null of a UUID - // has none, because its sealed leaf has none. + // 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.t == vcvalue.TypeUUID { + if row.name == "uuid" { want -= 4 } if len(got) != want { t.Fatalf("typed null is %d bytes, a value %d", len(got), want) } - // It reads back as nil, like every null, and writes back as one. + // 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) } }) } - if len(typedNullAnswers) != int(vcvalue.TypeUUID) { - t.Fatalf("pinned %d of %d types", len(typedNullAnswers), vcvalue.TypeUUID) - } -} - -func TestAnInvalidFixedTypeFailsTheEncode(t *testing.T) { - for _, ft := range []vcvalue.FixedType{0, vcvalue.TypeUUID + 1, 255} { - if _, err := Marshal(vcvalue.TypedNull{Type: ft}); !errors.Is(err, vcvalue.ErrInvalidFixedType) { - t.Fatalf("%v: got %v", ft, err) - } - } } type selfEncoded int32 @@ -101,10 +93,10 @@ func (p *ptrEncoded) EncryptValue(enc Encoder) error { // A pointer type that points at itself never reaches a non-pointer. type selfPointer *selfPointer -// A nil pointer to a fixed-width type is a typed null, the Go side of -// Rust's Option; a nil with no fixed-width type to go by is the plain -// null. Each case is encoded twice, since the second encode reads the -// per-type cache. +// 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 @@ -126,12 +118,12 @@ func TestANilPointerIsATypedNullWhenItsTypeIsFixedWidth(t *testing.T) { {"*float32", (*float32)(nil), "1508000000"}, {"*float64", (*float64)(nil), "1509" + zeros(7)}, {"*time.Time", (*time.Time)(nil), "1513" + zeros(11)}, - {"*vcvalue.Date", (*vcvalue.Date)(nil), "1512000000"}, - {"*vcvalue.Timestamp", (*vcvalue.Timestamp)(nil), "1513" + zeros(11)}, - {"*vcvalue.Decimal", (*vcvalue.Decimal)(nil), "1514" + zeros(15)}, - {"*vcvalue.UUID", (*vcvalue.UUID)(nil), "15f305000b" + zeros(15)}, - {"*vcvalue.Int128", (*vcvalue.Int128)(nil), "1510" + zeros(15)}, - {"*vcvalue.Uint128", (*vcvalue.Uint128)(nil), "1511" + zeros(15)}, + {"*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"}, @@ -164,90 +156,10 @@ func TestANilPointerIsATypedNullWhenItsTypeIsFixedWidth(t *testing.T) { } } -// An Encryptable that always writes one value of one fixed-width type: -// a FixedWidth, the Go side of Rust's Encrypt::FIXED. -type money struct{ cents int64 } - -func (m money) EncryptValue(enc Encoder) error { - enc.Int64(m.cents) - return nil -} - -func (money) FixedType() vcvalue.FixedType { return vcvalue.TypeInt64 } - -// The same, declared on the pointer. -type ptrMoney struct{ cents int64 } - -func (m *ptrMoney) EncryptValue(enc Encoder) error { - enc.Int64(m.cents) - return nil -} - -func (*ptrMoney) FixedType() vcvalue.FixedType { return vcvalue.TypeInt64 } - -// A FixedWidth that declares a type that is not one. -type badWidth struct{} - -func (badWidth) EncryptValue(enc Encoder) error { - enc.String("custom") - return nil -} - -func (badWidth) FixedType() vcvalue.FixedType { return 0 } - -func TestANilPointerToAFixedWidthEncryptableIsATypedNullOfItsType(t *testing.T) { - want := "1505" + zeros(7) - for _, c := range []struct { - name string - v any - }{ - {"*money", (*money)(nil)}, - {"**money", (**money)(nil)}, - {"*ptrMoney", (*ptrMoney)(nil)}, - {"**ptrMoney", (**ptrMoney)(nil)}, - } { - t.Run(c.name, func(t *testing.T) { - got, err := Marshal(c.v) - if err != nil { - t.Fatal(err) - } - if hex.EncodeToString(got) != want { - t.Fatalf("got %x, want %s", got, want) - } - }) - } - // A present value is as long, and still written by EncryptValue. - present, err := Marshal(&money{cents: 150}) - if err != nil { - t.Fatal(err) - } - if hex.EncodeToString(present) != "059600000000000000" { - t.Fatalf("present: got %x", present) - } - // Through a struct field, where a nil would otherwise show by length. - type order struct{ Refund *money } - absent, err := Marshal(order{}) - if err != nil { - t.Fatal(err) - } - if !bytes.HasSuffix(absent, []byte{tagTypedNull, tagInt64, 0, 0, 0, 0, 0, 0, 0}) { - t.Fatalf("absent: %x", absent) - } - // A declared type that is not a fixed-width type fails the encode, and - // never writes the plain null in its place. A present value is not - // asked. - if _, err := Marshal((*badWidth)(nil)); !errors.Is(err, vcvalue.ErrInvalidFixedType) { - t.Fatalf("invalid declared type: got %v", err) - } - if _, err := Marshal(badWidth{}); err != nil { - t.Fatalf("present: %v", err) - } -} - func TestAStructsNilFieldsAreTypedNulls(t *testing.T) { type person struct { Name string - Born *vcvalue.Date + Born *value.Date Age *int32 Tags []string Any any @@ -260,25 +172,27 @@ func TestAStructsNilFieldsAreTypedNulls(t *testing.T) { if err != nil { t.Fatal(err) } - for _, f := range v.(vcvalue.Object) { + 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 carry their padding; Any has no type to go by, and a nil - // slice is an empty sequence, as it always was. + // 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) } } -// The explicit channel, for an Encryptable that knows the type. +// 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(vcvalue.TypeInt32) + enc.typedNull(nullOf(tagInt32)) } else { enc.Int32(*m.v) } @@ -293,10 +207,11 @@ func TestTheTypedNullChannel(t *testing.T) { if hex.EncodeToString(got) != "1504000000" { t.Fatalf("got %x", got) } - // It completes exactly one slot, like every terminal. + // 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(vcvalue.TypeUint8) + s.Elem().typedNull(nullOf(tagUint8)) s.Elem().Null() return s.End() } @@ -313,9 +228,9 @@ type encryptableFunc func(Encoder) error func (f encryptableFunc) EncryptValue(e Encoder) error { return f(e) } -// Every absence has one encoding: the decoder refuses anything a writer -// does not write. The shared corpus pins the same refusals for every -// language; these are the Go-specific edges around them. +// 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", @@ -346,29 +261,27 @@ func TestATypedNullIsReadStrictly(t *testing.T) { } } -// Every fixed-width marker and kind writes its values with the header its -// typed null carries, so the one table cannot pad a type as something it is -// not. A marker added without a sample here fails the test. +// 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(vcvalue.Int128{}): vcvalue.Int128{1}, - reflect.TypeOf(vcvalue.Uint128{}): vcvalue.Uint128{1}, - reflect.TypeOf(vcvalue.Date{}): vcvalue.Date{Year: 2000, Month: 1, Day: 1}, - reflect.TypeOf(time.Time{}): time.Unix(7, 0), - reflect.TypeOf(vcvalue.Timestamp{}): vcvalue.Timestamp{Seconds: 7}, - reflect.TypeOf(vcvalue.Decimal{}): vcvalue.Decimal{Scale: 1}, - reflect.TypeOf(vcvalue.UUID{}): vcvalue.UUID{1}, - } - check := func(name string, ft vcvalue.FixedType, sample any) { - null, err := Marshal(vcvalue.TypedNull{Type: ft}) - if err != nil { - t.Fatalf("%s: %v", name, err) - } + 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 typed null's header (after its tag) begins the value's. + // 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] @@ -377,25 +290,26 @@ func TestEveryFixedTypeIsWrittenWithItsTypedNullsHeader(t *testing.T) { 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 marker, so a marker that loses its - // fixed type is caught, not skipped. + // 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].fixed == 0 { + if markers[typ].null == nil { t.Fatalf("%v has a sample but no typed null", typ) } } for typ, m := range markers { - if m.fixed == 0 { + 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.fixed, sample) + check(typ.String(), m.null, sample) } for kind, n := range numericKinds { - check(kind.String(), n.fixed, reflect.Zero(kindTypes[kind]).Interface()) + check(kind.String(), n.null, reflect.Zero(kindTypes[kind]).Interface()) } } diff --git a/languages/golang/encrypt/value/README.md b/languages/golang/encrypt/value/README.md deleted file mode 100644 index 644872656..000000000 --- a/languages/golang/encrypt/value/README.md +++ /dev/null @@ -1,126 +0,0 @@ -# vcvalue — the durable value layer - -`vcvalue` is the Go materialization of vitaminc's **frozen data model**: the -value types application code holds and stores — `Plain`, the sealed leaf -family, and the ordered `Object` decode shape. - -It has **zero dependencies** — no wazero, no crypto, and (deliberately) no -wire format. It is the module a future stack-encrypt Go SDK is expected to -import. Keeping it dependency-free is the point: the wasm reference harness -(`vcencrypt`, next door) is just *one* consumer, and neither its -wazero/crypto dependencies nor its FFI wire encoding may leak into the layer -real applications depend on. - -``` -import "github.com/cipherstash/vitaminc/bindings/go/vcvalue" -``` - -## The model, not this package - -The cross-language contract is the frozen sealed-leaf tag table -(`[tag] ++ payload`, sealed **inside** the AEAD envelope, defined in the Rust -crate `vitaminc-aead`'s leaf codec) — not any language's types. This package's types -*implement* that model; they are not the contract. A new tag is added only -when a value class cannot be represented in the existing model, and needs a -defined decode mapping in every supported language before it ships. - -The transport codec — the wire encoding that hands a tree across an FFI -boundary in one copy — is **not part of this module**. It lives in the -sibling module `vcffi`, shared by the bindings that own such a boundary -(`vcencrypt` for the wasm harness, the stack-encrypt Go SDK), because it is -transport-only and carries no storage commitment: the only bytes an -application should ever persist are the sealed leaves. The -`Encryptable`/`Encoder` encoding extension point lives with the codec in -`vcffi` for the same reason. - -## Passthrough — fields in the clear - -Some fields are not secret and should travel unencrypted alongside the sealed -ones. The model carries them as **passthrough**: unencrypted *and* -unauthenticated, non-sensitive fields only. Passthrough never happens -implicitly — you opt in by wrapping the value in `Plain`: - -```go -value := map[string]any{ - "id": vcvalue.Plain{V: int64(42)}, // in the clear - "email": "ada@example.com", // sealed -} -``` - -On decode a passthrough field surfaces back as `Plain{V: }`, so -the marking round-trips and a caller can tell which fields were in the clear. -A passthrough field inside a *ciphertext* is likewise a `Plain` — legible with -no key. - -## Ciphertexts are ordinary Go values - -There is no ciphertext tree type and no conversion step. A ciphertext has the -same dynamic shape as decoded plaintext, with marker types naming what is -sealed: - -| value | meaning | -| ----------------- | -------------------------------------------------------------------- | -| `Sealed` | one encrypted leaf: `version(1) \|\| nonce \|\| ciphertext \|\| tag` | -| `SealedEmptySeq` | the authenticated marker for an empty sequence | -| `SealedEmptyMap` | the authenticated marker for an empty map | -| `Plain{V: ...}` | a passthrough field, readable without the key | -| `map[string]any` | a record of named nodes (clear keys, bound into AAD) | -| `[]any` | a sequence of nodes | - -Every leaf-shaped type starts with a one-byte wire version, which is also -authenticated into the leaf's AAD — a relabeled version byte fails the tag, -not just the parse. All four leaf types share that byte layout: the *kind* of -a leaf is authenticated through domain-separated AAD, not written into the -bytes, so a stored leaf's kind must be tracked by the schema (see the note on -the marker types' `Scan`). - -The `Sealed` family here is **vitaminc-encrypt's** materialization of the -model. Another binding — a stack-encrypt SDK, say — defines its own distinct -sealed-leaf types and wires them to the codec via `vcffi.LeafSet`, so its -leaves can never scan or marshal where these belong: a stack-encrypt leaf is -never a `vcvalue.Sealed`. - -The sealed leaf types and `Plain` implement `driver.Valuer`, and the sealed -types `sql.Scanner`, so a record-shaped ciphertext binds straight into a -database as named parameters and sealed columns scan straight back out — no -adapter layer. Because a record is a plain map, any subset of its fields can -be handed back for decryption: there is no whole-map seal, and each key is -bound into its own value's AAD. - -## Decoding - -Decryption (in `vcencrypt`) returns Go natives at the exact numeric widths -(`nil`, `bool`, `int8`, `int16`, `int32`, `int64`, `uint8`, `uint16`, `uint32`, `uint64`, `float32`, `float64`, -`string`, `[]byte`, `[]any`), this package's ordered `Object` for maps, and -`Plain` for passthrough. A reflection-based decode into caller structs (the -mirror of the reflection encode) is future work. - - -## Extended scalars - -`Int128` and `Uint128` are 16-byte little-endian values, with exact decimal -`ParseInt128` / `ParseUint128` constructors and `String` methods. Out-of-range -inputs return `ErrIntegerRange`. - -`Date{Year, Month, Day}` is a Gregorian calendar date in the wire's range, -years -9999 through 9999. `time.Time` maps to Timestamp with nanoseconds and -decodes in UTC, without its location or monotonic reading, from --009999-01-02T01:59:59Z through 9999-12-30T22:00:00.999999999Z. These ranges -are jiff's, in every binding, so a value one binding seals, every binding -opens. `time.Time` itself reaches far wider, and a value outside the range is -refused. -`Timestamp{Seconds, Nanoseconds}` encodes an instant from its parts. A leap -second has no count since the epoch and is refused everywhere in the model -(ADR 0001). Invalid calendar/timestamp inputs return `ErrInvalidDate` or -`ErrInvalidTimestamp`. - -`UUID` is sixteen bytes under the Uuid logical type, spelled as hyphenated -hexadecimal by `ParseUUID` and `String`. `Tagged{ID, Param, V}` carries a -physical scalar under a logical id this build does not know, so a value -from a newer client is read and re-encoded unchanged rather than dropped. - -`ParseDecimal("1.50")` constructs a finite 96-bit coefficient with scale 0–28, -retaining trailing zeroes. A zero has no sign: `-0.00` is `0.00` with its -scale kept (ADR 0001). Exponents and rounding are not -accepted. NaN and infinities return `ErrNonFiniteDecimal`; malformed or -out-of-range text returns `ErrInvalidDecimal`. Match these with `errors.Is`. diff --git a/languages/golang/encrypt/value/doc.go b/languages/golang/encrypt/value/doc.go index 612b7f86a..704da829b 100644 --- a/languages/golang/encrypt/value/doc.go +++ b/languages/golang/encrypt/value/doc.go @@ -1,43 +1,19 @@ -// Package vcvalue is the durable, dependency-free module of the vitaminc Go -// bindings: the value model — the types application code holds and stores — -// with no dependency on wazero, any crypto, or any wire format. A future -// stack-encrypt Go SDK is expected to import this module; the wasm reference -// harness (module vcencrypt) is one consumer of it. +// Package value declares the values that the Stack Encrypt Go SDK reads and +// writes, beside Go's own types: // -// # The model +// - 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. // -// - Plain{V: ...} marks (and surfaces) a field that travels in the clear — -// unencrypted and unauthenticated — beside the sealed ones. It is always -// an explicit opt-in, never inferred. -// - Sealed is one encrypted leaf (version || nonce || ciphertext || tag), -// the only frozen byte format in the model. SealedEmptySeq and -// SealedEmptyMap are its authenticated marker siblings for empty -// composites; an absent value is a sealed null leaf (ADR 0001), padded -// to the length of a value when its type is fixed width (TypedNull, -// and a nil pointer to such a type; vitaminc#493). This -// sealed family is vitaminc-encrypt's materialization of the model: another binding (a stack-encrypt SDK, -// say) defines its own distinct sealed-leaf types and wires them to the -// codec via vcffi's LeafSet — a stack-encrypt leaf is never a Sealed. -// - Object is the ordered map-decode shape (entry order preserved, so -// results compare deterministically); Field is one entry of it. +// 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. // -// All of the sealed leaf types and Plain implement driver.Valuer (and the -// leaves sql.Scanner), so a map-shaped ciphertext binds directly as database -// named parameters and sealed columns load back without conversion. -// -// # What is deliberately NOT here -// -// The transport codec — the wire encoding that carries a value tree across -// an FFI boundary — lives in the sibling module vcffi, shared by the -// bindings that own such a boundary (vcencrypt, the stack-encrypt Go SDK). -// It is not a storage format, so this module does not carry it: the only -// bytes an application should ever persist are the sealed leaves above. The -// Encryptable/Encoder extension point for custom encodings lives with the -// codec in vcffi for the same reason. -// -// The cross-language contract is the frozen tag table plus the sealed leaf -// encodings defined in the Rust crate vitaminc-aead's leaf codec — the -// model, not any package. A new tag is added only when a value class cannot be -// represented in the existing model, and requires a defined decode mapping -// for every supported language before it ships. -package vcvalue +// 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 index 5e0382158..cb006c35d 100644 --- a/languages/golang/encrypt/value/model.go +++ b/languages/golang/encrypt/value/model.go @@ -1,23 +1,26 @@ -package vcvalue +package value -// Plain marks a value that must travel through the cipher **unencrypted and -// unauthenticated** — the reflection-encode opt-in for passthrough. Wrap a -// non-secret value (Plain{V: id}) and the vcencrypt -// encoder records it via its Passthrough channel instead of sealing it. Passthrough never -// happens implicitly: only an explicit Plain (or a direct -// enc.Passthrough() call) produces it. +// Plain marks a passthrough value. A passthrough value is neither encrypted +// nor authenticated, so use Plain only for a value that is not secret. // -// A decoded passthrough field surfaces back as Plain{V: }, -// so the marking round-trips and a caller can tell which fields were in the -// clear. See the package docs — non-sensitive fields only. +// 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 the decode result for a map-mode value: an ordered list of -// fields mirroring the wire order. Decoding uses this (rather than a Go map) -// so entry order is preserved and results compare deterministically. Encode -// takes any/struct/map instead — this type is decode-only. +// 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. diff --git a/languages/golang/encrypt/value/model_test.go b/languages/golang/encrypt/value/model_test.go deleted file mode 100644 index abbd80740..000000000 --- a/languages/golang/encrypt/value/model_test.go +++ /dev/null @@ -1,132 +0,0 @@ -package vcvalue_test - -import ( - "database/sql" - "database/sql/driver" - "math" - "reflect" - "testing" - - "github.com/cipherstash/vitaminc/bindings/go/vcvalue" -) - -// Every sealed leaf type must survive the database column round trip: -// Value() then Scan() back into the same type. -func TestSealedLeafTypesScanValueRoundTrip(t *testing.T) { - roundTrip := func(t *testing.T, value driver.Valuer, scan sql.Scanner, got func() []byte, want []byte) { - t.Helper() - v, err := value.Value() - if err != nil { - t.Fatalf("Value: %v", err) - } - if err := scan.Scan(v); err != nil { - t.Fatalf("Scan: %v", err) - } - if !reflect.DeepEqual(got(), want) { - t.Fatalf("got %#v, want %#v", got(), want) - } - } - - leaf := []byte{1, 2, 3} - var s vcvalue.Sealed - roundTrip(t, vcvalue.Sealed(leaf), &s, func() []byte { return []byte(s) }, leaf) - var es vcvalue.SealedEmptySeq - roundTrip(t, vcvalue.SealedEmptySeq(leaf), &es, func() []byte { return []byte(es) }, leaf) - var em vcvalue.SealedEmptyMap - roundTrip(t, vcvalue.SealedEmptyMap(leaf), &em, func() []byte { return []byte(em) }, leaf) - - // Non-byte sources are rejected. - if err := (&es).Scan("not bytes"); err == nil { - t.Fatal("scanning a string into SealedEmptySeq must fail") - } -} - -// Every integer kind the encoder accepts must also bind through the driver: -// Plain{V: user.ID} with ID int encodes fine, so Value() must not reject it. -func TestPlainValueBindsEveryEncodableIntegerKind(t *testing.T) { - cases := []struct { - in any - want driver.Value - }{ - {int(7), int64(7)}, - {int8(-8), int64(-8)}, - {int16(-16), int64(-16)}, - {int32(-32), int64(-32)}, - {int64(-64), int64(-64)}, - {uint8(8), int64(8)}, - {uint16(16), int64(16)}, - {uint32(32), int64(32)}, - {uint(64), int64(64)}, - {uint64(64), int64(64)}, - } - for _, c := range cases { - got, err := vcvalue.Plain{V: c.in}.Value() - if err != nil { - t.Fatalf("Value(%T): %v", c.in, err) - } - if got != c.want { - t.Fatalf("Value(%T): got %#v, want %#v", c.in, got, c.want) - } - } - - // The unsigned kinds that can exceed int64 must fail closed. - if _, err := (vcvalue.Plain{V: uint64(math.MaxInt64) + 1}).Value(); err == nil { - t.Fatal("uint64 above MaxInt64 must not bind") - } - if uint64(math.MaxUint) > math.MaxInt64 { // uint is 32-bit on GOARCH=386 - if _, err := (vcvalue.Plain{V: uint(math.MaxUint)}).Value(); err == nil { - t.Fatal("uint above MaxInt64 must not bind") - } - } -} - -// Plain.Value's driver conversions: width-narrowing, the uint64 overflow -// error, and the container-has-no-column error. -func TestPlainValueConversions(t *testing.T) { - cases := []struct { - in any - want driver.Value - }{ - {nil, nil}, - {true, true}, - {int64(7), int64(7)}, - {"s", "s"}, - {[]byte{1}, []byte{1}}, - {int32(-3), int64(-3)}, - {uint32(9), int64(9)}, - {float32(0.5), float64(0.5)}, - {float64(1.5), float64(1.5)}, - {uint64(11), int64(11)}, - } - for _, c := range cases { - got, err := vcvalue.Plain{V: c.in}.Value() - if err != nil { - t.Fatalf("Value(%#v): %v", c.in, err) - } - if !reflect.DeepEqual(got, c.want) { - t.Fatalf("Value(%#v) = %#v, want %#v", c.in, got, c.want) - } - } - - if _, err := (vcvalue.Plain{V: uint64(math.MaxInt64) + 1}).Value(); err == nil { - t.Fatal("uint64 above MaxInt64 must not silently truncate") - } - if _, err := (vcvalue.Plain{V: []any{int64(1)}}).Value(); err == nil { - t.Fatal("a container passthrough has no single-column form") - } -} - -// The remaining Sealed.Scan arms: nil source and the non-byte error arm -// (the byte round trip is covered with the marker types above). -func TestSealedScanNilAndErrorArms(t *testing.T) { - s := vcvalue.Sealed{1, 2, 3} - if err := s.Scan(nil); err != nil { - t.Fatalf("Scan(nil): %v", err) - } - if s != nil { - t.Fatalf("Scan(nil) should clear the leaf, got %#v", s) - } - if err := s.Scan("not bytes"); err == nil { - t.Fatal("scanning a string into Sealed must fail") - } -} diff --git a/languages/golang/encrypt/value/null.go b/languages/golang/encrypt/value/null.go deleted file mode 100644 index a9ebfd29c..000000000 --- a/languages/golang/encrypt/value/null.go +++ /dev/null @@ -1,48 +0,0 @@ -package vcvalue - -// FixedType names a fixed-width type: one whose every value seals to a leaf -// of the same length. An absent value of such a type is written as a typed -// null, padded to that length, so a sealed absence cannot be told from a -// sealed value by its length, as a plain null (one byte) could be. -// -// bool is fixed width too, but its leaf is already as short as a null's, -// and text and bytes are variable width, so neither has a FixedType. A UUID's -// sixteen bytes are fixed by its type, so it has one. -type FixedType uint8 - -// The fixed-width types, each named for the Go type it is written from. -// TypeInt64 and TypeUint64 cover int and uint too, as the codec writes them. -const ( - TypeInt8 FixedType = iota + 1 - TypeInt16 - TypeInt32 - TypeInt64 - TypeInt128 - TypeUint8 - TypeUint16 - TypeUint32 - TypeUint64 - TypeUint128 - TypeFloat32 - TypeFloat64 - TypeDate - TypeTimestamp - TypeDecimal - TypeUUID -) - -// Valid reports whether t is one of the named fixed-width types. -func (t FixedType) Valid() bool { - return t >= TypeInt8 && t <= TypeUUID -} - -// TypedNull is an absent value of a fixed-width type, for a caller whose Go -// type cannot say what is missing: a nil in a map[string]any or an []any. -// A nil pointer to a fixed-width type (*int32, *time.Time, *Date, …) is -// written as a typed null without it. -// -// It only encodes. A typed null decodes as nil, like every null: once -// decrypted, an absent value is absent whatever its type. -type TypedNull struct { - Type FixedType -} diff --git a/languages/golang/encrypt/value/scalars.go b/languages/golang/encrypt/value/scalars.go index 614a7e759..f275e2e84 100644 --- a/languages/golang/encrypt/value/scalars.go +++ b/languages/golang/encrypt/value/scalars.go @@ -1,4 +1,4 @@ -package vcvalue +package value import ( "errors" @@ -8,20 +8,20 @@ import ( ) var ( - ErrIntegerRange = errors.New("vcvalue: integer is outside its 128-bit range") - ErrInvalidDate = errors.New("vcvalue: invalid date") - ErrInvalidTimestamp = errors.New("vcvalue: invalid timestamp") - ErrInvalidDecimal = errors.New("vcvalue: invalid or out-of-range decimal") - ErrNonFiniteDecimal = errors.New("vcvalue: decimal must be finite") - ErrInvalidUUID = errors.New("vcvalue: invalid UUID") - ErrInvalidTagged = errors.New("vcvalue: a tagged value must hold a physical scalar under an unknown logical id") - ErrInvalidFixedType = errors.New("vcvalue: not a fixed-width type") + 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 two's-complement integer in little-endian byte order. +// Int128 is a signed 128-bit integer in two's complement, in little-endian +// byte order. type Int128 [16]byte -// Uint128 is an unsigned integer in little-endian byte order. +// Uint128 is an unsigned 128-bit integer in little-endian byte order. type Uint128 [16]byte func littleInteger(value *big.Int) [16]byte { @@ -72,10 +72,16 @@ func (v Int128) String() string { return value.String() } -// The wire's range is jiff's in every binding (vitaminc#626), so a value -// one binding seals, every binding opens: dates in years -9999 through -// 9999, and instants from -009999-01-02T01:59:59Z through -// 9999-12-30T22:00:00.999999999Z. +// 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 @@ -83,9 +89,9 @@ const ( maxTimestampSeconds = 253402207200 // 9999-12-30T22:00:00Z ) -// Date is a proleptic Gregorian calendar date, without time or timezone. -// Its range is the wire's, years -9999 through 9999, including year zero -// and BCE dates. +// 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 @@ -103,7 +109,8 @@ func (d Date) Validate() error { return nil } -// DaysFromCE returns the frozen wire day count (0001-01-01 is day 1). +// 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 @@ -117,12 +124,16 @@ func DateFromDaysCE(days int32) (Date, error) { return d, d.Validate() } -// Timestamp is an instant as Unix seconds and nanoseconds, for a caller -// that holds the parts rather than a time.Time. Timestamps decode to -// time.Time; this type only encodes. A leap second (nanoseconds of one -// billion or more) has no count since the epoch and is refused, as it is -// everywhere in the model (ADR 0001), and so is an instant outside the -// wire's range. +// 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 @@ -135,17 +146,22 @@ func (t Timestamp) Validate() error { return nil } -// UUID is sixteen bytes under the Uuid logical type: it travels in the -// 0xF3 envelope, since the type has no shorthand tag. ParseUUID reads the -// hyphenated hexadecimal spelling and String writes it in lower case. +// 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. // -// Another UUID type, such as github.com/google/uuid.UUID, is a plain -// [16]byte to the codec and is written as bytes. Convert it first, with -// vcvalue.UUID(id), so that Rust and Node read it as a UUID. +// 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 the hyphenated spelling, 8-4-4-4-12 hexadecimal digits in -// either case, and returns ErrInvalidUUID for anything else. +// 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] != '-' { @@ -178,7 +194,7 @@ func hexDigit(c byte) (byte, bool) { return 0, false } -// String is the hyphenated spelling in lower case. +// String returns u in its hyphenated form, in lower case. func (u UUID) String() string { const digits = "0123456789abcdef" var out [36]byte @@ -195,25 +211,41 @@ func (u UUID) String() string { return string(out[:]) } -// Tagged carries a scalar under a logical type this build does not know: -// the envelope's id and parameter, and the physical value as the Go native -// of its kind. A value from a newer client is read and re-encoded unchanged -// rather than dropped or mistaken for its bare physical value. V must be a -// physical scalar (nil, bool, an integer or float width, Int128, Uint128, -// string or []byte); ID must be above the ids this build knows. An int or -// uint is written as Int64 or UInt64, as everywhere else in the codec, so -// it reads back as int64 or uint64. +// 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 value: sign * Coefficient * 10^-Scale. -// Coefficient is an unsigned 96-bit little-endian integer. Scale is retained, -// including trailing zeroes, and must be at most 28 (rust_decimal's range). -// A zero has no sign: "-0.00" parses, decodes and encodes as 0.00 with its -// scale kept (ADR 0001). +// 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 @@ -227,8 +259,12 @@ func (d Decimal) Validate() error { return nil } -// ParseDecimal accepts exact fixed-point decimal text without rounding. -// NaN and infinities have their own error so callers can reject them by type. +// 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": @@ -277,7 +313,7 @@ func (d Decimal) IsZero() bool { return d.Coefficient == [12]byte{} } -// Normalized is the decimal with the sign dropped from a zero. +// Normalized returns d, with Negative cleared when d is zero. func (d Decimal) Normalized() Decimal { if d.IsZero() { d.Negative = false diff --git a/languages/golang/encrypt/value/scalars_test.go b/languages/golang/encrypt/value/scalars_test.go index 483684108..f3bc97a96 100644 --- a/languages/golang/encrypt/value/scalars_test.go +++ b/languages/golang/encrypt/value/scalars_test.go @@ -1,4 +1,4 @@ -package vcvalue +package value import ( "errors" @@ -38,7 +38,7 @@ func TestDecimalExactness(t *testing.T) { t.Fatalf("%s: %v %s", text, err, v.String()) } } - // A zero has no sign: the scale is kept and the sign is dropped (ADR 0001). + // 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() { @@ -82,7 +82,8 @@ func TestDatesAndTimestampBounds(t *testing.T) { t.Fatalf("accepted %v", d) } } - // The ends of the wire's range, which is jiff's. + // 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}} { @@ -90,8 +91,8 @@ func TestDatesAndTimestampBounds(t *testing.T) { t.Fatalf("rejected %v", ts) } } - // A leap second has no count since the epoch and is refused (ADR 0001). - // So is an instant past either end of the range. + // 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) diff --git a/languages/golang/encrypt/value/sealed.go b/languages/golang/encrypt/value/sealed.go deleted file mode 100644 index 0579f4457..000000000 --- a/languages/golang/encrypt/value/sealed.go +++ /dev/null @@ -1,125 +0,0 @@ -package vcvalue - -import ( - "database/sql/driver" - "fmt" - "math" -) - -// Sealed is one encrypted leaf: version(1) || nonce || ciphertext || tag — -// the only frozen byte format in the model. The leading wire-version byte is -// itself authenticated into the leaf's AAD, so a relabeled version fails the -// tag rather than selecting different parsing rules. Sealed is a named type -// so sealed bytes can never be confused with a plaintext []byte value in the -// dynamic ciphertext shape. -// -// Sealed implements driver.Valuer and sql.Scanner, so it stores into and -// loads from a BLOB/BYTEA column with no conversion. -type Sealed []byte - -// Value implements driver.Valuer: a Sealed binds as raw bytes. -func (s Sealed) Value() (driver.Value, error) { - return []byte(s), nil -} - -// Scan implements sql.Scanner: a BLOB/BYTEA column loads as a Sealed. -func (s *Sealed) Scan(src any) error { - b, err := scanLeafBytes(src, "Sealed") - *s = Sealed(b) - return err -} - -// SealedEmptySeq is the authenticated marker for an empty sequence: with no -// element ciphertexts to bind the AAD, the cipher seals an empty plaintext -// under domain-separated AAD instead. Produced by encrypting an empty array; -// decrypts back to an empty array. -type SealedEmptySeq []byte - -// SealedEmptyMap is the authenticated marker for an empty map, the map-shaped -// counterpart of SealedEmptySeq. Produced by encrypting an empty object; -// decrypts back to an empty object. -type SealedEmptyMap []byte - -// The marker types implement driver.Valuer and sql.Scanner like Sealed, so a -// column holding one stores and loads without conversion. -// -// ⚠️ The stored bytes do NOT record which leaf kind they are — every leaf is -// the same `version || nonce || ciphertext || tag` shape, and the kind is -// authenticated through domain-separated AAD, not written into the bytes. A -// marker scanned back into the wrong type (e.g. a SealedEmptySeq loaded as -// Sealed) fails decryption with an authentication error and no further hint. -// A column that can hold both real values and empty-composite markers needs -// the schema (or the application) to record which kind it stored; scan into -// the type matching that record. - -// Value implements driver.Valuer: the marker binds as raw bytes. -func (s SealedEmptySeq) Value() (driver.Value, error) { return []byte(s), nil } - -// Scan implements sql.Scanner — see the leaf-kind caveat above. -func (s *SealedEmptySeq) Scan(src any) error { - b, err := scanLeafBytes(src, "SealedEmptySeq") - *s = SealedEmptySeq(b) - return err -} - -// Value implements driver.Valuer: the marker binds as raw bytes. -func (s SealedEmptyMap) Value() (driver.Value, error) { return []byte(s), nil } - -// Scan implements sql.Scanner — see the leaf-kind caveat above. -func (s *SealedEmptyMap) Scan(src any) error { - b, err := scanLeafBytes(src, "SealedEmptyMap") - *s = SealedEmptyMap(b) - return err -} - -func scanLeafBytes(src any, into string) ([]byte, error) { - switch b := src.(type) { - case nil: - return nil, nil - case []byte: - return append([]byte(nil), b...), nil - default: - return nil, fmt.Errorf("vcvalue: cannot scan %T into %s", src, into) - } -} - -// Value implements driver.Valuer for passthrough fields, so a map-shaped -// ciphertext binds directly as database named parameters. Only scalar -// natives convert; a container passthrough has no single-column form. -func (p Plain) Value() (driver.Value, error) { - // Every integer kind the encoder accepts must convert here too: a value - // that encodes must also bind, or `Plain{V: user.ID}` with `ID int` works - // until it reaches the database driver. - switch v := p.V.(type) { - case nil, bool, int64, float64, string, []byte: - return v, nil - case int: - return int64(v), nil - case int8: - return int64(v), nil - case int16: - return int64(v), nil - case int32: - return int64(v), nil - case uint8: - return int64(v), nil - case uint16: - return int64(v), nil - case uint32: - return int64(v), nil - case float32: - return float64(v), nil - case uint: - if uint64(v) > math.MaxInt64 { - return nil, fmt.Errorf("vcvalue: passthrough uint %d overflows the driver's int64", v) - } - return int64(v), nil - case uint64: - if v > math.MaxInt64 { - return nil, fmt.Errorf("vcvalue: passthrough uint64 %d overflows the driver's int64", v) - } - return int64(v), nil - default: - return nil, fmt.Errorf("vcvalue: passthrough %T has no single-column driver representation", p.V) - } -} From c47a6bef77b21d59de3277ed9d1e5efc676c489a Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Wed, 2 Dec 2026 17:10:47 +1100 Subject: [PATCH 3/6] refactor(go)!: build the module on encrypt/frame and encrypt/value The module now encodes with its own copies of the frame codec and the value types, and imports nothing from vitaminc. Each value type is declared once, in encrypt/value. encrypt.Date, Decimal, Int128 and Uint128 stay aliases, as they were of vcvalue's types, so code that names only encrypt types needs no change. New aliases name the rest of what a program writes: encrypt.UUID (with ParseUUID), and encrypt.Encryptable and encrypt.Encoder, which are frame's. One type under two names means the codec encodes and decodes it with no conversion and no registry. Behaviour that changes with the move: - Without FixedWidth, a nil pointer to an Encryptable is written as a null, which the engine pads to the width of the field's declared type. A field that declares no type has no width to pad to, so the stored null's length would show that it is a null: Cipher.Seal refuses a nil Encryptable there, with ErrEncoding. Generated code always declares a type. - stashgen recognises the value types by their names in encrypt or in encrypt/value, so a field may be declared with either. BREAKING CHANGE: code that imports vitaminc's vcvalue or vcffi imports encrypt/value or encrypt/frame instead, or uses the encrypt aliases. The Encoder's unsigned methods are Uint8 to Uint128; what only vitaminc's own binding used (Sealed, TypedNull, FixedType, FixedWidth, VCValueLeaves and the rest) is gone. --- languages/golang/auth/answer_test.go | 14 +- languages/golang/auth/step.go | 14 +- languages/golang/auth/steps_test.go | 62 ++--- languages/golang/auth/store.go | 6 +- languages/golang/auth/strategy.go | 8 +- languages/golang/encrypt/audit_test.go | 8 +- languages/golang/encrypt/checker.go | 28 +- languages/golang/encrypt/ciphertext.go | 20 +- languages/golang/encrypt/client.go | 16 +- languages/golang/encrypt/conformance_test.go | 4 +- .../encrypt/context_conformance_test.go | 20 +- .../encrypt/declaration_conformance_test.go | 26 +- languages/golang/encrypt/diagnostic_test.go | 4 +- languages/golang/encrypt/doc.go | 14 +- languages/golang/encrypt/encoder.go | 25 ++ languages/golang/encrypt/errors.go | 13 +- .../encrypt/exchange_conformance_test.go | 4 +- languages/golang/encrypt/export_test.go | 14 +- languages/golang/encrypt/gensupport/codec.go | 41 +-- .../golang/encrypt/gensupport/convert.go | 37 ++- .../golang/encrypt/gensupport/declaration.go | 27 +- .../gensupport/gensupport_internal_test.go | 46 ++-- languages/golang/encrypt/gensupport/json.go | 36 +-- languages/golang/encrypt/gensupport/widen.go | 70 +++-- languages/golang/encrypt/guest_fuzz_test.go | 6 +- languages/golang/encrypt/json.go | 26 +- .../golang/encrypt/json_elements_test.go | 14 +- languages/golang/encrypt/json_match_test.go | 4 +- languages/golang/encrypt/json_tree_test.go | 36 +-- languages/golang/encrypt/keyset.go | 4 +- languages/golang/encrypt/kinds_test.go | 15 +- languages/golang/encrypt/query.go | 65 +++-- languages/golang/encrypt/query_test.go | 4 +- .../golang/encrypt/read_conformance_test.go | 8 +- languages/golang/encrypt/records.go | 69 +++-- languages/golang/encrypt/step.go | 14 +- .../golang/encrypt/step_parallel_test.go | 8 +- languages/golang/encrypt/step_test.go | 14 +- languages/golang/encrypt/targets_test.go | 120 ++++----- languages/golang/encrypt/testclient.go | 4 +- languages/golang/encrypt/typed_nil_test.go | 102 ++++++-- languages/golang/encrypt/unit_test.go | 17 +- .../golang/encrypt/value_conformance_test.go | 4 +- languages/golang/encrypt/value_kinds_test.go | 12 +- languages/golang/encrypt/values.go | 64 +++-- languages/golang/encrypt/values_test.go | 241 ++++++++++++++++++ languages/golang/internal/guest/answer.go | 42 ++- .../golang/internal/guest/answer_test.go | 32 +-- languages/golang/internal/guest/diagnostic.go | 24 +- .../golang/internal/guest/diagnostic_test.go | 4 +- languages/golang/internal/guest/wipe.go | 22 +- languages/golang/internal/guest/wipe_test.go | 18 +- languages/golang/internal/record/record.go | 34 +-- .../golang/internal/record/record_test.go | 30 +-- languages/golang/stashgen/read.go | 122 +++++---- languages/golang/stashgen/refusal_test.go | 6 + .../testdata/stubsdk/encrypt/encrypt.go | 25 +- .../testdata/stubsdk/encrypt/value/value.go | 21 ++ 58 files changed, 1132 insertions(+), 656 deletions(-) create mode 100644 languages/golang/encrypt/encoder.go create mode 100644 languages/golang/encrypt/values_test.go create mode 100644 languages/golang/stashgen/testdata/stubsdk/encrypt/value/value.go 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/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/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/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/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/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_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_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/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 + } +) From 2d0bb7a04b9491bfa70d2808829f5ef794e8bbe6 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Wed, 2 Dec 2026 17:11:20 +1100 Subject: [PATCH 4/6] build(go): drop the vitaminc requirements, and the release rule that guarded them Nothing in the module imports vitaminc's vcffi or vcvalue any more, so go.mod no longer requires them, and neither do the nested modules (encrypt/encrypttest, encrypt/example, examples/s3), which carried them as indirect requirements through the SDK they replace with a path. go mod tidy in each removes them and their go.sum lines, and changes nothing else. The TEMPORARY comment that explained the pin goes with it. scripts/go-release-version.mjs refused a final version while go.mod pinned a vitaminc module at a pseudo-version, because vitaminc's Go bindings had no tags. The module now has no dependency that could carry such a pin: the codec is in this repository. The rule and its tests go, and release-golang.yml no longer mentions it. A test now checks that the script reads the module path from the tree's go.mod and accepts a final version from main. Refs #1253 --- .github/workflows/release-golang.yml | 16 ++-- languages/golang/encrypt/encrypttest/go.mod | 2 - languages/golang/encrypt/encrypttest/go.sum | 4 - languages/golang/encrypt/example/go.mod | 2 - languages/golang/encrypt/example/go.sum | 4 - languages/golang/examples/s3/go.mod | 2 - languages/golang/examples/s3/go.sum | 4 - languages/golang/go.mod | 9 -- languages/golang/go.sum | 4 - scripts/__tests__/go-release-version.test.mjs | 94 +------------------ scripts/go-release-version.mjs | 43 +-------- 11 files changed, 18 insertions(+), 166 deletions(-) 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/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/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/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/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-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}`) From e2c4f46bcb16b8966a3dd94334fa77e7b2e8c308 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Wed, 2 Dec 2026 17:11:47 +1100 Subject: [PATCH 5/6] ci(go): fuzz the frame codec's decoders nightly, and test Go when the value corpus changes The frame codec came with three fuzz targets in encrypt/frame: FuzzUnmarshal, FuzzUnmarshalCipherText and FuzzUnmarshalStorage. The nightly go-fuzz-campaign job in fuzz.yml now fuzzes them, one matrix row each. They decode bytes in pure Go and run no guest, so their rows build no guest. `mise run go:fuzz` says that it fuzzes the codec as well as the guests' ABI. encrypt/frame's tests read conformance/vitaminc-aead, so tests-golang.yml now starts when that corpus changes. The storage corpus, under packages/recipher-frame, already starts it. scripts/go-binding-test.sh names the codec's new path in a comment. --- .github/workflows/fuzz.yml | 17 ++++++++++++----- .github/workflows/tests-golang.yml | 4 ++++ mise.toml | 2 +- scripts/go-binding-test.sh | 9 +++++---- 4 files changed, 22 insertions(+), 10 deletions(-) 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/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/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/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 From 5aa6552475eb3b6e9d905194376ef1c13cbdbebc Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Wed, 2 Dec 2026 17:12:04 +1100 Subject: [PATCH 6/6] docs(go): say where the frame codec and the value types now live, and record the breaking change vitaminc's vcffi and vcvalue are now encrypt/frame and encrypt/value, so the documents that named vitaminc's Go packages, or the module's own copy under internal/, name these instead: - AGENTS.md lists the two packages with the module's others, and says that encrypt's value types, Encryptable and Encoder are aliases of theirs. - languages/golang/CHANGELOG.md records the move under Breaking, with what changes for code that imported vcvalue or vcffi, and the new aliases and packages under Added. - docs/fuzzing.md lists the codec's three fuzz targets, and the plan for moving vitaminc's code here records stage 3 as done, two packages and all. - The SDK's README, stashgen's README, the conformance READMEs, recipher-frame's STORAGE.md, and comments in the Rust crates whose formats the Go codec matches, point at encrypt/frame. These documents are also rewritten in plain language where the review asked, including comments in Cargo.toml files about the guests' shared ABI. No code changes. --- AGENTS.md | 8 ++- .../stack-encrypt/exchange-contract.md | 2 +- conformance/vitaminc-aead/README.md | 13 ++-- docs/fuzzing.md | 29 ++++++++- ...11-14-move-vitaminc-aead-into-the-stack.md | 33 ++++++++++ languages/golang/CHANGELOG.md | 64 +++++++++++++++++-- languages/golang/auth/guest/Cargo.toml | 8 +-- languages/golang/cmd/stashgen/README.md | 3 +- languages/golang/encrypt/README.md | 8 ++- languages/golang/encrypt/guest/Cargo.toml | 8 +-- packages/recipher-frame/STORAGE.md | 9 +-- packages/recipher-frame/tests/serde.rs | 7 +- packages/stack-encrypt/Cargo.toml | 14 ++-- packages/stack-encrypt/src/blob.rs | 11 ++-- packages/stack-encrypt/tests/opaque_blob.rs | 14 ++-- packages/stack-encrypt/tests/value_bytes.rs | 6 +- packages/stack-guest-abi/Cargo.toml | 4 +- packages/stack-guest-abi/src/buffers.rs | 7 +- packages/stack-guest-abi/src/value.rs | 17 +++-- 19 files changed, 198 insertions(+), 67 deletions(-) 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/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/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/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/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/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::{