diff --git a/languages/golang/CHANGELOG.md b/languages/golang/CHANGELOG.md
index 91a657e56..e4b3a369a 100644
--- a/languages/golang/CHANGELOG.md
+++ b/languages/golang/CHANGELOG.md
@@ -35,8 +35,62 @@ and `languages/golang/encrypt/encrypttest/vX.Y.Z` on the same commit.
node in the unencrypted structure of a stored row. An error about a
decrypted value never names the kind that the value decrypted to.
+### Breaking
+
+- **`Match` refuses `vars` that are not a JSON object with the reason
+ `json_vars_not_object`, not `json_input`** (#1987). If your program
+ compares `Reason()` with `json_input` for this case, change it to the
+ 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 `the vars of the match are
+ null, not a JSON object`. The field follows.
+
### Changed
+- **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`. The stored value of a map field can decrypt to
+ something that is not an object. The message is then `decrypt: field
+ "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
+ - 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, 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.
+ - 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`, 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
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 000000000..3e99bd5ba
--- /dev/null
+++ b/languages/golang/auth/answer_test.go
@@ -0,0 +1,146 @@
+package auth
+
+import (
+ "errors"
+ "strings"
+ "testing"
+
+ "github.com/cipherstash/vitaminc/bindings/go/vcffi"
+ "github.com/cipherstash/vitaminc/bindings/go/vcvalue"
+)
+
+// 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
+ 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: 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)
+ }
+ 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.obj) != 1 {
+ t.Fatalf("an object: %v, %v", fields, err)
+ }
+ if _, err := object("sa_token", []byte{0xff}); !errors.Is(err, ErrInternal) ||
+ !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)
+ }
+}
+
+// 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)
+ 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}, "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") {
+ 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)
+ }
+}
+
+// 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)},
+ {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: 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)
+ }
+ }
+ if s, err := answer.optionalText("absent"); err != nil || s != "" {
+ t.Errorf("an absent optional field: %q, %v", s, err)
+ }
+}
+
+// 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)
+ if !errors.Is(err, ErrInternal) || !errors.Is(err, errStepMalformed) ||
+ !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)
+ }
+ }
+}
+
+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 ca11ac8e3..89b59b4f7 100644
--- a/languages/golang/auth/step.go
+++ b/languages/golang/auth/step.go
@@ -68,7 +68,14 @@ func (s *authStep) wipe() {
}
}
-var errMalformedStep = fmt.Errorf("%w: the guest's step is malformed", ErrInternal)
+// 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 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":
// [{"method", "url", "headers", "body"}, ...]}`. Every byte slice it
@@ -76,7 +83,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,19 +174,19 @@ 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, fmt.Errorf("%w: the runnable operations: %w", ErrInternal, err)
+ return nil, 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 c591ad65f..29e71bb28 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"
)
@@ -405,19 +404,25 @@ func (s *ProfileStore) ListWorkspaces(ctx context.Context) ([]string, error) {
if err != nil {
return nil, err
}
- decoded, err := vcffi.Unmarshal(out)
+ return workspaceIDs(out)
+}
+
+// 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 {
- return nil, fmt.Errorf("%w: decoding the workspace list: %w", ErrInternal, err)
+ return nil, 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)
}
@@ -484,7 +489,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 +523,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
}
@@ -532,23 +537,31 @@ func (s *ProfileStore) DeviceIdentity(ctx context.Context) (DeviceIdentity, erro
return d, nil
}
-// fields is a decoded codec object.
-type fields vcvalue.Object
+// 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
+}
-func object(encoded []byte) (fields, error) {
- decoded, err := vcffi.Unmarshal(encoded)
+// 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 {
- return nil, fmt.Errorf("%w: decoding the guest's result: %w", ErrInternal, err)
+ return fields{}, err
}
obj, ok := decoded.(vcvalue.Object)
if !ok {
- return nil, fmt.Errorf("%w: the guest's result is not an object", ErrInternal)
+ 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
}
@@ -556,15 +569,21 @@ func (f fields) get(key string) (any, bool) {
return nil, false
}
+// 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...))
+}
+
// 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
}
@@ -574,11 +593,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
}
@@ -591,7 +610,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
}
@@ -600,11 +619,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 3e9825d6c..4d9e7eaa9 100644
--- a/languages/golang/auth/token.go
+++ b/languages/golang/auth/token.go
@@ -2,7 +2,6 @@ package auth
import (
"context"
- "fmt"
"math"
"time"
@@ -43,7 +42,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
}
@@ -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 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/cmd/stashgen/README.md b/languages/golang/cmd/stashgen/README.md
index 5c4b1800a..8c6a40b07 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` 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:
@@ -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`). `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/checker.go b/languages/golang/encrypt/checker.go
index ca448fbc3..890255f30 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 := guest.DecodeAnswer("se_targets", out)
if err != nil {
- return nil, fmt.Errorf("%w: %v", ErrInternal, err)
+ return nil, err
}
return parseTargets(decoded)
}
@@ -104,13 +104,13 @@ 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 := guest.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 {
- return nil, fmt.Errorf("%w: se_operators: %v", ErrInternal, err)
+ return nil, guest.BadAnswer("se_operators", err)
}
return operators, nil
}
@@ -143,13 +143,13 @@ func contextsOf(ctx context.Context, c *Client, plan *record.Plan) (string, erro
if err != nil {
return "", err
}
- decoded, err := vcffi.Unmarshal(out)
+ decoded, err := guest.DecodeAnswer("se_contexts", out)
if err != nil {
- return "", fmt.Errorf("%w: %v", ErrInternal, err)
+ return "", err
}
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)
}
@@ -212,12 +215,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
@@ -235,7 +238,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":
@@ -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{}
@@ -361,7 +364,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/codec.go b/languages/golang/encrypt/gensupport/codec.go
index 63e828999..e2ecb3046 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
}
@@ -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 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 678c527f0..1c56d591d 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 notOfType(reflect.TypeOf(out).Elem())
}
switch out := out.(type) {
case *string:
@@ -108,13 +108,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
}
@@ -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("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("opened as %T, not %s", v, 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("opened as %T with %d elements, not %s", v, len(items), t)
+ return notOfType(t)
}
result := reflect.New(t).Elem()
for i, item := range items {
@@ -210,7 +210,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
}
@@ -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 notOfType(t)
}
// underlying is the built-in type a defined scalar type is declared over.
@@ -290,8 +290,18 @@ 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 returns the error for a decrypted value that is not of the type
+// that the field needs. want is a value of that type. See [notOfType].
+func mismatch(_, want any) error {
+ 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.
@@ -393,13 +403,16 @@ 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 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:
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 +427,7 @@ 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)
+ // 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("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 c1667dd37..44ece19a8 100644
--- a/languages/golang/encrypt/gensupport/gensupport_internal_test.go
+++ b/languages/golang/encrypt/gensupport/gensupport_internal_test.go
@@ -655,3 +655,112 @@ func TestOpaqueReadsARustWrittenBlob(t *testing.T) {
t.Fatalf("Opaque of the Go-written blob: %v %+v", err, back)
}
}
+
+// 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 }
+ 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
+ want string
+ }{
+ {asAny, []any{"secret"}, "map[string]any"},
+ {asAny, "secret", "map[string]any"},
+ {asValues, int64(7), "gensupport.Values"},
+ {asInts, []any{"secret"}, "map[string]int64"},
+ } {
+ err := tc.read(Values{"tags": tc.value}, "tags")
+ 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: 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)
+ }
+ assertNamesNoKind(t, err)
+ }
+}
+
+// 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"} {
+ if strings.Contains(err.Error(), kind) {
+ t.Errorf("%q in %v", kind, err)
+ }
+ }
+}
+
+// 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")
+ 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)
+ }
+ 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)
+ }
+}
+
+// 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})
+ }
+ 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, "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) {
+ 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 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)
+ }
+ 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/gensupport/json.go b/languages/golang/encrypt/gensupport/json.go
index 5a2726184..9f0ca9ef3 100644
--- a/languages/golang/encrypt/gensupport/json.go
+++ b/languages/golang/encrypt/gensupport/json.go
@@ -118,11 +118,13 @@ 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)
+ // 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: the decrypted value is not JSON text", name, encrypt.ErrEncoding)
}
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
}
@@ -339,9 +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, 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 20d6e110a..b7c682d09 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 {
+ // 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, 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", countMismatch("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("row %d of a selector read has %d decrypted values, not 0 or 1", i, len(values)))
}
}
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 decrypted 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(`it is not an object with "json" and either "key" or "index"`)
}
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("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/json_match_test.go b/languages/golang/encrypt/json_match_test.go
index 8ae6d3bb8..e0aeaca1f 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. 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
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(), "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 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 2d831d8d7..99d9a0d7c 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"
@@ -162,13 +163,13 @@ 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 := guest.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 {
- 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
@@ -239,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) {
@@ -250,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)
@@ -317,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 := guest.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 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 || 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", countMismatch("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
}
@@ -360,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 := guest.DecodeAnswer("se_target_limit", out)
if err != nil {
- return Limit{}, fmt.Errorf("%w: %v", ErrInternal, err)
+ return Limit{}, err
}
+ return parseLimit(decoded)
+}
+
+// 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:
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/records.go b/languages/golang/encrypt/records.go
index 6072b2e99..256137668 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", countMismatch("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
}
+ // 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 || 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", countMismatch("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
@@ -610,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.go b/languages/golang/encrypt/step.go
index cd3cac59b..a37085c1e 100644
--- a/languages/golang/encrypt/step.go
+++ b/languages/golang/encrypt/step.go
@@ -54,7 +54,14 @@ func (s *ioStep) wipe() {
}
}
-var errMalformedStep = errors.New("encrypt: the guest's step is malformed")
+// 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 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.
func (inst *instance) takeIO(ctx context.Context) (*ioStep, error) {
@@ -87,7 +94,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 73b03539b..867d50fb6 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,19 @@ 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. 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)})} {
- 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(), "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 451fcc7ab..e0a35a4d5 100644
--- a/languages/golang/encrypt/targets_test.go
+++ b/languages/golang/encrypt/targets_test.go
@@ -3,9 +3,12 @@ package encrypt
import (
"errors"
"reflect"
+ "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"
)
@@ -83,9 +86,30 @@ 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(), "cannot read the guest's answer from se_targets") {
+ t.Errorf("%s: %v does not name the export", name, err)
+ }
+ }
+ // 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
+ }{
+ {"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 +150,21 @@ func TestParseQueryTermTakesOnlyWhatTheEngineWrites(t *testing.T) {
t.Errorf("catalog %s: %v", name, err)
}
}
+ // 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
+ }{
+ {[]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"),
@@ -176,3 +215,105 @@ func TestParseQueryTermRefusesAMixedShape(t *testing.T) {
}
}
}
+
+// 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})
+ if !errors.Is(err, ErrInternal) || errors.Is(err, ErrEncoding) {
+ t.Fatalf("%s: %v, want ErrInternal alone", export, err)
+ }
+ 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)
+ }
+ }
+ 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)
+ }
+}
+
+// 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
+ count int
+ want string
+ }{
+ {"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") {
+ 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(), "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{}) {
+ 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)
+ }
+}
+
+// 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)}}}
+ }
+ 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 returns v as transport bytes.
+func mustMarshal(t *testing.T, v any) []byte {
+ t.Helper()
+ out, err := vcffi.Marshal(v)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return out
+}
+
+// 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
+ want string
+ }{
+ {"secret", `it is not an object with "json" and either "key" or "index"`},
+ {vcvalue.Object{{Key: "key", Value: "k"}, {Key: "json", Value: int64(7)}}, `the value at "json" is not text, an integer, or bytes`},
+ } {
+ _, 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
new file mode 100644
index 000000000..c4bc3c1db
--- /dev/null
+++ b/languages/golang/internal/guest/answer.go
@@ -0,0 +1,100 @@
+package guest
+
+import (
+ "fmt"
+ "reflect"
+
+ "github.com/cipherstash/vitaminc/bindings/go/vcffi"
+ "github.com/cipherstash/vitaminc/bindings/go/vcvalue"
+)
+
+// 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:
+ return "null"
+ case vcvalue.Object:
+ return "an object"
+ case vcvalue.Sealed:
+ return "an encrypted value"
+ case vcvalue.SealedEmptySeq:
+ return "an encrypted empty list"
+ case vcvalue.SealedEmptyMap:
+ return "an encrypted empty map"
+ case vcvalue.Plain:
+ return "a passthrough value"
+ case vcvalue.Tagged:
+ return "a value of a type this build does not define"
+ case vcvalue.Int128, vcvalue.Uint128:
+ 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"
+ }
+ 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 value of another kind"
+ }
+}
+
+// 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: 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.
+//
+// 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 {
+ 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
new file mode 100644
index 000000000..64959455f
--- /dev/null
+++ b/languages/golang/internal/guest/answer_test.go
@@ -0,0 +1,112 @@
+package guest_test
+
+import (
+ "errors"
+ "strings"
+ "testing"
+
+ "github.com/cipherstash/stack/languages/golang/internal/guest"
+ "github.com/cipherstash/vitaminc/bindings/go/vcffi"
+ "github.com/cipherstash/vitaminc/bindings/go/vcvalue"
+)
+
+// named is a defined Go type whose underlying type is string.
+type named string
+
+// KindOf names the kind of a decoded value, and never the value. KindOf
+// names a vcvalue type by what the type is, and any other Go value by its
+// reflect.Kind.
+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"},
+ {vcvalue.Sealed("secret"), "an encrypted value"},
+ {vcvalue.SealedEmptySeq("secret"), "an encrypted empty list"},
+ {vcvalue.SealedEmptyMap("secret"), "an encrypted empty map"},
+ {vcvalue.Plain{V: "secret"}, "a passthrough value"},
+ {vcvalue.Tagged{ID: 200, V: "secret"}, "a value of a type this build does not define"},
+ {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 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)
+ }
+ }
+}
+
+// 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) {
+ t.Fatalf("%v is not ErrInternal", err)
+ }
+ 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)
+ }
+ if strings.Contains(err.Error(), "malformed input") {
+ t.Errorf("reads as bad input: %v", err)
+ }
+ // 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. 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 {
+ 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: 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)
+ }
+}
diff --git a/packages/stack-encrypt/CHANGELOG.md b/packages/stack-encrypt/CHANGELOG.md
index e63e1efed..ca0482d82 100644
--- a/packages/stack-encrypt/CHANGELOG.md
+++ b/packages/stack-encrypt/CHANGELOG.md
@@ -589,6 +589,21 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
the field follow. For an error that names no field, the message starts
with `the record to encrypt`.
+- **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
+ `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.
+
- **`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 76a96909a..02364cc91 100644
--- a/packages/stack-encrypt/src/dynamic/json_query.rs
+++ b/packages/stack-encrypt/src/dynamic/json_query.rs
@@ -169,8 +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::JsonInput`].
+//! `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 `!`
@@ -460,9 +462,10 @@ 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));
- }
+ // 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))?;
Input::predicate(options, text, &vars.0, Some(bound))
diff --git a/packages/stack-encrypt/src/dynamic/record.rs b/packages/stack-encrypt/src/dynamic/record.rs
index 754a8f6dc..30acdc750 100644
--- a/packages/stack-encrypt/src/dynamic/record.rs
+++ b/packages/stack-encrypt/src/dynamic/record.rs
@@ -9641,6 +9641,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/json/inputs.rs b/packages/stack-encrypt/src/json/inputs.rs
index 88fd34fd8..db8375536 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};
@@ -209,15 +209,51 @@ impl Input {
bound: Option,
) -> Result {
let bound = wildcard_bound(bound)?;
- if !vars.is_object() {
- return Err(Error::bad_source(Reason::JsonInput));
- }
+ vars_object(vars)?;
Ok(Self::Predicate(Box::new(super::predicate::compile(
text, vars, options, bound,
)?)))
}
}
+/// 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(());
+ }
+ Err(Error::Source {
+ field: None,
+ row: None,
+ reason: Reason::JsonVarsNotObject,
+ found: Some(json_kind(vars)),
+ })
+}
+
+/// 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 {
+ 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 dd5deaa10..611c434f7 100644
--- a/packages/stack-encrypt/src/refusal.rs
+++ b/packages/stack-encrypt/src/refusal.rs
@@ -234,8 +234,10 @@ pub enum Error {
/// What was wrong with the source.
reason: Reason,
/// The kind of value that the source or the row is, when it is not
- /// an object of fields. `Some` only when `reason` is
- /// [`Reason::NotAnObject`].
+ /// an object of fields. Also the kind of value that the vars of a
+ /// `match` are, when they are not a JSON object. `Some` only when
+ /// `reason` is [`Reason::NotAnObject`] or
+ /// [`Reason::JsonVarsNotObject`].
found: Option,
},
@@ -473,6 +475,7 @@ fn answers_a_query(reason: Reason) -> bool {
| JsonNoPredicates
| JsonWildcardBoundZero
| JsonUnknownPredicateOp
+ | JsonVarsNotObject
)
}
@@ -489,10 +492,15 @@ enum Subject {
/// record.
///
/// 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. 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.
+/// 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:
+///
+/// - 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`.
///
/// Without a [`Found`], the message is `what`, then the reason, then the
/// row and the field if the error names them. An example is
@@ -509,6 +517,12 @@ fn misfit_text(
let Some(found) = found else {
return format!("{what}: {reason}{}", 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(),
(Subject::Plan, _, Some(_)) => "the field's spec".to_owned(),
@@ -665,9 +679,10 @@ impl Error {
/// The kind of value that the caller passed where the operation takes
/// an object.
///
- /// The value is a plan, a field spec, a record source, a stored record,
- /// or a row of a batch. `Some` only for an error whose reason is
- /// [`Reason::NotAnObject`]. `None` for every other error.
+ /// For [`Reason::NotAnObject`], the value is a plan, a field spec, a
+ /// record source, a stored record, or a row of a batch. For
+ /// [`Reason::JsonVarsNotObject`], the value is the vars of a `match`
+ /// query. `None` for every other error.
pub fn found(&self) -> Option {
match self {
Self::Plan { found, .. } | Self::Source { found, .. } | Self::Record { found, .. } => {
@@ -987,6 +1002,10 @@ reasons! {
/// A value returned an error of its own while the engine read it
/// ([`Error::SourceFailed`]).
SourceFailed => "source_failed", "a value returned an error while it was read";
+ /// 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", "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 1d46302cd..b9c5b2b89 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,110 @@ mod compiled_match {
"vars may be absent"
);
}
+
+ /// 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 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 [
+ (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#"the vars of the match are {phrase}, not a JSON object (field "profile")"#
+ ),
+ "{vars}: the message"
+ );
+ assert!(!message.contains("secret"), "{vars}: no value: {message}");
+ }
+ }
+
+ /// 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() {
+ /// 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,
+ }
+ 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 {