From 36070621d6c513cc4a9c2648f861510c11b5a2e7 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sat, 28 Nov 2026 01:41:00 +1100 Subject: [PATCH 01/10] fix(golang): say what a "not an object" error found, and that guest answers are internal A Go user could see "not an object" in four places, and none said what was there in words, or which operation it was: a map field that opened as another kind printed a Go type (`[]interface {}`) and never said decrypt; a Match whose vars were not an object said "the input is not the object the JSON operator takes"; and a guest answer this module could not read said "came back as T, not an object", which reads like bad input when it is an internal failure. - O2: a map field (`map[string]V`, `Values`, `map[string]any`) that opens as something else is `decrypt: field "x": ... opened as a list, and map[string]any needs an object`. The kind is in words, never the value. - N1: the engine gives vars that are not a JSON object their own reason, `json_vars_not_object`, with `found` (`array`, `uint64`, `null`, ...), and says `match takes its vars as a JSON object, found null`. The typed and the dynamic paths share the check; the field reaches Go's `Diagnostic.Field`. - O3, O4, O5: answers from se_query_term, se_targets, se_operators, se_contexts, sa_token, sa_secret_key and sa_device_identity that this module cannot read stay ErrInternal. They now name the export, say what the answer is by its kind, and say this is a bug or a guest that does not match this module's version, through one helper, `guest.BadAnswer`, with `guest.KindOf` for the words. Tests cover each message, including O2's and O5's, which had none. Stacked on the engine branch for the row and found fields it adds. Closes #1987 --- languages/golang/CHANGELOG.md | 18 ++++++ languages/golang/auth/answer_test.go | 50 +++++++++++++++ languages/golang/auth/store.go | 13 ++-- languages/golang/auth/token.go | 2 +- languages/golang/cmd/stashgen/README.md | 4 +- languages/golang/encrypt/checker.go | 21 ++++--- languages/golang/encrypt/gensupport/codec.go | 2 +- .../golang/encrypt/gensupport/convert.go | 15 +++-- .../gensupport/gensupport_internal_test.go | 36 +++++++++++ languages/golang/encrypt/gensupport/json.go | 5 +- languages/golang/encrypt/json_match_test.go | 35 ++++++++--- languages/golang/encrypt/query.go | 5 +- languages/golang/encrypt/targets_test.go | 37 ++++++++++- languages/golang/internal/guest/answer.go | 50 +++++++++++++++ .../golang/internal/guest/answer_test.go | 63 +++++++++++++++++++ packages/stack-encrypt/CHANGELOG.md | 8 +++ .../stack-encrypt/src/dynamic/json_query.rs | 8 +-- packages/stack-encrypt/src/json/inputs.rs | 26 +++++++- packages/stack-encrypt/src/refusal.rs | 17 +++-- .../stack-encrypt/tests/json_operators.rs | 50 ++++++++++++++- 20 files changed, 415 insertions(+), 50 deletions(-) create mode 100644 languages/golang/auth/answer_test.go create mode 100644 languages/golang/internal/guest/answer.go create mode 100644 languages/golang/internal/guest/answer_test.go diff --git a/languages/golang/CHANGELOG.md b/languages/golang/CHANGELOG.md index 3692bd9a3e..4f9da3d23d 100644 --- a/languages/golang/CHANGELOG.md +++ b/languages/golang/CHANGELOG.md @@ -33,6 +33,24 @@ and `languages/golang/encrypt/encrypttest/vX.Y.Z` on the same commit. ### Changed +- **`Match` refuses `vars` that are not a JSON object with the reason + `json_vars_not_object`, not `json_input`** (#1987). `Found` says what + they are (`"array"`, `"uint64"`, `"null"`), `Field` names the field, + and the message says `match takes its vars as a JSON object, found + null`. A program that switches on `Reason()` for this case needs the + new name. + +- **Errors that say "not an object" now say what was found, in words** + (#1987). A map field (`map[string]V`, `Values`, `map[string]any`) whose + stored value opens as something else is refused as `decrypt: field + "tags": ... opened as a list, and map[string]any needs an object`, + where it said `opened as []interface {}, not an object`. A guest answer + this module cannot read (from `se_query_term`, `se_targets`, + `se_operators`, `se_contexts`, `sa_token`, `sa_secret_key` or + `sa_device_identity`) is still `ErrInternal`, and now names the export, + says what the answer is by its kind, and says it is a bug or a guest + that does not match this module's version, not bad input. + - **A record field converts a number of another width or kind, as a query does.** A value sealed through `Cipher.Seal` for a field that declares a type is read as that type when the conversion is exact: an diff --git a/languages/golang/auth/answer_test.go b/languages/golang/auth/answer_test.go new file mode 100644 index 0000000000..32cbaf15be --- /dev/null +++ b/languages/golang/auth/answer_test.go @@ -0,0 +1,50 @@ +package auth + +import ( + "errors" + "strings" + "testing" + + "github.com/cipherstash/vitaminc/bindings/go/vcffi" + "github.com/cipherstash/vitaminc/bindings/go/vcvalue" +) + +// An auth guest's answer that is not an object is an internal failure that +// names the export and says what the answer is, by its kind: never its +// value, which can be a key or a token. +func TestAnAnswerThatIsNotAnObjectNamesTheExportAndItsKind(t *testing.T) { + for _, tc := range []struct { + answer any + kind string + }{ + {[]any{"secret-token"}, "a list"}, + {"secret-token", "a string"}, + {[]byte("secret-key"), "bytes"}, + } { + encoded, err := vcffi.Marshal(tc.answer) + if err != nil { + t.Fatal(err) + } + _, err = object("sa_token", encoded) + if !errors.Is(err, ErrInternal) { + t.Fatalf("%s: %v, want ErrInternal", tc.kind, err) + } + want := "cipherstash: internal guest failure: the guest's answer to sa_token does not read: it is " + tc.kind + ", not an object; this is a bug, or a guest that does not match this module's version" + if err.Error() != want { + t.Errorf("message:\n got %q\nwant %q", err.Error(), want) + } + if strings.Contains(err.Error(), "secret") { + t.Errorf("the error holds the answer: %v", err) + } + } + encoded, err := vcffi.Marshal(vcvalue.Object{{Key: "access_token", Value: "t"}}) + if err != nil { + t.Fatal(err) + } + if fields, err := object("sa_token", encoded); err != nil || len(fields) != 1 { + t.Fatalf("an object: %v, %v", fields, err) + } + if _, err := object("sa_token", []byte{0xff}); !errors.Is(err, ErrInternal) || !strings.Contains(err.Error(), "sa_token") { + t.Errorf("bytes that do not decode: %v", err) + } +} diff --git a/languages/golang/auth/store.go b/languages/golang/auth/store.go index c591ad65f8..2e5936301c 100644 --- a/languages/golang/auth/store.go +++ b/languages/golang/auth/store.go @@ -484,7 +484,7 @@ func (s *ProfileStore) SecretKey(ctx context.Context) (clientID string, key *Cli return "", nil, err } defer guest.Wipe(out) - fields, err := object(out) + fields, err := object("sa_secret_key", out) if err != nil { return "", nil, err } @@ -518,7 +518,7 @@ func (s *ProfileStore) DeviceIdentity(ctx context.Context) (DeviceIdentity, erro if err != nil { return DeviceIdentity{}, err } - fields, err := object(out) + fields, err := object("sa_device_identity", out) if err != nil { return DeviceIdentity{}, err } @@ -535,14 +535,17 @@ func (s *ProfileStore) DeviceIdentity(ctx context.Context) (DeviceIdentity, erro // fields is a decoded codec object. type fields vcvalue.Object -func object(encoded []byte) (fields, error) { +// object decodes export's answer as an object. One that is not is +// ErrInternal, saying what it is by its kind and never its value: the +// answer can hold a key or a token. +func object(export string, encoded []byte) (fields, error) { decoded, err := vcffi.Unmarshal(encoded) if err != nil { - return nil, fmt.Errorf("%w: decoding the guest's result: %w", ErrInternal, err) + return nil, fmt.Errorf("%w: decoding the guest's answer to %s: %w", ErrInternal, export, err) } obj, ok := decoded.(vcvalue.Object) if !ok { - return nil, fmt.Errorf("%w: the guest's result is not an object", ErrInternal) + return nil, guest.BadAnswer(export, fmt.Errorf("it is %s, not an object", guest.KindOf(decoded))) } return fields(obj), nil } diff --git a/languages/golang/auth/token.go b/languages/golang/auth/token.go index 3e9825d6ca..d0dd259a43 100644 --- a/languages/golang/auth/token.go +++ b/languages/golang/auth/token.go @@ -43,7 +43,7 @@ func (s *ProfileStore) Token(ctx context.Context) (Token, error) { return Token{}, err } defer guest.Wipe(out) - fields, err := object(out) + fields, err := object("sa_token", out) if err != nil { return Token{}, err } diff --git a/languages/golang/cmd/stashgen/README.md b/languages/golang/cmd/stashgen/README.md index 5c4b1800a4..58c69f9cc3 100644 --- a/languages/golang/cmd/stashgen/README.md +++ b/languages/golang/cmd/stashgen/README.md @@ -283,7 +283,7 @@ SELECT id FROM entity WHERE eql_v4.json_tree_match(custom_field_values, $1::eql_ `vars` are any value `encoding/json` writes as a JSON object (a map, a struct, or a `json.RawMessage` of one), and an empty map when the predicate has none; a Go string is refused, as it is for a `Contains` needle. A nil `vars` (`nil`, or a nil map, slice or pointer) does not mean "no variables". pgx and `database/sql` bind it as SQL `NULL`, and `jsonb_path_match` with `NULL` vars is `NULL` for every row, so `Match` does the same: it returns an empty operand, which binds as `NULL`, and the query matches no row. -The predicate is still compiled, so text the grammar does not read is still refused. `vars` that write the JSON `null`, such as `json.RawMessage("null")` or a pointer to a nil map, are refused as `json_input`, as plaintext refuses vars that are not an object. +The predicate is still compiled, so text the grammar does not read is still refused. `vars` that write the JSON `null`, such as `json.RawMessage("null")` or a pointer to a nil map, are refused as `json_vars_not_object`, as plaintext refuses vars that are not an object. The Go side reads nothing of the predicate: the engine parses it and compiles it into a tree of the operands the methods above derive, one leaf per comparison. The grammar is the subset of SQL/JSON path that the stored terms can answer, as PostgreSQL reads it: @@ -308,7 +308,7 @@ Anything else is refused before any term is derived, as an `*encrypt.Diagnostic` - `json_path_no_wildcard`: a filter on a path with no `[*]`. - `json_path_wildcard`: a `[*]` in a filter's member. - `json_syntax`: JSON text that does not parse, a literal in the predicate (`1e999`) or `vars` (`{`, or an empty or whitespace-only `json.RawMessage`); with `At()` for a literal, without it for `vars`. -- `json_input`: `vars` that are not a JSON object (`[1]`, `1`, `null`). +- `json_vars_not_object`: `vars` that are not a JSON object (`[1]`, `1`, `null`), with `Found()` naming what they are (`"array"`, `"uint64"`, `"null"`). An ordering at a path the tag does not order is `encrypt.ErrTerm` with the code `stack_encrypt::json_path_not_ordered`. diff --git a/languages/golang/encrypt/checker.go b/languages/golang/encrypt/checker.go index ca448fbc3b..d288fdc179 100644 --- a/languages/golang/encrypt/checker.go +++ b/languages/golang/encrypt/checker.go @@ -110,7 +110,7 @@ func (k *Checker) Operators(ctx context.Context, plan *record.Plan, field string } operators, err := parseOperators(decoded) if err != nil { - return nil, fmt.Errorf("%w: se_operators: %v", ErrInternal, err) + return nil, guest.BadAnswer("se_operators", err) } return operators, nil } @@ -149,7 +149,7 @@ func contextsOf(ctx context.Context, c *Client, plan *record.Plan) (string, erro } text, ok := decoded.(string) if !ok { - return "", fmt.Errorf("%w: se_contexts returned %T, not a string", ErrInternal, decoded) + return "", guest.BadAnswer("se_contexts", fmt.Errorf("it is %s, not a string", guest.KindOf(decoded))) } return text, nil } @@ -162,22 +162,25 @@ func contextsOf(ctx context.Context, c *Client, plan *record.Plan) (string, erro // encrypt_into on a type with no kind or no indexes. func parseTargets(decoded any) ([]record.Target, error) { obj, ok := decoded.(vcvalue.Object) - if !ok || len(obj) != 1 || obj[0].Key != "targets" { - return nil, fmt.Errorf("%w: se_targets returned %T, not {\"targets\": [...]}", ErrInternal, decoded) + if !ok { + return nil, guest.BadAnswer("se_targets", fmt.Errorf("it is %s, not an object", guest.KindOf(decoded))) + } + if len(obj) != 1 || obj[0].Key != "targets" { + return nil, guest.BadAnswer("se_targets", errors.New(`it is not {"targets": [...]}`)) } items, ok := obj[0].Value.([]any) if !ok { - return nil, fmt.Errorf("%w: se_targets returned %T for the list", ErrInternal, obj[0].Value) + return nil, guest.BadAnswer("se_targets", fmt.Errorf("targets is %s, not a list", guest.KindOf(obj[0].Value))) } targets := make([]record.Target, 0, len(items)) for i, item := range items { entry, ok := item.(vcvalue.Object) if !ok { - return nil, fmt.Errorf("%w: target %d came back as %T", ErrInternal, i, item) + return nil, guest.BadAnswer("se_targets", fmt.Errorf("target %d is %s, not an object", i, guest.KindOf(item))) } t, err := parseTarget(entry) if err != nil { - return nil, fmt.Errorf("%w: target %d: %v", ErrInternal, i, err) + return nil, guest.BadAnswer("se_targets", fmt.Errorf("target %d: %v", i, err)) } targets = append(targets, t) } @@ -266,13 +269,13 @@ func parseTarget(entry vcvalue.Object) (record.Target, error) { func parseOperators(value any) ([]record.Operator, error) { list, ok := value.([]any) if !ok { - return nil, fmt.Errorf("operators is %T, not a list", value) + return nil, fmt.Errorf("operators is %s, not a list", guest.KindOf(value)) } operators := make([]record.Operator, 0, len(list)) for i, item := range list { entry, ok := item.(vcvalue.Object) if !ok { - return nil, fmt.Errorf("operator %d is %T, not an object", i, item) + return nil, fmt.Errorf("operator %d is %s, not an object", i, guest.KindOf(item)) } var op record.Operator seen := map[string]bool{} diff --git a/languages/golang/encrypt/gensupport/codec.go b/languages/golang/encrypt/gensupport/codec.go index 63e8289990..04ae5ad667 100644 --- a/languages/golang/encrypt/gensupport/codec.go +++ b/languages/golang/encrypt/gensupport/codec.go @@ -305,7 +305,7 @@ func Get[T any](vals Values, name string) (T, error) { return out, nil } if err := convert(v, &out); err != nil { - return out, fmt.Errorf("gensupport: field %q: %w: %w", name, encrypt.ErrEncoding, err) + return out, fmt.Errorf("gensupport: decrypt: field %q: %w: %w", name, encrypt.ErrEncoding, err) } return out, nil } diff --git a/languages/golang/encrypt/gensupport/convert.go b/languages/golang/encrypt/gensupport/convert.go index 678c527f00..94aa6d820e 100644 --- a/languages/golang/encrypt/gensupport/convert.go +++ b/languages/golang/encrypt/gensupport/convert.go @@ -8,6 +8,7 @@ import ( "reflect" "strconv" + "github.com/cipherstash/stack/languages/golang/internal/guest" "github.com/cipherstash/vitaminc/bindings/go/vcvalue" ) @@ -108,13 +109,13 @@ func convert(v any, out any) error { return mismatch(v, *out) } case *Values: - vals, err := valuesOf(v) + vals, err := valuesOf(v, "gensupport.Values") if err != nil { return err } *out = vals case *map[string]any: - vals, err := valuesOf(v) + vals, err := valuesOf(v, "map[string]any") if err != nil { return err } @@ -210,7 +211,7 @@ func convertVia(v any, out any) error { if t.Key().Kind() != reflect.String { return fmt.Errorf("%s has a key that is not a string", t) } - vals, err := valuesOf(v) + vals, err := valuesOf(v, t.String()) if err != nil { return err } @@ -393,13 +394,15 @@ func setSlice[E any](v any, out *[]E) error { } // valuesOf reads an opened composite as Values, nested objects included. -func valuesOf(v any) (Values, error) { +// want is the Go type the field needs, which a refusal names beside what +// the value opened as, by its kind and never its value. +func valuesOf(v any, want string) (Values, error) { switch obj := v.(type) { case vcvalue.Object: vals := make(Values, len(obj)) for _, f := range obj { if inner, ok := f.Value.(vcvalue.Object); ok { - nested, err := valuesOf(inner) + nested, err := valuesOf(inner, want) if err != nil { return nil, err } @@ -414,5 +417,5 @@ func valuesOf(v any) (Values, error) { case map[string]any: return Values(obj), nil } - return nil, fmt.Errorf("opened as %T, not an object", v) + return nil, fmt.Errorf("opened as %s, and %s needs an object", guest.KindOf(v), want) } diff --git a/languages/golang/encrypt/gensupport/gensupport_internal_test.go b/languages/golang/encrypt/gensupport/gensupport_internal_test.go index c1667dd374..cc1c2ecf53 100644 --- a/languages/golang/encrypt/gensupport/gensupport_internal_test.go +++ b/languages/golang/encrypt/gensupport/gensupport_internal_test.go @@ -655,3 +655,39 @@ func TestOpaqueReadsARustWrittenBlob(t *testing.T) { t.Fatalf("Opaque of the Go-written blob: %v %+v", err, back) } } + +// A field of map type whose stored value opens as something else, a row +// written by another SDK or an older struct, is refused as decrypt's +// malformed input: the field, what it opened as by its kind, never its +// value, and the Go type that needs an object. +func TestAMapFieldThatOpensAsAnotherKindSaysWhatItOpenedAs(t *testing.T) { + read := func(read func(Values, string) error, v any) error { + return read(Values{"tags": v}, "tags") + } + asAny := func(vals Values, name string) error { _, err := Get[map[string]any](vals, name); return err } + asValues := func(vals Values, name string) error { _, err := Get[Values](vals, name); return err } + asInts := func(vals Values, name string) error { _, err := Get[map[string]int64](vals, name); return err } + for _, tc := range []struct { + read func(Values, string) error + value any + kind string + want string + }{ + {asAny, []any{"secret"}, "a list", "map[string]any"}, + {asAny, "secret", "a string", "map[string]any"}, + {asValues, int64(7), "a number", "gensupport.Values"}, + {asInts, []any{"secret"}, "a list", "map[string]int64"}, + } { + err := read(tc.read, tc.value) + if !errors.Is(err, encrypt.ErrEncoding) { + t.Fatalf("%s for %s: %v, want ErrEncoding", tc.kind, tc.want, err) + } + want := fmt.Sprintf(`gensupport: decrypt: field "tags": cipherstash: malformed input: opened as %s, and %s needs an object`, tc.kind, tc.want) + if err.Error() != want { + t.Errorf("message:\n got %q\nwant %q", err.Error(), want) + } + if strings.Contains(err.Error(), "secret") || strings.Contains(err.Error(), "7") { + t.Errorf("the error holds the value: %v", err) + } + } +} diff --git a/languages/golang/encrypt/gensupport/json.go b/languages/golang/encrypt/gensupport/json.go index 5a27261849..d9eb4b2962 100644 --- a/languages/golang/encrypt/gensupport/json.go +++ b/languages/golang/encrypt/gensupport/json.go @@ -340,8 +340,9 @@ func JSONElementMatch[Q ~[]byte, T, E any](ctx context.Context, f Field[T], c *e // compiled, so text the grammar does not read is still refused; a // variable it names is not, as plaintext does not look for one. // - A value that writes the JSON null (a json.RawMessage of null, or a -// pointer to a nil map) is refused as not an object, as plaintext -// refuses "vars" that are not an object. +// pointer to a nil map) is refused as not an object, with the reason +// json_vars_not_object, as plaintext refuses "vars" that are not an +// object. // - Any other json.RawMessage crosses as it is, so an empty or // whitespace-only one is refused by the engine as not JSON, as "{" is. // diff --git a/languages/golang/encrypt/json_match_test.go b/languages/golang/encrypt/json_match_test.go index 8ae6d3bb80..bdf25636fa 100644 --- a/languages/golang/encrypt/json_match_test.go +++ b/languages/golang/encrypt/json_match_test.go @@ -299,28 +299,43 @@ func TestMatchRefusalsNameTheConstructAndItsOffset(t *testing.T) { } } - // The input itself: vars that are not an object, or not JSON. + // The input itself: vars that are not an object, or not JSON. Vars that + // are not an object say what they are, by kind and never value, and + // name the field. for _, tc := range []struct { name string vars any reason string + found string }{ - {"vars that are a list", []string{"secret-nz"}, "json_input"}, - {"vars that are a number", 1, "json_input"}, - {"vars that are not JSON", json.RawMessage(`{"v": "secret-nz"`), "json_syntax"}, - {"vars that are an empty json.RawMessage", json.RawMessage{}, "json_syntax"}, - {"vars that are whitespace", json.RawMessage(" \t\n "), "json_syntax"}, + {"vars that are a list", []string{"secret-nz"}, "json_vars_not_object", "array"}, + {"vars that are a number", 1, "json_vars_not_object", "uint64"}, + {"vars that are not JSON", json.RawMessage(`{"v": "secret-nz"`), "json_syntax", ""}, + {"vars that are an empty json.RawMessage", json.RawMessage{}, "json_syntax", ""}, + {"vars that are whitespace", json.RawMessage(" \t\n "), "json_syntax", ""}, // Not nil, but the JSON null: not an object, as plaintext refuses it. - {"vars that are the JSON null", json.RawMessage(`null`), "json_input"}, - {"vars that are the JSON null with space", json.RawMessage(" null\n"), "json_input"}, - {"vars that point to a nil map", func() any { var m map[string]any; return &m }(), "json_input"}, + {"vars that are the JSON null", json.RawMessage(`null`), "json_vars_not_object", "null"}, + {"vars that are the JSON null with space", json.RawMessage(" null\n"), "json_vars_not_object", "null"}, + {"vars that point to a nil map", func() any { var m map[string]any; return &m }(), "json_vars_not_object", "null"}, } { _, err := f.Match(ctx, cipher, `$.extra.country == $v`, tc.vars, encrypt.JSONReadOptions{}) var d *encrypt.Diagnostic if !errors.Is(err, encrypt.ErrEncoding) || !errors.As(err, &d) || d.Reason() != tc.reason { t.Errorf("%s: %v, want ErrEncoding with reason %s", tc.name, err, tc.reason) + continue + } + if d.Found() != tc.found { + t.Errorf("%s: found %q, want %q", tc.name, d.Found(), tc.found) + } + if tc.found != "" { + if d.Field() != "custom_field_values" { + t.Errorf("%s: field %q, want custom_field_values", tc.name, d.Field()) + } + if !strings.Contains(err.Error(), "match takes its vars as a JSON object, found ") { + t.Errorf("%s: %v does not say what match takes", tc.name, err) + } } - if err != nil && strings.Contains(err.Error(), "secret") { + if strings.Contains(err.Error(), "secret") { t.Errorf("%s: the error holds a value: %v", tc.name, err) } } diff --git a/languages/golang/encrypt/query.go b/languages/golang/encrypt/query.go index 2d831d8d73..fa0d807b7b 100644 --- a/languages/golang/encrypt/query.go +++ b/languages/golang/encrypt/query.go @@ -8,6 +8,7 @@ import ( "log/slog" "math" + "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" @@ -168,7 +169,7 @@ func (cph *Cipher) QueryTerm(ctx context.Context, plan *record.Plan, field, oper } term, err := parseQueryTerm(decoded) if err != nil { - return QueryTerm{}, fmt.Errorf("%w: se_query_term: %v", ErrInternal, err) + return QueryTerm{}, guest.BadAnswer("se_query_term", err) } return term, nil } @@ -183,7 +184,7 @@ func (cph *Cipher) QueryTerm(ctx context.Context, plan *record.Plan, field, oper func parseQueryTerm(decoded any) (QueryTerm, error) { obj, ok := decoded.(vcvalue.Object) if !ok { - return QueryTerm{}, fmt.Errorf("came back as %T, not an object", decoded) + return QueryTerm{}, fmt.Errorf("it is %s, not an object", guest.KindOf(decoded)) } var t QueryTerm var shape string diff --git a/languages/golang/encrypt/targets_test.go b/languages/golang/encrypt/targets_test.go index 451fcc7ab6..e3016f0667 100644 --- a/languages/golang/encrypt/targets_test.go +++ b/languages/golang/encrypt/targets_test.go @@ -3,6 +3,7 @@ package encrypt import ( "errors" "reflect" + "strings" "testing" "github.com/cipherstash/stack/languages/golang/internal/record" @@ -83,9 +84,29 @@ func TestParseTargetsReadsEachEntry(t *testing.T) { "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"}}}), } { - if _, err := parseTargets(bad); !errors.Is(err, ErrInternal) { + _, err := parseTargets(bad) + if !errors.Is(err, ErrInternal) { t.Errorf("%s: %v, want ErrInternal", name, err) } + if err != nil && !strings.Contains(err.Error(), "the guest's answer to se_targets does not read") { + t.Errorf("%s: %v does not name the export", name, err) + } + } + // What was found is named by its kind, never its value: the answer + // itself, its list, an entry, and an operator of an entry. + for _, tc := range []struct { + answer any + 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"}, + {withOperators([]any{"secret"}), "target 0: operator 0 is a string, not an object"}, + } { + _, err := parseTargets(tc.answer) + if err == nil || !strings.Contains(err.Error(), tc.want) || strings.Contains(err.Error(), "secret") { + t.Errorf("%v, want it to say %q and hold no value", err, tc.want) + } } } @@ -126,6 +147,20 @@ func TestParseQueryTermTakesOnlyWhatTheEngineWrites(t *testing.T) { t.Errorf("catalog %s: %v", name, err) } } + // An answer that is not an object says what it is, by its kind. + for _, tc := range []struct { + answer any + want string + }{ + {[]any{"secret"}, "it is a list, not an object"}, + {nil, "it is null, not an object"}, + {"secret", "it is a string, not an object"}, + } { + _, err := parseQueryTerm(tc.answer) + if err == nil || err.Error() != tc.want { + t.Errorf("parseQueryTerm(%T) = %v, want %q", tc.answer, err, tc.want) + } + } for name, bad := range map[string]vcvalue.Object{ "unknown operator": term("like", "exact", "eq"), "operator case": term("Eq", "exact", "eq"), diff --git a/languages/golang/internal/guest/answer.go b/languages/golang/internal/guest/answer.go new file mode 100644 index 0000000000..755b97e784 --- /dev/null +++ b/languages/golang/internal/guest/answer.go @@ -0,0 +1,50 @@ +package guest + +import ( + "fmt" + + "github.com/cipherstash/vitaminc/bindings/go/vcvalue" +) + +// KindOf names what a decoded value is, by its kind and never its value: +// "null", "an object", "a list", "a string", "a number", and so on. It is +// what an error says it found where it expected something else, so the +// error can be logged without leaking the value. +func KindOf(v any) string { + switch v.(type) { + case nil, vcvalue.TypedNull: + return "null" + case vcvalue.Object: + return "an object" + case []any: + return "a list" + case string: + return "a string" + case []byte: + return "bytes" + case bool: + return "a boolean" + case int8, int16, int32, int64, uint8, uint16, uint32, uint64, vcvalue.Int128, vcvalue.Uint128, float32, float64: + return "a number" + case vcvalue.Date: + return "a date" + case vcvalue.Timestamp: + return "a timestamp" + case vcvalue.Decimal: + return "a decimal" + case vcvalue.UUID: + return "a UUID" + default: + return "a single value" + } +} + +// BadAnswer is the error for a guest export's answer this module cannot +// read: ErrInternal, naming the export and what was wrong with the answer. +// The caller's input is not at fault. The answer's shape is a contract +// between the guest and this module, so a bad one is a bug, or a guest that +// does not match this module's version, such as a guest built from other +// source than the module that embeds it. +func BadAnswer(export string, problem error) error { + return fmt.Errorf("%w: the guest's answer to %s does not read: %v; this is a bug, or a guest that does not match this module's version", ErrInternal, export, problem) +} diff --git a/languages/golang/internal/guest/answer_test.go b/languages/golang/internal/guest/answer_test.go new file mode 100644 index 0000000000..ed2a72f784 --- /dev/null +++ b/languages/golang/internal/guest/answer_test.go @@ -0,0 +1,63 @@ +package guest_test + +import ( + "errors" + "strings" + "testing" + + "github.com/cipherstash/stack/languages/golang/internal/guest" + "github.com/cipherstash/vitaminc/bindings/go/vcvalue" +) + +// KindOf names a decoded value by its kind, never its value. +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"}, + {[]any{"secret"}, "a list"}, + {"secret", "a string"}, + {[]byte("secret"), "bytes"}, + {true, "a boolean"}, + {int8(1), "a number"}, + {int16(1), "a number"}, + {int32(1), "a number"}, + {int64(1), "a number"}, + {uint8(1), "a number"}, + {uint16(1), "a number"}, + {uint32(1), "a number"}, + {uint64(1), "a number"}, + {vcvalue.Int128{}, "a number"}, + {vcvalue.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"}, + {struct{ secret string }{"secret"}, "a single value"}, + } { + if got := guest.KindOf(tc.value); got != tc.want { + t.Errorf("KindOf(%T) = %q, want %q", tc.value, got, tc.want) + } + } +} + +// A guest answer this module cannot read is an internal failure that names +// the export and what was wrong, and says it is not the caller's input. +func TestBadAnswerIsInternalAndNamesTheExport(t *testing.T) { + err := guest.BadAnswer("se_query_term", errors.New("it is a list, not an object")) + if !errors.Is(err, guest.ErrInternal) { + t.Fatalf("%v is not ErrInternal", err) + } + want := "cipherstash: internal guest failure: the guest's answer to se_query_term does not read: it is a list, not an object; this is a bug, or a guest that does not match this module's version" + if err.Error() != want { + t.Errorf("message:\n got %q\nwant %q", err.Error(), want) + } + if strings.Contains(err.Error(), "malformed input") { + t.Errorf("reads as bad input: %v", err) + } +} diff --git a/packages/stack-encrypt/CHANGELOG.md b/packages/stack-encrypt/CHANGELOG.md index 2e3388e079..2863fa5872 100644 --- a/packages/stack-encrypt/CHANGELOG.md +++ b/packages/stack-encrypt/CHANGELOG.md @@ -538,6 +538,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 every field needs `..`. Reason codes do not change, except the two new ones. +- **A `match` query's `vars` that are not a JSON object have their own + reason, `json_vars_not_object`, and say what they are** (#1987). Before, + they were `json_input`, the reason for any input a JSON operator does + not take, with nothing more. Now the error names the field, gives + `found` (`"array"`, `"uint64"`, `"null"`, ...), and says + `match takes its vars as a JSON object, found null`. The dynamic and + the typed paths refuse them alike. + - **`dynamic::ValueFrame` is removed. The engine reads a plaintext as a borrowed `Frame` and keeps one as vitaminc's `OwnedFrame`** (#1955). `dynamic::frame` re-exports both from vitaminc. A `Frame` is one value's diff --git a/packages/stack-encrypt/src/dynamic/json_query.rs b/packages/stack-encrypt/src/dynamic/json_query.rs index 76a96909a3..59b30b5797 100644 --- a/packages/stack-encrypt/src/dynamic/json_query.rs +++ b/packages/stack-encrypt/src/dynamic/json_query.rs @@ -170,7 +170,8 @@ //! refuse their own inputs as they would alone: an ordering at a path the //! field does not order ([`TermError::JsonPathNotOrdered`]). A //! `wildcard_bound` of `0` is [`Reason::JsonWildcardBoundZero`], and `vars` -//! that are not an object [`Reason::JsonInput`]. +//! that are not an object [`Reason::JsonVarsNotObject`], which says what +//! they are ([`Error::found`](crate::dynamic::Error::found)). //! //! The operand reveals what its leaves reveal when sent one by one, and //! the boolean shape of the filter; an ordering under an odd number of `!` @@ -460,9 +461,8 @@ fn read_match(options: &JsonOptions, input: Frame<'_>) -> Result { Some(vars) => vars.parse()?, None => Parsed::of(Value::Object(serde_json::Map::new())), }; - if !vars.0.is_object() { - return Err(Error::bad_source(Reason::JsonInput)); - } + // Vars that are not an object are refused by `Input::predicate`, saying + // what they are. let text = std::str::from_utf8(&input.predicate.0) .map_err(|_| Error::bad_source(Reason::JsonInput))?; Input::predicate(options, text, &vars.0, Some(bound)) diff --git a/packages/stack-encrypt/src/json/inputs.rs b/packages/stack-encrypt/src/json/inputs.rs index 88fd34fd81..dc5fd6df40 100644 --- a/packages/stack-encrypt/src/json/inputs.rs +++ b/packages/stack-encrypt/src/json/inputs.rs @@ -24,7 +24,7 @@ use super::{ wipe_value, IndexPath, JsonElementsMember, JsonElementsQuery, JsonLeafQuery, JsonOptions, JsonPath, JsonPredicateQuery, JsonQuery, JsonSelector, JsonSubtreeKey, }; -use crate::refusal::{Error, Reason}; +use crate::refusal::{Error, Found, Reason}; use crate::sem::TermError; use crate::target::{AeadContext, CallerContext, DeclaredContext, Owned}; use crate::{ContextPiece, KeysetCipher, Label, NonEmpty, Pending}; @@ -210,7 +210,12 @@ impl Input { ) -> Result { let bound = wildcard_bound(bound)?; if !vars.is_object() { - return Err(Error::bad_source(Reason::JsonInput)); + return Err(Error::Source { + field: None, + row: None, + reason: Reason::JsonVarsNotObject, + found: Some(json_kind(vars)), + }); } Ok(Self::Predicate(Box::new(super::predicate::compile( text, vars, options, bound, @@ -218,6 +223,23 @@ impl Input { } } +/// What a JSON value is, for a refusal that says what it found: its kind, +/// never the value. A number is the kind the engine reads it as: an +/// unsigned or a signed 64-bit integer, or a float. +fn json_kind(value: &Value) -> Found { + use vitaminc_aead::plaintext::ValueKind; + Found::Kind(match value { + Value::Null => return Found::Null, + Value::Bool(_) => ValueKind::Bool, + Value::Number(n) if n.is_u64() => ValueKind::UInt64, + Value::Number(n) if n.is_i64() => ValueKind::Int64, + Value::Number(_) => ValueKind::Float64, + Value::String(_) => ValueKind::String, + Value::Array(_) => ValueKind::Array, + Value::Object(_) => ValueKind::Object, + }) +} + /// The path of an array's elements that `element_match` reads: a path with /// a wildcard, and no position. pub(crate) fn elements_base(text: &str) -> Result { diff --git a/packages/stack-encrypt/src/refusal.rs b/packages/stack-encrypt/src/refusal.rs index b06c504fc1..2344043d71 100644 --- a/packages/stack-encrypt/src/refusal.rs +++ b/packages/stack-encrypt/src/refusal.rs @@ -180,8 +180,9 @@ pub enum Error { row: Option, /// What was wrong with the source. reason: Reason, - /// What the source, or the row, is instead of an object of fields: - /// set with [`Reason::NotAnObject`]. + /// What the source, or the row, is instead of an object of fields, + /// or what a match's vars are: set with [`Reason::NotAnObject`] and + /// [`Reason::JsonVarsNotObject`]. found: Option, }, @@ -324,6 +325,9 @@ fn misfit_text( let Some(found) = found else { return format!("{reason}{}", place_text(row, field)); }; + if reason != Reason::NotAnObject { + return format!("{reason}, found {found}{}", place_text(row, field)); + } let what = match (subject, row, field) { (Subject::Plan, _, None) => "the plan".to_owned(), (Subject::Plan, _, Some(_)) => "the field's spec".to_owned(), @@ -471,8 +475,9 @@ impl Error { } /// What a plan, a field's spec, a record source or a stored record was - /// where the operation takes an object ([`Reason::NotAnObject`]). - /// `None` for every other error. + /// where the operation takes an object ([`Reason::NotAnObject`]), or + /// what a match's vars were ([`Reason::JsonVarsNotObject`]). `None` for + /// every other error. pub fn found(&self) -> Option { match self { Self::Plan { found, .. } | Self::Source { found, .. } | Self::Record { found, .. } => { @@ -791,6 +796,10 @@ reasons! { /// A value failed while it was read, with an error of its own /// ([`Error::SourceFailed`]). SourceFailed => "source_failed", "a value failed while it was read"; + /// A `match` query's `vars` are not a JSON object: a list, a + /// number, a string, a boolean or the JSON `null`. The error says + /// which ([`Error::found`]). + JsonVarsNotObject => "json_vars_not_object", "match takes its vars as a JSON object"; } } diff --git a/packages/stack-encrypt/tests/json_operators.rs b/packages/stack-encrypt/tests/json_operators.rs index 1d46302cd4..a286aa9657 100644 --- a/packages/stack-encrypt/tests/json_operators.rs +++ b/packages/stack-encrypt/tests/json_operators.rs @@ -3098,7 +3098,10 @@ mod compiled_match { assert!(payload["construct"].is_string(), "{predicate}: {payload:?}"); } for (input, reason) in [ - (json!({"predicate": "$.a == 1", "vars": "[]"}), "json_input"), + ( + json!({"predicate": "$.a == 1", "vars": "[]"}), + "json_vars_not_object", + ), (json!({"predicate": "$.a == 1", "vars": "{"}), "json_syntax"), ( json!({"predicate": "$.a == 1", "wildcard_bound": 0}), @@ -3125,6 +3128,51 @@ mod compiled_match { "vars may be absent" ); } + + /// Vars that are not a JSON object are refused for the field, + /// saying what they are by kind and never the value, and that a + /// match takes an object. + #[test] + fn refuses_vars_that_are_not_an_object_saying_what_they_are() { + for (vars, found, phrase) in [ + (r#"["secret"]"#, "array", "an array"), + ("null", "null", "null"), + (r#""secret""#, "string", "a string"), + ("7", "uint64", "a uint64"), + ("-7", "int64", "an int64"), + ("1.5", "float64", "a float64"), + ("true", "bool", "a bool"), + ] { + let request = json!({"predicate": "$.a == $v", "vars": vars}); + let error = check(&request).unwrap_err(); + assert_eq!( + error.reason().map(Reason::as_str), + Some("json_vars_not_object"), + "{vars}: the reason" + ); + assert_eq!(error.field(), Some("profile"), "{vars}: the field"); + assert_eq!( + error.found().map(|found| found.as_str()), + Some(found), + "{vars}: what was found" + ); + let payload = stack_encrypt::ErrorPayload::payload(&error); + assert_eq!( + Value::Object(payload.clone()), + json!({"field": "profile", "reason": "json_vars_not_object", "found": found}), + "{vars}: the payload" + ); + let message = error.to_string(); + assert_eq!( + message, + format!( + r#"record source does not fit the plan: match takes its vars as a JSON object, found {phrase} (field "profile")"# + ), + "{vars}: the message" + ); + assert!(!message.contains("secret"), "{vars}: no value: {message}"); + } + } } mod given_the_fields_type { From 43982993cce346b26a78886b7da4c0b52b2afd38 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sat, 28 Nov 2026 02:20:36 +1100 Subject: [PATCH 02/10] fix(golang): read every guest answer through one path, and name more kinds in words Review of the Go errors change found the new wording only half applied: - `KindOf` missed the vcvalue types that are not plain Go values (a sealed value, the sealed empty list and map markers, a passthrough, a value of an unknown logical type), and named any other Go value, such as an `int` or a map of a concrete type, "a single value". It now names the vcvalue types first, so a sealed value is not taken for bytes, and any other Go value by its reflect.Kind. - An answer that did not decode still bypassed `BadAnswer`, so it named neither the export nor a version mismatch. Every encrypt export's answer is now decoded by `decodeAnswer`, and se_verify's and se_target_limit's shape checks, auth's object, workspace list and runnable operations go through `BadAnswer` too. `BadAnswer` wraps the problem with %w, so the decoder's error stays matchable. - Checks inside one answer (an index, `producible`, a target's name, a term part, the term) still printed a Go type with %T. They use `KindOf`. - `GetDocument` still said `gensupport: field` and printed a Go type. It says `gensupport: decrypt: field` and the kind, as `Get` does. - In the engine, moving the vars check into `Input::predicate` let a predicate that is not UTF-8 be refused before vars that are not an object. `read_match` checks the vars first again, through the shared `vars_object`. - The CHANGELOG no longer says the typed path refuses vars that are not an object: a field reference always builds an object. --- languages/golang/CHANGELOG.md | 15 ++-- languages/golang/auth/answer_test.go | 40 ++++++++- languages/golang/auth/step.go | 8 +- languages/golang/auth/store.go | 15 ++-- languages/golang/encrypt/checker.go | 31 ++++--- .../gensupport/gensupport_internal_test.go | 14 ++++ languages/golang/encrypt/gensupport/json.go | 5 +- languages/golang/encrypt/query.go | 39 ++++++--- languages/golang/encrypt/targets_test.go | 83 +++++++++++++++++++ languages/golang/internal/guest/answer.go | 59 +++++++++---- .../golang/internal/guest/answer_test.go | 30 ++++++- packages/stack-encrypt/CHANGELOG.md | 5 +- .../stack-encrypt/src/dynamic/json_query.rs | 5 +- packages/stack-encrypt/src/json/inputs.rs | 23 +++-- .../stack-encrypt/tests/json_operators.rs | 57 +++++++++++++ 15 files changed, 359 insertions(+), 70 deletions(-) diff --git a/languages/golang/CHANGELOG.md b/languages/golang/CHANGELOG.md index 4f9da3d23d..994666f311 100644 --- a/languages/golang/CHANGELOG.md +++ b/languages/golang/CHANGELOG.md @@ -44,12 +44,15 @@ and `languages/golang/encrypt/encrypttest/vX.Y.Z` on the same commit. (#1987). A map field (`map[string]V`, `Values`, `map[string]any`) whose stored value opens as something else is refused as `decrypt: field "tags": ... opened as a list, and map[string]any needs an object`, - where it said `opened as []interface {}, not an object`. A guest answer - this module cannot read (from `se_query_term`, `se_targets`, - `se_operators`, `se_contexts`, `sa_token`, `sa_secret_key` or - `sa_device_identity`) is still `ErrInternal`, and now names the export, - says what the answer is by its kind, and says it is a bug or a guest - that does not match this module's version, not bad input. + where it said `opened as []interface {}, not an object`, and a document + field likewise. A guest answer this module cannot read, whether it does + not decode or is not the shape the export writes (from `se_query_term`, + `se_targets`, `se_operators`, `se_contexts`, `se_verify`, + `se_target_limit`, `sa_token`, `sa_secret_key`, `sa_device_identity`, + `sa_list_workspaces` or `sa_auth_runnable`), is still `ErrInternal`, + and now names the export, says what the answer is by its kind, and says + it is a bug or a guest that does not match this module's version, not + bad input. - **A record field converts a number of another width or kind, as a query does.** A value sealed through `Cipher.Seal` for a field that diff --git a/languages/golang/auth/answer_test.go b/languages/golang/auth/answer_test.go index 32cbaf15be..af4f3a6e0e 100644 --- a/languages/golang/auth/answer_test.go +++ b/languages/golang/auth/answer_test.go @@ -44,7 +44,45 @@ func TestAnAnswerThatIsNotAnObjectNamesTheExportAndItsKind(t *testing.T) { if fields, err := object("sa_token", encoded); err != nil || len(fields) != 1 { t.Fatalf("an object: %v, %v", fields, err) } - if _, err := object("sa_token", []byte{0xff}); !errors.Is(err, ErrInternal) || !strings.Contains(err.Error(), "sa_token") { + if _, err := object("sa_token", []byte{0xff}); !errors.Is(err, ErrInternal) || + !strings.Contains(err.Error(), "the guest's answer to sa_token does not read") || + !strings.Contains(err.Error(), "does not match this module's version") { t.Errorf("bytes that do not decode: %v", err) } } + +// The workspace list and the runnable operations are read the same way: an +// answer that does not decode, or is not what the export writes, names the +// export and what it is, by kind. +func TestListAnswersNameTheExportAndTheirKind(t *testing.T) { + marshal := func(v any) []byte { + out, err := vcffi.Marshal(v) + if err != nil { + t.Fatal(err) + } + return out + } + for _, tc := range []struct { + read func([]byte) error + answer []byte + want string + }{ + {func(b []byte) error { _, err := workspaceIDs(b); return err }, []byte{0xff}, "the guest's answer to sa_list_workspaces does not read: "}, + {func(b []byte) error { _, err := workspaceIDs(b); return err }, marshal("secret"), "sa_list_workspaces does not read: it is a string, not a list"}, + {func(b []byte) error { _, err := workspaceIDs(b); return err }, marshal([]any{"ws", int64(1)}), "sa_list_workspaces does not read: workspace id 1 is a number, not a string"}, + {func(b []byte) error { _, err := decodeRunnable(b); return err }, []byte{0xff}, "the guest's answer to sa_auth_runnable does not read: "}, + {func(b []byte) error { _, err := decodeRunnable(b); return err }, marshal("secret"), "sa_auth_runnable does not read: it is a string, not a list"}, + {func(b []byte) error { _, err := decodeRunnable(b); return err }, marshal([]any{uint64(1), "secret"}), "sa_auth_runnable does not read: operation 1 is a string, not a handle"}, + } { + err := tc.read(tc.answer) + if !errors.Is(err, ErrInternal) || !strings.Contains(err.Error(), tc.want) || strings.Contains(err.Error(), "secret") { + t.Errorf("%v, want %q", err, tc.want) + } + } + if ids, err := workspaceIDs(marshal([]any{"a", "b"})); err != nil || len(ids) != 2 { + t.Errorf("a good list: %v, %v", ids, err) + } + if handles, err := decodeRunnable(marshal([]any{uint64(3)})); err != nil || len(handles) != 1 || handles[0] != 3 { + t.Errorf("good handles: %v, %v", handles, err) + } +} diff --git a/languages/golang/auth/step.go b/languages/golang/auth/step.go index ca11ac8e39..4af83cc50f 100644 --- a/languages/golang/auth/step.go +++ b/languages/golang/auth/step.go @@ -169,17 +169,17 @@ func decodeAuthRequest(item any) (authRequest, bool) { func decodeRunnable(raw []byte) ([]uint64, error) { decoded, err := vcffi.Unmarshal(raw) if err != nil { - return nil, fmt.Errorf("%w: the runnable operations: %w", ErrInternal, err) + return nil, guest.BadAnswer("sa_auth_runnable", err) } items, ok := decoded.([]any) if !ok { - return nil, fmt.Errorf("%w: the runnable operations are not a list", ErrInternal) + return nil, guest.BadAnswer("sa_auth_runnable", fmt.Errorf("it is %s, not a list", guest.KindOf(decoded))) } handles := make([]uint64, 0, len(items)) - for _, item := range items { + for i, item := range items { h, ok := item.(uint64) if !ok { - return nil, fmt.Errorf("%w: a runnable operation is not a handle", ErrInternal) + return nil, guest.BadAnswer("sa_auth_runnable", fmt.Errorf("operation %d is %s, not a handle", i, guest.KindOf(item))) } handles = append(handles, h) } diff --git a/languages/golang/auth/store.go b/languages/golang/auth/store.go index 2e5936301c..13955308d7 100644 --- a/languages/golang/auth/store.go +++ b/languages/golang/auth/store.go @@ -405,19 +405,24 @@ func (s *ProfileStore) ListWorkspaces(ctx context.Context) ([]string, error) { if err != nil { return nil, err } + return workspaceIDs(out) +} + +// workspaceIDs reads sa_list_workspaces's answer: a list of workspace ids. +func workspaceIDs(out []byte) ([]string, error) { decoded, err := vcffi.Unmarshal(out) if err != nil { - return nil, fmt.Errorf("%w: decoding the workspace list: %w", ErrInternal, err) + return nil, guest.BadAnswer("sa_list_workspaces", err) } items, ok := decoded.([]any) if !ok { - return nil, fmt.Errorf("%w: the workspace list is not a list", ErrInternal) + return nil, guest.BadAnswer("sa_list_workspaces", fmt.Errorf("it is %s, not a list", guest.KindOf(decoded))) } ids := make([]string, 0, len(items)) - for _, item := range items { + for i, item := range items { id, ok := item.(string) if !ok { - return nil, fmt.Errorf("%w: a workspace id is not a string", ErrInternal) + return nil, guest.BadAnswer("sa_list_workspaces", fmt.Errorf("workspace id %d is %s, not a string", i, guest.KindOf(item))) } ids = append(ids, id) } @@ -541,7 +546,7 @@ type fields vcvalue.Object func object(export string, encoded []byte) (fields, error) { decoded, err := vcffi.Unmarshal(encoded) if err != nil { - return nil, fmt.Errorf("%w: decoding the guest's answer to %s: %w", ErrInternal, export, err) + return nil, guest.BadAnswer(export, err) } obj, ok := decoded.(vcvalue.Object) if !ok { diff --git a/languages/golang/encrypt/checker.go b/languages/golang/encrypt/checker.go index d288fdc179..1d016b4e82 100644 --- a/languages/golang/encrypt/checker.go +++ b/languages/golang/encrypt/checker.go @@ -77,9 +77,9 @@ func (k *Checker) Targets(ctx context.Context) ([]record.Target, error) { if err != nil { return nil, err } - decoded, err := vcffi.Unmarshal(out) + decoded, err := decodeAnswer("se_targets", out) if err != nil { - return nil, fmt.Errorf("%w: %v", ErrInternal, err) + return nil, err } return parseTargets(decoded) } @@ -104,9 +104,9 @@ func (k *Checker) Operators(ctx context.Context, plan *record.Plan, field string if err != nil { return nil, err } - decoded, err := vcffi.Unmarshal(out) + decoded, err := decodeAnswer("se_operators", out) if err != nil { - return nil, fmt.Errorf("%w: %v", ErrInternal, err) + return nil, err } operators, err := parseOperators(decoded) if err != nil { @@ -143,9 +143,9 @@ func contextsOf(ctx context.Context, c *Client, plan *record.Plan) (string, erro if err != nil { return "", err } - decoded, err := vcffi.Unmarshal(out) + decoded, err := decodeAnswer("se_contexts", out) if err != nil { - return "", fmt.Errorf("%w: %v", ErrInternal, err) + return "", err } text, ok := decoded.(string) if !ok { @@ -154,6 +154,17 @@ func contextsOf(ctx context.Context, c *Client, plan *record.Plan) (string, erro return text, nil } +// decodeAnswer decodes export's answer from the transport. Bytes that do +// not decode are the guest's fault, not the caller's: ErrInternal, through +// [guest.BadAnswer], which names the export. +func decodeAnswer(export string, out []byte) (any, error) { + decoded, err := vcffi.Unmarshal(out) + if err != nil { + return nil, guest.BadAnswer(export, err) + } + return decoded, nil +} + // parseTargets reads se_targets's decoded value: {"targets": [entry, ...]}, // each entry an object with exactly the keys record.Target documents. The // shape is a contract between eql-bindings' serialiser and this reader, so @@ -215,12 +226,12 @@ func parseTarget(entry vcvalue.Object) (record.Target, error) { case "indexes": list, ok := f.Value.([]any) if !ok { - return t, fmt.Errorf("indexes is %T, not a list", f.Value) + return t, fmt.Errorf("indexes is %s, not a list", guest.KindOf(f.Value)) } for _, item := range list { s, ok := item.(string) if !ok { - return t, fmt.Errorf("an index is %T, not a string", item) + return t, fmt.Errorf("an index is %s, not a string", guest.KindOf(item)) } switch o := record.Output(s); o { // "json" is the JSON index a document type carries, which no plan output @@ -238,7 +249,7 @@ func parseTarget(entry vcvalue.Object) (record.Target, error) { case "producible": b, ok := f.Value.(bool) if !ok { - return t, fmt.Errorf("producible is %T, not a bool", f.Value) + return t, fmt.Errorf("producible is %s, not a bool", guest.KindOf(f.Value)) } t.Producible = b case "reason": @@ -364,7 +375,7 @@ func parseOperatorIndex(s string) (record.Output, error) { func targetString(f vcvalue.Field) (string, error) { s, ok := f.Value.(string) if !ok { - return "", fmt.Errorf("%s is %T, not a string", f.Key, f.Value) + return "", fmt.Errorf("%s is %s, not a string", f.Key, guest.KindOf(f.Value)) } return s, nil } diff --git a/languages/golang/encrypt/gensupport/gensupport_internal_test.go b/languages/golang/encrypt/gensupport/gensupport_internal_test.go index cc1c2ecf53..4e64dee535 100644 --- a/languages/golang/encrypt/gensupport/gensupport_internal_test.go +++ b/languages/golang/encrypt/gensupport/gensupport_internal_test.go @@ -691,3 +691,17 @@ func TestAMapFieldThatOpensAsAnotherKindSaysWhatItOpenedAs(t *testing.T) { } } } + +// A document field that opens as something other than its JSON text is a +// decrypt refusal naming the field and what it opened as, by kind. +func TestADocumentFieldThatOpensAsAnotherKindSaysWhatItOpenedAs(t *testing.T) { + _, err := GetDocument[map[string]any](Values{"doc": "secret"}, "doc") + want := `gensupport: decrypt: field "doc": cipherstash: malformed input: the document opened as a string, not its JSON text` + if !errors.Is(err, encrypt.ErrEncoding) || err.Error() != want { + t.Errorf("message:\n got %v\nwant %q", err, want) + } + _, err = GetDocument[map[string]any](Values{"doc": []byte("{")}, "doc") + if err == nil || !strings.HasPrefix(err.Error(), `gensupport: decrypt: field "doc": `) { + t.Errorf("JSON that does not decode: %v", err) + } +} diff --git a/languages/golang/encrypt/gensupport/json.go b/languages/golang/encrypt/gensupport/json.go index d9eb4b2962..97ca9bfcd9 100644 --- a/languages/golang/encrypt/gensupport/json.go +++ b/languages/golang/encrypt/gensupport/json.go @@ -12,6 +12,7 @@ import ( "strings" "github.com/cipherstash/stack/languages/golang/encrypt" + "github.com/cipherstash/stack/languages/golang/internal/guest" "github.com/cipherstash/stack/languages/golang/internal/record" "github.com/cipherstash/vitaminc/bindings/go/vcvalue" ) @@ -118,11 +119,11 @@ func GetDocument[T any](vals Values, name string) (T, error) { } text, ok := v.([]byte) if !ok { - return out, fmt.Errorf("gensupport: field %q: %w: the document opened as %T, not its JSON text", name, encrypt.ErrEncoding, v) + return out, fmt.Errorf("gensupport: decrypt: field %q: %w: the document opened as %s, not its JSON text", name, encrypt.ErrEncoding, guest.KindOf(v)) } out, err := encrypt.DecodeJSON[T](text) if err != nil { - return out, fmt.Errorf("gensupport: field %q: %w", name, err) + return out, fmt.Errorf("gensupport: decrypt: field %q: %w", name, err) } return out, nil } diff --git a/languages/golang/encrypt/query.go b/languages/golang/encrypt/query.go index fa0d807b7b..4bfbbcee8b 100644 --- a/languages/golang/encrypt/query.go +++ b/languages/golang/encrypt/query.go @@ -163,9 +163,9 @@ func (cph *Cipher) QueryTerm(ctx context.Context, plan *record.Plan, field, oper if err != nil { return QueryTerm{}, err } - decoded, err := vcffi.Unmarshal(out) + decoded, err := decodeAnswer("se_query_term", out) if err != nil { - return QueryTerm{}, fmt.Errorf("%w: %v", ErrInternal, err) + return QueryTerm{}, err } term, err := parseQueryTerm(decoded) if err != nil { @@ -240,7 +240,7 @@ func parseQueryTerm(decoded any) (QueryTerm, error) { case string: t.Text = append(t.Text, x) default: - return QueryTerm{}, fmt.Errorf("a term part is %T", item) + return QueryTerm{}, fmt.Errorf("a term part is %s", guest.KindOf(item)) } } if t.Terms != nil && (len(t.Terms) != 2 || t.Text != nil) { @@ -251,7 +251,7 @@ func parseQueryTerm(decoded any) (QueryTerm, error) { t.Text = []string{} } default: - return QueryTerm{}, fmt.Errorf("term is %T", f.Value) + return QueryTerm{}, fmt.Errorf("term is %s", guest.KindOf(f.Value)) } default: return QueryTerm{}, fmt.Errorf("unknown key %q", f.Key) @@ -318,19 +318,28 @@ func (cph *Cipher) Verify(ctx context.Context, plan *record.Plan, field, operato if err != nil { return nil, err } - decoded, err := vcffi.Unmarshal(out) + decoded, err := decodeAnswer("se_verify", out) if err != nil { - return nil, fmt.Errorf("%w: %v", ErrInternal, err) + return nil, err } + return parseVerified(decoded, len(values)) +} + +// parseVerified reads se_verify's answer: one boolean for each of the +// count values sent. +func parseVerified(decoded any, count int) ([]bool, error) { list, ok := decoded.([]any) - if !ok || len(list) != len(values) { - return nil, fmt.Errorf("%w: se_verify returned %T for %d values", ErrInternal, decoded, len(values)) + if !ok { + return nil, guest.BadAnswer("se_verify", fmt.Errorf("it is %s, not a list", guest.KindOf(decoded))) + } + if len(list) != count { + return nil, guest.BadAnswer("se_verify", fmt.Errorf("it has %d answers for %d values", len(list), count)) } verified := make([]bool, len(list)) for i, v := range list { b, ok := v.(bool) if !ok { - return nil, fmt.Errorf("%w: se_verify returned %T for value %d", ErrInternal, v, i) + return nil, guest.BadAnswer("se_verify", fmt.Errorf("answer %d is %s, not a boolean", i, guest.KindOf(v))) } verified[i] = b } @@ -361,17 +370,23 @@ func (cph *Cipher) TargetLimit(ctx context.Context, plan *record.Plan, field, op if err != nil { return Limit{}, err } - decoded, err := vcffi.Unmarshal(out) + decoded, err := decodeAnswer("se_target_limit", out) if err != nil { - return Limit{}, fmt.Errorf("%w: %v", ErrInternal, err) + return Limit{}, err } + return parseLimit(decoded) +} + +// parseLimit reads se_target_limit's answer: null for no bound, or the row +// count. +func parseLimit(decoded any) (Limit, error) { switch v := decoded.(type) { case nil: return Limit{}, nil case uint64: return Limit{rows: v, bounded: true}, nil default: - return Limit{}, fmt.Errorf("%w: se_target_limit returned %T", ErrInternal, decoded) + return Limit{}, guest.BadAnswer("se_target_limit", fmt.Errorf("it is %s, not a row count or null", guest.KindOf(decoded))) } } diff --git a/languages/golang/encrypt/targets_test.go b/languages/golang/encrypt/targets_test.go index e3016f0667..256ed7a9b8 100644 --- a/languages/golang/encrypt/targets_test.go +++ b/languages/golang/encrypt/targets_test.go @@ -7,6 +7,7 @@ import ( "testing" "github.com/cipherstash/stack/languages/golang/internal/record" + "github.com/cipherstash/vitaminc/bindings/go/vcffi" "github.com/cipherstash/vitaminc/bindings/go/vcvalue" ) @@ -211,3 +212,85 @@ func TestParseQueryTermRefusesAMixedShape(t *testing.T) { } } } + +// Every export's answer is decoded through one path: bytes that do not +// decode are ErrInternal naming the export, with the version hint, never +// bad input. +func TestAnAnswerThatDoesNotDecodeNamesTheExport(t *testing.T) { + for _, export := range []string{"se_query_term", "se_targets", "se_operators", "se_contexts", "se_verify", "se_target_limit"} { + _, err := decodeAnswer(export, []byte{0xff}) + if !errors.Is(err, ErrInternal) || errors.Is(err, ErrEncoding) { + t.Fatalf("%s: %v, want ErrInternal alone", export, err) + } + want := "cipherstash: internal guest failure: the guest's answer to " + export + " does not read: " + if !strings.HasPrefix(err.Error(), want) || !strings.Contains(err.Error(), "does not match this module's version") { + t.Errorf("%s: %v", export, err) + } + } + if decoded, err := decodeAnswer("se_contexts", mustMarshal(t, "users / email")); err != nil || decoded != "users / email" { + t.Errorf("a good answer: %v, %v", decoded, err) + } +} + +// se_verify's and se_target_limit's answers say what they are, by kind. +func TestVerifyAndLimitAnswersSayWhatTheyAre(t *testing.T) { + for _, tc := range []struct { + answer any + count int + want string + }{ + {"secret", 1, "se_verify does not read: it is a string, not a list"}, + {[]any{true}, 2, "se_verify does not read: it has 1 answers for 2 values"}, + {[]any{true, "secret"}, 2, "se_verify does not read: answer 1 is a string, not a boolean"}, + } { + _, err := parseVerified(tc.answer, tc.count) + if !errors.Is(err, ErrInternal) || !strings.Contains(err.Error(), tc.want) || strings.Contains(err.Error(), "secret") { + t.Errorf("%v, want %q", err, tc.want) + } + } + if got, err := parseVerified([]any{true, false}, 2); err != nil || !reflect.DeepEqual(got, []bool{true, false}) { + t.Errorf("a good answer: %v, %v", got, err) + } + _, err := parseLimit("secret") + if !errors.Is(err, ErrInternal) || !strings.Contains(err.Error(), "se_target_limit does not read: it is a string, not a row count or null") { + t.Errorf("limit: %v", err) + } + if limit, err := parseLimit(nil); err != nil || limit != (Limit{}) { + t.Errorf("no bound: %+v, %v", limit, err) + } + if limit, err := parseLimit(uint64(7)); err != nil || limit != (Limit{rows: 7, bounded: true}) { + t.Errorf("a bound: %+v, %v", limit, err) + } +} + +// An index, a producible flag or a name of the wrong kind says what it is. +func TestATargetFieldOfTheWrongKindSaysWhatItIs(t *testing.T) { + entry := func(fields ...vcvalue.Field) vcvalue.Object { + return vcvalue.Object{{Key: "targets", Value: []any{vcvalue.Object(fields)}}} + } + name := vcvalue.Field{Key: "name", Value: "TextEq"} + for _, tc := range []struct { + answer vcvalue.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"}, + } { + _, err := parseTargets(tc.answer) + if err == nil || !strings.Contains(err.Error(), tc.want) || strings.Contains(err.Error(), "secret") { + t.Errorf("%v, want %q", err, tc.want) + } + } +} + +// mustMarshal is v in the transport. +func mustMarshal(t *testing.T, v any) []byte { + t.Helper() + out, err := vcffi.Marshal(v) + if err != nil { + t.Fatal(err) + } + return out +} diff --git a/languages/golang/internal/guest/answer.go b/languages/golang/internal/guest/answer.go index 755b97e784..eda5fcb9b9 100644 --- a/languages/golang/internal/guest/answer.go +++ b/languages/golang/internal/guest/answer.go @@ -2,6 +2,7 @@ package guest import ( "fmt" + "reflect" "github.com/cipherstash/vitaminc/bindings/go/vcvalue" ) @@ -9,22 +10,26 @@ import ( // KindOf names what a decoded value is, by its kind and never its value: // "null", "an object", "a list", "a string", "a number", and so on. It is // what an error says it found where it expected something else, so the -// error can be logged without leaking the value. +// error can be logged without leaking the value. The vcvalue types are +// named first, so a sealed value is not taken for bytes; any other Go +// value is named by its reflect.Kind. func KindOf(v any) string { switch v.(type) { case nil, vcvalue.TypedNull: return "null" case vcvalue.Object: return "an object" - case []any: - return "a list" - case string: - return "a string" - case []byte: - return "bytes" - case bool: - return "a boolean" - case int8, int16, int32, int64, uint8, uint16, uint32, uint64, vcvalue.Int128, vcvalue.Uint128, float32, float64: + case vcvalue.Sealed: + return "a sealed value" + case vcvalue.SealedEmptySeq: + return "a sealed empty list" + case vcvalue.SealedEmptyMap: + return "a sealed empty map" + case vcvalue.Plain: + return "a passthrough value" + case vcvalue.Tagged: + return "a value of a type this build does not know" + case vcvalue.Int128, vcvalue.Uint128: return "a number" case vcvalue.Date: return "a date" @@ -34,17 +39,39 @@ func KindOf(v any) string { return "a decimal" case vcvalue.UUID: return "a UUID" + } + value := reflect.ValueOf(v) + switch value.Kind() { + case reflect.Bool: + return "a boolean" + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, + reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr, + reflect.Float32, reflect.Float64: + return "a number" + case reflect.String: + return "a string" + case reflect.Slice, reflect.Array: + if value.Type().Elem().Kind() == reflect.Uint8 { + return "bytes" + } + return "a list" + case reflect.Map: + return "a map" + case reflect.Struct: + return "a struct" + case reflect.Pointer: + return "a pointer" default: return "a single value" } } // BadAnswer is the error for a guest export's answer this module cannot -// read: ErrInternal, naming the export and what was wrong with the answer. -// The caller's input is not at fault. The answer's shape is a contract -// between the guest and this module, so a bad one is a bug, or a guest that -// does not match this module's version, such as a guest built from other -// source than the module that embeds it. +// read: ErrInternal, naming the export and what was wrong with the answer, +// which it wraps. The caller's input is not at fault. The answer's shape is +// a contract between the guest and this module, so a bad one is a bug, or a +// guest that does not match this module's version, such as a guest built +// from other source than the module that embeds it. func BadAnswer(export string, problem error) error { - return fmt.Errorf("%w: the guest's answer to %s does not read: %v; this is a bug, or a guest that does not match this module's version", ErrInternal, export, problem) + return fmt.Errorf("%w: the guest's answer to %s does not read: %w; this is a bug, or a guest that does not match this module's version", ErrInternal, export, problem) } diff --git a/languages/golang/internal/guest/answer_test.go b/languages/golang/internal/guest/answer_test.go index ed2a72f784..14636e4c0d 100644 --- a/languages/golang/internal/guest/answer_test.go +++ b/languages/golang/internal/guest/answer_test.go @@ -9,7 +9,11 @@ import ( "github.com/cipherstash/vitaminc/bindings/go/vcvalue" ) -// KindOf names a decoded value by its kind, never its value. +// named is a Go type of its own over a string. +type named string + +// KindOf names a decoded value by its kind, never its value: the vcvalue +// types by what they are, and any other Go value by its reflect.Kind. func TestKindOfNamesAValueByItsKind(t *testing.T) { for _, tc := range []struct { value any @@ -38,7 +42,24 @@ func TestKindOfNamesAValueByItsKind(t *testing.T) { {vcvalue.Timestamp{}, "a timestamp"}, {vcvalue.Decimal{}, "a decimal"}, {vcvalue.UUID{}, "a UUID"}, - {struct{ secret string }{"secret"}, "a single value"}, + {vcvalue.Sealed("secret"), "a sealed value"}, + {vcvalue.SealedEmptySeq("secret"), "a sealed empty list"}, + {vcvalue.SealedEmptyMap("secret"), "a sealed empty map"}, + {vcvalue.Plain{V: "secret"}, "a passthrough value"}, + {vcvalue.Tagged{ID: 200, V: "secret"}, "a value of a type this build does not know"}, + {int(1), "a number"}, + {uint(1), "a number"}, + {uintptr(1), "a number"}, + {named("secret"), "a string"}, + {[]int64{1}, "a list"}, + {[2]string{"secret"}, "a list"}, + {[4]byte{1}, "bytes"}, + {map[string]any{"secret": 1}, "a map"}, + {map[string]int64{"secret": 1}, "a map"}, + {struct{ secret string }{"secret"}, "a struct"}, + {new(int), "a pointer"}, + {func() {}, "a single value"}, + {make(chan int), "a single value"}, } { if got := guest.KindOf(tc.value); got != tc.want { t.Errorf("KindOf(%T) = %q, want %q", tc.value, got, tc.want) @@ -60,4 +81,9 @@ func TestBadAnswerIsInternalAndNamesTheExport(t *testing.T) { if strings.Contains(err.Error(), "malformed input") { t.Errorf("reads as bad input: %v", err) } + // The problem is wrapped, so a caller can still match what is behind it. + cause := errors.New("the decoder's error") + if !errors.Is(guest.BadAnswer("se_targets", cause), cause) { + t.Error("the problem is not wrapped") + } } diff --git a/packages/stack-encrypt/CHANGELOG.md b/packages/stack-encrypt/CHANGELOG.md index 2863fa5872..0e8469503b 100644 --- a/packages/stack-encrypt/CHANGELOG.md +++ b/packages/stack-encrypt/CHANGELOG.md @@ -543,8 +543,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 they were `json_input`, the reason for any input a JSON operator does not take, with nothing more. Now the error names the field, gives `found` (`"array"`, `"uint64"`, `"null"`, ...), and says - `match takes its vars as a JSON object, found null`. The dynamic and - the typed paths refuse them alike. + `match takes its vars as a JSON object, found null`. They are refused + before the predicate is read. Only the dynamic path can receive vars + that are not an object: a field reference always builds an object. - **`dynamic::ValueFrame` is removed. The engine reads a plaintext as a borrowed `Frame` and keeps one as vitaminc's `OwnedFrame`** (#1955). diff --git a/packages/stack-encrypt/src/dynamic/json_query.rs b/packages/stack-encrypt/src/dynamic/json_query.rs index 59b30b5797..b2d6e7ada6 100644 --- a/packages/stack-encrypt/src/dynamic/json_query.rs +++ b/packages/stack-encrypt/src/dynamic/json_query.rs @@ -461,8 +461,9 @@ fn read_match(options: &JsonOptions, input: Frame<'_>) -> Result { Some(vars) => vars.parse()?, None => Parsed::of(Value::Object(serde_json::Map::new())), }; - // Vars that are not an object are refused by `Input::predicate`, saying - // what they are. + // Vars that are not an object are refused before the predicate is + // read, so their refusal does not depend on the predicate's text. + crate::json::inputs::vars_object(&vars.0)?; let text = std::str::from_utf8(&input.predicate.0) .map_err(|_| Error::bad_source(Reason::JsonInput))?; Input::predicate(options, text, &vars.0, Some(bound)) diff --git a/packages/stack-encrypt/src/json/inputs.rs b/packages/stack-encrypt/src/json/inputs.rs index dc5fd6df40..437974b300 100644 --- a/packages/stack-encrypt/src/json/inputs.rs +++ b/packages/stack-encrypt/src/json/inputs.rs @@ -209,20 +209,27 @@ impl Input { bound: Option, ) -> Result { let bound = wildcard_bound(bound)?; - if !vars.is_object() { - return Err(Error::Source { - field: None, - row: None, - reason: Reason::JsonVarsNotObject, - found: Some(json_kind(vars)), - }); - } + vars_object(vars)?; Ok(Self::Predicate(Box::new(super::predicate::compile( text, vars, options, bound, )?))) } } +/// `match`'s vars, which must be a JSON object: one that is not is refused +/// as [`Reason::JsonVarsNotObject`], saying what it is by its kind. +pub(crate) fn vars_object(vars: &Value) -> Result<(), Error> { + if vars.is_object() { + return Ok(()); + } + Err(Error::Source { + field: None, + row: None, + reason: Reason::JsonVarsNotObject, + found: Some(json_kind(vars)), + }) +} + /// What a JSON value is, for a refusal that says what it found: its kind, /// never the value. A number is the kind the engine reads it as: an /// unsigned or a signed 64-bit integer, or a float. diff --git a/packages/stack-encrypt/tests/json_operators.rs b/packages/stack-encrypt/tests/json_operators.rs index a286aa9657..837182bcd4 100644 --- a/packages/stack-encrypt/tests/json_operators.rs +++ b/packages/stack-encrypt/tests/json_operators.rs @@ -3173,6 +3173,63 @@ mod compiled_match { assert!(!message.contains("secret"), "{vars}: no value: {message}"); } } + + /// Vars that are not an object are refused before the predicate is + /// read: a predicate that is not UTF-8 beside vars `[]` is refused + /// for its vars. + #[test] + fn refuses_vars_before_reading_the_predicate() { + /// A match input whose predicate is bytes, as a binding may send it. + struct Input<'a> { + predicate: &'a [u8], + vars: &'a str, + } + struct Bytes<'a>(&'a [u8]); + impl serde::Serialize for Bytes<'_> { + fn serialize(&self, s: S) -> Result { + s.serialize_bytes(self.0) + } + } + impl serde::Serialize for Input<'_> { + fn serialize(&self, s: S) -> Result { + use serde::ser::SerializeMap; + let mut map = s.serialize_map(Some(2))?; + map.serialize_entry("predicate", &Bytes(self.predicate))?; + map.serialize_entry("vars", self.vars)?; + map.end() + } + } + let request = |vars| { + OwnedFrame::from_buffer( + dynamic::frame::serde::to_vec(&Input { + predicate: &[0xff, 0xfe], + vars, + }) + .unwrap(), + ) + .unwrap() + }; + let check = |vars| { + dynamic::check_query(&people(), "profile", Op::Match, request(vars), &Documents) + .unwrap_err() + }; + let error = check("[]"); + assert_eq!( + error.reason().map(Reason::as_str), + Some("json_vars_not_object"), + "the vars are refused first" + ); + assert_eq!( + error.found().map(|found| found.as_str()), + Some("array"), + "what the vars are" + ); + assert_eq!( + check("{}").reason().map(Reason::as_str), + Some("json_input"), + "with object vars, the predicate that is not UTF-8 is refused" + ); + } } mod given_the_fields_type { From c2147202a0bf903a8d03d97f5c2584310ad21e1f Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sat, 28 Nov 2026 03:08:19 +1100 Subject: [PATCH 03/10] fix(golang): a decrypt error never names what the value opened as A map field, or a document field, whose stored value opened as something else was refused saying what it opened as ("opened as a list"). The kind of a decrypted value is known only once it is opened, so it is the plaintext's own metadata, such as which rows hold a null or a list. The refusals now name the field and the Go type needed and nothing about the value: `gensupport: decrypt: field "x": ... does not open as an object, and map[string]any needs one`, and for a document `does not open as its JSON text`. Guest answers and input-side messages keep naming kinds: they are not decrypted plaintext. Tests assert each message names no kind. --- languages/golang/CHANGELOG.md | 7 ++- .../golang/encrypt/gensupport/convert.go | 9 +-- .../gensupport/gensupport_internal_test.go | 57 +++++++++++-------- languages/golang/encrypt/gensupport/json.go | 4 +- 4 files changed, 44 insertions(+), 33 deletions(-) diff --git a/languages/golang/CHANGELOG.md b/languages/golang/CHANGELOG.md index 2ac1ca63f7..c3288c6a3e 100644 --- a/languages/golang/CHANGELOG.md +++ b/languages/golang/CHANGELOG.md @@ -41,12 +41,13 @@ and `languages/golang/encrypt/encrypttest/vX.Y.Z` on the same commit. null`. A program that switches on `Reason()` for this case needs the new name. -- **Errors that say "not an object" now say what was found, in words** +- **Errors that said "not an object" now say what they mean, in words** (#1987). A map field (`map[string]V`, `Values`, `map[string]any`) whose stored value opens as something else is refused as `decrypt: field - "tags": ... opened as a list, and map[string]any needs an object`, + "tags": ... does not open as an object, and map[string]any needs one`, where it said `opened as []interface {}, not an object`, and a document - field likewise. A guest answer this module cannot read, whether it does + field likewise. It no longer names what the value opened as: that is + known only once the value is decrypted. A guest answer this module cannot read, whether it does not decode or is not the shape the export writes (from `se_query_term`, `se_targets`, `se_operators`, `se_contexts`, `se_verify`, `se_target_limit`, `sa_token`, `sa_secret_key`, `sa_device_identity`, diff --git a/languages/golang/encrypt/gensupport/convert.go b/languages/golang/encrypt/gensupport/convert.go index 94aa6d820e..f52bb7a852 100644 --- a/languages/golang/encrypt/gensupport/convert.go +++ b/languages/golang/encrypt/gensupport/convert.go @@ -8,7 +8,6 @@ import ( "reflect" "strconv" - "github.com/cipherstash/stack/languages/golang/internal/guest" "github.com/cipherstash/vitaminc/bindings/go/vcvalue" ) @@ -394,8 +393,8 @@ func setSlice[E any](v any, out *[]E) error { } // valuesOf reads an opened composite as Values, nested objects included. -// want is the Go type the field needs, which a refusal names beside what -// the value opened as, by its kind and never its value. +// want is the Go type the field needs, which a refusal names. It never +// names what the value opened as, which only decryption shows. func valuesOf(v any, want string) (Values, error) { switch obj := v.(type) { case vcvalue.Object: @@ -417,5 +416,7 @@ func valuesOf(v any, want string) (Values, error) { case map[string]any: return Values(obj), nil } - return nil, fmt.Errorf("opened as %s, and %s needs an object", guest.KindOf(v), want) + // What the value opened as is not named: it is known only once the + // value is decrypted, so it is the plaintext's own metadata. + return nil, fmt.Errorf("does not open as an object, and %s needs one", want) } diff --git a/languages/golang/encrypt/gensupport/gensupport_internal_test.go b/languages/golang/encrypt/gensupport/gensupport_internal_test.go index 4e64dee535..7480d7bc13 100644 --- a/languages/golang/encrypt/gensupport/gensupport_internal_test.go +++ b/languages/golang/encrypt/gensupport/gensupport_internal_test.go @@ -658,49 +658,58 @@ func TestOpaqueReadsARustWrittenBlob(t *testing.T) { // A field of map type whose stored value opens as something else, a row // written by another SDK or an older struct, is refused as decrypt's -// malformed input: the field, what it opened as by its kind, never its -// value, and the Go type that needs an object. -func TestAMapFieldThatOpensAsAnotherKindSaysWhatItOpenedAs(t *testing.T) { - read := func(read func(Values, string) error, v any) error { - return read(Values{"tags": v}, "tags") - } +// malformed input naming the field and the Go type that needs an object, +// and never what the value opened as: that is known only once it is +// decrypted, so it is the plaintext's own metadata. +func TestAMapFieldThatOpensAsAnotherKindNamesNoKind(t *testing.T) { asAny := func(vals Values, name string) error { _, err := Get[map[string]any](vals, name); return err } asValues := func(vals Values, name string) error { _, err := Get[Values](vals, name); return err } asInts := func(vals Values, name string) error { _, err := Get[map[string]int64](vals, name); return err } for _, tc := range []struct { read func(Values, string) error value any - kind string want string }{ - {asAny, []any{"secret"}, "a list", "map[string]any"}, - {asAny, "secret", "a string", "map[string]any"}, - {asValues, int64(7), "a number", "gensupport.Values"}, - {asInts, []any{"secret"}, "a list", "map[string]int64"}, + {asAny, []any{"secret"}, "map[string]any"}, + {asAny, "secret", "map[string]any"}, + {asValues, int64(7), "gensupport.Values"}, + {asInts, []any{"secret"}, "map[string]int64"}, } { - err := read(tc.read, tc.value) + err := tc.read(Values{"tags": tc.value}, "tags") if !errors.Is(err, encrypt.ErrEncoding) { - t.Fatalf("%s for %s: %v, want ErrEncoding", tc.kind, tc.want, err) + t.Fatalf("%T for %s: %v, want ErrEncoding", tc.value, tc.want, err) } - want := fmt.Sprintf(`gensupport: decrypt: field "tags": cipherstash: malformed input: opened as %s, and %s needs an object`, tc.kind, tc.want) + want := fmt.Sprintf(`gensupport: decrypt: field "tags": cipherstash: malformed input: does not open as an object, and %s needs one`, tc.want) if err.Error() != want { t.Errorf("message:\n got %q\nwant %q", err.Error(), want) } - if strings.Contains(err.Error(), "secret") || strings.Contains(err.Error(), "7") { - t.Errorf("the error holds the value: %v", err) + assertNamesNoKind(t, err) + } +} + +// assertNamesNoKind fails if a decrypt error names what the value opened +// as, or holds the value. +func assertNamesNoKind(t *testing.T, err error) { + t.Helper() + for _, kind := range []string{"a list", "a string", "a number", "bytes", "null", "interface", "secret", "7"} { + if strings.Contains(err.Error(), kind) { + t.Errorf("%q in %v", kind, err) } } } // A document field that opens as something other than its JSON text is a -// decrypt refusal naming the field and what it opened as, by kind. -func TestADocumentFieldThatOpensAsAnotherKindSaysWhatItOpenedAs(t *testing.T) { - _, err := GetDocument[map[string]any](Values{"doc": "secret"}, "doc") - want := `gensupport: decrypt: field "doc": cipherstash: malformed input: the document opened as a string, not its JSON text` - if !errors.Is(err, encrypt.ErrEncoding) || err.Error() != want { - t.Errorf("message:\n got %v\nwant %q", err, want) - } - _, err = GetDocument[map[string]any](Values{"doc": []byte("{")}, "doc") +// decrypt refusal naming the field, and never what it opened as. +func TestADocumentFieldThatOpensAsAnotherKindNamesNoKind(t *testing.T) { + for _, v := range []any{"secret", int64(7), []any{"secret"}} { + _, err := GetDocument[map[string]any](Values{"doc": v}, "doc") + want := `gensupport: decrypt: field "doc": cipherstash: malformed input: does not open as its JSON text` + if !errors.Is(err, encrypt.ErrEncoding) || err.Error() != want { + t.Errorf("%T: message:\n got %v\nwant %q", v, err, want) + } + assertNamesNoKind(t, err) + } + _, err := GetDocument[map[string]any](Values{"doc": []byte("{")}, "doc") if err == nil || !strings.HasPrefix(err.Error(), `gensupport: decrypt: field "doc": `) { t.Errorf("JSON that does not decode: %v", err) } diff --git a/languages/golang/encrypt/gensupport/json.go b/languages/golang/encrypt/gensupport/json.go index 97ca9bfcd9..cd88a2c944 100644 --- a/languages/golang/encrypt/gensupport/json.go +++ b/languages/golang/encrypt/gensupport/json.go @@ -12,7 +12,6 @@ import ( "strings" "github.com/cipherstash/stack/languages/golang/encrypt" - "github.com/cipherstash/stack/languages/golang/internal/guest" "github.com/cipherstash/stack/languages/golang/internal/record" "github.com/cipherstash/vitaminc/bindings/go/vcvalue" ) @@ -119,7 +118,8 @@ func GetDocument[T any](vals Values, name string) (T, error) { } text, ok := v.([]byte) if !ok { - return out, fmt.Errorf("gensupport: decrypt: field %q: %w: the document opened as %s, not its JSON text", name, encrypt.ErrEncoding, guest.KindOf(v)) + // What the value opened as is not named: only decryption shows it. + return out, fmt.Errorf("gensupport: decrypt: field %q: %w: does not open as its JSON text", name, encrypt.ErrEncoding) } out, err := encrypt.DecodeJSON[T](text) if err != nil { From 94e0961382fae6ace64ae039447c68c0c03dff05 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sat, 28 Nov 2026 04:52:19 +1100 Subject: [PATCH 04/10] fix(golang): decrypt errors name no kind, and every guest answer reads through one path Review of the Go errors change found decrypt refusals that still named what a value opened as, guest answers that still bypassed the shared refusal, and a CHANGELOG that filed a break under Changed. - Privacy. Every refusal of an opened value now names the Go type the field needs and nothing about the value: a null for a type that holds one ("opened as nothing"), a list or an array of another kind or length (which printed the element count), the fallback for a type convert does not name, an opaque value that is not bytes, and `mismatch()` itself ("opened as %T, not %T"). Each says `does not open as `. The tests assert the message names no kind and no length. The kind of a decrypted value is the plaintext's own metadata. - `guest.DecodeAnswer(export, out)` decodes an answer and refuses bytes that do not decode through `BadAnswer`. `encrypt` and `auth` both use it, and so do se_json_open, se_encrypt_record and se_decrypt_record, whose shape checks also go through `BadAnswer`. What se_json_open and se_decrypt_record return is plaintext, so their refusals name a position and never a kind. A step that does not read is `BadAnswer` naming se_io or sa_auth_io; the encrypt guest's was not ErrInternal at all. - auth's answer fields (`text`, `bytes`, `optionalText`, `uint64Field`) and the token's expiry carry the export and refuse through `BadAnswer`. - se_verify's count says "it answers 1 of 2 values". - The vars refusal is a query refusal: the engine's `json_vars_not_object` now says "query input does not fit the field", as the other query refusals do since the engine branch's change. - CHANGELOG: the `json_input` to `json_vars_not_object` rename moves to a new Breaking section, and the guest-answer change is its own bullet, listing every export. --- languages/golang/CHANGELOG.md | 52 ++++++++++------- languages/golang/auth/answer_test.go | 56 ++++++++++++++++++- languages/golang/auth/step.go | 14 +++-- languages/golang/auth/store.go | 42 ++++++++------ languages/golang/auth/token.go | 3 +- languages/golang/encrypt/checker.go | 17 +----- languages/golang/encrypt/gensupport/codec.go | 2 +- .../golang/encrypt/gensupport/convert.go | 18 +++--- .../gensupport/gensupport_internal_test.go | 45 ++++++++++++++- languages/golang/encrypt/json.go | 28 ++++++---- languages/golang/encrypt/query.go | 8 +-- languages/golang/encrypt/records.go | 33 +++++++---- languages/golang/encrypt/step.go | 10 +++- languages/golang/encrypt/step_test.go | 14 ++++- languages/golang/encrypt/targets_test.go | 25 ++++++++- languages/golang/internal/guest/answer.go | 12 ++++ .../golang/internal/guest/answer_test.go | 19 +++++++ packages/stack-encrypt/src/dynamic/record.rs | 1 + packages/stack-encrypt/src/refusal.rs | 1 + .../stack-encrypt/tests/json_operators.rs | 2 +- 20 files changed, 298 insertions(+), 104 deletions(-) diff --git a/languages/golang/CHANGELOG.md b/languages/golang/CHANGELOG.md index c3288c6a3e..82158bf526 100644 --- a/languages/golang/CHANGELOG.md +++ b/languages/golang/CHANGELOG.md @@ -32,29 +32,39 @@ and `languages/golang/encrypt/encrypttest/vX.Y.Z` on the same commit. own structure: an error about a decrypted value never says what it opened as. -### Changed +### Breaking - **`Match` refuses `vars` that are not a JSON object with the reason - `json_vars_not_object`, not `json_input`** (#1987). `Found` says what - they are (`"array"`, `"uint64"`, `"null"`), `Field` names the field, - and the message says `match takes its vars as a JSON object, found - null`. A program that switches on `Reason()` for this case needs the - new name. - -- **Errors that said "not an object" now say what they mean, in words** - (#1987). A map field (`map[string]V`, `Values`, `map[string]any`) whose - stored value opens as something else is refused as `decrypt: field - "tags": ... does not open as an object, and map[string]any needs one`, - where it said `opened as []interface {}, not an object`, and a document - field likewise. It no longer names what the value opened as: that is - known only once the value is decrypted. A guest answer this module cannot read, whether it does - not decode or is not the shape the export writes (from `se_query_term`, - `se_targets`, `se_operators`, `se_contexts`, `se_verify`, - `se_target_limit`, `sa_token`, `sa_secret_key`, `sa_device_identity`, - `sa_list_workspaces` or `sa_auth_runnable`), is still `ErrInternal`, - and now names the export, says what the answer is by its kind, and says - it is a bug or a guest that does not match this module's version, not - bad input. + `json_vars_not_object`, not `json_input`** (#1987). A program that + switches on `Reason()` for this case needs the new name. `Found` says + what the vars are (`"array"`, `"uint64"`, `"null"`), `Field` names the + field, and the message says `query input does not fit the field: match + takes its vars as a JSON object, found null`. + +### Changed + +- **A decrypt refusal names the field and the Go type it needs, and never + what the value opened as** (#1987). A map field (`map[string]V`, + `Values`, `map[string]any`) whose stored value opens as something else + is refused as `decrypt: field "tags": ... does not open as an object, + and map[string]any needs one`, where it said `opened as []interface {}, + not an object`. Every other opened value of another type, a null for a + type that holds a value, a list or an array of another length, a + document that is not its JSON text and an opaque value that is not + bytes say `does not open as` the type needed, with no Go type, kind or + length of the value: those are known only once it is decrypted. + +- **A guest answer this module cannot read is an internal failure that + says so** (#1987). Whether it does not decode or is not the shape the + export writes, an answer from `se_query_term`, `se_targets`, + `se_operators`, `se_contexts`, `se_verify`, `se_target_limit`, + `se_json_open`, `se_encrypt_record`, `se_decrypt_record`, `se_io`, + `sa_token`, `sa_secret_key`, `sa_device_identity`, + `sa_list_workspaces`, `sa_auth_runnable` or `sa_auth_io` is still + `ErrInternal`. It now names the export, says it is a bug or a guest + that does not match this module's version, not bad input, and, for an + answer that is not plaintext, what it is by its kind. A step the encrypt + guest returns that does not read is now `ErrInternal` too. - **A record field converts a number of another width or kind, as a query does.** A value sealed through `Cipher.Seal` for a field that diff --git a/languages/golang/auth/answer_test.go b/languages/golang/auth/answer_test.go index af4f3a6e0e..0d31c5bf8b 100644 --- a/languages/golang/auth/answer_test.go +++ b/languages/golang/auth/answer_test.go @@ -41,7 +41,7 @@ func TestAnAnswerThatIsNotAnObjectNamesTheExportAndItsKind(t *testing.T) { if err != nil { t.Fatal(err) } - if fields, err := object("sa_token", encoded); err != nil || len(fields) != 1 { + if fields, err := object("sa_token", encoded); err != nil || len(fields.obj) != 1 { t.Fatalf("an object: %v, %v", fields, err) } if _, err := object("sa_token", []byte{0xff}); !errors.Is(err, ErrInternal) || @@ -86,3 +86,57 @@ func TestListAnswersNameTheExportAndTheirKind(t *testing.T) { t.Errorf("good handles: %v, %v", handles, err) } } + +// A field of an answer that is missing or of the wrong kind is ErrInternal +// naming the export and the field, with the version hint, and never the +// field's value: it can be a token or a key. +func TestAnAnswersFieldsNameTheExport(t *testing.T) { + answer := fields{export: "sa_token", obj: vcvalue.Object{ + {Key: "access_token", Value: int64(7)}, + {Key: "client_key", Value: "secret-key"}, + {Key: "region", Value: []byte("secret")}, + {Key: "expires_at", Value: "secret"}, + }} + for _, tc := range []struct { + read func() error + want string + }{ + {func() error { _, err := answer.text("token_type"); return err }, "it has no token_type"}, + {func() error { _, err := answer.text("access_token"); return err }, "access_token is a number, not a string"}, + {func() error { _, err := answer.bytes("missing"); return err }, "it has no missing"}, + {func() error { _, err := answer.bytes("client_key"); return err }, "client_key is a string, not bytes"}, + {func() error { _, err := answer.optionalText("region"); return err }, "region is bytes, not a string"}, + {func() error { _, err := answer.uint64Field("missing"); return err }, "it has no missing"}, + {func() error { _, err := answer.uint64Field("expires_at"); return err }, "expires_at is a string, not an unsigned integer"}, + } { + err := tc.read() + want := "cipherstash: internal guest failure: the guest's answer to sa_token does not read: " + tc.want + "; this is a bug, or a guest that does not match this module's version" + if !errors.Is(err, ErrInternal) || err == nil || err.Error() != want { + t.Errorf("message:\n got %v\nwant %q", err, want) + } + } + if s, err := answer.optionalText("absent"); err != nil || s != "" { + t.Errorf("an absent optional field: %q, %v", s, err) + } +} + +// A step that does not read names sa_auth_io. +func TestAStepThatDoesNotReadNamesTheExport(t *testing.T) { + for _, raw := range [][]byte{{0xff}, mustMarshalAuth(t, "secret")} { + _, err := decodeAuthStep(raw) + if !errors.Is(err, ErrInternal) || !errors.Is(err, errStepMalformed) || + !strings.Contains(err.Error(), "the guest's answer to sa_auth_io does not read: the step is malformed") || + strings.Contains(err.Error(), "secret") { + t.Errorf("%x: %v", raw, err) + } + } +} + +func mustMarshalAuth(t *testing.T, v any) []byte { + t.Helper() + out, err := vcffi.Marshal(v) + if err != nil { + t.Fatal(err) + } + return out +} diff --git a/languages/golang/auth/step.go b/languages/golang/auth/step.go index 4af83cc50f..9a63c5eba5 100644 --- a/languages/golang/auth/step.go +++ b/languages/golang/auth/step.go @@ -68,7 +68,13 @@ func (s *authStep) wipe() { } } -var errMalformedStep = fmt.Errorf("%w: the guest's step is malformed", ErrInternal) +// errStepMalformed is what is wrong with a step that does not read. A +// refusal of a step is ErrInternal through guest.BadAnswer, naming +// sa_auth_io, and wraps it. +var errStepMalformed = errors.New("the step is malformed") + +// errMalformedStep is a step that does not read. +var errMalformedStep = guest.BadAnswer("sa_auth_io", errStepMalformed) // decodeAuthStep reads `{"handle": u64, "parked": bool, "requests": // [{"method", "url", "headers", "body"}, ...]}`. Every byte slice it @@ -76,7 +82,7 @@ var errMalformedStep = fmt.Errorf("%w: the guest's step is malformed", ErrIntern func decodeAuthStep(raw []byte) (*authStep, error) { decoded, err := vcffi.Unmarshal(raw) if err != nil { - return nil, fmt.Errorf("%w: %w", errMalformedStep, err) + return nil, guest.BadAnswer("sa_auth_io", fmt.Errorf("%w: %w", errStepMalformed, err)) } return authStepFrom(decoded) } @@ -167,9 +173,9 @@ func decodeAuthRequest(item any) (authRequest, bool) { // decodeRunnable reads the list of parked handles the guest may resume. func decodeRunnable(raw []byte) ([]uint64, error) { - decoded, err := vcffi.Unmarshal(raw) + decoded, err := guest.DecodeAnswer("sa_auth_runnable", raw) if err != nil { - return nil, guest.BadAnswer("sa_auth_runnable", err) + return nil, err } items, ok := decoded.([]any) if !ok { diff --git a/languages/golang/auth/store.go b/languages/golang/auth/store.go index 13955308d7..c71992aac4 100644 --- a/languages/golang/auth/store.go +++ b/languages/golang/auth/store.go @@ -14,7 +14,6 @@ import ( "time" "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" ) @@ -410,9 +409,9 @@ func (s *ProfileStore) ListWorkspaces(ctx context.Context) ([]string, error) { // workspaceIDs reads sa_list_workspaces's answer: a list of workspace ids. func workspaceIDs(out []byte) ([]string, error) { - decoded, err := vcffi.Unmarshal(out) + decoded, err := guest.DecodeAnswer("sa_list_workspaces", out) if err != nil { - return nil, guest.BadAnswer("sa_list_workspaces", err) + return nil, err } items, ok := decoded.([]any) if !ok { @@ -537,26 +536,30 @@ func (s *ProfileStore) DeviceIdentity(ctx context.Context) (DeviceIdentity, erro return d, nil } -// fields is a decoded codec object. -type fields vcvalue.Object +// fields is a decoded codec object: an export's answer, which names the +// export so every refusal of it says whose answer it was. +type fields struct { + export string + obj vcvalue.Object +} // object decodes export's answer as an object. One that is not is // ErrInternal, saying what it is by its kind and never its value: the // answer can hold a key or a token. func object(export string, encoded []byte) (fields, error) { - decoded, err := vcffi.Unmarshal(encoded) + decoded, err := guest.DecodeAnswer(export, encoded) if err != nil { - return nil, guest.BadAnswer(export, err) + return fields{}, err } obj, ok := decoded.(vcvalue.Object) if !ok { - return nil, guest.BadAnswer(export, fmt.Errorf("it is %s, not an object", guest.KindOf(decoded))) + return fields{}, guest.BadAnswer(export, fmt.Errorf("it is %s, not an object", guest.KindOf(decoded))) } - return fields(obj), nil + return fields{export: export, obj: obj}, nil } func (f fields) get(key string) (any, bool) { - for _, field := range f { + for _, field := range f.obj { if field.Key == key { return field.Value, true } @@ -564,15 +567,20 @@ func (f fields) get(key string) (any, bool) { return nil, false } +// refuse is the answer's refusal: ErrInternal, naming the export. +func (f fields) refuse(format string, args ...any) error { + return guest.BadAnswer(f.export, fmt.Errorf(format, args...)) +} + // text is a string field that must be present. func (f fields) text(key string) (string, error) { v, ok := f.get(key) if !ok { - return "", fmt.Errorf("%w: the guest's result has no %s", ErrInternal, key) + return "", f.refuse("it has no %s", key) } s, ok := v.(string) if !ok { - return "", fmt.Errorf("%w: %s is not a string", ErrInternal, key) + return "", f.refuse("%s is %s, not a string", key, guest.KindOf(v)) } return s, nil } @@ -582,11 +590,11 @@ func (f fields) text(key string) (string, error) { func (f fields) bytes(key string) ([]byte, error) { v, ok := f.get(key) if !ok { - return nil, fmt.Errorf("%w: the guest's result has no %s", ErrInternal, key) + return nil, f.refuse("it has no %s", key) } b, ok := v.([]byte) if !ok { - return nil, fmt.Errorf("%w: %s is not bytes", ErrInternal, key) + return nil, f.refuse("%s is %s, not bytes", key, guest.KindOf(v)) } return b, nil } @@ -599,7 +607,7 @@ func (f fields) optionalText(key string) (string, error) { } s, ok := v.(string) if !ok { - return "", fmt.Errorf("%w: %s is not a string", ErrInternal, key) + return "", f.refuse("%s is %s, not a string", key, guest.KindOf(v)) } return s, nil } @@ -608,11 +616,11 @@ func (f fields) optionalText(key string) (string, error) { func (f fields) uint64Field(key string) (uint64, error) { v, ok := f.get(key) if !ok { - return 0, fmt.Errorf("%w: the guest's result has no %s", ErrInternal, key) + return 0, f.refuse("it has no %s", key) } n, ok := v.(uint64) if !ok { - return 0, fmt.Errorf("%w: %s is not an integer", ErrInternal, key) + return 0, f.refuse("%s is %s, not an unsigned integer", key, guest.KindOf(v)) } return n, nil } diff --git a/languages/golang/auth/token.go b/languages/golang/auth/token.go index d0dd259a43..e21267e46c 100644 --- a/languages/golang/auth/token.go +++ b/languages/golang/auth/token.go @@ -2,7 +2,6 @@ package auth import ( "context" - "fmt" "math" "time" @@ -59,7 +58,7 @@ func (s *ProfileStore) Token(ctx context.Context) (Token, error) { return Token{}, err } if expiresAt > math.MaxInt64 { - return Token{}, fmt.Errorf("%w: expires_at %d is out of range", ErrInternal, expiresAt) + return Token{}, fields.refuse("expires_at is past the range of a time") } t.ExpiresAt = time.Unix(int64(expiresAt), 0) if t.Region, err = fields.optionalText("region"); err != nil { diff --git a/languages/golang/encrypt/checker.go b/languages/golang/encrypt/checker.go index 1d016b4e82..890255f30d 100644 --- a/languages/golang/encrypt/checker.go +++ b/languages/golang/encrypt/checker.go @@ -77,7 +77,7 @@ func (k *Checker) Targets(ctx context.Context) ([]record.Target, error) { if err != nil { return nil, err } - decoded, err := decodeAnswer("se_targets", out) + decoded, err := guest.DecodeAnswer("se_targets", out) if err != nil { return nil, err } @@ -104,7 +104,7 @@ func (k *Checker) Operators(ctx context.Context, plan *record.Plan, field string if err != nil { return nil, err } - decoded, err := decodeAnswer("se_operators", out) + decoded, err := guest.DecodeAnswer("se_operators", out) if err != nil { return nil, err } @@ -143,7 +143,7 @@ func contextsOf(ctx context.Context, c *Client, plan *record.Plan) (string, erro if err != nil { return "", err } - decoded, err := decodeAnswer("se_contexts", out) + decoded, err := guest.DecodeAnswer("se_contexts", out) if err != nil { return "", err } @@ -154,17 +154,6 @@ func contextsOf(ctx context.Context, c *Client, plan *record.Plan) (string, erro return text, nil } -// decodeAnswer decodes export's answer from the transport. Bytes that do -// not decode are the guest's fault, not the caller's: ErrInternal, through -// [guest.BadAnswer], which names the export. -func decodeAnswer(export string, out []byte) (any, error) { - decoded, err := vcffi.Unmarshal(out) - if err != nil { - return nil, guest.BadAnswer(export, err) - } - return decoded, nil -} - // parseTargets reads se_targets's decoded value: {"targets": [entry, ...]}, // each entry an object with exactly the keys record.Target documents. The // shape is a contract between eql-bindings' serialiser and this reader, so diff --git a/languages/golang/encrypt/gensupport/codec.go b/languages/golang/encrypt/gensupport/codec.go index 04ae5ad667..36fbb5eab1 100644 --- a/languages/golang/encrypt/gensupport/codec.go +++ b/languages/golang/encrypt/gensupport/codec.go @@ -412,7 +412,7 @@ func Opaque[T any](vals Values, out *T) error { } encoded, ok := v.([]byte) if !ok { - return fmt.Errorf("gensupport: %w: the opaque value opened as %T, not bytes", encrypt.ErrEncoding, v) + return fmt.Errorf("gensupport: %w: the opaque value does not open as bytes", encrypt.ErrEncoding) } if bytes.HasPrefix(encoded, vcffi.StorageHeader[:3]) { if err := vcffi.UnmarshalStorage(encoded, out); err != nil { diff --git a/languages/golang/encrypt/gensupport/convert.go b/languages/golang/encrypt/gensupport/convert.go index f52bb7a852..ef5fafe438 100644 --- a/languages/golang/encrypt/gensupport/convert.go +++ b/languages/golang/encrypt/gensupport/convert.go @@ -45,7 +45,7 @@ func convert(v any, out any) error { case *[]byte, *[]any, *[]string, *[]int64, *[]int32, *[]uint32, *[]uint64, *[]float64, *[]bool, *[][]byte, *Values, *map[string]any, *any: return nil } - return fmt.Errorf("opened as nothing, and %T holds a value", out) + return fmt.Errorf("does not open as %s", reflect.TypeOf(out).Elem()) } switch out := out.(type) { case *string: @@ -156,7 +156,7 @@ func convert(v any, out any) error { func convertVia(v any, out any) error { target := reflect.ValueOf(out) if target.Kind() != reflect.Pointer || target.IsNil() { - return fmt.Errorf("the opened value is a %T, which %T cannot hold", v, out) + return fmt.Errorf("%T is not a pointer an opened value is read into", out) } elem := target.Elem() t := elem.Type() @@ -183,7 +183,7 @@ func convertVia(v any, out any) error { } items, ok := v.([]any) if !ok { - return fmt.Errorf("opened as %T, not %s", v, t) + return fmt.Errorf("does not open as %s", t) } result := reflect.MakeSlice(t, len(items), len(items)) for i, item := range items { @@ -196,7 +196,7 @@ func convertVia(v any, out any) error { case reflect.Array: items, ok := v.([]any) if !ok || len(items) != t.Len() { - return fmt.Errorf("opened as %T with %d elements, not %s", v, len(items), t) + return fmt.Errorf("does not open as %s", t) } result := reflect.New(t).Elem() for i, item := range items { @@ -225,7 +225,7 @@ func convertVia(v any, out any) error { elem.Set(result) return nil } - return fmt.Errorf("the opened value is a %T, which this field's type %s cannot hold", v, t) + return fmt.Errorf("does not open as %s", t) } // underlying is the built-in type a defined scalar type is declared over. @@ -290,8 +290,12 @@ func widenNumber(n json.Number, out any) (any, error) { return n, nil } -func mismatch(v, want any) error { - return fmt.Errorf("opened as %T, not %T", v, want) +// mismatch is the refusal of an opened value that is not of the type the +// field needs. It names the type needed and never what the value opened +// as: that is known only once the value is decrypted, so it is the +// plaintext's own metadata. +func mismatch(_, want any) error { + return fmt.Errorf("does not open as %T", want) } // outOfRange names the target type and not the value, which is plaintext. diff --git a/languages/golang/encrypt/gensupport/gensupport_internal_test.go b/languages/golang/encrypt/gensupport/gensupport_internal_test.go index 7480d7bc13..2f20b02bd8 100644 --- a/languages/golang/encrypt/gensupport/gensupport_internal_test.go +++ b/languages/golang/encrypt/gensupport/gensupport_internal_test.go @@ -691,7 +691,7 @@ func TestAMapFieldThatOpensAsAnotherKindNamesNoKind(t *testing.T) { // as, or holds the value. func assertNamesNoKind(t *testing.T, err error) { t.Helper() - for _, kind := range []string{"a list", "a string", "a number", "bytes", "null", "interface", "secret", "7"} { + for _, kind := range []string{"a list", "a string", "a number", "bytes", "null", "nothing", "interface", "elements", "secret", "7"} { if strings.Contains(err.Error(), kind) { t.Errorf("%q in %v", kind, err) } @@ -714,3 +714,46 @@ func TestADocumentFieldThatOpensAsAnotherKindNamesNoKind(t *testing.T) { t.Errorf("JSON that does not decode: %v", err) } } + +// Every other refusal of an opened value names the type the field needs and +// never what the value opened as, nor how many elements it held: a null +// for a type that holds a value, a list or an array of another kind or +// length, a value of another type, and an opaque value that is not bytes. +func TestAnOpenedValueOfAnotherTypeNamesNoKind(t *testing.T) { + read := func(get func(Values) error, v any) error { + return get(Values{"f": v}) + } + type flag bool + for _, tc := range []struct { + name string + get func(Values) error + v any + want string + }{ + {"a null for an integer", func(vals Values) error { _, err := Get[int32](vals, "f"); return err }, nil, "does not open as int32"}, + {"a value for a list", func(vals Values) error { _, err := Get[[]flag](vals, "f"); return err }, "secret", "does not open as []gensupport.flag"}, + {"a longer list for an array", func(vals Values) error { _, err := Get[[2]flag](vals, "f"); return err }, []any{true, true, true, true, true, true, true}, "does not open as [2]gensupport.flag"}, + {"a list for an array", func(vals Values) error { _, err := Get[[2]flag](vals, "f"); return err }, "secret", "does not open as [2]gensupport.flag"}, + {"a value for a struct", func(vals Values) error { _, err := Get[struct{ A int32 }](vals, "f"); return err }, "secret", "does not open as struct { A int32 }"}, + {"a list for a bool", func(vals Values) error { _, err := Get[bool](vals, "f"); return err }, []any{"secret"}, "does not open as bool"}, + } { + err := read(tc.get, tc.v) + if !errors.Is(err, encrypt.ErrEncoding) { + t.Fatalf("%s: %v, want ErrEncoding", tc.name, err) + } + want := `gensupport: decrypt: field "f": cipherstash: malformed input: ` + tc.want + if err.Error() != want { + t.Errorf("%s:\n got %q\nwant %q", tc.name, err.Error(), want) + } + assertNamesNoKind(t, err) + } + var out struct{ A int32 } + err := Opaque(Values{OpaqueField: "secret"}, &out) + want := "gensupport: cipherstash: malformed input: the opaque value does not open as bytes" + if !errors.Is(err, encrypt.ErrEncoding) || err == nil || err.Error() != want { + t.Errorf("opaque:\n got %v\nwant %q", err, want) + } + if err != nil && (strings.Contains(err.Error(), "string") || strings.Contains(err.Error(), "secret")) { + t.Errorf("the opaque refusal names what it opened as: %v", err) + } +} diff --git a/languages/golang/encrypt/json.go b/languages/golang/encrypt/json.go index 20d6e110ac..e68269b92c 100644 --- a/languages/golang/encrypt/json.go +++ b/languages/golang/encrypt/json.go @@ -11,6 +11,7 @@ import ( "log/slog" "strings" + "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" @@ -69,15 +70,17 @@ func (cph *Cipher) JSONOpen(ctx context.Context, plan *record.Plan, field string } opened := make([][][]byte, len(list)) for i, item := range list { + // What the guest opened is plaintext: a refusal names where in the + // answer it is, never what kind of value it found. values, ok := item.([]any) if !ok { - return nil, fmt.Errorf("%w: se_json_open group %d is %T", ErrInternal, i, item) + return nil, guest.BadAnswer("se_json_open", fmt.Errorf("group %d is not a list", i)) } opened[i] = make([][]byte, len(values)) for j, v := range values { text, ok := v.([]byte) if !ok { - return nil, fmt.Errorf("%w: se_json_open value %d.%d is %T", ErrInternal, i, j, v) + return nil, guest.BadAnswer("se_json_open", fmt.Errorf("value %d.%d is not JSON text", i, j)) } opened[i][j] = text } @@ -126,13 +129,16 @@ func (cph *Cipher) jsonOpen(ctx context.Context, plan *record.Plan, field string // The output is plaintext: wiped once it is decoded into the caller's // values. defer wipe(out) - decoded, err := vcffi.Unmarshal(out) + decoded, err := guest.DecodeAnswer("se_json_open", out) if err != nil { - return nil, fmt.Errorf("%w: %v", ErrInternal, err) + return nil, err } list, ok := decoded.([]any) - if !ok || len(list) != len(rows) { - return nil, fmt.Errorf("%w: se_json_open returned %T for %d groups", ErrInternal, decoded, len(rows)) + if !ok { + return nil, guest.BadAnswer("se_json_open", errors.New("it is not a list of groups")) + } + if len(list) != len(rows) { + return nil, guest.BadAnswer("se_json_open", fmt.Errorf("it answers %d of %d groups", len(list), len(rows))) } return list, nil } @@ -407,7 +413,7 @@ func (s JSONSelection[E]) Open(ctx context.Context, rows []*E) ([]JSONValue, err case 1: out[i] = JSONValue{Found: true, JSON: values[0]} default: - return nil, fmt.Errorf("%w: se_json_open opened %d values for row %d of a selector read", ErrInternal, len(values), i) + return nil, guest.BadAnswer("se_json_open", fmt.Errorf("it opened %d values for row %d of a selector read", len(values), i)) } } return out, nil @@ -631,10 +637,10 @@ func (c JSONChildren[E]) Open(ctx context.Context, entries []E) ([]JSONChildValu for i, item := range list { children, ok := item.([]any) if !ok || len(children) != 1 { - return nil, fmt.Errorf("%w: se_json_open opened %T for child %d", ErrInternal, item, i) + return nil, guest.BadAnswer("se_json_open", fmt.Errorf("child %d is not one opened entry", i)) } if out[i], err = jsonChildValue(children[0]); err != nil { - return nil, fmt.Errorf("%w: se_json_open child %d: %v", ErrInternal, i, err) + return nil, guest.BadAnswer("se_json_open", fmt.Errorf("child %d: %w", i, err)) } } return out, nil @@ -701,7 +707,7 @@ func (v JSONChildValue) LogValue() slog.Value { return slog.StringValue(redacted func jsonChildValue(item any) (JSONChildValue, error) { fields, ok := item.(vcvalue.Object) if !ok || len(fields) != 2 { - return JSONChildValue{}, fmt.Errorf("a child is %T, not a map of a key or an index and json", item) + return JSONChildValue{}, errors.New("a child is not a map of a key or an index and json") } var child JSONChildValue for _, field := range fields { @@ -722,7 +728,7 @@ func jsonChildValue(item any) (JSONChildValue, error) { } child.JSON = value default: - return JSONChildValue{}, fmt.Errorf("a %T at %q", value, field.Key) + return JSONChildValue{}, fmt.Errorf("a value of another kind at %q", field.Key) } } if child.label == noLabel || child.JSON == nil { diff --git a/languages/golang/encrypt/query.go b/languages/golang/encrypt/query.go index 4bfbbcee8b..db0c72ea38 100644 --- a/languages/golang/encrypt/query.go +++ b/languages/golang/encrypt/query.go @@ -163,7 +163,7 @@ func (cph *Cipher) QueryTerm(ctx context.Context, plan *record.Plan, field, oper if err != nil { return QueryTerm{}, err } - decoded, err := decodeAnswer("se_query_term", out) + decoded, err := guest.DecodeAnswer("se_query_term", out) if err != nil { return QueryTerm{}, err } @@ -318,7 +318,7 @@ func (cph *Cipher) Verify(ctx context.Context, plan *record.Plan, field, operato if err != nil { return nil, err } - decoded, err := decodeAnswer("se_verify", out) + decoded, err := guest.DecodeAnswer("se_verify", out) if err != nil { return nil, err } @@ -333,7 +333,7 @@ func parseVerified(decoded any, count int) ([]bool, error) { return nil, guest.BadAnswer("se_verify", fmt.Errorf("it is %s, not a list", guest.KindOf(decoded))) } if len(list) != count { - return nil, guest.BadAnswer("se_verify", fmt.Errorf("it has %d answers for %d values", len(list), count)) + return nil, guest.BadAnswer("se_verify", fmt.Errorf("it answers %d of %d values", len(list), count)) } verified := make([]bool, len(list)) for i, v := range list { @@ -370,7 +370,7 @@ func (cph *Cipher) TargetLimit(ctx context.Context, plan *record.Plan, field, op if err != nil { return Limit{}, err } - decoded, err := decodeAnswer("se_target_limit", out) + decoded, err := guest.DecodeAnswer("se_target_limit", out) if err != nil { return Limit{}, err } diff --git a/languages/golang/encrypt/records.go b/languages/golang/encrypt/records.go index 6072b2e995..33b736cf31 100644 --- a/languages/golang/encrypt/records.go +++ b/languages/golang/encrypt/records.go @@ -5,6 +5,7 @@ import ( "errors" "fmt" + "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" @@ -91,16 +92,19 @@ func (cph *Cipher) Seal(ctx context.Context, plan *record.Plan, rows []record.So defer wipe(out) tree, err := unmarshalCipherText(out) if err != nil { - return nil, fmt.Errorf("%w: %v", ErrInternal, err) + return nil, guest.BadAnswer("se_encrypt_record", err) } items, ok := tree.([]any) - if !ok || len(items) != len(rows) { - return nil, fmt.Errorf("%w: %d rows came back as %T", ErrInternal, len(rows), tree) + if !ok { + return nil, guest.BadAnswer("se_encrypt_record", fmt.Errorf("it is %s, not a list of rows", guest.KindOf(tree))) + } + if len(items) != len(rows) { + return nil, guest.BadAnswer("se_encrypt_record", fmt.Errorf("it answers %d of %d rows", len(items), len(rows))) } sealed := make([]record.Sealed, len(items)) for i, item := range items { if sealed[i], err = sealedOf(p, item); err != nil { - return nil, fmt.Errorf("%w: row %d: %v", ErrInternal, i, err) + return nil, guest.BadAnswer("se_encrypt_record", fmt.Errorf("row %d: %w", i, err)) } } return sealed, nil @@ -505,13 +509,18 @@ func (c *Client) openEncoded(ctx context.Context, call callOptions, p *record.Pl } // The output is plaintext: decode, then wipe the transport copy. defer wipe(out) - decoded, err := vcffi.Unmarshal(out) + decoded, err := guest.DecodeAnswer("se_decrypt_record", out) if err != nil { - return nil, fmt.Errorf("%w: %v", ErrInternal, err) + return nil, err } + // What the guest opened is plaintext: a refusal names where in the + // answer it is, never what kind of value it found. items, ok := decoded.([]any) - if !ok || len(items) != rows { - return nil, fmt.Errorf("%w: %d records came back as %T", ErrInternal, rows, decoded) + if !ok { + return nil, guest.BadAnswer("se_decrypt_record", errors.New("it is not a list of records")) + } + if len(items) != rows { + return nil, guest.BadAnswer("se_decrypt_record", fmt.Errorf("it answers %d of %d records", len(items), rows)) } order := make([]string, 0, len(p.Fields)+1) if p.ContextField != "" { @@ -526,14 +535,14 @@ func (c *Client) openEncoded(ctx context.Context, call callOptions, p *record.Pl for i, item := range items { obj, ok := item.(vcvalue.Object) if !ok { - return nil, fmt.Errorf("%w: record %d decrypted as %T", ErrInternal, i, item) + return nil, guest.BadAnswer("se_decrypt_record", fmt.Errorf("record %d is not a map of fields", i)) } if len(obj) != len(order) { - return nil, fmt.Errorf("%w: record %d has %d fields, expected %d", ErrInternal, i, len(obj), len(order)) + return nil, guest.BadAnswer("se_decrypt_record", fmt.Errorf("record %d has %d fields, expected %d", i, len(obj), len(order))) } for j, f := range obj { if f.Key != order[j] { - return nil, fmt.Errorf("%w: record %d field %d is %q, expected %q", ErrInternal, i, j, f.Key, order[j]) + return nil, guest.BadAnswer("se_decrypt_record", fmt.Errorf("record %d field %d is %q, expected %q", i, j, f.Key, order[j])) } } src := make(record.Source, len(obj)) @@ -544,7 +553,7 @@ func (c *Client) openEncoded(ctx context.Context, call callOptions, p *record.Pl if _, ok := src[f.Name]; !ok && f.HasCiphertext() { // An index-only field has no ciphertext to open and comes // back as nothing; every sealed or target field must. - return nil, fmt.Errorf("%w: record %d lacks field %q", ErrInternal, i, f.Name) + return nil, guest.BadAnswer("se_decrypt_record", fmt.Errorf("record %d lacks field %q", i, f.Name)) } } sources[i] = src diff --git a/languages/golang/encrypt/step.go b/languages/golang/encrypt/step.go index cd3cac59bd..9644a75fb8 100644 --- a/languages/golang/encrypt/step.go +++ b/languages/golang/encrypt/step.go @@ -54,7 +54,13 @@ func (s *ioStep) wipe() { } } -var errMalformedStep = errors.New("encrypt: the guest's step is malformed") +// errStepMalformed is what is wrong with a step that does not read. A +// refusal of a step is ErrInternal through guest.BadAnswer, naming se_io, +// and wraps it. +var errStepMalformed = errors.New("the step is malformed") + +// errMalformedStep is a step that does not read. +var errMalformedStep = guest.BadAnswer("se_io", errStepMalformed) // takeIO takes the step a paused export left (se_io), once. func (inst *instance) takeIO(ctx context.Context) (*ioStep, error) { @@ -87,7 +93,7 @@ func (inst *instance) takeIO(ctx context.Context) (*ioStep, error) { func decodeStep(raw []byte) (*ioStep, error) { decoded, err := vcffi.Unmarshal(raw) if err != nil { - return nil, fmt.Errorf("%w: %w", errMalformedStep, err) + return nil, guest.BadAnswer("se_io", fmt.Errorf("%w: %w", errStepMalformed, err)) } obj, ok := decoded.(vcvalue.Object) if !ok { diff --git a/languages/golang/encrypt/step_test.go b/languages/golang/encrypt/step_test.go index 73b03539b6..a8a70da470 100644 --- a/languages/golang/encrypt/step_test.go +++ b/languages/golang/encrypt/step_test.go @@ -12,6 +12,7 @@ import ( "path/filepath" "regexp" "strconv" + "strings" "sync/atomic" "testing" "time" @@ -307,11 +308,18 @@ func TestAYieldStepDecodesWithNoRequests(t *testing.T) { } } -// A step the host cannot decode is refused, never performed. +// A step the host cannot decode is refused, never performed: an internal +// failure naming se_io, with the version hint. func TestAMalformedStepIsRefused(t *testing.T) { for _, raw := range [][]byte{nil, {0xff}, marshalStep(t, map[string]any{"handle": uint64(1)})} { - if _, err := decodeStep(raw); !errors.Is(err, errMalformedStep) { - t.Errorf("decodeStep(%x): %v, want errMalformedStep", raw, err) + _, err := decodeStep(raw) + if !errors.Is(err, errStepMalformed) || !errors.Is(err, ErrInternal) { + t.Errorf("decodeStep(%x): %v, want ErrInternal for a malformed step", raw, err) + continue + } + if !strings.Contains(err.Error(), "the guest's answer to se_io does not read: the step is malformed") || + !strings.Contains(err.Error(), "does not match this module's version") { + t.Errorf("decodeStep(%x): %v", raw, err) } } } diff --git a/languages/golang/encrypt/targets_test.go b/languages/golang/encrypt/targets_test.go index 256ed7a9b8..2d110d983b 100644 --- a/languages/golang/encrypt/targets_test.go +++ b/languages/golang/encrypt/targets_test.go @@ -6,6 +6,7 @@ import ( "strings" "testing" + "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" @@ -218,7 +219,7 @@ func TestParseQueryTermRefusesAMixedShape(t *testing.T) { // bad input. func TestAnAnswerThatDoesNotDecodeNamesTheExport(t *testing.T) { for _, export := range []string{"se_query_term", "se_targets", "se_operators", "se_contexts", "se_verify", "se_target_limit"} { - _, err := decodeAnswer(export, []byte{0xff}) + _, err := guest.DecodeAnswer(export, []byte{0xff}) if !errors.Is(err, ErrInternal) || errors.Is(err, ErrEncoding) { t.Fatalf("%s: %v, want ErrInternal alone", export, err) } @@ -227,7 +228,7 @@ func TestAnAnswerThatDoesNotDecodeNamesTheExport(t *testing.T) { t.Errorf("%s: %v", export, err) } } - if decoded, err := decodeAnswer("se_contexts", mustMarshal(t, "users / email")); err != nil || decoded != "users / email" { + if decoded, err := guest.DecodeAnswer("se_contexts", mustMarshal(t, "users / email")); err != nil || decoded != "users / email" { t.Errorf("a good answer: %v, %v", decoded, err) } } @@ -240,7 +241,7 @@ func TestVerifyAndLimitAnswersSayWhatTheyAre(t *testing.T) { want string }{ {"secret", 1, "se_verify does not read: it is a string, not a list"}, - {[]any{true}, 2, "se_verify does not read: it has 1 answers for 2 values"}, + {[]any{true}, 2, "se_verify does not read: it answers 1 of 2 values"}, {[]any{true, "secret"}, 2, "se_verify does not read: answer 1 is a string, not a boolean"}, } { _, err := parseVerified(tc.answer, tc.count) @@ -294,3 +295,21 @@ func mustMarshal(t *testing.T, v any) []byte { } return out } + +// A child se_json_open opened that is not what the export writes is refused +// by position and key, never by what kind of value it found: the value is +// plaintext. +func TestAnOpenedChildOfTheWrongShapeNamesNoKind(t *testing.T) { + for _, tc := range []struct { + item any + want string + }{ + {"secret", "a child is not a map of a key or an index and json"}, + {vcvalue.Object{{Key: "key", Value: "k"}, {Key: "json", Value: int64(7)}}, `a value of another kind at "json"`}, + } { + _, err := jsonChildValue(tc.item) + if err == nil || err.Error() != tc.want { + t.Errorf("%v, want %q", err, tc.want) + } + } +} diff --git a/languages/golang/internal/guest/answer.go b/languages/golang/internal/guest/answer.go index eda5fcb9b9..acbffbaf66 100644 --- a/languages/golang/internal/guest/answer.go +++ b/languages/golang/internal/guest/answer.go @@ -4,6 +4,7 @@ import ( "fmt" "reflect" + "github.com/cipherstash/vitaminc/bindings/go/vcffi" "github.com/cipherstash/vitaminc/bindings/go/vcvalue" ) @@ -75,3 +76,14 @@ func KindOf(v any) string { func BadAnswer(export string, problem error) error { return fmt.Errorf("%w: the guest's answer to %s does not read: %w; this is a bug, or a guest that does not match this module's version", ErrInternal, export, problem) } + +// DecodeAnswer decodes export's answer from the transport. Bytes that do +// not decode are the guest's fault, not the caller's: ErrInternal, through +// [BadAnswer], which names the export and wraps the decoder's error. +func DecodeAnswer(export string, out []byte) (any, error) { + decoded, err := vcffi.Unmarshal(out) + if err != nil { + return nil, BadAnswer(export, err) + } + return decoded, nil +} diff --git a/languages/golang/internal/guest/answer_test.go b/languages/golang/internal/guest/answer_test.go index 14636e4c0d..7f66a7d1b4 100644 --- a/languages/golang/internal/guest/answer_test.go +++ b/languages/golang/internal/guest/answer_test.go @@ -6,6 +6,7 @@ import ( "testing" "github.com/cipherstash/stack/languages/golang/internal/guest" + "github.com/cipherstash/vitaminc/bindings/go/vcffi" "github.com/cipherstash/vitaminc/bindings/go/vcvalue" ) @@ -87,3 +88,21 @@ func TestBadAnswerIsInternalAndNamesTheExport(t *testing.T) { t.Error("the problem is not wrapped") } } + +// DecodeAnswer decodes an answer, and refuses bytes that do not decode as +// an internal failure naming the export, wrapping the decoder's error. +func TestDecodeAnswerNamesTheExport(t *testing.T) { + encoded, err := vcffi.Marshal("users / email") + if err != nil { + t.Fatal(err) + } + if decoded, err := guest.DecodeAnswer("se_contexts", encoded); err != nil || decoded != "users / email" { + t.Errorf("a good answer: %v, %v", decoded, err) + } + _, err = guest.DecodeAnswer("se_contexts", []byte{0xff}) + if !errors.Is(err, guest.ErrInternal) || + !strings.HasPrefix(err.Error(), "cipherstash: internal guest failure: the guest's answer to se_contexts does not read: ") || + !strings.HasSuffix(err.Error(), "; this is a bug, or a guest that does not match this module's version") { + t.Errorf("bytes that do not decode: %v", err) + } +} diff --git a/packages/stack-encrypt/src/dynamic/record.rs b/packages/stack-encrypt/src/dynamic/record.rs index 6a0126dbe3..9b404ca385 100644 --- a/packages/stack-encrypt/src/dynamic/record.rs +++ b/packages/stack-encrypt/src/dynamic/record.rs @@ -9534,6 +9534,7 @@ mod tests { JsonNoPredicates, JsonWildcardBoundZero, JsonUnknownPredicateOp, + JsonVarsNotObject, ] { let error = Error::bad_source(reason).in_field("age"); assert_eq!( diff --git a/packages/stack-encrypt/src/refusal.rs b/packages/stack-encrypt/src/refusal.rs index 58980248e6..23fa26cd70 100644 --- a/packages/stack-encrypt/src/refusal.rs +++ b/packages/stack-encrypt/src/refusal.rs @@ -432,6 +432,7 @@ fn answers_a_query(reason: Reason) -> bool { | JsonNoPredicates | JsonWildcardBoundZero | JsonUnknownPredicateOp + | JsonVarsNotObject ) } diff --git a/packages/stack-encrypt/tests/json_operators.rs b/packages/stack-encrypt/tests/json_operators.rs index 837182bcd4..9ae1ee075b 100644 --- a/packages/stack-encrypt/tests/json_operators.rs +++ b/packages/stack-encrypt/tests/json_operators.rs @@ -3166,7 +3166,7 @@ mod compiled_match { assert_eq!( message, format!( - r#"record source does not fit the plan: match takes its vars as a JSON object, found {phrase} (field "profile")"# + r#"query input does not fit the field: match takes its vars as a JSON object, found {phrase} (field "profile")"# ), "{vars}: the message" ); From 190de0f7ffdce3e71fed0e40e8bcf4bdac8107a2 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sat, 28 Nov 2026 19:19:09 +1100 Subject: [PATCH 05/10] docs(golang): rewrite the guest answer and decrypt error docs in plain language The Go comments about guest answers and decrypt errors were hard to follow. They joined several rules with colons, and used "refusal", "does not read" and "the version hint" with no explanation. The comments now say what each function returns and what its error names. They explain an answer (the value a guest export returns) where the word first appears. They state the rule for decrypted values in the same words each time: an error never names the kind that a value decrypted to, because that kind was inside the ciphertext. Only comments and Markdown change. No message text changes. --- languages/golang/auth/answer_test.go | 24 ++++++----- languages/golang/auth/step.go | 9 ++-- languages/golang/auth/store.go | 17 ++++---- languages/golang/cmd/stashgen/README.md | 2 +- .../golang/encrypt/gensupport/convert.go | 17 ++++---- .../gensupport/gensupport_internal_test.go | 33 +++++++++------ languages/golang/encrypt/gensupport/json.go | 11 ++--- languages/golang/encrypt/json.go | 4 +- languages/golang/encrypt/json_match_test.go | 6 +-- languages/golang/encrypt/query.go | 8 ++-- languages/golang/encrypt/records.go | 4 +- languages/golang/encrypt/step.go | 9 ++-- languages/golang/encrypt/step_test.go | 5 ++- languages/golang/encrypt/targets_test.go | 28 +++++++------ languages/golang/internal/guest/answer.go | 41 ++++++++++++------- .../golang/internal/guest/answer_test.go | 20 +++++---- 16 files changed, 138 insertions(+), 100 deletions(-) diff --git a/languages/golang/auth/answer_test.go b/languages/golang/auth/answer_test.go index 0d31c5bf8b..34ae81505f 100644 --- a/languages/golang/auth/answer_test.go +++ b/languages/golang/auth/answer_test.go @@ -9,9 +9,10 @@ import ( "github.com/cipherstash/vitaminc/bindings/go/vcvalue" ) -// An auth guest's answer that is not an object is an internal failure that -// names the export and says what the answer is, by its kind: never its -// value, which can be a key or a token. +// When the answer of an auth guest is not an object, the error is +// ErrInternal. The error names the export and the kind of value that the +// answer is. The error never contains the value, because the value can be a +// key or a token. func TestAnAnswerThatIsNotAnObjectNamesTheExportAndItsKind(t *testing.T) { for _, tc := range []struct { answer any @@ -51,9 +52,10 @@ func TestAnAnswerThatIsNotAnObjectNamesTheExportAndItsKind(t *testing.T) { } } -// The workspace list and the runnable operations are read the same way: an -// answer that does not decode, or is not what the export writes, names the -// export and what it is, by kind. +// The workspace list and the runnable operations are read the same way. +// For an answer that does not decode, or that is not what the export +// writes, the error names the export. The error also names the kind of +// value that the answer is. func TestListAnswersNameTheExportAndTheirKind(t *testing.T) { marshal := func(v any) []byte { out, err := vcffi.Marshal(v) @@ -87,9 +89,11 @@ func TestListAnswersNameTheExportAndTheirKind(t *testing.T) { } } -// A field of an answer that is missing or of the wrong kind is ErrInternal -// naming the export and the field, with the version hint, and never the -// field's value: it can be a token or a key. +// When a field of an answer is missing or is of the wrong kind, the error +// is ErrInternal. The error names the export and the field. The error says +// that the cause is a bug, or a guest of another version. The error never +// 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{ {Key: "access_token", Value: int64(7)}, @@ -120,7 +124,7 @@ func TestAnAnswersFieldsNameTheExport(t *testing.T) { } } -// A step that does not read names sa_auth_io. +// The error for a step that this package cannot read names sa_auth_io. func TestAStepThatDoesNotReadNamesTheExport(t *testing.T) { for _, raw := range [][]byte{{0xff}, mustMarshalAuth(t, "secret")} { _, err := decodeAuthStep(raw) diff --git a/languages/golang/auth/step.go b/languages/golang/auth/step.go index 9a63c5eba5..89b59b4f74 100644 --- a/languages/golang/auth/step.go +++ b/languages/golang/auth/step.go @@ -68,12 +68,13 @@ func (s *authStep) wipe() { } } -// errStepMalformed is what is wrong with a step that does not read. A -// refusal of a step is ErrInternal through guest.BadAnswer, naming -// sa_auth_io, and wraps it. +// errStepMalformed describes the problem with a step that this package +// cannot read. The error for such a step wraps errStepMalformed. +// guest.BadAnswer builds that error. The error is ErrInternal, and it +// names sa_auth_io, the export that returns the step. var errStepMalformed = errors.New("the step is malformed") -// errMalformedStep is a step that does not read. +// errMalformedStep is the error for a step that this package cannot read. var errMalformedStep = guest.BadAnswer("sa_auth_io", errStepMalformed) // decodeAuthStep reads `{"handle": u64, "parked": bool, "requests": diff --git a/languages/golang/auth/store.go b/languages/golang/auth/store.go index c71992aac4..29e71bb286 100644 --- a/languages/golang/auth/store.go +++ b/languages/golang/auth/store.go @@ -407,7 +407,8 @@ func (s *ProfileStore) ListWorkspaces(ctx context.Context) ([]string, error) { return workspaceIDs(out) } -// workspaceIDs reads sa_list_workspaces's answer: a list of workspace ids. +// workspaceIDs reads the answer of sa_list_workspaces. The answer is a +// list of workspace ids. func workspaceIDs(out []byte) ([]string, error) { decoded, err := guest.DecodeAnswer("sa_list_workspaces", out) if err != nil { @@ -536,16 +537,17 @@ func (s *ProfileStore) DeviceIdentity(ctx context.Context) (DeviceIdentity, erro return d, nil } -// fields is a decoded codec object: an export's answer, which names the -// export so every refusal of it says whose answer it was. +// fields is the decoded answer of one export: an object, and the name of +// the export. Every error about the answer names that export. type fields struct { export string obj vcvalue.Object } -// object decodes export's answer as an object. One that is not is -// ErrInternal, saying what it is by its kind and never its value: the -// answer can hold a key or a token. +// object decodes the answer of export as an object. For an answer that is +// not an object, object returns an ErrInternal error. The error names the +// kind of value that the answer is. The error never contains the value, +// because an answer can contain a key or a token. func object(export string, encoded []byte) (fields, error) { decoded, err := guest.DecodeAnswer(export, encoded) if err != nil { @@ -567,7 +569,8 @@ func (f fields) get(key string) (any, bool) { return nil, false } -// refuse is the answer's refusal: ErrInternal, naming the export. +// refuse returns the error for an answer that this package cannot read. +// The error is ErrInternal, and it names the export. func (f fields) refuse(format string, args ...any) error { return guest.BadAnswer(f.export, fmt.Errorf(format, args...)) } diff --git a/languages/golang/cmd/stashgen/README.md b/languages/golang/cmd/stashgen/README.md index 58c69f9cc3..15129b2f7d 100644 --- a/languages/golang/cmd/stashgen/README.md +++ b/languages/golang/cmd/stashgen/README.md @@ -308,7 +308,7 @@ Anything else is refused before any term is derived, as an `*encrypt.Diagnostic` - `json_path_no_wildcard`: a filter on a path with no `[*]`. - `json_path_wildcard`: a `[*]` in a filter's member. - `json_syntax`: JSON text that does not parse, a literal in the predicate (`1e999`) or `vars` (`{`, or an empty or whitespace-only `json.RawMessage`); with `At()` for a literal, without it for `vars`. -- `json_vars_not_object`: `vars` that are not a JSON object (`[1]`, `1`, `null`), with `Found()` naming what they are (`"array"`, `"uint64"`, `"null"`). +- `json_vars_not_object`: `vars` that are not a JSON object (`[1]`, `1`, `null`). `Found()` returns the kind of value that the vars are (`"array"`, `"uint64"`, `"null"`). An ordering at a path the tag does not order is `encrypt.ErrTerm` with the code `stack_encrypt::json_path_not_ordered`. diff --git a/languages/golang/encrypt/gensupport/convert.go b/languages/golang/encrypt/gensupport/convert.go index ef5fafe438..05e5717a39 100644 --- a/languages/golang/encrypt/gensupport/convert.go +++ b/languages/golang/encrypt/gensupport/convert.go @@ -290,10 +290,10 @@ func widenNumber(n json.Number, out any) (any, error) { return n, nil } -// mismatch is the refusal of an opened value that is not of the type the -// field needs. It names the type needed and never what the value opened -// as: that is known only once the value is decrypted, so it is the -// plaintext's own metadata. +// mismatch returns the error for a decrypted value that is not of the type +// that the field needs. The error names that type. The error never names +// the kind that the value decrypted to. That kind was inside the +// ciphertext, so it is part of the plaintext. func mismatch(_, want any) error { return fmt.Errorf("does not open as %T", want) } @@ -397,8 +397,9 @@ func setSlice[E any](v any, out *[]E) error { } // valuesOf reads an opened composite as Values, nested objects included. -// want is the Go type the field needs, which a refusal names. It never -// names what the value opened as, which only decryption shows. +// want is the Go type that the field needs, and an error names it. An +// error never names the kind that the value decrypted to, because that +// kind was inside the ciphertext. func valuesOf(v any, want string) (Values, error) { switch obj := v.(type) { case vcvalue.Object: @@ -420,7 +421,7 @@ func valuesOf(v any, want string) (Values, error) { case map[string]any: return Values(obj), nil } - // What the value opened as is not named: it is known only once the - // value is decrypted, so it is the plaintext's own metadata. + // The error does not name the kind that the value decrypted to. That + // kind was inside the ciphertext, so it is part of the plaintext. return nil, fmt.Errorf("does not open as an object, and %s needs one", want) } diff --git a/languages/golang/encrypt/gensupport/gensupport_internal_test.go b/languages/golang/encrypt/gensupport/gensupport_internal_test.go index 2f20b02bd8..f5cfe4812a 100644 --- a/languages/golang/encrypt/gensupport/gensupport_internal_test.go +++ b/languages/golang/encrypt/gensupport/gensupport_internal_test.go @@ -656,11 +656,13 @@ func TestOpaqueReadsARustWrittenBlob(t *testing.T) { } } -// A field of map type whose stored value opens as something else, a row -// written by another SDK or an older struct, is refused as decrypt's -// malformed input naming the field and the Go type that needs an object, -// and never what the value opened as: that is known only once it is -// decrypted, so it is the plaintext's own metadata. +// A field of map type can have a stored value that decrypts to something +// that is not an object. An example is a row written by another SDK, or by +// an older struct. Decrypt refuses that value as malformed input. The error +// names the field and the Go type that needs an object. +// +// The error never names the kind that the value decrypted to. That kind was +// inside the ciphertext, so it is part of the plaintext. func TestAMapFieldThatOpensAsAnotherKindNamesNoKind(t *testing.T) { asAny := func(vals Values, name string) error { _, err := Get[map[string]any](vals, name); return err } asValues := func(vals Values, name string) error { _, err := Get[Values](vals, name); return err } @@ -687,8 +689,8 @@ func TestAMapFieldThatOpensAsAnotherKindNamesNoKind(t *testing.T) { } } -// assertNamesNoKind fails if a decrypt error names what the value opened -// as, or holds the value. +// assertNamesNoKind fails the test if a decrypt error names the kind that +// the value decrypted to, or contains the value. func assertNamesNoKind(t *testing.T, err error) { t.Helper() for _, kind := range []string{"a list", "a string", "a number", "bytes", "null", "nothing", "interface", "elements", "secret", "7"} { @@ -698,8 +700,9 @@ func assertNamesNoKind(t *testing.T, err error) { } } -// A document field that opens as something other than its JSON text is a -// decrypt refusal naming the field, and never what it opened as. +// When a document field decrypts to something that is not its JSON text, +// the decrypt error names the field. The error never names the kind that +// the value decrypted to. func TestADocumentFieldThatOpensAsAnotherKindNamesNoKind(t *testing.T) { for _, v := range []any{"secret", int64(7), []any{"secret"}} { _, err := GetDocument[map[string]any](Values{"doc": v}, "doc") @@ -715,10 +718,14 @@ func TestADocumentFieldThatOpensAsAnotherKindNamesNoKind(t *testing.T) { } } -// Every other refusal of an opened value names the type the field needs and -// never what the value opened as, nor how many elements it held: a null -// for a type that holds a value, a list or an array of another kind or -// length, a value of another type, and an opaque value that is not bytes. +// Every other error about a decrypted value names the type that the field +// needs. The error never names the kind that the value decrypted to, or the +// number of elements in the value. The cases are: +// +// - a null for a type that does not take a null +// - a list or an array of another kind or length +// - a value of another type +// - an opaque value that is not bytes func TestAnOpenedValueOfAnotherTypeNamesNoKind(t *testing.T) { read := func(get func(Values) error, v any) error { return get(Values{"f": v}) diff --git a/languages/golang/encrypt/gensupport/json.go b/languages/golang/encrypt/gensupport/json.go index cd88a2c944..c443088199 100644 --- a/languages/golang/encrypt/gensupport/json.go +++ b/languages/golang/encrypt/gensupport/json.go @@ -118,7 +118,8 @@ func GetDocument[T any](vals Values, name string) (T, error) { } text, ok := v.([]byte) if !ok { - // What the value opened as is not named: only decryption shows it. + // The error does not name the kind that the value decrypted to, + // because that kind was inside the ciphertext. return out, fmt.Errorf("gensupport: decrypt: field %q: %w: does not open as its JSON text", name, encrypt.ErrEncoding) } out, err := encrypt.DecodeJSON[T](text) @@ -340,10 +341,10 @@ func JSONElementMatch[Q ~[]byte, T, E any](ctx context.Context, f Field[T], c *e // json_tree_match are NULL for every row too. The predicate is still // compiled, so text the grammar does not read is still refused; a // variable it names is not, as plaintext does not look for one. -// - A value that writes the JSON null (a json.RawMessage of null, or a -// pointer to a nil map) is refused as not an object, with the reason -// json_vars_not_object, as plaintext refuses "vars" that are not an -// object. +// - A value that writes the JSON null is refused as not an object, with +// the reason json_vars_not_object. Examples are a json.RawMessage of +// null, and a pointer to a nil map. jsonb_path_match over plaintext +// refuses "vars" that are not an object too. // - Any other json.RawMessage crosses as it is, so an empty or // whitespace-only one is refused by the engine as not JSON, as "{" is. // diff --git a/languages/golang/encrypt/json.go b/languages/golang/encrypt/json.go index e68269b92c..c90a9fd5fc 100644 --- a/languages/golang/encrypt/json.go +++ b/languages/golang/encrypt/json.go @@ -70,8 +70,8 @@ func (cph *Cipher) JSONOpen(ctx context.Context, plan *record.Plan, field string } opened := make([][][]byte, len(list)) for i, item := range list { - // What the guest opened is plaintext: a refusal names where in the - // answer it is, never what kind of value it found. + // The answer is decrypted plaintext. So an error names the position + // of a value in the answer, and never the kind of the value. values, ok := item.([]any) if !ok { return nil, guest.BadAnswer("se_json_open", fmt.Errorf("group %d is not a list", i)) diff --git a/languages/golang/encrypt/json_match_test.go b/languages/golang/encrypt/json_match_test.go index bdf25636fa..8807298675 100644 --- a/languages/golang/encrypt/json_match_test.go +++ b/languages/golang/encrypt/json_match_test.go @@ -299,9 +299,9 @@ func TestMatchRefusalsNameTheConstructAndItsOffset(t *testing.T) { } } - // The input itself: vars that are not an object, or not JSON. Vars that - // are not an object say what they are, by kind and never value, and - // name the field. + // The input itself: vars that are not an object, or not JSON. For vars + // that are not an object, the error names the field and the kind of + // value that the vars are. The error never contains the value. for _, tc := range []struct { name string vars any diff --git a/languages/golang/encrypt/query.go b/languages/golang/encrypt/query.go index db0c72ea38..a31d239be8 100644 --- a/languages/golang/encrypt/query.go +++ b/languages/golang/encrypt/query.go @@ -325,8 +325,8 @@ func (cph *Cipher) Verify(ctx context.Context, plan *record.Plan, field, operato return parseVerified(decoded, len(values)) } -// parseVerified reads se_verify's answer: one boolean for each of the -// count values sent. +// parseVerified reads the answer of se_verify. The answer has one boolean +// for each of the count values that the caller sent. func parseVerified(decoded any, count int) ([]bool, error) { list, ok := decoded.([]any) if !ok { @@ -377,8 +377,8 @@ func (cph *Cipher) TargetLimit(ctx context.Context, plan *record.Plan, field, op return parseLimit(decoded) } -// parseLimit reads se_target_limit's answer: null for no bound, or the row -// count. +// parseLimit reads the answer of se_target_limit. The answer is null when +// there is no bound, or the number of rows. func parseLimit(decoded any) (Limit, error) { switch v := decoded.(type) { case nil: diff --git a/languages/golang/encrypt/records.go b/languages/golang/encrypt/records.go index 33b736cf31..2fad23740f 100644 --- a/languages/golang/encrypt/records.go +++ b/languages/golang/encrypt/records.go @@ -513,8 +513,8 @@ func (c *Client) openEncoded(ctx context.Context, call callOptions, p *record.Pl if err != nil { return nil, err } - // What the guest opened is plaintext: a refusal names where in the - // answer it is, never what kind of value it found. + // The answer is decrypted plaintext. So an error names the position of + // a value in the answer, and never the kind of the value. items, ok := decoded.([]any) if !ok { return nil, guest.BadAnswer("se_decrypt_record", errors.New("it is not a list of records")) diff --git a/languages/golang/encrypt/step.go b/languages/golang/encrypt/step.go index 9644a75fb8..a37085c1e3 100644 --- a/languages/golang/encrypt/step.go +++ b/languages/golang/encrypt/step.go @@ -54,12 +54,13 @@ func (s *ioStep) wipe() { } } -// errStepMalformed is what is wrong with a step that does not read. A -// refusal of a step is ErrInternal through guest.BadAnswer, naming se_io, -// and wraps it. +// errStepMalformed describes the problem with a step that this package +// cannot read. The error for such a step wraps errStepMalformed. +// guest.BadAnswer builds that error. The error is ErrInternal, and it +// names se_io, the export that returns the step. var errStepMalformed = errors.New("the step is malformed") -// errMalformedStep is a step that does not read. +// errMalformedStep is the error for a step that this package cannot read. var errMalformedStep = guest.BadAnswer("se_io", errStepMalformed) // takeIO takes the step a paused export left (se_io), once. diff --git a/languages/golang/encrypt/step_test.go b/languages/golang/encrypt/step_test.go index a8a70da470..e42c18e9b0 100644 --- a/languages/golang/encrypt/step_test.go +++ b/languages/golang/encrypt/step_test.go @@ -308,8 +308,9 @@ func TestAYieldStepDecodesWithNoRequests(t *testing.T) { } } -// A step the host cannot decode is refused, never performed: an internal -// failure naming se_io, with the version hint. +// A step the host cannot decode is refused, never performed. The error is +// ErrInternal. The error names se_io, and says that the cause is a bug or a +// guest of another version. func TestAMalformedStepIsRefused(t *testing.T) { for _, raw := range [][]byte{nil, {0xff}, marshalStep(t, map[string]any{"handle": uint64(1)})} { _, err := decodeStep(raw) diff --git a/languages/golang/encrypt/targets_test.go b/languages/golang/encrypt/targets_test.go index 2d110d983b..7e14b4f0ae 100644 --- a/languages/golang/encrypt/targets_test.go +++ b/languages/golang/encrypt/targets_test.go @@ -94,8 +94,9 @@ func TestParseTargetsReadsEachEntry(t *testing.T) { t.Errorf("%s: %v does not name the export", name, err) } } - // What was found is named by its kind, never its value: the answer - // itself, its list, an entry, and an operator of an entry. + // Each error names the kind of the value that is wrong, and never the + // value. The value is the answer itself, its list, an entry, or an + // operator of an entry. for _, tc := range []struct { answer any want string @@ -149,7 +150,8 @@ func TestParseQueryTermTakesOnlyWhatTheEngineWrites(t *testing.T) { t.Errorf("catalog %s: %v", name, err) } } - // An answer that is not an object says what it is, by its kind. + // For an answer that is not an object, the error names the kind of + // value that the answer is. for _, tc := range []struct { answer any want string @@ -214,9 +216,9 @@ func TestParseQueryTermRefusesAMixedShape(t *testing.T) { } } -// Every export's answer is decoded through one path: bytes that do not -// decode are ErrInternal naming the export, with the version hint, never -// bad input. +// The same code decodes the answer of every export. For bytes that do not +// decode, the error is ErrInternal and names the export. The error says +// that the cause is a bug or a guest of another version, and not bad input. func TestAnAnswerThatDoesNotDecodeNamesTheExport(t *testing.T) { for _, export := range []string{"se_query_term", "se_targets", "se_operators", "se_contexts", "se_verify", "se_target_limit"} { _, err := guest.DecodeAnswer(export, []byte{0xff}) @@ -233,7 +235,8 @@ func TestAnAnswerThatDoesNotDecodeNamesTheExport(t *testing.T) { } } -// se_verify's and se_target_limit's answers say what they are, by kind. +// For an answer of se_verify or se_target_limit that is of the wrong kind, +// the error names the kind of value that the answer is. func TestVerifyAndLimitAnswersSayWhatTheyAre(t *testing.T) { for _, tc := range []struct { answer any @@ -264,7 +267,8 @@ func TestVerifyAndLimitAnswersSayWhatTheyAre(t *testing.T) { } } -// An index, a producible flag or a name of the wrong kind says what it is. +// 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)}}} @@ -286,7 +290,7 @@ func TestATargetFieldOfTheWrongKindSaysWhatItIs(t *testing.T) { } } -// mustMarshal is v in the transport. +// mustMarshal returns v as transport bytes. func mustMarshal(t *testing.T, v any) []byte { t.Helper() out, err := vcffi.Marshal(v) @@ -296,9 +300,9 @@ func mustMarshal(t *testing.T, v any) []byte { return out } -// A child se_json_open opened that is not what the export writes is refused -// by position and key, never by what kind of value it found: the value is -// plaintext. +// se_json_open can return a child that is not what the export writes. The +// error names the position and the key of the child. The error never names +// the kind of the value, because the value is decrypted plaintext. func TestAnOpenedChildOfTheWrongShapeNamesNoKind(t *testing.T) { for _, tc := range []struct { item any diff --git a/languages/golang/internal/guest/answer.go b/languages/golang/internal/guest/answer.go index acbffbaf66..6c6384183c 100644 --- a/languages/golang/internal/guest/answer.go +++ b/languages/golang/internal/guest/answer.go @@ -8,12 +8,17 @@ import ( "github.com/cipherstash/vitaminc/bindings/go/vcvalue" ) -// KindOf names what a decoded value is, by its kind and never its value: -// "null", "an object", "a list", "a string", "a number", and so on. It is -// what an error says it found where it expected something else, so the -// error can be logged without leaking the value. The vcvalue types are -// named first, so a sealed value is not taken for bytes; any other Go -// value is named by its reflect.Kind. +// KindOf returns a phrase that names the kind of a decoded value, such as +// "null", "an object", "a list", "a string", or "a number". The phrase +// never contains the value. +// +// An error uses the phrase to name the kind of value that it got in place +// 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. func KindOf(v any) string { switch v.(type) { case nil, vcvalue.TypedNull: @@ -67,19 +72,25 @@ func KindOf(v any) string { } } -// BadAnswer is the error for a guest export's answer this module cannot -// read: ErrInternal, naming the export and what was wrong with the answer, -// which it wraps. The caller's input is not at fault. The answer's shape is -// a contract between the guest and this module, so a bad one is a bug, or a -// guest that does not match this module's version, such as a guest built -// from other source than the module that embeds it. +// BadAnswer returns the error for an answer that this module cannot read. +// An answer is the value that a guest export returns. The error is +// ErrInternal. The message of the error names the export and the problem. +// The error wraps problem. +// +// The cause is never the caller's input. The guest and this module agree +// on the format of each answer. So an unreadable answer means a bug, or a +// guest that does not match the version of this module. An example is a +// guest built from other source than the module that embeds it. func BadAnswer(export string, problem error) error { return fmt.Errorf("%w: the guest's answer to %s does not read: %w; this is a bug, or a guest that does not match this module's version", ErrInternal, export, problem) } -// DecodeAnswer decodes export's answer from the transport. Bytes that do -// not decode are the guest's fault, not the caller's: ErrInternal, through -// [BadAnswer], which names the export and wraps the decoder's error. +// DecodeAnswer decodes the answer of export from its transport bytes. +// +// When the bytes do not decode, the fault is in the guest, and not in the +// caller's input. DecodeAnswer then returns the ErrInternal error from +// [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) if err != nil { diff --git a/languages/golang/internal/guest/answer_test.go b/languages/golang/internal/guest/answer_test.go index 7f66a7d1b4..f19e7909ac 100644 --- a/languages/golang/internal/guest/answer_test.go +++ b/languages/golang/internal/guest/answer_test.go @@ -10,11 +10,12 @@ import ( "github.com/cipherstash/vitaminc/bindings/go/vcvalue" ) -// named is a Go type of its own over a string. +// named is a defined Go type whose underlying type is string. type named string -// KindOf names a decoded value by its kind, never its value: the vcvalue -// types by what they are, and any other Go value by its reflect.Kind. +// 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. func TestKindOfNamesAValueByItsKind(t *testing.T) { for _, tc := range []struct { value any @@ -68,8 +69,9 @@ func TestKindOfNamesAValueByItsKind(t *testing.T) { } } -// A guest answer this module cannot read is an internal failure that names -// the export and what was wrong, and says it is not the caller's input. +// For a guest answer that this module cannot read, the error is +// ErrInternal. The error names the export and the problem, and says that +// the cause is not the caller's input. func TestBadAnswerIsInternalAndNamesTheExport(t *testing.T) { err := guest.BadAnswer("se_query_term", errors.New("it is a list, not an object")) if !errors.Is(err, guest.ErrInternal) { @@ -82,15 +84,17 @@ func TestBadAnswerIsInternalAndNamesTheExport(t *testing.T) { if strings.Contains(err.Error(), "malformed input") { t.Errorf("reads as bad input: %v", err) } - // The problem is wrapped, so a caller can still match what is behind it. + // The error wraps the problem, so a caller can still match the wrapped + // error. cause := errors.New("the decoder's error") if !errors.Is(guest.BadAnswer("se_targets", cause), cause) { t.Error("the problem is not wrapped") } } -// DecodeAnswer decodes an answer, and refuses bytes that do not decode as -// an internal failure naming the export, wrapping the decoder's error. +// DecodeAnswer decodes an answer. For bytes that do not decode, +// 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") if err != nil { From 26719c36345be9dd7d409431825ee7485463bcd5 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sat, 28 Nov 2026 19:19:09 +1100 Subject: [PATCH 06/10] docs(stack-encrypt): rewrite the match vars error docs in plain language The comments and the CHANGELOG entry for `json_vars_not_object` now use short sentences, and the entry says what a caller must change to upgrade. The comment on `misfit_text` also covers the message for a reason other than `not_an_object` that names a kind of value, such as `match takes its vars as a JSON object, found null`. Only comments and Markdown change. --- packages/stack-encrypt/CHANGELOG.md | 21 ++++++++++------- .../stack-encrypt/src/dynamic/json_query.rs | 12 ++++++---- packages/stack-encrypt/src/json/inputs.rs | 17 ++++++++++---- packages/stack-encrypt/src/refusal.rs | 23 ++++++++++++------- .../stack-encrypt/tests/json_operators.rs | 16 +++++++------ 5 files changed, 56 insertions(+), 33 deletions(-) diff --git a/packages/stack-encrypt/CHANGELOG.md b/packages/stack-encrypt/CHANGELOG.md index a3eb451c0c..8724bcbca5 100644 --- a/packages/stack-encrypt/CHANGELOG.md +++ b/packages/stack-encrypt/CHANGELOG.md @@ -573,14 +573,19 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 plan`. Those reasons are about an operator, a range, a term, statistics, a null query, or the input of a JSON operator. -- **A `match` query's `vars` that are not a JSON object have their own - reason, `json_vars_not_object`, and say what they are** (#1987). Before, - they were `json_input`, the reason for any input a JSON operator does - not take, with nothing more. Now the error names the field, gives - `found` (`"array"`, `"uint64"`, `"null"`, ...), and says - `match takes its vars as a JSON object, found null`. They are refused - before the predicate is read. Only the dynamic path can receive vars - that are not an object: a field reference always builds an object. +- **The `vars` of a `match` query that are not a JSON object get the new + reason `json_vars_not_object`** (#1987). Before, the reason was + `json_input`. The error had no more detail. `json_input` is the reason + for any input that a JSON operator does not take. To upgrade, change + code that compares the reason with `json_input` for this case. + - The error names the field. + - The payload field `found` is the kind of value that the vars are, + such as `"array"`, `"uint64"`, or `"null"`. + - The message for vars that are null is + `match takes its vars as a JSON object, found null`. + - The engine refuses the vars before it reads the predicate. + - Only the dynamic path can get vars that are not an object. A field + reference always builds an object. - **`dynamic::ValueFrame` is removed. The engine reads a plaintext as a borrowed `Frame` and keeps one as vitaminc's `OwnedFrame`** (#1955). diff --git a/packages/stack-encrypt/src/dynamic/json_query.rs b/packages/stack-encrypt/src/dynamic/json_query.rs index b2d6e7ada6..02364cc91f 100644 --- a/packages/stack-encrypt/src/dynamic/json_query.rs +++ b/packages/stack-encrypt/src/dynamic/json_query.rs @@ -169,9 +169,10 @@ //! filter's member ([`Reason::JsonPathWildcard`]). The leaves' operators //! refuse their own inputs as they would alone: an ordering at a path the //! field does not order ([`TermError::JsonPathNotOrdered`]). A -//! `wildcard_bound` of `0` is [`Reason::JsonWildcardBoundZero`], and `vars` -//! that are not an object [`Reason::JsonVarsNotObject`], which says what -//! they are ([`Error::found`](crate::dynamic::Error::found)). +//! `wildcard_bound` of `0` is [`Reason::JsonWildcardBoundZero`]. `vars` +//! that are not an object are [`Reason::JsonVarsNotObject`], and +//! [`Error::found`](crate::dynamic::Error::found) returns the kind of value +//! that they are. //! //! The operand reveals what its leaves reveal when sent one by one, and //! the boolean shape of the filter; an ordering under an odd number of `!` @@ -461,8 +462,9 @@ fn read_match(options: &JsonOptions, input: Frame<'_>) -> Result { Some(vars) => vars.parse()?, None => Parsed::of(Value::Object(serde_json::Map::new())), }; - // Vars that are not an object are refused before the predicate is - // read, so their refusal does not depend on the predicate's text. + // The engine refuses vars that are not an object before it reads the + // predicate. So the error for the vars does not depend on the text of + // the predicate. crate::json::inputs::vars_object(&vars.0)?; let text = std::str::from_utf8(&input.predicate.0) .map_err(|_| Error::bad_source(Reason::JsonInput))?; diff --git a/packages/stack-encrypt/src/json/inputs.rs b/packages/stack-encrypt/src/json/inputs.rs index 437974b300..db8375536a 100644 --- a/packages/stack-encrypt/src/json/inputs.rs +++ b/packages/stack-encrypt/src/json/inputs.rs @@ -216,8 +216,13 @@ impl Input { } } -/// `match`'s vars, which must be a JSON object: one that is not is refused -/// as [`Reason::JsonVarsNotObject`], saying what it is by its kind. +/// Checks that the vars of a `match` are a JSON object. +/// +/// # Errors +/// +/// Returns [`Error::Source`] with [`Reason::JsonVarsNotObject`] when the +/// vars are not an object. The error names the kind of value that the vars +/// are. pub(crate) fn vars_object(vars: &Value) -> Result<(), Error> { if vars.is_object() { return Ok(()); @@ -230,9 +235,11 @@ pub(crate) fn vars_object(vars: &Value) -> Result<(), Error> { }) } -/// What a JSON value is, for a refusal that says what it found: its kind, -/// never the value. A number is the kind the engine reads it as: an -/// unsigned or a signed 64-bit integer, or a float. +/// The kind of a JSON value, for an error that names the kind and never +/// contains the value. +/// +/// A number has the kind that the engine reads it as: an unsigned 64-bit +/// integer, a signed 64-bit integer, or a float. fn json_kind(value: &Value) -> Found { use vitaminc_aead::plaintext::ValueKind; Found::Kind(match value { diff --git a/packages/stack-encrypt/src/refusal.rs b/packages/stack-encrypt/src/refusal.rs index f5627ca721..de210818e8 100644 --- a/packages/stack-encrypt/src/refusal.rs +++ b/packages/stack-encrypt/src/refusal.rs @@ -528,11 +528,18 @@ enum Subject { /// The main part of the message of an error about a plan, a record /// source, or a stored record. /// -/// With a [`Found`], the text is a sentence that names the input, the kind -/// of value the input is, and the kind the operation takes. An example is -/// `row 2 of the records to encrypt is null, not an object of fields`. -/// Without a [`Found`], the text is the reason, then the row and the field -/// if the error names them. +/// The text depends on the reason and on whether there is a [`Found`]: +/// +/// - With a [`Found`] and [`Reason::NotAnObject`], the text is one +/// sentence. The sentence names the input, the kind of value the input +/// is, and the kind the operation takes. An example is +/// `row 2 of the records to encrypt is null, not an object of fields`. +/// - With a [`Found`] and any other reason, the text starts with the +/// reason and the kind of value. The row and the field follow, if the +/// error names them. An example is +/// `match takes its vars as a JSON object, found null`. +/// - Without a [`Found`], the text is the reason, then the row and the +/// field if the error names them. fn misfit_text( subject: Subject, reason: Reason, @@ -1025,9 +1032,9 @@ reasons! { /// A value returned an error of its own while the engine read it /// ([`Error::SourceFailed`]). SourceFailed => "source_failed", "a value failed while it was read"; - /// A `match` query's `vars` are not a JSON object: a list, a - /// number, a string, a boolean or the JSON `null`. The error says - /// which ([`Error::found`]). + /// The `vars` of a `match` query are not a JSON object. The vars + /// are a list, a number, a string, a boolean, or the JSON `null`. + /// [`Error::found`] returns the kind. JsonVarsNotObject => "json_vars_not_object", "match takes its vars as a JSON object"; } } diff --git a/packages/stack-encrypt/tests/json_operators.rs b/packages/stack-encrypt/tests/json_operators.rs index 9ae1ee075b..95c0879fa4 100644 --- a/packages/stack-encrypt/tests/json_operators.rs +++ b/packages/stack-encrypt/tests/json_operators.rs @@ -3129,9 +3129,10 @@ mod compiled_match { ); } - /// Vars that are not a JSON object are refused for the field, - /// saying what they are by kind and never the value, and that a - /// match takes an object. + /// The engine refuses vars that are not a JSON object. The error + /// names the field and the kind of value that the vars are, and + /// never contains the value. The message says that a match takes an + /// object. #[test] fn refuses_vars_that_are_not_an_object_saying_what_they_are() { for (vars, found, phrase) in [ @@ -3174,12 +3175,13 @@ mod compiled_match { } } - /// Vars that are not an object are refused before the predicate is - /// read: a predicate that is not UTF-8 beside vars `[]` is refused - /// for its vars. + /// The engine refuses vars that are not an object before it reads + /// the predicate. The input here has a predicate that is not UTF-8, + /// and the vars `[]`. The error is about the vars. #[test] fn refuses_vars_before_reading_the_predicate() { - /// A match input whose predicate is bytes, as a binding may send it. + /// The input of a match whose predicate is bytes. A binding can + /// send the predicate as bytes. struct Input<'a> { predicate: &'a [u8], vars: &'a str, From 70040a1a85def835364def1ba8215e66f5637b7e Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sat, 28 Nov 2026 19:19:10 +1100 Subject: [PATCH 07/10] docs(golang): rewrite the changelog entries for decrypt errors and guest answers Each entry now starts with what changed for a program that uses the module, then lists the details in short sentences. The entry about guest answers explains "guest", "answer" and "step" where they first appear. Only Markdown changes. --- languages/golang/CHANGELOG.md | 68 ++++++++++++++++++++++------------- 1 file changed, 44 insertions(+), 24 deletions(-) diff --git a/languages/golang/CHANGELOG.md b/languages/golang/CHANGELOG.md index 7484a9294b..c6846f9b08 100644 --- a/languages/golang/CHANGELOG.md +++ b/languages/golang/CHANGELOG.md @@ -38,36 +38,56 @@ and `languages/golang/encrypt/encrypttest/vX.Y.Z` on the same commit. ### Breaking - **`Match` refuses `vars` that are not a JSON object with the reason - `json_vars_not_object`, not `json_input`** (#1987). A program that - switches on `Reason()` for this case needs the new name. `Found` says - what the vars are (`"array"`, `"uint64"`, `"null"`), `Field` names the - field, and the message says `query input does not fit the field: match - takes its vars as a JSON object, found null`. + `json_vars_not_object`, not `json_input`** (#1987). If your program + compares `Reason()` with `json_input` for this case, change it to the + new name. The error also has more detail: + - `Found` is the kind of value that the vars are, such as `"array"`, + `"uint64"`, or `"null"`. + - `Field` names the field. + - The message for vars that are null is `query input does not fit the + field: match takes its vars as a JSON object, found null`. ### Changed -- **A decrypt refusal names the field and the Go type it needs, and never - what the value opened as** (#1987). A map field (`map[string]V`, - `Values`, `map[string]any`) whose stored value opens as something else - is refused as `decrypt: field "tags": ... does not open as an object, - and map[string]any needs one`, where it said `opened as []interface {}, - not an object`. Every other opened value of another type, a null for a - type that holds a value, a list or an array of another length, a - document that is not its JSON text and an opaque value that is not - bytes say `does not open as` the type needed, with no Go type, kind or - length of the value: those are known only once it is decrypted. - -- **A guest answer this module cannot read is an internal failure that - says so** (#1987). Whether it does not decode or is not the shape the - export writes, an answer from `se_query_term`, `se_targets`, +- **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 + ciphertext, so an error message leaves them out. + - A map field has the type `map[string]V`, `Values`, or + `map[string]any`. Its stored value can decrypt to something that is + not an object. The message is then `decrypt: field "tags": ... does + not open as an object, and map[string]any needs one`. Before, the + message said `opened as []interface {}, not an object`. + - The message for every other mismatch says `does not open as`, then + the type that the field needs. Those mismatches are: + - a value of another type + - a null for a type that does not take a null + - a list or an array of another length + - a document that is not its JSON text + - an opaque value that is not bytes + +- **An error about a guest answer that this module cannot read says that + the fault is internal** (#1987). A guest is a WebAssembly module that + this module embeds. An answer is the value that an exported function of + a guest returns. This module cannot read an answer that does not decode, + or that does not have the format that the function writes. The error for + such an answer is still `ErrInternal`. The message of the error now has + more detail: + - The message names the exported function. + - The message says that the cause is a bug, or a guest that does not + match the version of this module. The cause is not the program's + input. + - When the answer is not plaintext, the message names the kind of value + that the answer is. + + The change covers the answers of `se_query_term`, `se_targets`, `se_operators`, `se_contexts`, `se_verify`, `se_target_limit`, `se_json_open`, `se_encrypt_record`, `se_decrypt_record`, `se_io`, `sa_token`, `sa_secret_key`, `sa_device_identity`, - `sa_list_workspaces`, `sa_auth_runnable` or `sa_auth_io` is still - `ErrInternal`. It now names the export, says it is a bug or a guest - that does not match this module's version, not bad input, and, for an - answer that is not plaintext, what it is by its kind. A step the encrypt - guest returns that does not read is now `ErrInternal` too. + `sa_list_workspaces`, `sa_auth_runnable`, and `sa_auth_io`. The encrypt + guest also returns steps. A step is a request for the host to do I/O. + The error for a step that this module cannot read is now `ErrInternal` + too. - **A record field converts a number of another width or kind, as a query does.** A value sealed through `Cipher.Seal` for a field that From 605a0f8a44e3e3902e840a1ad86dc5a77401ecdf Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sat, 28 Nov 2026 19:19:51 +1100 Subject: [PATCH 08/10] docs(golang): split two long sentences about match vars and map fields The stashgen README sentence about `vars` that write the JSON `null` had three ideas. It is now three sentences. The CHANGELOG sentence about a map field names its subject. Only Markdown changes. --- languages/golang/CHANGELOG.md | 9 +++++---- languages/golang/cmd/stashgen/README.md | 2 +- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/languages/golang/CHANGELOG.md b/languages/golang/CHANGELOG.md index c6846f9b08..e2600bc7c9 100644 --- a/languages/golang/CHANGELOG.md +++ b/languages/golang/CHANGELOG.md @@ -54,10 +54,11 @@ and `languages/golang/encrypt/encrypttest/vX.Y.Z` on the same commit. type, the kind, and the length of a decrypted value were inside the ciphertext, so an error message leaves them out. - A map field has the type `map[string]V`, `Values`, or - `map[string]any`. Its stored value can decrypt to something that is - not an object. The message is then `decrypt: field "tags": ... does - not open as an object, and map[string]any needs one`. Before, the - message said `opened as []interface {}, not an object`. + `map[string]any`. The stored value of a map field can decrypt to + something that is not an object. The message is then `decrypt: field + "tags": ... does not open as an object, and map[string]any needs + one`. Before, the message said `opened as []interface {}, not an + object`. - The message for every other mismatch says `does not open as`, then the type that the field needs. Those mismatches are: - a value of another type diff --git a/languages/golang/cmd/stashgen/README.md b/languages/golang/cmd/stashgen/README.md index 15129b2f7d..8c6a40b07c 100644 --- a/languages/golang/cmd/stashgen/README.md +++ b/languages/golang/cmd/stashgen/README.md @@ -283,7 +283,7 @@ SELECT id FROM entity WHERE eql_v4.json_tree_match(custom_field_values, $1::eql_ `vars` are any value `encoding/json` writes as a JSON object (a map, a struct, or a `json.RawMessage` of one), and an empty map when the predicate has none; a Go string is refused, as it is for a `Contains` needle. A nil `vars` (`nil`, or a nil map, slice or pointer) does not mean "no variables". pgx and `database/sql` bind it as SQL `NULL`, and `jsonb_path_match` with `NULL` vars is `NULL` for every row, so `Match` does the same: it returns an empty operand, which binds as `NULL`, and the query matches no row. -The predicate is still compiled, so text the grammar does not read is still refused. `vars` that write the JSON `null`, such as `json.RawMessage("null")` or a pointer to a nil map, are refused as `json_vars_not_object`, as plaintext refuses vars that are not an object. +The predicate is still compiled, so text the grammar does not read is still refused. `vars` that write the JSON `null` are refused as `json_vars_not_object`. Examples are `json.RawMessage("null")` and a pointer to a nil map. `jsonb_path_match` over plaintext refuses vars that are not an object too. The Go side reads nothing of the predicate: the engine parses it and compiles it into a tree of the operands the methods above derive, one leaf per comparison. The grammar is the subset of SQL/JSON path that the stored terms can answer, as PostgreSQL reads it: From 6c0017fccc77668e5c1e9d1f7bb2fbfd8838f9d7 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sat, 28 Nov 2026 21:16:42 +1100 Subject: [PATCH 09/10] fix(stack-encrypt): say that the vars of a match are not a JSON object The message for `match` vars that are not an object was "match takes its vars as a JSON object, found null". "Takes its vars as" is the wording of the code. "Found null" is not a sentence. The message is now one sentence: "the vars of the match are null, not a JSON object". The field follows. The other errors about a value that is not an object have the same form. The phrase of the reason is "the vars of a match must be a JSON object". Only the text changes. The reason `json_vars_not_object`, the code, and the payload fields `field` and `found` stay the same. The message names the kind of the vars and never a value. The caller sent the vars, so the engine reads that kind without decrypting anything. The Rust test and the Go test that pin the message have the new text. Both CHANGELOG entries quote the new text too. --- languages/golang/CHANGELOG.md | 4 +-- languages/golang/encrypt/json_match_test.go | 4 +-- packages/stack-encrypt/CHANGELOG.md | 3 +- packages/stack-encrypt/src/refusal.rs | 36 ++++++++++--------- .../stack-encrypt/tests/json_operators.rs | 6 ++-- 5 files changed, 28 insertions(+), 25 deletions(-) diff --git a/languages/golang/CHANGELOG.md b/languages/golang/CHANGELOG.md index e2600bc7c9..5e987b762d 100644 --- a/languages/golang/CHANGELOG.md +++ b/languages/golang/CHANGELOG.md @@ -44,8 +44,8 @@ and `languages/golang/encrypt/encrypttest/vX.Y.Z` on the same commit. - `Found` is the kind of value that the vars are, such as `"array"`, `"uint64"`, or `"null"`. - `Field` names the field. - - The message for vars that are null is `query input does not fit the - field: match takes its vars as a JSON object, found null`. + - The message for vars that are null is `the vars of the match are + null, not a JSON object`. The field follows. ### Changed diff --git a/languages/golang/encrypt/json_match_test.go b/languages/golang/encrypt/json_match_test.go index 8807298675..e0aeaca1fa 100644 --- a/languages/golang/encrypt/json_match_test.go +++ b/languages/golang/encrypt/json_match_test.go @@ -331,8 +331,8 @@ func TestMatchRefusalsNameTheConstructAndItsOffset(t *testing.T) { if d.Field() != "custom_field_values" { t.Errorf("%s: field %q, want custom_field_values", tc.name, d.Field()) } - if !strings.Contains(err.Error(), "match takes its vars as a JSON object, found ") { - t.Errorf("%s: %v does not say what match takes", tc.name, err) + if !strings.Contains(err.Error(), "the vars of the match are ") || !strings.Contains(err.Error(), ", not a JSON object") { + t.Errorf("%s: %v does not say that the vars are not a JSON object", tc.name, err) } } if strings.Contains(err.Error(), "secret") { diff --git a/packages/stack-encrypt/CHANGELOG.md b/packages/stack-encrypt/CHANGELOG.md index c02aa7e207..ca0482d825 100644 --- a/packages/stack-encrypt/CHANGELOG.md +++ b/packages/stack-encrypt/CHANGELOG.md @@ -598,7 +598,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - The payload field `found` is the kind of value that the vars are, such as `"array"`, `"uint64"`, or `"null"`. - The message for vars that are null is - `match takes its vars as a JSON object, found null`. + `the vars of the match are null, not a JSON object`. The field + follows. - The engine refuses the vars before it reads the predicate. - Only the dynamic path can get vars that are not an object. A field reference always builds an object. diff --git a/packages/stack-encrypt/src/refusal.rs b/packages/stack-encrypt/src/refusal.rs index 383a57bc74..9db3fa9804 100644 --- a/packages/stack-encrypt/src/refusal.rs +++ b/packages/stack-encrypt/src/refusal.rs @@ -571,22 +571,21 @@ enum Subject { /// The message of an error about a plan, a record source, or a stored /// record. /// -/// The message depends on the reason and on whether there is a [`Found`]: +/// With a [`Found`], the message is one sentence that names the input, the +/// kind of value the input is, and the kind the operation takes. The +/// sentence says everything that `what` would, so the message leaves `what` +/// out. There are two forms: /// -/// - With a [`Found`] and [`Reason::NotAnObject`], the message is one -/// sentence. The sentence names the input, the kind of value the input -/// is, and the kind the operation takes. An example is +/// - For [`Reason::JsonVarsNotObject`], the input is the vars of a `match`. +/// An example is `the vars of the match are null, not a JSON object`. +/// - For [`Reason::NotAnObject`], the input is a plan, a field spec, a +/// record, or a row. An example is /// `row 2 of the records to encrypt is null, not an object of fields`. -/// The sentence says everything that `what` would, so the message leaves -/// `what` out. -/// - With a [`Found`] and any other reason, the message is `what`, then the -/// reason and the kind of value. The row and the field follow, if the -/// error names them. An example is `the query input does not match the -/// field: match takes its vars as a JSON object, found null`. -/// - Without a [`Found`], the message is `what`, then the reason, then the -/// row and the field if the error names them. An example is -/// `the record to encrypt does not match the plan: a field is given twice -/// (field "age")`. +/// +/// Without a [`Found`], the message is `what`, then the reason, then the +/// row and the field if the error names them. An example is +/// `the record to encrypt does not match the plan: a field is given twice +/// (field "age")`. fn misfit_text( what: &str, subject: Subject, @@ -598,8 +597,11 @@ fn misfit_text( let Some(found) = found else { return format!("{what}: {reason}{}", place_text(row, field)); }; - if reason != Reason::NotAnObject { - return format!("{what}: {reason}, found {found}{}", place_text(row, field)); + if reason == Reason::JsonVarsNotObject { + return format!( + "the vars of the match are {found}, not a JSON object{}", + place_text(row, field) + ); } let input = match (subject, row, field) { (Subject::Plan, _, None) => "the plan".to_owned(), @@ -1083,7 +1085,7 @@ reasons! { /// The `vars` of a `match` query are not a JSON object. The vars /// are a list, a number, a string, a boolean, or the JSON `null`. /// [`Error::found`] returns the kind. - JsonVarsNotObject => "json_vars_not_object", "match takes its vars as a JSON object"; + JsonVarsNotObject => "json_vars_not_object", "the vars of a match must be a JSON object"; } } diff --git a/packages/stack-encrypt/tests/json_operators.rs b/packages/stack-encrypt/tests/json_operators.rs index ec9b33fec8..b9c5b2b891 100644 --- a/packages/stack-encrypt/tests/json_operators.rs +++ b/packages/stack-encrypt/tests/json_operators.rs @@ -3131,8 +3131,8 @@ mod compiled_match { /// The engine refuses vars that are not a JSON object. The error /// names the field and the kind of value that the vars are, and - /// never contains the value. The message says that a match takes an - /// object. + /// never contains the value. The message says that the vars are of + /// that kind, and not a JSON object. #[test] fn refuses_vars_that_are_not_an_object_saying_what_they_are() { for (vars, found, phrase) in [ @@ -3167,7 +3167,7 @@ mod compiled_match { assert_eq!( message, format!( - r#"the query input does not match the field: match takes its vars as a JSON object, found {phrase} (field "profile")"# + r#"the vars of the match are {phrase}, not a JSON object (field "profile")"# ), "{vars}: the message" ); From 409aa27f375aa86039b3612665644ba801d21425 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sat, 28 Nov 2026 21:16:43 +1100 Subject: [PATCH 10/10] fix(golang): say what was wrong in the answer and decrypt error messages Several messages that this branch added used the wording of the code. Examples are "does not read", "does not open as", "it answers 1 of 2 rows", and "a sealed value". A developer who gets one of these errors has to guess what they mean. The messages now say what was wrong in plain words. Only the text changes. Every error is still `ErrInternal` or `ErrEncoding`, and `errors.Is` gives the same results. - An answer that this module cannot read: "cannot read the guest's answer from se_query_term: it is a list, not an object. The cause is a bug, or a guest that does not match the version of this module". - A decrypted value of the wrong type: "the decrypted value is not of type int32". For a map field: "the decrypted value is not an object, and map[string]any needs an object". Both messages name the type that the field needs, and never the kind that the value decrypted to. - An answer with the wrong number of items says both numbers: "the number of rows is 1, not the 2 that were sent". - `KindOf` says "an encrypted value" for a sealed value, and "a value of another kind" for a Go value that it has no name for. - `expires_at` that is past the range of `time.Unix` is "too large for a time". The tests and the CHANGELOG entry that quote these messages have the new text. --- languages/golang/CHANGELOG.md | 13 +++++----- languages/golang/auth/answer_test.go | 22 ++++++++-------- languages/golang/auth/token.go | 2 +- languages/golang/encrypt/gensupport/codec.go | 2 +- .../golang/encrypt/gensupport/convert.go | 26 ++++++++++++------- .../gensupport/gensupport_internal_test.go | 18 ++++++------- languages/golang/encrypt/gensupport/json.go | 2 +- languages/golang/encrypt/json.go | 10 +++---- languages/golang/encrypt/query.go | 2 +- languages/golang/encrypt/records.go | 12 +++++++-- languages/golang/encrypt/step_test.go | 4 +-- languages/golang/encrypt/targets_test.go | 18 ++++++------- languages/golang/internal/guest/answer.go | 12 ++++----- .../golang/internal/guest/answer_test.go | 18 ++++++------- 14 files changed, 88 insertions(+), 73 deletions(-) diff --git a/languages/golang/CHANGELOG.md b/languages/golang/CHANGELOG.md index 5e987b762d..e4b3a369ab 100644 --- a/languages/golang/CHANGELOG.md +++ b/languages/golang/CHANGELOG.md @@ -56,11 +56,11 @@ and `languages/golang/encrypt/encrypttest/vX.Y.Z` on the same commit. - A map field has the type `map[string]V`, `Values`, or `map[string]any`. The stored value of a map field can decrypt to something that is not an object. The message is then `decrypt: field - "tags": ... does not open as an object, and map[string]any needs - one`. Before, the message said `opened as []interface {}, not an - object`. - - The message for every other mismatch says `does not open as`, then - the type that the field needs. Those mismatches are: + "tags": ... the decrypted value is not an object, and map[string]any + needs an object`. Before, the message said `opened as []interface {}, + not an object`. + - The message for every other mismatch says `the decrypted value is not + of type`, then the type that the field needs. Those mismatches are: - a value of another type - a null for a type that does not take a null - a list or an array of another length @@ -74,7 +74,8 @@ and `languages/golang/encrypt/encrypttest/vX.Y.Z` on the same commit. or that does not have the format that the function writes. The error for such an answer is still `ErrInternal`. The message of the error now has more detail: - - The message names the exported function. + - The message names the exported function, as in `cannot read the + guest's answer from se_query_term`. - The message says that the cause is a bug, or a guest that does not match the version of this module. The cause is not the program's input. diff --git a/languages/golang/auth/answer_test.go b/languages/golang/auth/answer_test.go index 34ae81505f..3e99bd5ba1 100644 --- a/languages/golang/auth/answer_test.go +++ b/languages/golang/auth/answer_test.go @@ -30,7 +30,7 @@ func TestAnAnswerThatIsNotAnObjectNamesTheExportAndItsKind(t *testing.T) { if !errors.Is(err, ErrInternal) { t.Fatalf("%s: %v, want ErrInternal", tc.kind, err) } - want := "cipherstash: internal guest failure: the guest's answer to sa_token does not read: it is " + tc.kind + ", not an object; this is a bug, or a guest that does not match this module's version" + want := "cipherstash: internal guest failure: cannot read the guest's answer from sa_token: it is " + tc.kind + ", not an object. The cause is a bug, or a guest that does not match the version of this module" if err.Error() != want { t.Errorf("message:\n got %q\nwant %q", err.Error(), want) } @@ -46,8 +46,8 @@ func TestAnAnswerThatIsNotAnObjectNamesTheExportAndItsKind(t *testing.T) { t.Fatalf("an object: %v, %v", fields, err) } if _, err := object("sa_token", []byte{0xff}); !errors.Is(err, ErrInternal) || - !strings.Contains(err.Error(), "the guest's answer to sa_token does not read") || - !strings.Contains(err.Error(), "does not match this module's version") { + !strings.Contains(err.Error(), "cannot read the guest's answer from sa_token") || + !strings.Contains(err.Error(), "does not match the version of this module") { t.Errorf("bytes that do not decode: %v", err) } } @@ -69,12 +69,12 @@ func TestListAnswersNameTheExportAndTheirKind(t *testing.T) { answer []byte want string }{ - {func(b []byte) error { _, err := workspaceIDs(b); return err }, []byte{0xff}, "the guest's answer to sa_list_workspaces does not read: "}, - {func(b []byte) error { _, err := workspaceIDs(b); return err }, marshal("secret"), "sa_list_workspaces does not read: it is a string, not a list"}, - {func(b []byte) error { _, err := workspaceIDs(b); return err }, marshal([]any{"ws", int64(1)}), "sa_list_workspaces does not read: workspace id 1 is a number, not a string"}, - {func(b []byte) error { _, err := decodeRunnable(b); return err }, []byte{0xff}, "the guest's answer to sa_auth_runnable does not read: "}, - {func(b []byte) error { _, err := decodeRunnable(b); return err }, marshal("secret"), "sa_auth_runnable does not read: it is a string, not a list"}, - {func(b []byte) error { _, err := decodeRunnable(b); return err }, marshal([]any{uint64(1), "secret"}), "sa_auth_runnable does not read: operation 1 is a string, not a handle"}, + {func(b []byte) error { _, err := workspaceIDs(b); return err }, []byte{0xff}, "cannot read the guest's answer from sa_list_workspaces: "}, + {func(b []byte) error { _, err := workspaceIDs(b); return err }, marshal("secret"), "from sa_list_workspaces: it is a string, not a list"}, + {func(b []byte) error { _, err := workspaceIDs(b); return err }, marshal([]any{"ws", int64(1)}), "from sa_list_workspaces: workspace id 1 is a number, not a string"}, + {func(b []byte) error { _, err := decodeRunnable(b); return err }, []byte{0xff}, "cannot read the guest's answer from sa_auth_runnable: "}, + {func(b []byte) error { _, err := decodeRunnable(b); return err }, marshal("secret"), "from sa_auth_runnable: it is a string, not a list"}, + {func(b []byte) error { _, err := decodeRunnable(b); return err }, marshal([]any{uint64(1), "secret"}), "from sa_auth_runnable: operation 1 is a string, not a handle"}, } { err := tc.read(tc.answer) if !errors.Is(err, ErrInternal) || !strings.Contains(err.Error(), tc.want) || strings.Contains(err.Error(), "secret") { @@ -114,7 +114,7 @@ func TestAnAnswersFieldsNameTheExport(t *testing.T) { {func() error { _, err := answer.uint64Field("expires_at"); return err }, "expires_at is a string, not an unsigned integer"}, } { err := tc.read() - want := "cipherstash: internal guest failure: the guest's answer to sa_token does not read: " + tc.want + "; this is a bug, or a guest that does not match this module's version" + want := "cipherstash: internal guest failure: cannot read the guest's answer from sa_token: " + tc.want + ". The cause is a bug, or a guest that does not match the version of this module" if !errors.Is(err, ErrInternal) || err == nil || err.Error() != want { t.Errorf("message:\n got %v\nwant %q", err, want) } @@ -129,7 +129,7 @@ func TestAStepThatDoesNotReadNamesTheExport(t *testing.T) { for _, raw := range [][]byte{{0xff}, mustMarshalAuth(t, "secret")} { _, err := decodeAuthStep(raw) if !errors.Is(err, ErrInternal) || !errors.Is(err, errStepMalformed) || - !strings.Contains(err.Error(), "the guest's answer to sa_auth_io does not read: the step is malformed") || + !strings.Contains(err.Error(), "cannot read the guest's answer from sa_auth_io: the step is malformed") || strings.Contains(err.Error(), "secret") { t.Errorf("%x: %v", raw, err) } diff --git a/languages/golang/auth/token.go b/languages/golang/auth/token.go index e21267e46c..4d9e7eaa97 100644 --- a/languages/golang/auth/token.go +++ b/languages/golang/auth/token.go @@ -58,7 +58,7 @@ func (s *ProfileStore) Token(ctx context.Context) (Token, error) { return Token{}, err } if expiresAt > math.MaxInt64 { - return Token{}, fields.refuse("expires_at is past the range of a time") + return Token{}, fields.refuse("expires_at is too large for a time") } t.ExpiresAt = time.Unix(int64(expiresAt), 0) if t.Region, err = fields.optionalText("region"); err != nil { diff --git a/languages/golang/encrypt/gensupport/codec.go b/languages/golang/encrypt/gensupport/codec.go index 36fbb5eab1..e2ecb3046d 100644 --- a/languages/golang/encrypt/gensupport/codec.go +++ b/languages/golang/encrypt/gensupport/codec.go @@ -412,7 +412,7 @@ func Opaque[T any](vals Values, out *T) error { } encoded, ok := v.([]byte) if !ok { - return fmt.Errorf("gensupport: %w: the opaque value does not open as bytes", encrypt.ErrEncoding) + 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 { diff --git a/languages/golang/encrypt/gensupport/convert.go b/languages/golang/encrypt/gensupport/convert.go index 05e5717a39..1c56d591d5 100644 --- a/languages/golang/encrypt/gensupport/convert.go +++ b/languages/golang/encrypt/gensupport/convert.go @@ -45,7 +45,7 @@ func convert(v any, out any) error { case *[]byte, *[]any, *[]string, *[]int64, *[]int32, *[]uint32, *[]uint64, *[]float64, *[]bool, *[][]byte, *Values, *map[string]any, *any: return nil } - return fmt.Errorf("does not open as %s", reflect.TypeOf(out).Elem()) + return notOfType(reflect.TypeOf(out).Elem()) } switch out := out.(type) { case *string: @@ -156,7 +156,7 @@ func convert(v any, out any) error { func convertVia(v any, out any) error { target := reflect.ValueOf(out) if target.Kind() != reflect.Pointer || target.IsNil() { - return fmt.Errorf("%T is not a pointer an opened value is read into", out) + return fmt.Errorf("cannot read a decrypted value into %T, because the target must be a pointer that is not nil", out) } elem := target.Elem() t := elem.Type() @@ -183,7 +183,7 @@ func convertVia(v any, out any) error { } items, ok := v.([]any) if !ok { - return fmt.Errorf("does not open as %s", t) + return notOfType(t) } result := reflect.MakeSlice(t, len(items), len(items)) for i, item := range items { @@ -196,7 +196,7 @@ func convertVia(v any, out any) error { case reflect.Array: items, ok := v.([]any) if !ok || len(items) != t.Len() { - return fmt.Errorf("does not open as %s", t) + return notOfType(t) } result := reflect.New(t).Elem() for i, item := range items { @@ -225,7 +225,7 @@ func convertVia(v any, out any) error { elem.Set(result) return nil } - return fmt.Errorf("does not open as %s", t) + return notOfType(t) } // underlying is the built-in type a defined scalar type is declared over. @@ -291,11 +291,17 @@ func widenNumber(n json.Number, out any) (any, error) { } // mismatch returns the error for a decrypted value that is not of the type -// that the field needs. The error names that type. The error never names -// the kind that the value decrypted to. That kind was inside the -// ciphertext, so it is part of the plaintext. +// that the field needs. want is a value of that type. See [notOfType]. func mismatch(_, want any) error { - return fmt.Errorf("does not open as %T", want) + return fmt.Errorf("the decrypted value is not of type %T", want) +} + +// notOfType returns the error for a decrypted value that is not of the Go +// type that the field needs. The error names that type. The error never +// names the kind that the value decrypted to. That kind was inside the +// ciphertext, so it is part of the plaintext. +func notOfType(want reflect.Type) error { + return fmt.Errorf("the decrypted value is not of type %s", want) } // outOfRange names the target type and not the value, which is plaintext. @@ -423,5 +429,5 @@ func valuesOf(v any, want string) (Values, error) { } // The error does not name the kind that the value decrypted to. That // kind was inside the ciphertext, so it is part of the plaintext. - return nil, fmt.Errorf("does not open as an object, and %s needs one", want) + return nil, fmt.Errorf("the decrypted value is not an object, and %s needs an object", want) } diff --git a/languages/golang/encrypt/gensupport/gensupport_internal_test.go b/languages/golang/encrypt/gensupport/gensupport_internal_test.go index f5cfe4812a..44ece19a80 100644 --- a/languages/golang/encrypt/gensupport/gensupport_internal_test.go +++ b/languages/golang/encrypt/gensupport/gensupport_internal_test.go @@ -681,7 +681,7 @@ func TestAMapFieldThatOpensAsAnotherKindNamesNoKind(t *testing.T) { if !errors.Is(err, encrypt.ErrEncoding) { t.Fatalf("%T for %s: %v, want ErrEncoding", tc.value, tc.want, err) } - want := fmt.Sprintf(`gensupport: decrypt: field "tags": cipherstash: malformed input: does not open as an object, and %s needs one`, tc.want) + want := fmt.Sprintf(`gensupport: decrypt: field "tags": cipherstash: malformed input: the decrypted value is not an object, and %s needs an object`, tc.want) if err.Error() != want { t.Errorf("message:\n got %q\nwant %q", err.Error(), want) } @@ -706,7 +706,7 @@ func assertNamesNoKind(t *testing.T, err error) { func TestADocumentFieldThatOpensAsAnotherKindNamesNoKind(t *testing.T) { for _, v := range []any{"secret", int64(7), []any{"secret"}} { _, err := GetDocument[map[string]any](Values{"doc": v}, "doc") - want := `gensupport: decrypt: field "doc": cipherstash: malformed input: does not open as its JSON text` + want := `gensupport: decrypt: field "doc": cipherstash: malformed input: the decrypted value is not JSON text` if !errors.Is(err, encrypt.ErrEncoding) || err.Error() != want { t.Errorf("%T: message:\n got %v\nwant %q", v, err, want) } @@ -737,12 +737,12 @@ func TestAnOpenedValueOfAnotherTypeNamesNoKind(t *testing.T) { v any want string }{ - {"a null for an integer", func(vals Values) error { _, err := Get[int32](vals, "f"); return err }, nil, "does not open as int32"}, - {"a value for a list", func(vals Values) error { _, err := Get[[]flag](vals, "f"); return err }, "secret", "does not open as []gensupport.flag"}, - {"a longer list for an array", func(vals Values) error { _, err := Get[[2]flag](vals, "f"); return err }, []any{true, true, true, true, true, true, true}, "does not open as [2]gensupport.flag"}, - {"a list for an array", func(vals Values) error { _, err := Get[[2]flag](vals, "f"); return err }, "secret", "does not open as [2]gensupport.flag"}, - {"a value for a struct", func(vals Values) error { _, err := Get[struct{ A int32 }](vals, "f"); return err }, "secret", "does not open as struct { A int32 }"}, - {"a list for a bool", func(vals Values) error { _, err := Get[bool](vals, "f"); return err }, []any{"secret"}, "does not open as bool"}, + {"a null for an integer", func(vals Values) error { _, err := Get[int32](vals, "f"); return err }, nil, "the decrypted value is not of type int32"}, + {"a value for a list", func(vals Values) error { _, err := Get[[]flag](vals, "f"); return err }, "secret", "the decrypted value is not of type []gensupport.flag"}, + {"a longer list for an array", func(vals Values) error { _, err := Get[[2]flag](vals, "f"); return err }, []any{true, true, true, true, true, true, true}, "the decrypted value is not of type [2]gensupport.flag"}, + {"a list for an array", func(vals Values) error { _, err := Get[[2]flag](vals, "f"); return err }, "secret", "the decrypted value is not of type [2]gensupport.flag"}, + {"a value for a struct", func(vals Values) error { _, err := Get[struct{ A int32 }](vals, "f"); return err }, "secret", "the decrypted value is not of type struct { A int32 }"}, + {"a list for a bool", func(vals Values) error { _, err := Get[bool](vals, "f"); return err }, []any{"secret"}, "the decrypted value is not of type bool"}, } { err := read(tc.get, tc.v) if !errors.Is(err, encrypt.ErrEncoding) { @@ -756,7 +756,7 @@ func TestAnOpenedValueOfAnotherTypeNamesNoKind(t *testing.T) { } var out struct{ A int32 } err := Opaque(Values{OpaqueField: "secret"}, &out) - want := "gensupport: cipherstash: malformed input: the opaque value does not open as bytes" + want := "gensupport: cipherstash: malformed input: the decrypted opaque value is not bytes" if !errors.Is(err, encrypt.ErrEncoding) || err == nil || err.Error() != want { t.Errorf("opaque:\n got %v\nwant %q", err, want) } diff --git a/languages/golang/encrypt/gensupport/json.go b/languages/golang/encrypt/gensupport/json.go index c443088199..9f0ca9ef30 100644 --- a/languages/golang/encrypt/gensupport/json.go +++ b/languages/golang/encrypt/gensupport/json.go @@ -120,7 +120,7 @@ func GetDocument[T any](vals Values, name string) (T, error) { if !ok { // The error does not name the kind that the value decrypted to, // because that kind was inside the ciphertext. - return out, fmt.Errorf("gensupport: decrypt: field %q: %w: does not open as its JSON text", name, encrypt.ErrEncoding) + return out, fmt.Errorf("gensupport: decrypt: field %q: %w: the decrypted value is not JSON text", name, encrypt.ErrEncoding) } out, err := encrypt.DecodeJSON[T](text) if err != nil { diff --git a/languages/golang/encrypt/json.go b/languages/golang/encrypt/json.go index c90a9fd5fc..b7c682d091 100644 --- a/languages/golang/encrypt/json.go +++ b/languages/golang/encrypt/json.go @@ -138,7 +138,7 @@ func (cph *Cipher) jsonOpen(ctx context.Context, plan *record.Plan, field string return nil, guest.BadAnswer("se_json_open", errors.New("it is not a list of groups")) } if len(list) != len(rows) { - return nil, guest.BadAnswer("se_json_open", fmt.Errorf("it answers %d of %d groups", len(list), len(rows))) + return nil, guest.BadAnswer("se_json_open", countMismatch("groups", len(list), len(rows))) } return list, nil } @@ -413,7 +413,7 @@ func (s JSONSelection[E]) Open(ctx context.Context, rows []*E) ([]JSONValue, err case 1: out[i] = JSONValue{Found: true, JSON: values[0]} default: - return nil, guest.BadAnswer("se_json_open", fmt.Errorf("it opened %d values for row %d of a selector read", len(values), i)) + return nil, guest.BadAnswer("se_json_open", fmt.Errorf("row %d of a selector read has %d decrypted values, not 0 or 1", i, len(values))) } } return out, nil @@ -637,7 +637,7 @@ func (c JSONChildren[E]) Open(ctx context.Context, entries []E) ([]JSONChildValu for i, item := range list { children, ok := item.([]any) if !ok || len(children) != 1 { - return nil, guest.BadAnswer("se_json_open", fmt.Errorf("child %d is not one opened entry", i)) + return nil, guest.BadAnswer("se_json_open", fmt.Errorf("child %d is not one decrypted entry", i)) } if out[i], err = jsonChildValue(children[0]); err != nil { return nil, guest.BadAnswer("se_json_open", fmt.Errorf("child %d: %w", i, err)) @@ -707,7 +707,7 @@ func (v JSONChildValue) LogValue() slog.Value { return slog.StringValue(redacted func jsonChildValue(item any) (JSONChildValue, error) { fields, ok := item.(vcvalue.Object) if !ok || len(fields) != 2 { - return JSONChildValue{}, errors.New("a child is not a map of a key or an index and json") + return JSONChildValue{}, errors.New(`it is not an object with "json" and either "key" or "index"`) } var child JSONChildValue for _, field := range fields { @@ -728,7 +728,7 @@ func jsonChildValue(item any) (JSONChildValue, error) { } child.JSON = value default: - return JSONChildValue{}, fmt.Errorf("a value of another kind at %q", field.Key) + return JSONChildValue{}, fmt.Errorf("the value at %q is not text, an integer, or bytes", field.Key) } } if child.label == noLabel || child.JSON == nil { diff --git a/languages/golang/encrypt/query.go b/languages/golang/encrypt/query.go index a31d239be8..99d9a0d7c5 100644 --- a/languages/golang/encrypt/query.go +++ b/languages/golang/encrypt/query.go @@ -333,7 +333,7 @@ func parseVerified(decoded any, count int) ([]bool, error) { return nil, guest.BadAnswer("se_verify", fmt.Errorf("it is %s, not a list", guest.KindOf(decoded))) } if len(list) != count { - return nil, guest.BadAnswer("se_verify", fmt.Errorf("it answers %d of %d values", len(list), count)) + return nil, guest.BadAnswer("se_verify", countMismatch("values", len(list), count)) } verified := make([]bool, len(list)) for i, v := range list { diff --git a/languages/golang/encrypt/records.go b/languages/golang/encrypt/records.go index 2fad23740f..256137668b 100644 --- a/languages/golang/encrypt/records.go +++ b/languages/golang/encrypt/records.go @@ -99,7 +99,7 @@ func (cph *Cipher) Seal(ctx context.Context, plan *record.Plan, rows []record.So return nil, guest.BadAnswer("se_encrypt_record", fmt.Errorf("it is %s, not a list of rows", guest.KindOf(tree))) } if len(items) != len(rows) { - return nil, guest.BadAnswer("se_encrypt_record", fmt.Errorf("it answers %d of %d rows", len(items), len(rows))) + return nil, guest.BadAnswer("se_encrypt_record", countMismatch("rows", len(items), len(rows))) } sealed := make([]record.Sealed, len(items)) for i, item := range items { @@ -520,7 +520,7 @@ func (c *Client) openEncoded(ctx context.Context, call callOptions, p *record.Pl return nil, guest.BadAnswer("se_decrypt_record", errors.New("it is not a list of records")) } if len(items) != rows { - return nil, guest.BadAnswer("se_decrypt_record", fmt.Errorf("it answers %d of %d records", len(items), rows)) + return nil, guest.BadAnswer("se_decrypt_record", countMismatch("records", len(items), rows)) } order := make([]string, 0, len(p.Fields)+1) if p.ContextField != "" { @@ -619,3 +619,11 @@ func sourceDiagnostic(reason, field, message string) error { return &Diagnostic{Code: "stack_encrypt::dynamic_source", Message: message, Fields: map[string]any{"reason": reason, "field": field}} } + +// countMismatch returns the problem with an answer that has the wrong +// number of items. The parameter what is the plural name of the items, +// such as "rows". The answer has got items, and the caller sent want +// items. The caller passes the problem to guest.BadAnswer. +func countMismatch(what string, got, want int) error { + return fmt.Errorf("the number of %s is %d, not the %d that were sent", what, got, want) +} diff --git a/languages/golang/encrypt/step_test.go b/languages/golang/encrypt/step_test.go index e42c18e9b0..867d50fb66 100644 --- a/languages/golang/encrypt/step_test.go +++ b/languages/golang/encrypt/step_test.go @@ -318,8 +318,8 @@ func TestAMalformedStepIsRefused(t *testing.T) { t.Errorf("decodeStep(%x): %v, want ErrInternal for a malformed step", raw, err) continue } - if !strings.Contains(err.Error(), "the guest's answer to se_io does not read: the step is malformed") || - !strings.Contains(err.Error(), "does not match this module's version") { + if !strings.Contains(err.Error(), "cannot read the guest's answer from se_io: the step is malformed") || + !strings.Contains(err.Error(), "does not match the version of this module") { t.Errorf("decodeStep(%x): %v", raw, err) } } diff --git a/languages/golang/encrypt/targets_test.go b/languages/golang/encrypt/targets_test.go index 7e14b4f0ae..e0a35a4d51 100644 --- a/languages/golang/encrypt/targets_test.go +++ b/languages/golang/encrypt/targets_test.go @@ -90,7 +90,7 @@ func TestParseTargetsReadsEachEntry(t *testing.T) { if !errors.Is(err, ErrInternal) { t.Errorf("%s: %v, want ErrInternal", name, err) } - if err != nil && !strings.Contains(err.Error(), "the guest's answer to se_targets does not read") { + if err != nil && !strings.Contains(err.Error(), "cannot read the guest's answer from se_targets") { t.Errorf("%s: %v does not name the export", name, err) } } @@ -225,8 +225,8 @@ func TestAnAnswerThatDoesNotDecodeNamesTheExport(t *testing.T) { if !errors.Is(err, ErrInternal) || errors.Is(err, ErrEncoding) { t.Fatalf("%s: %v, want ErrInternal alone", export, err) } - want := "cipherstash: internal guest failure: the guest's answer to " + export + " does not read: " - if !strings.HasPrefix(err.Error(), want) || !strings.Contains(err.Error(), "does not match this module's version") { + want := "cipherstash: internal guest failure: cannot read the guest's answer from " + export + ": " + if !strings.HasPrefix(err.Error(), want) || !strings.Contains(err.Error(), "does not match the version of this module") { t.Errorf("%s: %v", export, err) } } @@ -243,9 +243,9 @@ func TestVerifyAndLimitAnswersSayWhatTheyAre(t *testing.T) { count int want string }{ - {"secret", 1, "se_verify does not read: it is a string, not a list"}, - {[]any{true}, 2, "se_verify does not read: it answers 1 of 2 values"}, - {[]any{true, "secret"}, 2, "se_verify does not read: answer 1 is a string, not a boolean"}, + {"secret", 1, "from se_verify: it is a string, not a list"}, + {[]any{true}, 2, "from se_verify: the number of values is 1, not the 2 that were sent"}, + {[]any{true, "secret"}, 2, "from se_verify: answer 1 is a string, not a boolean"}, } { _, err := parseVerified(tc.answer, tc.count) if !errors.Is(err, ErrInternal) || !strings.Contains(err.Error(), tc.want) || strings.Contains(err.Error(), "secret") { @@ -256,7 +256,7 @@ func TestVerifyAndLimitAnswersSayWhatTheyAre(t *testing.T) { t.Errorf("a good answer: %v, %v", got, err) } _, err := parseLimit("secret") - if !errors.Is(err, ErrInternal) || !strings.Contains(err.Error(), "se_target_limit does not read: it is a string, not a row count or null") { + if !errors.Is(err, ErrInternal) || !strings.Contains(err.Error(), "from se_target_limit: it is a string, not a row count or null") { t.Errorf("limit: %v", err) } if limit, err := parseLimit(nil); err != nil || limit != (Limit{}) { @@ -308,8 +308,8 @@ func TestAnOpenedChildOfTheWrongShapeNamesNoKind(t *testing.T) { item any want string }{ - {"secret", "a child is not a map of a key or an index and json"}, - {vcvalue.Object{{Key: "key", Value: "k"}, {Key: "json", Value: int64(7)}}, `a value of another kind at "json"`}, + {"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`}, } { _, err := jsonChildValue(tc.item) if err == nil || err.Error() != tc.want { diff --git a/languages/golang/internal/guest/answer.go b/languages/golang/internal/guest/answer.go index 6c6384183c..c4bc3c1db7 100644 --- a/languages/golang/internal/guest/answer.go +++ b/languages/golang/internal/guest/answer.go @@ -26,15 +26,15 @@ func KindOf(v any) string { case vcvalue.Object: return "an object" case vcvalue.Sealed: - return "a sealed value" + return "an encrypted value" case vcvalue.SealedEmptySeq: - return "a sealed empty list" + return "an encrypted empty list" case vcvalue.SealedEmptyMap: - return "a sealed empty map" + return "an encrypted empty map" case vcvalue.Plain: return "a passthrough value" case vcvalue.Tagged: - return "a value of a type this build does not know" + return "a value of a type this build does not define" case vcvalue.Int128, vcvalue.Uint128: return "a number" case vcvalue.Date: @@ -68,7 +68,7 @@ func KindOf(v any) string { case reflect.Pointer: return "a pointer" default: - return "a single value" + return "a value of another kind" } } @@ -82,7 +82,7 @@ func KindOf(v any) string { // guest that does not match the version of this module. An example is a // guest built from other source than the module that embeds it. func BadAnswer(export string, problem error) error { - return fmt.Errorf("%w: the guest's answer to %s does not read: %w; this is a bug, or a guest that does not match this module's version", ErrInternal, export, problem) + return fmt.Errorf("%w: cannot read the guest's answer from %s: %w. The cause is a bug, or a guest that does not match the version of this module", ErrInternal, export, problem) } // DecodeAnswer decodes the answer of export from its transport bytes. diff --git a/languages/golang/internal/guest/answer_test.go b/languages/golang/internal/guest/answer_test.go index f19e7909ac..64959455fd 100644 --- a/languages/golang/internal/guest/answer_test.go +++ b/languages/golang/internal/guest/answer_test.go @@ -44,11 +44,11 @@ func TestKindOfNamesAValueByItsKind(t *testing.T) { {vcvalue.Timestamp{}, "a timestamp"}, {vcvalue.Decimal{}, "a decimal"}, {vcvalue.UUID{}, "a UUID"}, - {vcvalue.Sealed("secret"), "a sealed value"}, - {vcvalue.SealedEmptySeq("secret"), "a sealed empty list"}, - {vcvalue.SealedEmptyMap("secret"), "a sealed empty map"}, + {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 know"}, + {vcvalue.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"}, @@ -60,8 +60,8 @@ func TestKindOfNamesAValueByItsKind(t *testing.T) { {map[string]int64{"secret": 1}, "a map"}, {struct{ secret string }{"secret"}, "a struct"}, {new(int), "a pointer"}, - {func() {}, "a single value"}, - {make(chan int), "a single value"}, + {func() {}, "a value of another kind"}, + {make(chan int), "a value of another kind"}, } { if got := guest.KindOf(tc.value); got != tc.want { t.Errorf("KindOf(%T) = %q, want %q", tc.value, got, tc.want) @@ -77,7 +77,7 @@ func TestBadAnswerIsInternalAndNamesTheExport(t *testing.T) { if !errors.Is(err, guest.ErrInternal) { t.Fatalf("%v is not ErrInternal", err) } - want := "cipherstash: internal guest failure: the guest's answer to se_query_term does not read: it is a list, not an object; this is a bug, or a guest that does not match this module's version" + want := "cipherstash: internal guest failure: cannot read the guest's answer from se_query_term: it is a list, not an object. The cause is a bug, or a guest that does not match the version of this module" if err.Error() != want { t.Errorf("message:\n got %q\nwant %q", err.Error(), want) } @@ -105,8 +105,8 @@ func TestDecodeAnswerNamesTheExport(t *testing.T) { } _, err = guest.DecodeAnswer("se_contexts", []byte{0xff}) if !errors.Is(err, guest.ErrInternal) || - !strings.HasPrefix(err.Error(), "cipherstash: internal guest failure: the guest's answer to se_contexts does not read: ") || - !strings.HasSuffix(err.Error(), "; this is a bug, or a guest that does not match this module's version") { + !strings.HasPrefix(err.Error(), "cipherstash: internal guest failure: cannot read the guest's answer from se_contexts: ") || + !strings.HasSuffix(err.Error(), ". The cause is a bug, or a guest that does not match the version of this module") { t.Errorf("bytes that do not decode: %v", err) } }