From 85c1605451c46af75f1cf7bc9351c316d3267fe8 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sat, 28 Nov 2026 00:22:57 +1100 Subject: [PATCH 01/14] docs(stack-encrypt): the dynamic path admits a uuid without the uuid feature The comment on the `uuid` feature said the dynamic path refuses a uuid. It does not: the dynamic path admits `ValueKind::Uuid`, and seals and indexes a UUID with the feature off. The feature adds only the typed `value::Uuid`. Say that, so nobody turns the feature on for the dynamic path, or off believing it removes UUIDs from it. --- packages/stack-encrypt/Cargo.toml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/packages/stack-encrypt/Cargo.toml b/packages/stack-encrypt/Cargo.toml index c9a28dfb0..ff205035d 100644 --- a/packages/stack-encrypt/Cargo.toml +++ b/packages/stack-encrypt/Cargo.toml @@ -150,7 +150,9 @@ rust_decimal = ["vitaminc-aead/rust_decimal", "vitaminc-ore/rust_decimal"] # `value::Uuid`: vitaminc's wipeable uuid, built from the uuid crate's # `Uuid`, sealed as one leaf with an equality term. On by default. It turns # on no order term: an order index takes no uuid, so `vitaminc-ore/uuid` -# stays off. `dynamic` does not need it: the dynamic path refuses a uuid. +# stays off. `dynamic` does not need it: the dynamic path admits a uuid +# (`ValueKind::Uuid`), and seals and indexes one without this feature. The +# feature adds only the typed `value::Uuid`. uuid = ["vitaminc-aead/uuid"] # `stack_encrypt::kms::FakeDataKeySource`: the in-memory key source for tests # with no ZeroKMS, so a caller's dev-dependency on stack-encrypt is enough and From 02b6d46d9f6d6e61f35661a1a14485cf8c148c90 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sat, 28 Nov 2026 00:26:54 +1100 Subject: [PATCH 02/14] docs(stack-encrypt): a UUID can take a sealed null The `SealedNullType` refusal and the record plan's docs listed the types of fixed width that take `"null": "sealed"` as a bool, a number, a date, a timestamp or a decimal. A UUID is fixed width too: `ValueKind::Uuid` has a sealed null (a typed null of sixteen bytes), the dynamic plan admits one, and the declaration corpus accepts `sealed-null-uuid`. Name it, so a caller refused for a sealed null of text is not steered away from a UUID. --- packages/stack-encrypt/src/dynamic/record.rs | 6 +++--- packages/stack-encrypt/src/refusal.rs | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/stack-encrypt/src/dynamic/record.rs b/packages/stack-encrypt/src/dynamic/record.rs index cb1686a52..8cfa5d395 100644 --- a/packages/stack-encrypt/src/dynamic/record.rs +++ b/packages/stack-encrypt/src/dynamic/record.rs @@ -237,8 +237,8 @@ pub enum NullMode { /// the one term every null of the field shares, so an `eq` query of a /// null finds the absent rows; no other index has a term for a null. /// Only for a field of a declared type of fixed width (a boolean, a - /// number, a date, a timestamp or a decimal) whose indexes are equality - /// alone; a target field takes it when its EQL type's are. + /// number, a date, a timestamp, a decimal or a UUID) whose indexes are + /// equality alone; a target field takes it when its EQL type's are. Sealed, /// `"sql"`: a null, or a row with no entry for the field, produces /// nothing: the stored record has no entry for the field, so the host @@ -1275,7 +1275,7 @@ pub fn plan(frame: vitaminc_protected::ProtectedRef<'_, [u8]>) -> Result "sealed_null_type", "a sealed null needs a declared type of fixed width: a bool, a number, a date, a timestamp or a decimal"; + SealedNullType => "sealed_null_type", "a sealed null needs a declared type of fixed width: a bool, a number, a date, a timestamp, a decimal or a UUID"; /// A query's input is a null, and the field does not seal its nulls /// beside an equality term: only `eq` on a `"null": "sealed"` field /// finds a null by its term. A `"null": "sql"` field's nulls are SQL From d9649c66aae59fa34c8e4e3f9fc24aeae4b0057a Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sat, 28 Nov 2026 00:47:15 +1100 Subject: [PATCH 03/14] fix(stack-encrypt): say what a record found where it takes an object, and where A plan, a field's spec, a record to encrypt or a stored record that was not an object was refused as `not_an_object` with nothing more: five of the six places named no field, none named the row of a batch or what was there, and a value that failed while it was read, or bytes that were not a frame, were reported the same way. A caller could not tell which input was wrong, or why. Each of those refusals now says what it found, where, and in which operation, and never the value: - `dynamic::Found` names a value's kind (null, a passthrough, a sealed value, or a schema kind such as array, string or uint32). `Error::Plan` gains `found`; `Error::Source` and `Error::Record` gain `row` and `found`. Both reach the payload (`found`, `row`) and the message, as in "row 2 of the records to decrypt is a passthrough value, not an object of stored fields". - Bytes given as a plan that are not one transport frame get their own reason, `not_a_frame`. A frame whose root, or a field's spec, is not an object keeps `not_an_object` and says what it is. The spec's keys are now read through a sink, so a passthrough elsewhere in the plan no longer turns an unknown key into the wrong reason. - A source that fails as it is read is `Error::SourceFailed` (`stack_encrypt::dynamic_source_failed`, reason `source_failed`). It names the field and the row being read and keeps the value's own error as its cause, outside the message, since a host's error can quote the value. The split now keeps the field for such a failure, and forgets it once a record's values are written. - A typed field that opens as another type says what it opened as: `PlanError::FieldType` gains `found`, as in `field "doc" opened as an array, not an object`. The guest maps `SourceFailed` to the encoding status like the other input refusals. Go's `Diagnostic` gains `Row` and `Found`. The TypeScript addon passes the payload through unchanged. stack-profile's payload policy now lists a value's kind and a row's position as allowed detail. Conformance cases changed in place (every reader is in this repository): - record-declarations-v1: root-null, root-list, field-not-object, field-null gain `found`; frame-empty, frame-invalid, frame-truncated, frame-duplicate-key, frame-trailing expect `not_a_frame`. - record-reads-v1: row-not-map gains `row` and `found`; authenticated-int32-as-int64, authenticated-int32-as-string, authenticated-int32-as-uint64, authenticated-null-as-required gain `found`. - record-raw-frames-v1: authenticated-int64, authenticated-string gain `found`. Closes #1985 --- .../stack-encrypt/declaration-grammar.md | 2 +- .../v1/record-declarations-v1.cases.json | 26 +- .../v1/record-raw-frames-v1.cases.json | 6 +- .../v1/record-reads-v1.cases.json | 20 +- languages/golang/CHANGELOG.md | 9 + languages/golang/encrypt/errors.go | 10 +- languages/golang/encrypt/guest/src/ops.rs | 2 + languages/golang/encrypt/guest/src/status.rs | 22 +- languages/golang/internal/guest/diagnostic.go | 29 +- .../golang/internal/guest/diagnostic_test.go | 24 + packages/stack-encrypt/CHANGELOG.md | 33 ++ packages/stack-encrypt/src/codes.rs | 34 ++ .../stack-encrypt/src/dynamic/json_query.rs | 4 + packages/stack-encrypt/src/dynamic/mod.rs | 2 +- packages/stack-encrypt/src/dynamic/planned.rs | 9 +- packages/stack-encrypt/src/dynamic/query.rs | 19 + packages/stack-encrypt/src/dynamic/record.rs | 545 +++++++++++++++--- packages/stack-encrypt/src/dynamic/source.rs | 268 ++++++--- packages/stack-encrypt/src/plan/error.rs | 40 +- packages/stack-encrypt/src/plan/mod.rs | 1 + packages/stack-encrypt/src/plan/values.rs | 1 + packages/stack-encrypt/src/refusal.rs | 429 +++++++++++++- packages/stack-encrypt/tests/planned.rs | 2 +- packages/stack-profile/src/diagnostic.rs | 3 + 24 files changed, 1322 insertions(+), 218 deletions(-) diff --git a/conformance/stack-encrypt/declaration-grammar.md b/conformance/stack-encrypt/declaration-grammar.md index afdbbe447..6ae67da0e 100644 --- a/conformance/stack-encrypt/declaration-grammar.md +++ b/conformance/stack-encrypt/declaration-grammar.md @@ -277,7 +277,7 @@ native engine diagnostic code and structured payload. Accepted cases may include `normalized`. Runners reject unknown corpus keys and contradictory outcomes. A malformed transport frame also has `boundary_error`. The native parser reports -`stack_encrypt::dynamic_plan` with `not_an_object`; the WASI frame check reports +`stack_encrypt::dynamic_plan` with `not_a_frame`; the WASI frame check reports `stack_guest_abi::malformed_input` before reaching that parser. Both runners verify the frame really is malformed. Valid-frame declaration errors must agree exactly on code and payload; Go also requires `ErrEncoding`. Error prose is not contractual. diff --git a/conformance/stack-encrypt/v1/record-declarations-v1.cases.json b/conformance/stack-encrypt/v1/record-declarations-v1.cases.json index 2ec585146..60896ca35 100644 --- a/conformance/stack-encrypt/v1/record-declarations-v1.cases.json +++ b/conformance/stack-encrypt/v1/record-declarations-v1.cases.json @@ -2326,7 +2326,7 @@ "accepted": false, "expected_error": { "code": "stack_encrypt::dynamic_plan", - "fields": { "reason": "not_an_object" } + "fields": { "reason": "not_an_object", "found": "null" } } }, { @@ -2335,7 +2335,7 @@ "accepted": false, "expected_error": { "code": "stack_encrypt::dynamic_plan", - "fields": { "reason": "not_an_object" } + "fields": { "reason": "not_an_object", "found": "array" } } }, { @@ -2353,7 +2353,11 @@ "accepted": false, "expected_error": { "code": "stack_encrypt::dynamic_plan", - "fields": { "reason": "not_an_object", "field": "value" } + "fields": { + "reason": "not_an_object", + "field": "value", + "found": "string" + } } }, { @@ -2362,7 +2366,11 @@ "accepted": false, "expected_error": { "code": "stack_encrypt::dynamic_plan", - "fields": { "reason": "not_an_object", "field": "value" } + "fields": { + "reason": "not_an_object", + "field": "value", + "found": "null" + } } }, { @@ -3364,7 +3372,7 @@ "accepted": false, "expected_error": { "code": "stack_encrypt::dynamic_plan", - "fields": { "reason": "not_an_object" } + "fields": { "reason": "not_a_frame" } }, "boundary_error": { "code": "stack_guest_abi::malformed_input", @@ -3377,7 +3385,7 @@ "accepted": false, "expected_error": { "code": "stack_encrypt::dynamic_plan", - "fields": { "reason": "not_an_object" } + "fields": { "reason": "not_a_frame" } }, "boundary_error": { "code": "stack_guest_abi::malformed_input", @@ -3390,7 +3398,7 @@ "accepted": false, "expected_error": { "code": "stack_encrypt::dynamic_plan", - "fields": { "reason": "not_an_object" } + "fields": { "reason": "not_a_frame" } }, "boundary_error": { "code": "stack_guest_abi::malformed_input", @@ -3405,7 +3413,7 @@ "accepted": false, "expected_error": { "code": "stack_encrypt::dynamic_plan", - "fields": { "reason": "not_an_object" } + "fields": { "reason": "not_a_frame" } }, "boundary_error": { "code": "stack_guest_abi::malformed_input", @@ -3420,7 +3428,7 @@ "accepted": false, "expected_error": { "code": "stack_encrypt::dynamic_plan", - "fields": { "reason": "not_an_object" } + "fields": { "reason": "not_a_frame" } }, "boundary_error": { "code": "stack_guest_abi::malformed_input", diff --git a/conformance/stack-encrypt/v1/record-raw-frames-v1.cases.json b/conformance/stack-encrypt/v1/record-raw-frames-v1.cases.json index e98211d45..084f027c8 100644 --- a/conformance/stack-encrypt/v1/record-raw-frames-v1.cases.json +++ b/conformance/stack-encrypt/v1/record-raw-frames-v1.cases.json @@ -44,7 +44,8 @@ "code": "stack_encrypt::plan_field_type", "fields": { "expected": "int64", - "field": "value" + "field": "value", + "found": "int32" } } }, @@ -61,7 +62,8 @@ "code": "stack_encrypt::plan_field_type", "fields": { "expected": "string", - "field": "value" + "field": "value", + "found": "int32" } } }, diff --git a/conformance/stack-encrypt/v1/record-reads-v1.cases.json b/conformance/stack-encrypt/v1/record-reads-v1.cases.json index 7cdaad2a9..5aeec0460 100644 --- a/conformance/stack-encrypt/v1/record-reads-v1.cases.json +++ b/conformance/stack-encrypt/v1/record-reads-v1.cases.json @@ -210,14 +210,18 @@ "error": { "code": "stack_encrypt::dynamic_record", "fields": { - "reason": "not_an_object" + "reason": "not_an_object", + "row": 0, + "found": "passthrough" } } }, "check_error": { "code": "stack_encrypt::dynamic_record", "fields": { - "reason": "not_an_object" + "reason": "not_an_object", + "row": 0, + "found": "passthrough" } } }, @@ -449,7 +453,8 @@ "code": "stack_encrypt::plan_field_type", "fields": { "field": "value", - "expected": "int64" + "expected": "int64", + "found": "int32" } } } @@ -485,7 +490,8 @@ "code": "stack_encrypt::plan_field_type", "fields": { "field": "value", - "expected": "string" + "expected": "string", + "found": "int32" } } } @@ -521,7 +527,8 @@ "code": "stack_encrypt::plan_field_type", "fields": { "field": "value", - "expected": "uint64" + "expected": "uint64", + "found": "int32" } } } @@ -557,7 +564,8 @@ "code": "stack_encrypt::plan_field_type", "fields": { "field": "value", - "expected": "int32" + "expected": "int32", + "found": "null" } } } diff --git a/languages/golang/CHANGELOG.md b/languages/golang/CHANGELOG.md index 2396d5666..3692bd9a3 100644 --- a/languages/golang/CHANGELOG.md +++ b/languages/golang/CHANGELOG.md @@ -22,6 +22,15 @@ and `languages/golang/encrypt/encrypttest/vX.Y.Z` on the same commit. `[16]byte` (`github.com/google/uuid.UUID`, say), which is converted to one. `stashgen` does not yet map a Go type to it. +- `Diagnostic.Row` and `Diagnostic.Found` (#1985). A plan, a record or a + stored row that is not an object now says what it is instead, by its + kind and never its value: `Found` is `"null"`, `"array"`, `"string"`, + `"passthrough"`, `"sealed"` and so on. `Row` is the row of a batch it + is in, from 0, and the message names it too, as in `row 2 of the + records to decrypt is a passthrough value, not an object of stored + fields`. A field declared as one type that opens as another names what + it opened as in `Found` and in the message. + ### Changed - **A record field converts a number of another width or kind, as a diff --git a/languages/golang/encrypt/errors.go b/languages/golang/encrypt/errors.go index 15b9dc931..26eb85e36 100644 --- a/languages/golang/encrypt/errors.go +++ b/languages/golang/encrypt/errors.go @@ -91,12 +91,14 @@ var ErrStorageVersion = vcffi.ErrUnsupportedVersion // structured fields, by name) and Causes (the errors behind it, outermost // first). Accessors read the fields a caller branches on: ExpectedKeyset // and FoundKeyset on an [ErrForeignKeyset] (each a [KeysetID]'s bytes); -// Field and Reason on a refused plan, record or value; and Construct and At -// on a refused Match predicate, the construct in the grammar's words and -// the byte offset in the predicate where it starts. +// Field and Reason on a refused plan, record or value; Row and Found on a +// plan, record or row that is not an object, the row of a batch from 0 and +// what was there by its kind ("null", "array", "string", ...); and +// Construct and At on a refused Match predicate, the construct in the +// grammar's words and the byte offset in the predicate where it starts. // // What one may carry is fixed: keyset ids and names, field names, counts, -// index kinds, ZeroKMS request kinds and HTTP statuses, and a refused +// row positions, value kinds, index kinds, ZeroKMS request kinds and HTTP statuses, and a refused // predicate's construct and offset. Never plaintext, key material, // tokens, ciphertext or term bytes, or the values of an encryption context. // diff --git a/languages/golang/encrypt/guest/src/ops.rs b/languages/golang/encrypt/guest/src/ops.rs index 76530a7b4..49328e65d 100644 --- a/languages/golang/encrypt/guest/src/ops.rs +++ b/languages/golang/encrypt/guest/src/ops.rs @@ -429,7 +429,9 @@ fn parse_query<'f>( .ok_or_else(|| { fail_dynamic(&dynamic::Error::Source { field: Some(field.to_owned()), + row: None, reason: dynamic::Reason::UnknownOperator, + found: None, }) })?; Ok((plan, field, operator)) diff --git a/languages/golang/encrypt/guest/src/status.rs b/languages/golang/encrypt/guest/src/status.rs index 570dd9e5b..61f307948 100644 --- a/languages/golang/encrypt/guest/src/status.rs +++ b/languages/golang/encrypt/guest/src/status.rs @@ -166,9 +166,9 @@ pub fn status_for_error(error: &stack_encrypt::Error) -> u32 { /// A dynamic-path error as a status code. /// /// The split the library draws is the one the ABI needs: `Context`, `Term`, -/// `Plan`, `UntypedIndex`, `Source`, `Record` and `Predicate` are each a -/// statement about the caller's input, decided before any key is minted or -/// retrieved, so they are +/// `Plan`, `UntypedIndex`, `Source`, `SourceFailed`, `Record` and +/// `Predicate` are each a statement about the caller's input, decided +/// before any key is minted or retrieved, so they are /// [`STATUS_ENCODING`] — named one by one, because that verdict is the /// host's to act on and must be given deliberately. `Cipher` defers to /// [`status_for_error`]; `Internal` is the library's own invariant failing @@ -189,6 +189,7 @@ pub fn status_for_dynamic(error: &stack_encrypt::dynamic::Error) -> u32 { | Error::Plan { .. } | Error::UntypedIndex { .. } | Error::Source { .. } + | Error::SourceFailed { .. } | Error::Record { .. } // A `match` predicate refused at an offset in its text: a construct // the grammar does not read or the index cannot answer, a variable @@ -433,7 +434,9 @@ mod tests { use stack_encrypt::refusal::{Error, Reason}; let refused = Error::Source { field: None, + row: None, reason: Reason::JsonPathNoWildcard, + found: None, }; assert_eq!( status_for_error(&stack_encrypt::Error::Input(Box::new(refused))), @@ -562,6 +565,7 @@ mod tests { Error::Plan { field: age(), reason: Reason::DuplicateOutput, + found: None, }, ), ( @@ -574,14 +578,26 @@ mod tests { "a bad source", Error::Source { field: age(), + row: None, reason: Reason::FieldMissing, + found: None, + }, + ), + ( + "a source that failed while it was read", + Error::SourceFailed { + field: age(), + row: Some(2), + cause: stack_encrypt::dynamic::plaintext::SourceError::msg("getter threw"), }, ), ( "a bad record", Error::Record { field: age(), + row: None, reason: Reason::NoCiphertextNode, + found: None, }, ), ( diff --git a/languages/golang/internal/guest/diagnostic.go b/languages/golang/internal/guest/diagnostic.go index 26ddf3403..89cfaee44 100644 --- a/languages/golang/internal/guest/diagnostic.go +++ b/languages/golang/internal/guest/diagnostic.go @@ -22,10 +22,10 @@ import ( // if errors.As(err, &d) { log.Print(d.Code, d.Help) } // // What it may carry is the rule written on stack-profile's ErrorPayload: -// keyset ids and names, field names, counts, index kinds, ZeroKMS request -// kinds and HTTP statuses, workspace ids, CRNs and regions, profile file -// paths, and for a refused predicate the construct in the grammar's words -// and a byte offset. Never plaintext, key material, tokens, ciphertext or +// keyset ids and names, field names, counts, row positions, value kinds, +// index kinds, ZeroKMS request kinds and HTTP statuses, workspace ids, CRNs +// and regions, profile file paths, and for a refused predicate the +// construct in the grammar's words and a byte offset. Never plaintext, key material, tokens, ciphertext or // term bytes, or a context's values: a stored context's length and parts // at most. // @@ -129,6 +129,27 @@ func (d *Diagnostic) Reason() string { return reason } +// Row is the row of a batch a refusal is about, counted from 0: a record +// to encrypt or a stored record that is not an object of fields, or the row +// a value failed to be read in. ok is false for an error that names no row, +// such as one about a single record, and for a row that is negative, not a +// whole number, or past int. +func (d *Diagnostic) Row() (row int, ok bool) { + return nonNegativeInt(d.Fields["row"]) +} + +// Found is what a refusal found where it expected an object, by its kind +// and never its value: "null", "array", "string", "passthrough", "sealed" +// (a sealed value where a stored record or row should be), another kind's +// schema name ("uint32", "object", ...), "undefined" or "unknown". A field +// declared as one type that opens as another names what it opened as the +// same way. "" for an error that names none. New kinds may appear: keep a +// fallback. +func (d *Diagnostic) Found() string { + found, _ := d.Fields["found"].(string) + return found +} + // Construct is what a refused predicate (a JSONSearch field's Match) names // as refused, in the grammar's own words ("`like_regex`", "a position // (`[2]`)", "a variable"), or "" for an error that names none. It is a diff --git a/languages/golang/internal/guest/diagnostic_test.go b/languages/golang/internal/guest/diagnostic_test.go index 28f60b687..357e77a4f 100644 --- a/languages/golang/internal/guest/diagnostic_test.go +++ b/languages/golang/internal/guest/diagnostic_test.go @@ -319,6 +319,30 @@ func TestConstructAndAtReadARefusedPredicate(t *testing.T) { } } +// A refusal of a value that is not an object reads its row of a batch and +// what it found, as decoded; an error with neither gives none. +func TestRowAndFoundReadARefusedShape(t *testing.T) { + d := &guest.Diagnostic{Fields: map[string]any{"reason": "not_an_object", "row": uint64(2), "found": "null"}} + if row, ok := d.Row(); !ok || row != 2 { + t.Errorf("Row() = %d, %v; want 2", row, ok) + } + if d.Found() != "null" { + t.Errorf("Found() = %q; want null", d.Found()) + } + if row, ok := (&guest.Diagnostic{Fields: map[string]any{"row": uint32(0)}}).Row(); !ok || row != 0 { + t.Errorf("row 0: %d, %v", row, ok) + } + for _, bad := range []any{nil, "2", int64(-1), float64(1.5)} { + if _, ok := (&guest.Diagnostic{Fields: map[string]any{"row": bad}}).Row(); ok { + t.Errorf("Row read %#v", bad) + } + } + none := &guest.Diagnostic{Fields: map[string]any{"found": 7}} + if _, ok := none.Row(); ok || none.Found() != "" { + t.Error("Row or Found answered for an error that gives none") + } +} + // A float offset is read only up to math.MaxInt: where int is 32 bits, a // whole float past 2^31-1 is refused rather than overflowing the int it // converts to. The bound is tested at a 32-bit limit on every platform, and diff --git a/packages/stack-encrypt/CHANGELOG.md b/packages/stack-encrypt/CHANGELOG.md index 399b28ef7..d166339da 100644 --- a/packages/stack-encrypt/CHANGELOG.md +++ b/packages/stack-encrypt/CHANGELOG.md @@ -504,6 +504,39 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Breaking +- **A record refused as "not an object" says what it found, and where** + (#1985). Before, a plan, a field's spec, a record to encrypt or a stored + record that was not an object was refused as `not_an_object` with no + more detail, and most of them named no field and no row. Now: + - The error says what was there instead, by its kind and never its + value: `Error::found()`, the payload's `found` (`"null"`, `"array"`, + `"string"`, `"uint32"`, `"passthrough"`, `"sealed"`, ...), and the + message, as in `row 2 of the records to encrypt is null, not an + object of fields`. The new `dynamic::Found` names the kinds. + - A row of a batch to encrypt or decrypt is named by its position from + 0: `Error::row()`, the payload's `row`, and the message. The message + also says whether the record was to encrypt or to decrypt. + - Bytes given as a plan that are not one transport frame (empty, cut + short, JSON text, a repeated key, bytes after the value) have their + own reason, `not_a_frame`. A frame that is not an object of field + specs keeps `not_an_object`, with what it is. + - A value that fails while it is read, such as a JSON document nested + too deep, is the new `Error::SourceFailed`, with the code + `stack_encrypt::dynamic_source_failed` and the reason `source_failed`. + It names the field and the row being read, and keeps the value's own + error as its cause. The cause is not in the message, because a host's + error can quote the value. Before, it was `not_an_object` with no + field. + - A typed field that opens as another type says what it opened as: + `PlanError::FieldType` has `found`, in its payload too, as in + `field "doc" opened as an array, not an object`. + + `Error::Plan` has a new `found` field, `Error::Source` and + `Error::Record` new `row` and `found` fields, and + `PlanError::FieldType` a new `found` field, so a match on them that names + every field needs `..`. Reason codes do not change, except the two new + ones. + - **`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/codes.rs b/packages/stack-encrypt/src/codes.rs index 10ced550e..12ab6bde6 100644 --- a/packages/stack-encrypt/src/codes.rs +++ b/packages/stack-encrypt/src/codes.rs @@ -184,6 +184,7 @@ mod tests { PlanError::FieldType { .. } => PlanError::FieldType { field: field(), expected: "int64", + found: None, }, PlanError::NoSuchField { .. } => PlanError::NoSuchField { field: field() }, PlanError::IndexOverlap { .. } => PlanError::IndexOverlap { @@ -219,6 +220,11 @@ mod tests { Error::Plan { .. } => Error::bad_plan(Reason::NoFields), Error::UntypedIndex { .. } => Error::UntypedIndex { field: name() }, Error::Source { .. } => Error::bad_source(Reason::FieldMissing), + Error::SourceFailed { .. } => Error::SourceFailed { + field: Some(name()), + row: None, + cause: vitaminc_aead::plaintext::SourceError::msg("getter threw"), + }, Error::Record { .. } => Error::bad_record(Reason::NoCiphertextNode), Error::Predicate { .. } => Error::Predicate { field: Some(name()), @@ -521,9 +527,20 @@ mod tests { Box::new(PlanError::FieldType { field: "age".into(), expected: "int64", + found: None, }), json!({ "field": "age", "expected": "int64" }), ), + ( + Box::new(PlanError::FieldType { + field: "age".into(), + expected: "int64", + found: Some(crate::refusal::Found::Kind( + vitaminc_aead::plaintext::ValueKind::String, + )), + }), + json!({ "field": "age", "expected": "int64", "found": "string" }), + ), ( Box::new(PlanError::TwoContextSources { first: "the plan", @@ -587,6 +604,23 @@ mod tests { Box::new(Error::bad_record(Reason::NoCiphertextNode)), json!({ "reason": "no_ciphertext_node" }), ), + ( + Box::new(Error::Record { + field: None, + row: Some(2), + reason: Reason::NotAnObject, + found: Some(crate::dynamic::Found::Sealed), + }), + json!({ "reason": "not_an_object", "row": 2, "found": "sealed" }), + ), + ( + Box::new(Error::SourceFailed { + field: Some(name()), + row: Some(0), + cause: vitaminc_aead::plaintext::SourceError::msg("getter threw"), + }), + json!({ "field": "email", "reason": "source_failed", "row": 0 }), + ), ( Box::new(Error::UntypedIndex { field: name() }), json!({ "field": "email" }), diff --git a/packages/stack-encrypt/src/dynamic/json_query.rs b/packages/stack-encrypt/src/dynamic/json_query.rs index 98ed17560..76a96909a 100644 --- a/packages/stack-encrypt/src/dynamic/json_query.rs +++ b/packages/stack-encrypt/src/dynamic/json_query.rs @@ -333,6 +333,8 @@ impl JsonText { .map_err(|error| Error::Source { field: None, reason: json_reason(error), + found: None, + row: None, }) } } @@ -408,6 +410,8 @@ fn read_frame Deserialize<'de>>(input: Frame<'_>) -> Result { } } -pub use crate::refusal::{Error, Reason}; +pub use crate::refusal::{Error, Found, Reason}; diff --git a/packages/stack-encrypt/src/dynamic/planned.rs b/packages/stack-encrypt/src/dynamic/planned.rs index 22ce22925..d69d1b518 100644 --- a/packages/stack-encrypt/src/dynamic/planned.rs +++ b/packages/stack-encrypt/src/dynamic/planned.rs @@ -259,6 +259,7 @@ impl Plan { return Err(Error::Plan { field: Some(field.to_owned()), reason: Reason::BindInQuery, + found: None, }); } if !scopes.is_extended() { @@ -301,6 +302,8 @@ impl Plan { return Err(Error::Source { field: Some(field.to_owned()), reason: Reason::OperatorNotAnswered, + found: None, + row: None, }); } Ok(QueryPlan { @@ -958,6 +961,7 @@ impl QueryPlan { wrap(Error::Plan { field: Some(self.field.clone()), reason: Reason::NoSuchField, + found: None, }) }) } @@ -1557,6 +1561,7 @@ fn field_type(field: &str, expected: &'static str) -> crate::Error { PlanError::FieldType { field: field.to_owned(), expected, + found: None, } .into() } @@ -1953,7 +1958,7 @@ mod tests { let _ = typed.insert("age", 34u32); assert!(matches!( reason(check_values(&plan, &typed, &absent).unwrap_err()), - PlanError::FieldType { field, expected } + PlanError::FieldType { field, expected, .. } if field == "age" && expected == type_name::() )); @@ -2020,7 +2025,7 @@ mod tests { let swapped = stored(Slot::new(frame(Tree::UInt32(34)))); assert!(matches!( reason(check_stored(&plan, &swapped, &absent).unwrap_err()), - PlanError::FieldType { field, expected } + PlanError::FieldType { field, expected, .. } if field == "age" && expected == type_name::() )); let mut extra = stored(Slot::new(ciphertext)); diff --git a/packages/stack-encrypt/src/dynamic/query.rs b/packages/stack-encrypt/src/dynamic/query.rs index 56cdd9b1b..ee2916237 100644 --- a/packages/stack-encrypt/src/dynamic/query.rs +++ b/packages/stack-encrypt/src/dynamic/query.rs @@ -428,6 +428,8 @@ fn answer<'p>( let not_answered = || Error::Source { field: Some(field.to_owned()), reason: Reason::OperatorNotAnswered, + found: None, + row: None, }; let kind = found.field_type().ok_or_else(not_answered)?; let (operators, target) = answers(found, resolver)?; @@ -451,6 +453,7 @@ pub(super) fn find<'p>(plan: &'p Plan, field: &str) -> Result<&'p FieldPlan, Err .ok_or_else(|| Error::Plan { field: Some(field.to_owned()), reason: Reason::NoSuchField, + found: None, }) } @@ -586,6 +589,7 @@ fn has_context(plan: &Plan, field: &str) -> Result<(), Error> { return Err(Error::Plan { field: Some(field.to_owned()), reason: Reason::BindInQuery, + found: None, }); } names_its_context(plan, field) @@ -603,6 +607,7 @@ fn names_its_context(plan: &Plan, field: &str) -> Result<(), Error> { Some(_) => Err(Error::Plan { field: Some(field.to_owned()), reason: Reason::QueryContextField, + found: None, }), None => Ok(()), } @@ -622,6 +627,8 @@ fn read_input(answer: &Answer<'_>, operator: Op, input: impl Encrypt) -> Result< let input = OwnedFrame::of(input).map_err(|_| Error::Source { field: Some(name.to_owned()), reason: Reason::FieldType, + found: None, + row: None, })?; // A null is found by its equality term, which a field that seals // its nulls stores beside each one (#1298); nothing else has one. @@ -632,6 +639,8 @@ fn read_input(answer: &Answer<'_>, operator: Op, input: impl Encrypt) -> Result< _ => Err(Error::Source { field: Some(name.to_owned()), reason: Reason::NullQuery, + found: None, + row: None, }), }; } @@ -652,6 +661,8 @@ fn not_a_range(field: &str) -> Error { Error::Source { field: Some(field.to_owned()), reason: Reason::NotARange, + found: None, + row: None, } } @@ -863,6 +874,8 @@ fn json_input(field: &str) -> Error { Error::Source { field: Some(field.to_owned()), reason: Reason::JsonInput, + found: None, + row: None, } } @@ -1191,6 +1204,8 @@ fn probabilistic( _ => Err(Error::Source { field: Some(field.to_owned()), reason: Reason::ExactOperator, + found: None, + row: None, }), } } @@ -1247,6 +1262,8 @@ pub fn verify( .map_err(|_| Error::Source { field: Some(field.to_owned()), reason: Reason::FieldType, + found: None, + row: None, }) }) .collect() @@ -1292,6 +1309,8 @@ pub fn target_limit( let bits = bits.ok_or_else(|| Error::Source { field: Some(field.to_owned()), reason: Reason::NotAQueryTerm, + found: None, + row: None, })?; Ok(match_limit(bits, &options, None, want, stats)) } diff --git a/packages/stack-encrypt/src/dynamic/record.rs b/packages/stack-encrypt/src/dynamic/record.rs index 8cfa5d395..948ebe7b8 100644 --- a/packages/stack-encrypt/src/dynamic/record.rs +++ b/packages/stack-encrypt/src/dynamic/record.rs @@ -160,7 +160,9 @@ use vitaminc_protected::{Controlled, Protected}; use super::kind::convert; use super::planned::{check_stored, check_values, compose, opening_base, Planned}; -use super::{not_admitted, Error, NoTargets, Reason, TargetError, TargetResolver, TermBytes}; +use super::{ + not_admitted, Error, Found, NoTargets, Reason, TargetError, TargetResolver, TermBytes, +}; use crate::plan::FieldValues; use crate::target::{CallerContext, DeclaredContext, Encrypted, IndexSpec}; use crate::{ @@ -313,6 +315,7 @@ impl FieldPlan { let refuse = |reason| Error::Plan { field: Some(name.clone()), reason, + found: None, }; if outputs.is_empty() { return Err(refuse(Reason::NoOutputs)); @@ -376,6 +379,7 @@ impl FieldPlan { return Err(Error::Plan { field: Some(name), reason: Reason::InvalidTarget, + found: None, }); } let (label, extension) = field_context(&name, context.get())?; @@ -428,6 +432,7 @@ impl FieldPlan { return Err(Error::Plan { field: Some(self.name.clone()), reason, + found: None, }); } } @@ -541,6 +546,7 @@ impl FieldPlan { Label::new(prefix).map_err(|_| Error::Plan { field: Some(self.name.clone()), reason: Reason::ContextNotLabel, + found: None, }) } @@ -646,6 +652,7 @@ fn field_context( split_context(piece).ok_or_else(|| Error::Plan { field: Some(name.to_owned()), reason: Reason::ContextNotLabel, + found: None, }) } @@ -755,6 +762,7 @@ impl Plan { return Err(Error::Plan { field: Some(field.name.clone()), reason: Reason::MixedContexts, + found: None, }); } } @@ -802,6 +810,7 @@ impl Plan { options.check().map_err(|_| Error::Plan { field: Some(field.name.clone()), reason: Reason::InvalidTarget, + found: None, })?; Some(TargetOptions::Json(options)) } @@ -809,6 +818,7 @@ impl Plan { return Err(Error::Plan { field: Some(field.name.clone()), reason: Reason::TargetOptions, + found: None, }) } }; @@ -823,6 +833,7 @@ impl Plan { return Err(Error::Plan { field: Some(field.name.clone()), reason: Reason::SealedNullIndex, + found: None, }); } } @@ -857,6 +868,7 @@ impl Plan { let refuse = |reason| Error::Plan { field: Some(context_field.clone()), reason, + found: None, }; let Some(field) = fields.iter().find(|field| field.name == context_field) else { return Err(refuse(Reason::NoSuchField)); @@ -875,6 +887,7 @@ impl Plan { return Err(Error::Plan { field: Some(field.name.clone()), reason: Reason::ContextNotLabel, + found: None, }); } // A target field's label must be a column, `/`, @@ -915,6 +928,7 @@ impl Plan { let refuse = |reason| Error::Plan { field: Some(field.name.clone()), reason, + found: None, }; if fields[..at].iter().any(|prior| prior.name == field.name) { return Err(refuse(Reason::DuplicateField)); @@ -1346,6 +1360,7 @@ pub fn plan_with( let spec = FieldSpec::try_from(spec).map_err(|reason| Error::Plan { field: Some(name.clone()), reason, + found: None, })?; let context = super::context::non_empty(spec.context.0).map_err(|e| e.in_field(&name))?; let field = match spec.what { @@ -1467,24 +1482,6 @@ fn entry_key(frame: &[u8], position: usize) -> Option { /// The keys a field's spec reads ([`FieldSpecWire`]). const SPEC_KEYS: [&str; 5] = ["context", "outputs", "target", "type", "null"]; -/// The keys of the spec `field` holds in the plan `frame`, or `None` when -/// that spec is not an object (or the plan is not one frame of unique keys). -fn spec_keys(frame: &[u8], field: &str) -> Option> { - #[derive(Deserialize)] - #[serde(untagged)] - enum Spec { - Object(std::collections::BTreeMap), - Other(serde::de::IgnoredAny), - } - match recipher_frame::serde::from_slice::>(frame) - .ok()? - .remove(field)? - { - Spec::Object(keys) => Some(keys.into_keys().collect()), - Spec::Other(_) => None, - } -} - /// The plan-level key naming the field a plan takes its context from. const CONTEXT_FIELD: &str = "context_field"; /// The plan-level key listing the caller's bindings: a list of parts, each @@ -1654,8 +1651,15 @@ fn plan_refusal(error: &recipher_frame::serde::Error, frame: &[u8]) -> Error { _ => None, }; let Some(field) = field else { - // The root: not an object, or not one frame. - return Error::bad_plan(Reason::NotAnObject); + // The root: not one frame, or a frame that is not an object. + return match Frame::parse(frame) { + Err(_) => Error::bad_plan(Reason::NotAFrame), + Ok(root) => Error::Plan { + field: None, + reason: Reason::NotAnObject, + found: Some(Found::of_frame(root)), + }, + }; }; let field = &field; if field == CONTEXT_FIELD { @@ -1676,23 +1680,37 @@ fn plan_refusal(error: &recipher_frame::serde::Error, frame: &[u8]) -> Error { // key an error inside a spec's value is placed under (an unknown // key is never on the path). Some(_) => Reason::UnknownType, - // The spec itself: a key it does not know, a missing context, or not - // an object at all. Read from the spec's own keys, not the error's - // wording, so a reworded message cannot change the reason. An object - // of known keys refused at its own level lacks its context: a value - // under a key is refused under that key, a repeated key is not an - // object, and the outputs-or-target rule is checked after parsing. - None => match spec_keys(frame, field) { - Some(keys) if keys.iter().any(|key| !SPEC_KEYS.contains(&key.as_str())) => { - Reason::UnknownKey + // The spec itself: not an object at all, a key it does not know, or + // a missing context. Read from the spec's kind and its own keys, not + // the error's wording, so a reworded message cannot change the + // reason. An object of known keys refused at its own level lacks + // its context: a value under a key is refused under that key, a + // frame never holds a repeated key, and the outputs-or-target rule + // is checked after parsing. + None => match Frame::parse(frame) + .ok() + .and_then(|root| Found::of_entry(root, field)) + { + Some((Found::Kind(ValueKind::Object), keys)) => { + if keys.iter().any(|key| !SPEC_KEYS.contains(&key.as_str())) { + Reason::UnknownKey + } else { + Reason::MissingContext + } + } + found => { + return Error::Plan { + field: Some(field.clone()), + reason: Reason::NotAnObject, + found: found.map(|(found, _)| found), + } } - Some(_) => Reason::MissingContext, - None => Reason::NotAnObject, }, }; Error::Plan { field: Some(field.clone()), reason, + found: None, } } @@ -1835,14 +1853,18 @@ pub fn query<'a, K: 'static>( .ok_or_else(|| Error::Plan { field: Some(field.to_owned()), reason: Reason::NoSuchField, + found: None, })?; let name = field.target().ok_or_else(|| Error::Plan { field: Some(field.name.clone()), reason: Reason::NotATarget, + found: None, })?; let value = OwnedFrame::of(value).map_err(|_| Error::Source { field: Some(field.name.clone()), reason: Reason::FieldType, + found: None, + row: None, })?; // A null is queried by the term a field that seals its nulls stores // beside each (#1298), through the type's equality index alone. @@ -1851,6 +1873,8 @@ pub fn query<'a, K: 'static>( return Err(Error::Source { field: Some(field.name.clone()), reason: Reason::NullQuery, + found: None, + row: None, }); } value @@ -2008,7 +2032,12 @@ pub fn check_source(source: impl Encrypt, plan: &Plan) -> Result<(), Error> { let check = |row: &Row| { check_values(plan, &row.values, &row.absent).map_err(|error| { let (field, reason) = refusal(error); - Error::Source { field, reason } + Error::Source { + field, + reason, + found: None, + row: None, + } }) }; match &rows { @@ -2048,7 +2077,12 @@ pub fn check_record( mismatch @ crate::Error::ContextMismatch { .. } => Error::Cipher(mismatch), error => { let (field, reason) = refusal(error); - Error::Record { field, reason } + Error::Record { + field, + reason, + found: None, + row: None, + } } }) }; @@ -2090,7 +2124,9 @@ impl RecordTree for StackCipherText { fn misfit(field: &str, reason: Reason) -> Error { Error::Record { field: Some(field.to_owned()), + row: None, reason, + found: None, } } @@ -2226,12 +2262,22 @@ fn check_tree(tree: &T, field: &str) -> Result<(), Error> { /// is copied. A value the frame cannot carry, or that holds a repeated key, /// is refused naming its field. pub(super) fn source_rows(source: impl Encrypt, plan: &Plan) -> Result, Error> { - let not_an_object = || Error::bad_source(Reason::NotAnObject); - let row = |row: SourceRecord| source_row(row.ok_or_else(not_an_object)?, plan); + let row = |at: Option, record: SourceRecord| match record { + Ok(fields) => source_row(fields, plan), + Err(found) => Err(Error::Source { + field: None, + row: at, + reason: Reason::NotAnObject, + found: Some(found), + }), + }; match split_source(source).map_err(split_refusal)? { - SplitSource::One(one) => Ok(Rows::One(row(one)?)), + SplitSource::One(one) => Ok(Rows::One(row(None, one)?)), SplitSource::Batch(rows) => Ok(Rows::Batch( - rows.into_iter().map(row).collect::, _>>()?, + rows.into_iter() + .enumerate() + .map(|(at, record)| row(Some(at), record)) + .collect::, _>>()?, )), } } @@ -2239,27 +2285,35 @@ pub(super) fn source_rows(source: impl Encrypt, plan: &Plan) -> Result /// A value refused while the source was split, as the source error that /// names its field: a repeated key as [`Reason::RepeatedKey`], a scalar its /// logical type does not admit as [`Reason::FieldType`], and anything else (too -/// deep or too long for a frame) as [`Reason::Unframeable`]. A refusal that -/// names no field is the source's shape, [`Reason::NotAnObject`]. -fn split_refusal(SplitRefusal { field, error }: SplitRefusal) -> Error { - let Some(field) = field else { - return Error::bad_source(Reason::NotAnObject); - }; +/// deep or too long for a frame) as [`Reason::Unframeable`]. A failure of +/// the source's own is [`Error::SourceFailed`], with the field and the row +/// it was reading and its error as the cause. +fn split_refusal(SplitRefusal { row, field, error }: SplitRefusal) -> Error { let reason = match error { + FrameWriteError::Source(cause) => return Error::SourceFailed { field, row, cause }, FrameWriteError::DuplicateKey => Reason::RepeatedKey, FrameWriteError::Invalid => Reason::FieldType, _ => Reason::Unframeable, }; + // Only a field's frame writer refuses a value, and the split names + // the field it hands one to. + let Some(field) = field else { + return Error::Internal; + }; Error::Source { field: Some(field), + row: None, reason, + found: None, } } fn source_row(mut row: Vec<(String, OwnedFrame)>, plan: &Plan) -> Result { let misfit = |field: &str, reason| Error::Source { field: Some(field.to_owned()), + row: None, reason, + found: None, }; let mut values = FieldValues::new(); let mut targets = Vec::new(); @@ -2331,6 +2385,8 @@ fn check_field(value: OwnedFrame, field: &FieldPlan) -> Result convert(declared, value.frame()) @@ -2536,6 +2592,7 @@ pub(super) fn open_record( return Err(crate::PlanError::FieldType { field: field.name.clone(), expected: kind.name(), + found: Some(Found::of_frame(value.frame())), } .into()); } @@ -2596,18 +2653,38 @@ pub(super) fn write_record( /// `"passthrough"` node carrying a value of the field's kind. Terms, and /// entries the plan does not open, are ignored: comparands, not ciphertext. pub(super) fn record_rows(tree: StackCipherText, plan: &Plan) -> Result, Error> { + let not_an_object = |row, tree: &StackCipherText| Error::Record { + field: None, + row, + reason: Reason::NotAnObject, + found: Some(stored_kind(tree)), + }; match tree { CipherText::Map(row) => Ok(Rows::One(record_row(row, plan)?)), CipherText::Sequence(items) => Ok(Rows::Batch( items .into_iter() - .map(|item| match item { + .enumerate() + .map(|(at, item)| match item { CipherText::Map(row) => record_row(row, plan), - _ => Err(Error::bad_record(Reason::NotAnObject)), + other => Err(not_an_object(Some(at), &other)), }) .collect::, _>>()?, )), - _ => Err(Error::bad_record(Reason::NotAnObject)), + other => Err(not_an_object(None, &other)), + } +} + +/// What a stored node that is not a map of fields is, for the error that +/// refuses it. +fn stored_kind(tree: &StackCipherText) -> Found { + match tree { + CipherText::Sequence(_) => Found::Kind(ValueKind::Array), + CipherText::Passthrough(_) => Found::Passthrough, + CipherText::Map(_) => Found::Kind(ValueKind::Object), + CipherText::Single(_) | CipherText::EmptySequence(_) | CipherText::EmptyMap(_) => { + Found::Sealed + } } } @@ -3066,6 +3143,11 @@ mod tests { let error = plan(obj(vec![("age", spec)])).expect_err("refused"); assert_eq!(error.field(), Some("age"), "{error}"); assert_eq!(error.reason(), Some(Reason::NotAnObject), "{error}"); + assert_eq!( + error.found(), + Some(Found::Kind(ValueKind::Array)), + "{error}" + ); } let positional = obj(vec![( "match", @@ -3236,7 +3318,7 @@ mod tests { assert!( matches!( &parsed, - Err(Error::Plan { field: Some(field), reason: Reason::SharedIdentity }) + Err(Error::Plan { field: Some(field), reason: Reason::SharedIdentity, .. }) if field == "mail2" ), "the later field is named: {parsed:?}" @@ -3262,7 +3344,7 @@ mod tests { assert!( matches!( &parsed, - Err(Error::Plan { field: Some(field), reason: Reason::SharedIdentity }) + Err(Error::Plan { field: Some(field), reason: Reason::SharedIdentity, .. }) if field == "mail_eq" ), "{parsed:?}" @@ -4269,7 +4351,7 @@ mod tests { assert!( matches!( &refused, - Error::Plan { field: Some(field), reason: Reason::OverlappingOutputs } if field == "age" + Error::Plan { field: Some(field), reason: Reason::OverlappingOutputs, .. } if field == "age" ), "{outputs:?}: {refused:?}" ); @@ -4297,7 +4379,8 @@ mod tests { &refused, Error::Plan { field: None, - reason: Reason::EmptyBinding + reason: Reason::EmptyBinding, + .. } ), "{refused:?}" @@ -4320,7 +4403,8 @@ mod tests { &refused, Error::Plan { field: None, - reason: Reason::Bind + reason: Reason::Bind, + .. } ), "{refused:?}" @@ -4349,7 +4433,8 @@ mod tests { &refused, Error::Plan { field: None, - reason: Reason::EmptyBinding + reason: Reason::EmptyBinding, + .. } ), "{refused:?}" @@ -4371,7 +4456,8 @@ mod tests { &refused, Error::Plan { field: None, - reason: Reason::Bind + reason: Reason::Bind, + .. } ), "{refused:?}" @@ -5664,7 +5750,7 @@ mod tests { assert!( matches!( &refused, - Some(Error::Plan { field: Some(f), reason: r }) if f == "f" && *r == reason + Some(Error::Plan { field: Some(f), reason: r, .. }) if f == "f" && *r == reason ), "{what}: {refused:?}" ); @@ -5835,7 +5921,7 @@ mod tests { for (field, op) in [("rank", Op::Eq), ("rank", Op::Lt)] { let refused = query(field, op).err(); assert!( - matches!(&refused, Some(Error::Source { field: Some(f), reason: Reason::NullQuery }) if f == field), + matches!(&refused, Some(Error::Source { field: Some(f), reason: Reason::NullQuery, .. }) if f == field), "{field} {op}: {refused:?}" ); } @@ -6054,7 +6140,7 @@ mod tests { ] { let result = encrypt(&keyset, obj(vec![("age", value)]), &u64_plan).err(); assert!( - matches!(&result, Some(Error::Source { field: Some(field), reason: Reason::FieldType }) if field == "age"), + matches!(&result, Some(Error::Source { field: Some(field), reason: Reason::FieldType, .. }) if field == "age"), "{label_}: {result:?}" ); } @@ -6116,12 +6202,20 @@ mod tests { let result = decrypt(&cipher, sealed, &as_int64, None) .expect("the shape fits") .await; + let refused = plan_error(result.expect_err("refused")); assert_eq!( - plan_error(result.expect_err("refused")), + refused, PlanError::FieldType { field: "age".into(), expected: "int64", - } + found: Some(Found::Kind(ValueKind::UInt64)), + }, + "the field, the declared type and what it opened as" + ); + assert_eq!( + refused.to_string(), + r#"field "age" opened as a uint64, not an int64"#, + "the message says what the field opened as" ); let sealed = seal(&keyset, obj(vec![("age", Tree::UInt64(34))]), &untyped).await; @@ -6153,10 +6247,55 @@ mod tests { PlanError::FieldType { field: "age".into(), expected: "uint64", - } + found: Some(Found::Kind(ValueKind::Float64)), + }, + "the row that opened as a float64" ); } + /// A field declared as an object that opens as a list, a single + /// value or a null says what it opened as, by its kind and never its + /// value. + #[tokio::test] + async fn decrypt_says_what_an_object_field_opened_as() { + let cipher = cipher().await; + let keyset = cipher.default_keyset(); + let untyped = plan(obj(vec![("doc", spec(label("doc"), &["c"]))])).expect("plan"); + let as_object = + plan(obj(vec![("doc", typed(label("doc"), &["c"], "object"))])).expect("plan"); + for (stored, found, text) in [ + ( + Tree::Array(vec![s("secret")]), + Found::Kind(ValueKind::Array), + "an array", + ), + (s("secret"), Found::Kind(ValueKind::String), "a string"), + (Tree::Null, Found::Null, "null"), + ] { + let sealed = seal(&keyset, obj(vec![("doc", stored)]), &untyped).await; + let result = decrypt(&cipher, sealed, &as_object, None) + .expect("the shape fits") + .await; + let refused = plan_error(result.expect_err("refused")); + assert_eq!( + refused, + PlanError::FieldType { + field: "doc".into(), + expected: "object", + found: Some(found), + }, + "{text}" + ); + let message = refused.to_string(); + assert_eq!( + message, + format!(r#"field "doc" opened as {text}, not an object"#), + "the message names the field and the kind" + ); + assert!(!message.contains("secret"), "no value: {message}"); + } + } + /// The migration path the CHANGELOG gives for rows stored as /// another kind: a plan that gives the field only `"c"` and no /// `"type"` opens a row of any kind, whatever indexes it was sealed @@ -6683,7 +6822,7 @@ mod tests { let plan = plan_of(ty, &["c"]); let result = encrypt(&keyset, obj(vec![("v", sent.clone())]), &plan).err(); assert!( - matches!(&result, Some(Error::Source { field: Some(field), reason: Reason::FieldType }) if field == "v"), + matches!(&result, Some(Error::Source { field: Some(field), reason: Reason::FieldType, .. }) if field == "v"), "{ty} from {sent:?}: {result:?}" ); let checked = check_source(obj(vec![("v", sent.clone())]), &plan); @@ -6738,7 +6877,7 @@ mod tests { let plan = plan_of(kind.name(), &["c"]); let result = encrypt(&keyset, obj(vec![("v", Tree::Undefined)]), &plan).err(); assert!( - matches!(&result, Some(Error::Source { field: Some(field), reason: Reason::Undefined }) if field == "v"), + matches!(&result, Some(Error::Source { field: Some(field), reason: Reason::Undefined, .. }) if field == "v"), "{kind}: {result:?}" ); let checked = check_source(obj(vec![("v", Tree::Undefined)]), &plan); @@ -7656,7 +7795,7 @@ mod tests { let null_query = |plan: &Plan, index: IndexSpec| { query(&keyset, plan, "f", &index, &Tree::Null, &FakeEql).err() }; - let refused = |error: &Option| matches!(error, Some(Error::Source { field: Some(f), reason: Reason::NullQuery }) if f == "f"); + let refused = |error: &Option| matches!(error, Some(Error::Source { field: Some(f), reason: Reason::NullQuery, .. }) if f == "f"); let through = null_query(&sealed, IndexSpec::Equality); assert!( !refused(&through), @@ -7706,7 +7845,7 @@ mod tests { ] { for error in [queried(value.clone()), written(value.clone())] { assert!( - matches!(&error, Some(Error::Source { field: Some(f), reason: r }) if f == "f" && *r == reason), + matches!(&error, Some(Error::Source { field: Some(f), reason: r, .. }) if f == "f" && *r == reason), "{value:?}: {error:?}" ); } @@ -7732,7 +7871,7 @@ mod tests { assert!( matches!( &refused("IntegerOrd"), - Some(Error::Plan { field: Some(f), reason: Reason::SealedNullIndex }) if f == "f" + Some(Error::Plan { field: Some(f), reason: Reason::SealedNullIndex, .. }) if f == "f" ), "an order term has no null: {:?}", refused("IntegerOrd") @@ -7740,7 +7879,7 @@ mod tests { assert!( matches!( &refused(TEXT_EQ), - Some(Error::Plan { field: Some(f), reason: Reason::SealedNullType }) if f == "f" + Some(Error::Plan { field: Some(f), reason: Reason::SealedNullType, .. }) if f == "f" ), "text has no fixed width: {:?}", refused(TEXT_EQ) @@ -8779,18 +8918,121 @@ mod tests { } } - /// Bytes that are not one frame are not a plan. + /// A refusal of a value that is not the object the operation takes: + /// the variant, the field, the row of a batch and what was found, in + /// the accessors, the payload and the message. + fn expect_shape( + error: &Error, + variant: &str, + field: Option<&str>, + row: Option, + found: Found, + ) { + expect(error, variant, field, Reason::NotAnObject); + assert_eq!(error.row(), row, "the row: {error}"); + assert_eq!(error.found(), Some(found), "what was found: {error}"); + let fields = error.payload(); + assert_eq!( + fields.get("row").and_then(serde_json::Value::as_u64), + row.map(|row| row as u64), + "the payload's row: {error}" + ); + assert_eq!( + fields["found"], + found.as_str(), + "the payload's found: {error}" + ); + let message = error.to_string(); + assert!( + message.contains(&format!(" is {found}, not an object")), + "the message says what was found: {message}" + ); + if let Some(row) = row { + assert!( + message.contains(&format!("row {row} of the records")), + "the message names the row: {message}" + ); + } + } + + /// Bytes that are not one frame are not a plan: empty, cut short, + /// JSON text, or a frame whose spec repeats a key, which no frame + /// holds. #[test] fn bytes_that_are_not_a_frame_are_not_a_plan() { - for bytes in [&[][..], &[0xff, 1, 2]] { + let mut repeated = vec![vitaminc_aead::frame::OBJECT, 1, 0, 0, 0]; + repeated.extend_from_slice(&3u32.to_le_bytes()); + repeated.extend_from_slice(b"age"); + repeated.extend_from_slice(&[vitaminc_aead::frame::OBJECT, 2, 0, 0, 0]); + for _ in 0..2 { + repeated.extend_from_slice(&4u32.to_le_bytes()); + repeated.extend_from_slice(b"type"); + repeated.extend_from_slice( + crate::dynamic::test_frame::frame_of(&s("uint32")).risky_ref(), + ); + } + let json = br#"{"age": {"context": ["users", "age"], "outputs": ["c"]}}"#; + for bytes in [&[][..], &[0xff, 1, 2], &json[..], &repeated] { let error = super::super::plan( Protected::new(bytes.to_vec()).as_protected_ref().as_deref(), ) .expect_err("refused"); - expect(&error, "Plan", None, Reason::NotAnObject); + expect(&error, "Plan", None, Reason::NotAFrame); + assert_eq!(error.found(), None, "no kind for bytes: {error}"); + assert_eq!( + error.to_string(), + "record plan is malformed: the bytes are not one transport frame", + "the message" + ); } } + /// A plan, or a field's spec, that is a frame but not an object + /// says what it is instead. + #[test] + fn a_plan_or_spec_that_is_not_an_object_says_what_it_is() { + for (value, found) in [ + (Tree::Null, Found::Null), + (Tree::Array(vec![]), Found::Kind(ValueKind::Array)), + (s("{}"), Found::Kind(ValueKind::String)), + (Tree::UInt32(1), Found::Kind(ValueKind::UInt32)), + (Tree::Passthrough(Box::new(obj(vec![]))), Found::Passthrough), + ] { + let error = plan(value.clone()).expect_err("not an object"); + expect_shape(&error, "Plan", None, None, found); + assert_eq!( + error.to_string(), + format!( + "record plan is malformed: the plan is {found}, not an object of field specs" + ), + "the message" + ); + + let error = plan(obj(vec![("age", value)])).expect_err("a spec not an object"); + expect_shape(&error, "Plan", Some("age"), None, found); + assert_eq!( + error.to_string(), + format!( + r#"record plan is malformed: the field's spec is {found}, not an object (field "age")"# + ), + "the message" + ); + } + // A spec that is an object of keys the spec does not take is not + // refused as not an object, even where the frame holds a + // passthrough the reader does not read. + let error = plan(obj(vec![( + "age", + obj(vec![ + ("context", label("age")), + ("bogus", Tree::Passthrough(Box::new(s("x")))), + ]), + )])) + .expect_err("an unknown key"); + expect(&error, "Plan", Some("age"), Reason::UnknownKey); + assert_eq!(error.found(), None, "an object: {error}"); + } + /// A plan or context refusal names its field in the message as well /// as the payload. Which reason each shape is refused as is the /// shared declaration corpus (`missing-context`, `context-null`); @@ -8837,18 +9079,39 @@ mod tests { fn a_source_is_split_into_one_frame_per_field() { use Reason::*; let plan = the_plan(); - for (what, element) in [ - ("a sequence", Tree::Array(vec![s("x")])), - ("a passthrough", Tree::Passthrough(Box::new(s("x")))), - ("a null", Tree::Null), + for (what, element, found) in [ + ( + "a sequence", + Tree::Array(vec![s("x")]), + Found::Kind(ValueKind::Array), + ), + ( + "a passthrough", + Tree::Passthrough(Box::new(s("x"))), + Found::Passthrough, + ), + ("a null", Tree::Null, Found::Null), + ("a string", s("x"), Found::Kind(ValueKind::String)), ] { - let batch = Tree::Array(vec![row(34), element]); + let batch = Tree::Array(vec![row(34), row(35), element]); let error = check_source(batch, &plan).expect_err(what); - expect(&error, "Source", None, NotAnObject); + expect_shape(&error, "Source", None, Some(2), found); + assert_eq!( + error.to_string(), + format!( + "record source does not fit the plan: row 2 of the records to encrypt is {found}, not an object of fields" + ), + "the message" + ); } let error = check_source(Tree::Passthrough(Box::new(row(34))), &plan) .expect_err("a passthrough at the top"); - expect(&error, "Source", None, NotAnObject); + expect_shape(&error, "Source", None, None, Found::Passthrough); + assert_eq!( + error.to_string(), + "record source does not fit the plan: the record to encrypt is a passthrough value, not an object of fields", + "the message" + ); // A value that is not of its field's declared type is refused // naming the field: a UUID or a logical type this build does // not know, in a `uint32` field. @@ -8932,12 +9195,13 @@ mod tests { check_source(Tree::Object(distinct), &plan).expect("distinct keys in a passthrough"); } - /// A refusal from the split that names no field is the source's - /// shape; one that names a field is that field's, by its cause. + /// A refusal from the split names its field, by its cause. One that + /// names no field and is not the source's own is this module's bug. #[test] fn a_split_refusal_names_its_field_and_cause() { let refusal = |field: Option<&str>, error| { split_refusal(SplitRefusal { + row: None, field: field.map(str::to_owned), error, }) @@ -8958,11 +9222,64 @@ mod tests { for error in [FrameWriteError::TooDeep, FrameWriteError::Unwritten] { expect(&fault(error), "Source", Some("age"), Reason::Unframeable); } - expect( - &refusal(None, FrameWriteError::Invalid), - "Source", - None, - Reason::NotAnObject, + assert!( + matches!(refusal(None, FrameWriteError::Invalid), Error::Internal), + "a value refused outside any field" + ); + } + + /// A source that fails as it is read is refused as + /// [`Error::SourceFailed`], naming the field and the row it was + /// reading, with its own error as the cause and not in the message. + #[test] + fn a_source_that_fails_names_its_field_and_row_and_keeps_its_cause() { + use vitaminc_aead::plaintext::SourceError; + const SECRET: &str = "the getter saw marker-value"; + /// A batch of two records whose second fails in its `email`. + struct Fails; + impl Encrypt for &Fails { + fn visit(self, sink: S) -> Result { + let mut seq = sink.seq(Some(2))?; + row(34).visit(seq.element()?)?; + let mut map = seq.element()?.map(Some(4))?; + Tree::UInt32(35).visit(map.entry("age")?)?; + let _ = map.entry("email")?; + Err(::source( + SourceError::msg(SECRET), + )) + } + } + let error = check_source(&Fails, &the_plan()).expect_err("the source failed"); + assert!( + matches!(&error, Error::SourceFailed { .. }), + "a failure of the source's own: {error:?}" + ); + assert_eq!(error.field(), Some("email"), "the field being read"); + assert_eq!(error.row(), Some(1), "the row being read"); + assert_eq!(error.reason(), Some(Reason::SourceFailed), "the reason"); + assert_eq!(error.found(), None, "nothing was found"); + let message = error.to_string(); + assert_eq!( + message, r#"record source failed while it was read (row 1, field "email")"#, + "the message" + ); + let cause = std::error::Error::source(&error).expect("a cause"); + assert_eq!( + cause.to_string(), + SECRET, + "the source's own error is the cause" + ); + let fields = error.payload(); + assert_eq!( + serde_json::Value::Object(fields.clone()), + serde_json::json!({ "field": "email", "row": 1, "reason": "source_failed" }), + "the payload" + ); + let shown = format!("{message} {fields:?}"); + assert!(!shown.contains("marker-value"), "no cause text: {shown}"); + assert!( + matches!(error.into_crate(), crate::Error::Input(_)), + "an input error" ); } @@ -8995,7 +9312,6 @@ mod tests { ]), )); let cases: Vec<(&str, Tree, Option<&str>, Reason)> = vec![ - ("not an object", s("x"), None, NotAnObject), ( "a passthrough deeper than a frame carries", Tree::Object(deep_id), @@ -9008,12 +9324,6 @@ mod tests { Some("id"), RepeatedKey, ), - ( - "a batch row that is not an object", - Tree::Array(vec![s("x")]), - None, - NotAnObject, - ), ( "a field given twice", Tree::Object(repeated), @@ -9030,7 +9340,20 @@ mod tests { for (what, source, field, reason) in cases { let error = check_source(source, &plan).expect_err(what); expect(&error, "Source", field, reason); + assert_eq!(error.row(), None, "{what}: no row"); + assert_eq!(error.found(), None, "{what}: nothing found"); } + let error = check_source(s("x"), &plan).expect_err("not an object"); + expect_shape(&error, "Source", None, None, Found::Kind(ValueKind::String)); + let error = check_source(Tree::Array(vec![s("x")]), &plan) + .expect_err("a batch row that is not an object"); + expect_shape( + &error, + "Source", + None, + Some(0), + Found::Kind(ValueKind::String), + ); } /// A stored field given twice is refused as repeated by the engine's @@ -9059,7 +9382,46 @@ mod tests { let mut age = map(node(&mut fields, "age")); let error = check_record(node(&mut age, "c"), &plan, None) .expect_err("a record that is a leaf"); - expect(&error, "Record", None, Reason::NotAnObject); + expect_shape(&error, "Record", None, None, Found::Sealed); + assert_eq!( + error.to_string(), + "stored record does not fit the plan: the record to decrypt is a sealed value, not an object of stored fields", + "the message" + ); + for (what, stored, found) in [ + ("a passthrough", forged(Tree::UInt32(1)), Found::Passthrough), + ( + "a list", + CipherText::Sequence(vec![]), + Found::Kind(ValueKind::Array), + ), + ] { + let batch = CipherText::Sequence(vec![seal(&keyset, row(34), &plan).await, stored]); + let error = check_record(batch, &plan, None).expect_err(what); + expect_shape(&error, "Record", None, Some(1), found); + assert_eq!( + error.to_string(), + format!( + "stored record does not fit the plan: row 1 of the records to decrypt is {found}, not an object of stored fields" + ), + "{what}: the message" + ); + } + let error = + check_record(forged(Tree::Null), &plan, None).expect_err("a passthrough record"); + expect_shape(&error, "Record", None, None, Found::Passthrough); + let leaf = |tree: StackCipherText| match tree { + CipherText::Single(leaf) => leaf, + _ => panic!("a leaf"), + }; + let mut fields = map(seal(&keyset, row(35), &plan).await); + let one = leaf(node(&mut map(node(&mut fields, "age")), "c")); + let mut fields = map(seal(&keyset, row(36), &plan).await); + let two = leaf(node(&mut map(node(&mut fields, "age")), "c")); + for marker in [CipherText::EmptySequence(one), CipherText::EmptyMap(two)] { + let error = check_record(marker, &plan, None).expect_err("a sealed marker"); + expect_shape(&error, "Record", None, None, Found::Sealed); + } } /// A binding switches on `as_str`, so no two reasons share a name. @@ -9143,6 +9505,7 @@ mod tests { P::FieldType { field: field(), expected: "int64", + found: None, } .into(), some("age"), diff --git a/packages/stack-encrypt/src/dynamic/source.rs b/packages/stack-encrypt/src/dynamic/source.rs index e1f00a406..3d684ef5c 100644 --- a/packages/stack-encrypt/src/dynamic/source.rs +++ b/packages/stack-encrypt/src/dynamic/source.rs @@ -16,30 +16,35 @@ //! value lists them. A field name that appears twice is kept twice. //! * A sequence is a batch. Each element of the sequence is one record. //! * Anything else is not a record: a single value, a null, a passthrough -//! value, or a sequence inside a batch. The entry for that value is -//! `None`. Nothing inside the value is copied or checked. +//! value, or a sequence inside a batch. The entry for that value is the +//! kind of value it is ([`Found`]). Nothing inside the value is copied or +//! checked. //! //! This module does not compare the fields with the plan. The caller, //! `record::source_rows`, refuses a value that is not a record, a missing //! field, an extra field, and a value of the wrong type. //! //! [`split_source`] fails when the frame writer refuses a field's value, -//! such as a date out of range or a map that repeats a key. The error names -//! that field, so the caller can report which field was wrong. When the -//! source fails to describe itself, the error names no field. +//! such as a date out of range or a map that repeats a key, or when the +//! source fails to describe itself, such as a host getter that throws. The +//! error names the field whose value was being written, and the row of a +//! batch, so the caller can report where it happened. A source that fails +//! outside any field's value names no field. -use std::cell::RefCell; +use std::cell::{Cell, RefCell}; use vitaminc_aead::frame::{FrameWriteError, FrameWriter, OwnedFrame}; use vitaminc_aead::plaintext::{ - Encrypt, EncryptRef, FixedType, Logical, MapSink, Physical, SeqSink, Sink, + Encrypt, EncryptRef, FixedType, Logical, MapSink, Physical, SeqSink, Sink, ValueKind, }; use vitaminc_protected::Buffer; +use crate::refusal::Found; + /// One record's fields, each name with its value in a frame of its own, in -/// the order the source lists them. `None` when the source gave a value -/// that is not a map, so is not a record. -pub(super) type SourceRecord = Option>; +/// the order the source lists them. The kind of value the source gave +/// instead, when it is not a map, so is not a record. +pub(super) type SourceRecord = Result, Found>; /// A source split by [`split_source`]: one record, or a batch of them. pub(super) enum SplitSource { @@ -49,10 +54,12 @@ pub(super) enum SplitSource { Batch(Vec), } -/// Why [`split_source`] failed: the error from the frame writer, and the -/// field whose value it was writing, if it was writing one. +/// Why [`split_source`] failed: the error from the frame writer, or the +/// source's own, the row of a batch the split was in, and the field whose +/// value it was writing, if it was writing one. #[derive(Debug)] pub(super) struct SplitRefusal { + pub(super) row: Option, pub(super) field: Option, pub(super) error: FrameWriteError, } @@ -61,21 +68,26 @@ pub(super) struct SplitRefusal { /// frame of its own. The [module documentation](self) says what counts as /// a record and when the split fails. pub(super) fn split_source(source: P) -> Result { - // The field whose value is being written. Field names are not secret: - // the plan and the stored record both contain them unencrypted. So the - // name is not wiped. - let open = RefCell::new(None); - source.visit(TopSink(&open)).map_err(|error| SplitRefusal { - field: match error { - FrameWriteError::Source(_) => None, - _ => open.take(), - }, + let place = Place::default(); + source.visit(TopSink(&place)).map_err(|error| SplitRefusal { + row: place.row.get(), + field: place.field.take(), error, }) } -/// The name of the field being written, shared by every sink in a split. -type Open<'f> = &'f RefCell>; +/// Where the split is: the row of a batch it began last, and the field +/// whose value it is writing. Shared by every sink in a split. Field names +/// are not secret: the plan and the stored record both contain them +/// unencrypted. So the name is not wiped. +#[derive(Default)] +struct Place { + row: Cell>, + field: RefCell>, +} + +/// The place shared by every sink in a split. +type Open<'f> = &'f Place; /// Where a finished record goes: returned to the caller, or added to a /// batch. @@ -113,12 +125,16 @@ impl<'f> Sink for TopSink<'f> { type Seq = BatchSink<'f>; type Map = RecordMap<'f, TopRecord>; - fn scalar(self, _: Option, _: Physical<'_>) -> Result { - Ok(SplitSource::One(None)) + fn scalar( + self, + logical: Option, + value: Physical<'_>, + ) -> Result { + Ok(SplitSource::One(Err(Found::scalar(logical, &value)))) } fn typed_null(self, _: FixedType) -> Result { - Ok(SplitSource::One(None)) + Ok(SplitSource::One(Err(Found::Null))) } fn seq(self, _: Option) -> Result, FrameWriteError> { @@ -133,7 +149,7 @@ impl<'f> Sink for TopSink<'f> { } fn passthrough(self, _: &P) -> Result { - Ok(SplitSource::One(None)) + Ok(SplitSource::One(Err(Found::Passthrough))) } } @@ -152,6 +168,7 @@ impl<'f> SeqSink for BatchSink<'f> { Self: 's; fn element(&mut self) -> Result, FrameWriteError> { + self.open.row.set(Some(self.records.len())); Ok(ElementSink { open: self.open, record: BatchRecord(&mut self.records), @@ -176,13 +193,13 @@ impl<'f, 's> Sink for ElementSink<'f, 's> { type Seq = NotARecord<'s>; type Map = RecordMap<'f, BatchRecord<'s>>; - fn scalar(self, _: Option, _: Physical<'_>) -> Result<(), FrameWriteError> { - self.record.put(None); + fn scalar(self, logical: Option, value: Physical<'_>) -> Result<(), FrameWriteError> { + self.record.put(Err(Found::scalar(logical, &value))); Ok(()) } fn typed_null(self, _: FixedType) -> Result<(), FrameWriteError> { - self.record.put(None); + self.record.put(Err(Found::Null)); Ok(()) } @@ -197,14 +214,14 @@ impl<'f, 's> Sink for ElementSink<'f, 's> { } fn passthrough(self, _: &P) -> Result<(), FrameWriteError> { - self.record.put(None); + self.record.put(Err(Found::Passthrough)); Ok(()) } } /// A batch element that is a sequence, so is not a record. The source still /// describes its elements, and [`Discard`] reads past them without copying -/// them. When the sequence ends, the batch gets `None` for it. +/// them. When the sequence ends, the batch notes that it was an array. struct NotARecord<'s> { record: BatchRecord<'s>, } @@ -222,7 +239,7 @@ impl SeqSink for NotARecord<'_> { } fn end(self) -> Result<(), FrameWriteError> { - self.record.put(None); + self.record.put(Err(Found::Kind(ValueKind::Array))); Ok(()) } } @@ -320,7 +337,7 @@ impl MapSink for RecordMap<'_, O> { Self: 's; fn entry(&mut self, key: &str) -> Result, FrameWriteError> { - *self.open.borrow_mut() = Some(key.to_owned()); + *self.open.field.borrow_mut() = Some(key.to_owned()); self.entries.push((key.to_owned(), Buffer::new())); let buffer = match self.entries.last_mut() { Some((_, buffer)) => buffer, @@ -331,17 +348,20 @@ impl MapSink for RecordMap<'_, O> { } fn end(self) -> Result { + // The record's values are written: a failure after this is not one + // of its fields'. + *self.open.field.borrow_mut() = None; let mut record = Vec::with_capacity(self.entries.len()); for (key, buffer) in self.entries { // A source that dropped an entry's sink without writing to it // left no frame. let value = OwnedFrame::from_buffer(buffer).map_err(|_| { - *self.open.borrow_mut() = Some(key.clone()); + *self.open.field.borrow_mut() = Some(key.clone()); FrameWriteError::Unwritten })?; record.push((key, value)); } - Ok(self.out.put(Some(record))) + Ok(self.out.put(Ok(record))) } } @@ -350,7 +370,7 @@ mod tests { use super::*; use crate::dynamic::test_frame::Tree; use vitaminc_aead::frame::{Frame, ARRAY}; - use vitaminc_aead::plaintext::{Int, Width}; + use vitaminc_aead::plaintext::{Int, Raw, SourceError, Width}; fn s(value: &str) -> Tree { Tree::String(value.into()) @@ -365,9 +385,10 @@ mod tests { ) } - /// A record's fields as their frames' bytes, in source order. - fn bytes(record: &SourceRecord) -> Option)>> { - record.as_ref().map(|entries| { + /// A record's fields as their frames' bytes, in source order, or what + /// the value was instead of a record. + fn bytes(record: &SourceRecord) -> Result)>, Found> { + record.as_ref().map_err(|found| *found).map(|entries| { entries .iter() .map(|(key, value)| (key.clone(), value.frame().as_bytes().to_vec())) @@ -396,14 +417,17 @@ mod tests { }; assert_eq!( bytes(&record), - Some(vec![ + Ok(vec![ ("b".to_owned(), owned(&Tree::UInt32(7))), ("a".to_owned(), owned(&obj(vec![("k", s("v"))]))), ("b".to_owned(), owned(&Tree::Passthrough(Box::new(s("p"))))), - ]) + ]), + "each field's frame, in source order" ); } + /// A value that is not a map is not a record: the split notes what + /// kind of value it is, at the top or as an element of a batch. #[test] fn a_sequence_is_a_batch_and_what_is_not_a_map_is_not_a_record() { let ty = FixedType::new(Some(Logical::Date), Width::I32).expect("fixed"); @@ -413,6 +437,9 @@ mod tests { Tree::Array(vec![s("y"), obj(vec![("k", Tree::Null)])]), Tree::Passthrough(Box::new(obj(vec![]))), obj(vec![]), + Tree::Null, + Tree::Undefined, + Tree::UInt32(7), ]); let Ok(SplitSource::Batch(records)) = split_source(&source) else { panic!("a batch"); @@ -421,36 +448,54 @@ mod tests { assert_eq!( records, [ - Some(vec![("a".to_owned(), owned(&Tree::Int32(1)))]), - None, - None, - None, - Some(vec![]), - ] + Ok(vec![("a".to_owned(), owned(&Tree::Int32(1)))]), + Err(Found::Kind(ValueKind::String)), + Err(Found::Kind(ValueKind::Array)), + Err(Found::Passthrough), + Ok(vec![]), + Err(Found::Null), + Err(Found::Undefined), + Err(Found::Kind(ValueKind::UInt32)), + ], + "a record per map, and the kind of every other element" ); - for top in [s("x"), Tree::Null, Tree::Passthrough(Box::new(obj(vec![])))] { - assert!(matches!(split_source(&top), Ok(SplitSource::One(None)))); + for (top, found) in [ + (s("x"), Found::Kind(ValueKind::String)), + (Tree::Null, Found::Null), + (Tree::Passthrough(Box::new(obj(vec![]))), Found::Passthrough), + ] { + assert!( + matches!(split_source(&top), Ok(SplitSource::One(Err(kind))) if kind == found), + "{found:?} at the top is not a record" + ); } // A typed null, at the top or as a batch element, is a null. let mut one = Vec::new(); vitaminc_aead::leaf::write_typed_null(ty, &mut one); let top = Frame::parse(&one).expect("a frame"); - assert!(matches!(split_source(top), Ok(SplitSource::One(None)))); + assert!( + matches!(split_source(top), Ok(SplitSource::One(Err(Found::Null)))), + "a typed null at the top is a null" + ); let mut batch = vec![ARRAY, 2, 0, 0, 0]; batch.extend(&one); batch.extend(&one); let batch = Frame::parse(&batch).expect("a frame"); - assert!(matches!( - split_source(batch), - Ok(SplitSource::Batch(records)) if records.len() == 2 && records.iter().all(Option::is_none) - )); + assert!( + matches!( + split_source(batch), + Ok(SplitSource::Batch(records)) + if records.len() == 2 && records.iter().all(|r| matches!(r, Err(Found::Null))) + ), + "a typed null in a batch is a null" + ); } - /// A refusal names the field whose value the writer refused, in the - /// first record or a later one. A failure of the source itself names none. + /// A refusal names the field whose value the writer refused, and the + /// row of a batch it is in. #[test] - fn a_refusal_names_the_field_being_written() { + fn a_refusal_names_the_field_and_row_being_written() { let refused = |source: &Tree| split_source(source).err().expect("refused"); let bad_date = Tree::Typed(Logical::Date, Box::new(Tree::Int64(i64::MAX))); @@ -458,21 +503,31 @@ mod tests { ("ok", Tree::Int32(1)), ("when", bad_date.clone()), ])); - assert_eq!(one.field.as_deref(), Some("when")); - assert!(matches!(one.error, FrameWriteError::Invalid)); + assert_eq!(one.field.as_deref(), Some("when"), "the field refused"); + assert_eq!(one.row, None, "a single record has no row"); + assert!( + matches!(one.error, FrameWriteError::Invalid), + "{:?}", + one.error + ); let batch = refused(&Tree::Array(vec![ obj(vec![("when", Tree::Int32(1))]), obj(vec![("at", Tree::Array(vec![bad_date.clone()]))]), ])); - assert_eq!(batch.field.as_deref(), Some("at")); + assert_eq!(batch.field.as_deref(), Some("at"), "the field refused"); + assert_eq!(batch.row, Some(1), "the second row"); let repeated = refused(&obj(vec![( "doc", obj(vec![("k", Tree::Null), ("k", Tree::Null)]), )])); - assert_eq!(repeated.field.as_deref(), Some("doc")); - assert!(matches!(repeated.error, FrameWriteError::DuplicateKey)); + assert_eq!(repeated.field.as_deref(), Some("doc"), "the field refused"); + assert!( + matches!(repeated.error, FrameWriteError::DuplicateKey), + "{:?}", + repeated.error + ); // A batch element that is not a record is read past, not written: // a value inside it that no frame could hold is not refused here. @@ -483,21 +538,75 @@ mod tests { ])) else { panic!("a batch"); }; - assert!(matches!(records.as_slice(), [Some(_), None])); + assert!( + matches!( + records.as_slice(), + [Ok(_), Err(Found::Kind(ValueKind::Array))] + ), + "the second element is an array" + ); + } - struct Fails; + /// A source that fails as it describes itself keeps its own error, and + /// the split names the field and the row it was reading. A failure + /// after a record's fields are written names no field. + #[test] + fn a_source_failure_names_the_field_and_row_it_was_reading() { + /// Describes a batch of `rows` records of one field `a`, and fails + /// in the last one: inside `a`'s value, or after the record ends. + struct Fails { + rows: usize, + after_the_record: bool, + } impl Encrypt for &Fails { fn visit(self, sink: S) -> Result { - let mut map = sink.map(None)?; - let _ = map.entry("a")?; - Err(::source( - vitaminc_aead::plaintext::SourceError::msg("getter threw"), - )) + let fail = || { + ::source(SourceError::msg( + "getter threw", + )) + }; + let mut seq = sink.seq(Some(self.rows))?; + for row in 0..self.rows { + let mut map = seq.element()?.map(Some(1))?; + let entry = map.entry("a")?; + if row + 1 < self.rows || self.after_the_record { + Raw(None, Physical::Int(Int::I32(1))).visit(entry)?; + map.end()?; + } else { + return Err(fail()); + } + } + Err(fail()) } } - let failed = split_source(&Fails).err().expect("refused"); - assert_eq!(failed.field, None); - assert!(matches!(failed.error, FrameWriteError::Source(_))); + + let failed = split_source(&Fails { + rows: 3, + after_the_record: false, + }) + .err() + .expect("refused"); + assert!( + matches!(&failed.error, FrameWriteError::Source(cause) if cause.to_string() == "getter threw"), + "the source's own error is kept: {:?}", + failed.error + ); + assert_eq!(failed.field.as_deref(), Some("a"), "the field being read"); + assert_eq!(failed.row, Some(2), "the row being read"); + + let after = split_source(&Fails { + rows: 2, + after_the_record: true, + }) + .err() + .expect("refused"); + assert!( + matches!(after.error, FrameWriteError::Source(_)), + "{:?}", + after.error + ); + assert_eq!(after.field, None, "no field is being read"); + assert_eq!(after.row, Some(1), "the last row begun"); } /// An entry whose sink the source dropped unwritten has no frame: the @@ -513,9 +622,16 @@ mod tests { map.end() } } - use vitaminc_aead::plaintext::Raw; let refused = split_source(&DropsAnEntry).err().expect("refused"); - assert_eq!(refused.field.as_deref(), Some("dropped")); - assert!(matches!(refused.error, FrameWriteError::Unwritten)); + assert_eq!( + refused.field.as_deref(), + Some("dropped"), + "the dropped entry" + ); + assert!( + matches!(refused.error, FrameWriteError::Unwritten), + "{:?}", + refused.error + ); } } diff --git a/packages/stack-encrypt/src/plan/error.rs b/packages/stack-encrypt/src/plan/error.rs index df4bcea1f..225e9cafa 100644 --- a/packages/stack-encrypt/src/plan/error.rs +++ b/packages/stack-encrypt/src/plan/error.rs @@ -1,5 +1,6 @@ //! Why a plan was refused. use crate::op::Op; +use crate::refusal::Found; use crate::LabelError; /// Why a plan was refused: when it was parsed, or when it was run against a @@ -102,8 +103,9 @@ pub enum PlanError { field: String, }, /// A field is not of the type the plan declares for it, so the plan - /// cannot resolve how to seal, index or read it. - #[error("field {field:?} is not {article} {expected}", article = article(expected))] + /// cannot resolve how to seal, index or read it. A field that opens + /// as another type says what it opened as. + #[error("{}", field_type_text(field, expected, *found))] #[diagnostic( code(stack_encrypt::plan_field_type), help("Give the field a value of the type the plan declares. A row stored as another type opens only after it is re-encrypted as the declared one.") @@ -113,6 +115,9 @@ pub enum PlanError { field: String, /// The type the plan declares. expected: &'static str, + /// What the field opened as, when it was opened: a stored row + /// sealed as another type than the plan now declares. + found: Option, }, /// The plan has no field of that name. #[error("the plan has no field {field:?}")] @@ -229,10 +234,20 @@ impl crate::ErrorPayload for PlanError { Self::DuplicateIndex { at, index } => { payload([("field", at.as_str().into()), ("index", (*index).into())]) } - Self::FieldType { field, expected } => payload([ - ("field", field.as_str().into()), - ("expected", (*expected).into()), - ]), + Self::FieldType { + field, + expected, + found, + } => { + let mut fields = payload([ + ("field", field.as_str().into()), + ("expected", (*expected).into()), + ]); + if let Some(found) = found { + let _ = fields.insert("found".to_owned(), found.as_str().into()); + } + fields + } Self::IndexOverlap { at, first, @@ -252,10 +267,20 @@ impl crate::ErrorPayload for PlanError { } } +/// `field "age" is not an int64`, or, for a field that was opened, +/// `field "age" opened as a string, not an int64`. +fn field_type_text(field: &str, expected: &str, found: Option) -> String { + let article = article(expected); + match found { + Some(found) => format!("field {field:?} opened as {found}, not {article} {expected}"), + None => format!("field {field:?} is not {article} {expected}"), + } +} + /// The indefinite article for a type's name, as it is read aloud: "an" before /// a vowel sound (`an int8`, `an i64`, `an object`), and "a" otherwise. A name /// starting with `u` is read as "you" (`a uint8`, `a u32`), so it takes "a". -fn article(name: &str) -> &'static str { +pub(crate) fn article(name: &str) -> &'static str { match name.chars().next().map(|c| c.to_ascii_lowercase()) { Some('a' | 'e' | 'i' | 'o') => "an", _ => "a", @@ -272,6 +297,7 @@ mod tests { PlanError::FieldType { field: "f".to_owned(), expected, + found: None, } .to_string() }; diff --git a/packages/stack-encrypt/src/plan/mod.rs b/packages/stack-encrypt/src/plan/mod.rs index b1b184e89..c8d718a99 100644 --- a/packages/stack-encrypt/src/plan/mod.rs +++ b/packages/stack-encrypt/src/plan/mod.rs @@ -12,6 +12,7 @@ mod label; #[cfg(feature = "dynamic")] mod values; +pub(crate) use error::article; pub use error::PlanError; pub use label::IntoLabel; #[cfg(feature = "dynamic")] diff --git a/packages/stack-encrypt/src/plan/values.rs b/packages/stack-encrypt/src/plan/values.rs index 5ef093483..bd54bf632 100644 --- a/packages/stack-encrypt/src/plan/values.rs +++ b/packages/stack-encrypt/src/plan/values.rs @@ -103,6 +103,7 @@ impl FieldValues { PlanError::FieldType { field: name.to_string(), expected: type_name::(), + found: None, } .into() }) diff --git a/packages/stack-encrypt/src/refusal.rs b/packages/stack-encrypt/src/refusal.rs index f8643702a..373eae630 100644 --- a/packages/stack-encrypt/src/refusal.rs +++ b/packages/stack-encrypt/src/refusal.rs @@ -20,8 +20,14 @@ allow(dead_code, rustdoc::broken_intra_doc_links) )] +use std::cell::{Cell, RefCell}; use std::fmt; +use vitaminc_aead::frame::{Frame, FrameWriteError}; +use vitaminc_aead::plaintext::{ + Encrypt as _, EncryptRef, FixedType, Logical, MapSink, Physical, SeqSink, Sink, ValueKind, +}; + use crate::target::IndexSpec; /// What went wrong in a dynamic operation, or in the input of a typed JSON @@ -56,9 +62,17 @@ use crate::target::IndexSpec; /// [`read`](crate::dynamic::read)); [`in_field`](Self::in_field) names it /// from the caller's side. /// +/// Where a plan, a record to encrypt or a stored record is not the object +/// the operation takes, the error says what it found instead: its kind +/// ([`Found`]), never the value. It is in the message, in +/// [`found`](Self::found) and in the payload (`found`). A row of a batch is +/// named by its position, from 0: in the message, in [`row`](Self::row) and +/// in the payload (`row`). +/// /// Not every variant has a [`Reason`]. [`Context`](Error::Context), /// [`Plan`](Error::Plan), [`Source`](Error::Source), -/// [`Record`](Error::Record) and [`Predicate`](Error::Predicate) do: it is +/// [`SourceFailed`](Error::SourceFailed), [`Record`](Error::Record) and +/// [`Predicate`](Error::Predicate) do: it is /// in the message, in [`reason`](Self::reason) and in the payload /// (`reason`). The others carry their own payload fields instead: /// [`Term`](Error::Term) names the index it was asked for (`index`), @@ -102,20 +116,26 @@ pub enum Error { kind: IndexSpec, }, - /// A record plan is malformed: not an object of field specs, empty, - /// missing or duplicating an output, carrying a key that is not + /// A record plan is malformed: not one transport frame, not an object + /// of field specs, empty, missing or duplicating an output, carrying a key that is not /// `"context"`, `"outputs"`, `"target"` or `"type"`, naming a type that /// is not one, asking for an index its declared type is not defined /// for, giving a field a context that is not a label a plan can /// seal it under, or declaring what no plan allows (two fields /// under one identity, fields under different contexts). - #[error("record plan is malformed: {reason}{}", in_field_text(field))] + #[error( + "record plan is malformed: {}", + misfit_text(Subject::Plan, *reason, *found, None, field) + )] #[diagnostic(code(stack_encrypt::dynamic_plan))] Plan { /// The plan field at fault, if the fault is one field's. field: Option, /// What was wrong with the plan. reason: Reason, + /// What the plan, or the field's spec, is instead of an object: + /// set with [`Reason::NotAnObject`]. + found: Option, }, /// A record plan field has a term output (`"eq"`, `"match"`, `"ore"`, @@ -136,7 +156,7 @@ pub enum Error { }, /// A record source does not fit its plan: not an object (or an array of - /// them), a field the plan does not name, a plan field the source does + /// them, the row then named), a field the plan does not name, a plan field the source does /// not carry or carries twice, or a passthrough or a repeated map key /// under a field the plan seals, or a value of another type than its /// field declares that does not convert to it exactly, or `undefined` @@ -147,19 +167,46 @@ pub enum Error { /// or a term that are not what [`target_limit`](crate::dynamic::target_limit) reads — the same shape of /// refusal as a mistyped field, naming the field. #[error( - "record source does not fit the plan: {reason}{}", - in_field_text(field) + "record source does not fit the plan: {}", + misfit_text(Subject::Source, *reason, *found, *row, field) )] #[diagnostic(code(stack_encrypt::dynamic_source))] Source { /// The source field at fault, if the fault is one field's. field: Option, + /// The row of a batch at fault, from 0, if the fault is one row's + /// shape. + 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`]. + found: Option, + }, + + /// A record source failed while it was read: a value reported a failure + /// of its own as it described itself, such as a host getter that threw, + /// or a JSON document nested too deep. The value's own error is the + /// cause ([`source`](std::error::Error::source)). It is not in the + /// message, because a host's error can quote the value it failed on. + /// Its reason is [`Reason::SourceFailed`]. + #[error("record source failed while it was read{}", place_text(*row, field))] + #[diagnostic( + code(stack_encrypt::dynamic_source_failed), + help("The value's own error is this error's cause. It is left out of the message, because it can quote the value.") + )] + SourceFailed { + /// The field whose value was being read, if one was. + field: Option, + /// The row of a batch being read, from 0, if the source is a batch. + row: Option, + /// The value's own error. + #[source] + cause: vitaminc_aead::plaintext::SourceError, }, /// A stored record does not fit its plan: not a map (or a sequence of - /// them), a ciphertext-bearing field that is absent or given twice, or + /// them, the row then named), a ciphertext-bearing field that is absent or given twice, or /// has no `"c"` node or two of them, a repeated map key under `"c"`, a /// passthrough under `"c"` — which would hand back unauthenticated /// bytes as if they had been opened — or a passthrough field that is @@ -169,15 +216,21 @@ pub enum Error { /// ([`PlanError::FieldType`](crate::PlanError::FieldType)): the type tag /// is inside the AEAD envelope. #[error( - "stored record does not fit the plan: {reason}{}", - in_field_text(field) + "stored record does not fit the plan: {}", + misfit_text(Subject::Record, *reason, *found, *row, field) )] #[diagnostic(code(stack_encrypt::dynamic_record))] Record { /// The stored field at fault, if the fault is one field's. field: Option, + /// The row of a batch at fault, from 0, if the fault is one row's + /// shape. + row: Option, /// What was wrong with the stored record. reason: Reason, + /// What the stored record, or the row, is instead of an object of + /// stored fields: set with [`Reason::NotAnObject`]. + found: Option, }, /// A `match` predicate is refused at a place in its text: text the @@ -239,6 +292,54 @@ fn in_field_text(field: &Option) -> String { .unwrap_or_default() } +/// ` (row 2, field "age")`, ` (row 2)`, ` (field "age")`, or nothing: the +/// tail of an error that can name a row of a batch. +fn place_text(row: Option, field: &Option) -> String { + match (row, field.as_deref()) { + (Some(row), Some(field)) => format!(" (row {row}, field {field:?})"), + (Some(row), None) => format!(" (row {row})"), + (None, _) => in_field_text(field), + } +} + +/// What a plan, source or stored-record error is about. +#[derive(Clone, Copy)] +enum Subject { + Plan, + Source, + Record, +} + +/// The body of a plan, source or stored-record error's message. With +/// [`Found`], a sentence that says what was there, where, and what the +/// operation takes; without, the reason and where it was. +fn misfit_text( + subject: Subject, + reason: Reason, + found: Option, + row: Option, + field: &Option, +) -> String { + let Some(found) = found else { + return format!("{reason}{}", 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(), + (Subject::Source, None, _) => "the record to encrypt".to_owned(), + (Subject::Source, Some(row), _) => format!("row {row} of the records to encrypt"), + (Subject::Record, None, _) => "the record to decrypt".to_owned(), + (Subject::Record, Some(row), _) => format!("row {row} of the records to decrypt"), + }; + let expected = match (subject, field) { + (Subject::Plan, None) => "an object of field specs", + (Subject::Plan, Some(_)) => "an object", + (Subject::Source, _) => "an object of fields", + (Subject::Record, _) => "an object of stored fields", + }; + format!("{what} is {found}, not {expected}{}", in_field_text(field)) +} + impl Error { /// A context error with no field named yet. pub(crate) fn bad_context(reason: Reason) -> Self { @@ -253,6 +354,7 @@ impl Error { Self::Plan { field: None, reason, + found: None, } } @@ -260,15 +362,20 @@ impl Error { pub(crate) fn bad_source(reason: Reason) -> Self { Self::Source { field: None, + row: None, reason, + found: None, } } /// A stored-record error with no field named yet. + #[cfg(test)] pub(crate) fn bad_record(reason: Reason) -> Self { Self::Record { field: None, + row: None, reason, + found: None, } } @@ -284,6 +391,7 @@ impl Error { | Self::Term { field, .. } | Self::Plan { field, .. } | Self::Source { field, .. } + | Self::SourceFailed { field, .. } | Self::Record { field, .. } | Self::Predicate { field, .. } if field.is_none() => @@ -302,6 +410,7 @@ impl Error { | Self::Term { field, .. } | Self::Plan { field, .. } | Self::Source { field, .. } + | Self::SourceFailed { field, .. } | Self::Record { field, .. } | Self::Predicate { field, .. } => field.as_deref(), Self::UntypedIndex { field } => Some(field), @@ -338,6 +447,7 @@ impl Error { | Self::Source { reason, .. } | Self::Record { reason, .. } | Self::Predicate { reason, .. } => Some(*reason), + Self::SourceFailed { .. } => Some(Reason::SourceFailed), #[cfg(feature = "dynamic")] Self::Target(_) => None, Self::Term { .. } | Self::UntypedIndex { .. } | Self::Internal | Self::Cipher(_) => { @@ -345,6 +455,31 @@ impl Error { } } } + + /// The row of a batch an input error is about, from 0: a row of a + /// record source or a stored record that is not an object, or the row + /// a source failed in. `None` for a single record, and for every other + /// error. + pub fn row(&self) -> Option { + match self { + Self::Source { row, .. } + | Self::SourceFailed { row, .. } + | Self::Record { row, .. } => *row, + _ => None, + } + } + + /// 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. + pub fn found(&self) -> Option { + match self { + Self::Plan { found, .. } | Self::Source { found, .. } | Self::Record { found, .. } => { + *found + } + _ => None, + } + } } impl crate::ErrorPayload for Error { @@ -366,6 +501,12 @@ impl crate::ErrorPayload for Error { if let Some(reason) = self.reason() { let _ = fields.insert("reason".to_owned(), reason.as_str().into()); } + if let Some(row) = self.row() { + let _ = fields.insert("row".to_owned(), (row as u64).into()); + } + if let Some(found) = self.found() { + let _ = fields.insert("found".to_owned(), found.as_str().into()); + } fields } } @@ -418,7 +559,9 @@ reasons! { #[non_exhaustive] pub enum Reason { /// A plan, field spec, source or stored record is not an object (a - /// map), or a list of them, where one is expected. + /// map), or a list of them, where one is expected. The error says + /// what it is instead ([`Error::found`]), and which row of a batch + /// ([`Error::row`]). NotAnObject => "not_an_object", "not an object where one is expected"; /// A context value is of a kind a context cannot hold: a boolean, /// float, null, object or passthrough. @@ -640,6 +783,13 @@ reasons! { /// than the engine reads, or names a path with more steps than a /// document has levels. JsonPredicateTooDeep => "json_predicate_too_deep", "the predicate nests too deep"; + /// Bytes given as a plan are not one transport frame: empty, cut + /// short, holding a repeated key at any depth, or with bytes after + /// the value. A plan sent as JSON text is refused so. + NotAFrame => "not_a_frame", "the bytes are not one transport frame"; + /// 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"; } } @@ -655,3 +805,260 @@ impl fmt::Display for Reason { f.write_str(Self::WORDS[*self as usize].1) } } + +/// What an input error found where it expected an object: a value's kind, +/// never the value. A binding reads [`as_str`](Self::as_str), the name in +/// the payload's `found` field; `Display` is the phrase the message uses. +/// +/// `#[non_exhaustive]`: a kind added later is not a break, and a binding +/// that switches on one keeps a fallback. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +#[non_exhaustive] +pub enum Found { + /// A null, plain or typed: `"null"`. + Null, + /// JavaScript's `undefined`: `"undefined"`. + Undefined, + /// A passthrough, a value that travels in the clear: `"passthrough"`. + Passthrough, + /// A sealed value where a stored record or a row of one should be: a + /// ciphertext leaf, or the marker of a sealed empty list or map. + /// `"sealed"`. + Sealed, + /// A value of this kind: its schema name, such as `"string"`, + /// `"uint32"` or `"array"`. + Kind(ValueKind), + /// A scalar of a logical type this build does not know: `"unknown"`. + Unknown, +} + +impl Found { + /// The name a binding reports in its payload's `found` field. + pub fn as_str(self) -> &'static str { + match self { + Self::Null => "null", + Self::Undefined => "undefined", + Self::Passthrough => "passthrough", + Self::Sealed => "sealed", + Self::Kind(kind) => kind.name(), + Self::Unknown => "unknown", + } + } + + /// What a scalar is, from how it describes itself. + pub(crate) fn scalar(logical: Option, value: &Physical<'_>) -> Self { + match (ValueKind::of(logical, value), logical, value) { + (Some(kind), _, _) => Self::Kind(kind), + (None, Some(Logical::Undefined), _) => Self::Undefined, + (None, None, Physical::Null) => Self::Null, + (None, _, _) => Self::Unknown, + } + } + + /// What a frame holds, reading no more of it than its first node. + pub(crate) fn of_frame(frame: Frame<'_>) -> Self { + if let Some(kind) = frame.kind() { + return Self::Kind(kind); + } + if frame.is_null() { + return Self::Null; + } + // A passthrough, `undefined` or a logical type this build does not + // know: one node, which the probe reads without walking inside it. + let found = Cell::new(None); + let _ = frame.visit(Probe::noting(&found, None)); + found.get().unwrap_or(Self::Unknown) + } + + /// What the entry under `key` holds, for a frame that is an object with + /// one, and the entry's own keys, in order, when it is an object too. + /// `None` for a frame that is not an object or has no such key. + pub(crate) fn of_entry(frame: Frame<'_>, key: &str) -> Option<(Self, Vec)> { + let found = Cell::new(None); + let keys = RefCell::new(Vec::new()); + let _ = frame.visit(Lookup { + key, + found: &found, + keys: &keys, + }); + found.get().map(|found| (found, keys.into_inner())) + } +} + +impl fmt::Display for Found { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Null => f.write_str("null"), + Self::Undefined => f.write_str("undefined"), + Self::Passthrough => f.write_str("a passthrough value"), + Self::Sealed => f.write_str("a sealed value"), + Self::Kind(kind) => { + let name = kind.name(); + write!(f, "{} {name}", crate::plan::article(name)) + } + Self::Unknown => f.write_str("a value of a type this build does not know"), + } + } +} + +/// A sink that reads past a value and keeps none of it: where it is given +/// a cell, it notes what kind of value the node is, and where it is given +/// a list, the keys of an object it is. Children are read past with +/// neither, so nothing inside a container is noted, and no value is copied. +struct Probe<'c> { + found: Option<&'c Cell>>, + keys: Option<&'c RefCell>>, +} + +impl<'c> Probe<'c> { + /// A probe that notes the node's kind, and its keys if `keys` is given. + fn noting(found: &'c Cell>, keys: Option<&'c RefCell>>) -> Self { + Self { + found: Some(found), + keys, + } + } + + /// A probe that reads past a node and notes nothing. + fn past() -> Self { + Self { + found: None, + keys: None, + } + } + + fn note(&self, found: Found) { + if let Some(cell) = self.found { + cell.set(Some(found)); + } + } +} + +impl<'c> Sink for Probe<'c> { + type Ok = (); + type Error = FrameWriteError; + type Seq = Probe<'c>; + type Map = Probe<'c>; + + fn scalar(self, logical: Option, value: Physical<'_>) -> Result<(), FrameWriteError> { + self.note(Found::scalar(logical, &value)); + Ok(()) + } + + fn typed_null(self, _: FixedType) -> Result<(), FrameWriteError> { + self.note(Found::Null); + Ok(()) + } + + fn seq(self, _: Option) -> Result, FrameWriteError> { + self.note(Found::Kind(ValueKind::Array)); + Ok(Probe::past()) + } + + fn map(self, _: Option) -> Result, FrameWriteError> { + self.note(Found::Kind(ValueKind::Object)); + // The map's entries are read with the keys list, to note their keys. + Ok(Probe { + found: None, + keys: self.keys, + }) + } + + fn passthrough(self, _: &P) -> Result<(), FrameWriteError> { + self.note(Found::Passthrough); + Ok(()) + } +} + +impl<'c> SeqSink for Probe<'c> { + type Ok = (); + type Error = FrameWriteError; + type Element<'e> + = Probe<'c> + where + Self: 'e; + + fn element(&mut self) -> Result, FrameWriteError> { + Ok(Probe::past()) + } + + fn end(self) -> Result<(), FrameWriteError> { + Ok(()) + } +} + +impl<'c> MapSink for Probe<'c> { + type Ok = (); + type Error = FrameWriteError; + type Entry<'e> + = Probe<'c> + where + Self: 'e; + + fn entry(&mut self, key: &str) -> Result, FrameWriteError> { + if let Some(keys) = self.keys { + keys.borrow_mut().push(key.to_owned()); + } + Ok(Probe::past()) + } + + fn end(self) -> Result<(), FrameWriteError> { + Ok(()) + } +} + +/// A sink that notes what kind of value one entry of an object is, and its +/// keys if it is an object, and reads past everything else. +struct Lookup<'k, 'c> { + key: &'k str, + found: &'c Cell>, + keys: &'c RefCell>, +} + +impl<'k, 'c> Sink for Lookup<'k, 'c> { + type Ok = (); + type Error = FrameWriteError; + type Seq = Probe<'c>; + type Map = Lookup<'k, 'c>; + + fn scalar(self, _: Option, _: Physical<'_>) -> Result<(), FrameWriteError> { + Ok(()) + } + + fn typed_null(self, _: FixedType) -> Result<(), FrameWriteError> { + Ok(()) + } + + fn seq(self, _: Option) -> Result, FrameWriteError> { + Ok(Probe::past()) + } + + fn map(self, _: Option) -> Result { + Ok(self) + } + + fn passthrough(self, _: &P) -> Result<(), FrameWriteError> { + Ok(()) + } +} + +impl<'c> MapSink for Lookup<'_, 'c> { + type Ok = (); + type Error = FrameWriteError; + type Entry<'e> + = Probe<'c> + where + Self: 'e; + + fn entry(&mut self, key: &str) -> Result, FrameWriteError> { + if key == self.key { + Ok(Probe::noting(self.found, Some(self.keys))) + } else { + Ok(Probe::past()) + } + } + + fn end(self) -> Result<(), FrameWriteError> { + Ok(()) + } +} diff --git a/packages/stack-encrypt/tests/planned.rs b/packages/stack-encrypt/tests/planned.rs index 68a252501..bf45fb389 100644 --- a/packages/stack-encrypt/tests/planned.rs +++ b/packages/stack-encrypt/tests/planned.rs @@ -402,7 +402,7 @@ mod a_query_plan { assert!( matches!( &refused, - dynamic::Error::Source { field: Some(field), reason: dynamic::Reason::OperatorNotAnswered } if field == "email" + dynamic::Error::Source { field: Some(field), reason: dynamic::Reason::OperatorNotAnswered, .. } if field == "email" ), "{refused}" ); diff --git a/packages/stack-profile/src/diagnostic.rs b/packages/stack-profile/src/diagnostic.rs index c1b790343..f2bdb0631 100644 --- a/packages/stack-profile/src/diagnostic.rs +++ b/packages/stack-profile/src/diagnostic.rs @@ -58,6 +58,9 @@ //! //! - Keyset IDs and names; counts and lengths; index names and kinds. //! - Schema field names from a plan or Go struct, rather than field values. +//! - A value's kind, such as null, an array or a uint32, rather than the +//! value, and the position of a row in a batch. The kind is what a schema +//! declares, and a frame carries it in the clear. //! - Request kinds and HTTP status codes for ZeroKMS, CipherStash's //! key-management service. //! - Workspace IDs, workspace resource names (CRNs), and regions. From 629991069323228ca598e68ec6d43e74b824659a Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sat, 28 Nov 2026 01:47:22 +1100 Subject: [PATCH 04/14] fix(stack-encrypt): name the field of a plan spec that is a typed null The mutation gate found the probe's typed-null arm unobserved, and the test that observes it found a defect: a plan whose spec was a typed null was refused as "the plan is an object, not an object of field specs", naming no field. The frame reader refuses a typed null wherever it is, and the plan parser read the refused entry's key with that reader, so the key was lost and the refusal fell back to the root. The keys are now read with the probe, which reads past a typed null, so the spec is refused for its field as `not_an_object` with `found` null. Conformance case added to record-declarations-v1: frame-typed-null-spec, a frame whose spec is a typed null, refused by both readers with `not_an_object`, field `value`, found `null`. --- .../v1/record-declarations-v1.cases.json | 15 +++++++ packages/stack-encrypt/CHANGELOG.md | 3 +- packages/stack-encrypt/src/dynamic/record.rs | 42 +++++++------------ packages/stack-encrypt/src/refusal.rs | 23 +++++++--- 4 files changed, 50 insertions(+), 33 deletions(-) diff --git a/conformance/stack-encrypt/v1/record-declarations-v1.cases.json b/conformance/stack-encrypt/v1/record-declarations-v1.cases.json index 60896ca35..4367ba4fb 100644 --- a/conformance/stack-encrypt/v1/record-declarations-v1.cases.json +++ b/conformance/stack-encrypt/v1/record-declarations-v1.cases.json @@ -3435,6 +3435,21 @@ "fields": {} } }, + { + "id": "frame-typed-null-spec", + "input": { + "frame_hex": "f1010000000500000076616c75651506000000" + }, + "accepted": false, + "expected_error": { + "code": "stack_encrypt::dynamic_plan", + "fields": { + "reason": "not_an_object", + "field": "value", + "found": "null" + } + } + }, { "id": "frame-field-order", "input": { diff --git a/packages/stack-encrypt/CHANGELOG.md b/packages/stack-encrypt/CHANGELOG.md index d166339da..2e3388e07 100644 --- a/packages/stack-encrypt/CHANGELOG.md +++ b/packages/stack-encrypt/CHANGELOG.md @@ -519,7 +519,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Bytes given as a plan that are not one transport frame (empty, cut short, JSON text, a repeated key, bytes after the value) have their own reason, `not_a_frame`. A frame that is not an object of field - specs keeps `not_an_object`, with what it is. + specs keeps `not_an_object`, with what it is. A field's spec that is a + typed null now names its field, where it named none. - A value that fails while it is read, such as a JSON document nested too deep, is the new `Error::SourceFailed`, with the code `stack_encrypt::dynamic_source_failed` and the reason `source_failed`. diff --git a/packages/stack-encrypt/src/dynamic/record.rs b/packages/stack-encrypt/src/dynamic/record.rs index 948ebe7b8..30f7ec86c 100644 --- a/packages/stack-encrypt/src/dynamic/record.rs +++ b/packages/stack-encrypt/src/dynamic/record.rs @@ -1451,32 +1451,8 @@ impl<'de> Deserialize<'de> for PlanWire { /// The key of the `position`th entry of the object `frame` holds, or `None` /// when it is not an object of that many entries. fn entry_key(frame: &[u8], position: usize) -> Option { - struct Keys(Vec); - impl<'de> Deserialize<'de> for Keys { - fn deserialize>(d: D) -> Result { - struct V; - impl<'de> Visitor<'de> for V { - type Value = Keys; - fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.write_str("an object") - } - fn visit_map>(self, mut map: A) -> Result { - let mut keys = Vec::new(); - while let Some(key) = map.next_key::<&'de str>()? { - let _: serde::de::IgnoredAny = map.next_value()?; - keys.push(key.to_owned()); - } - Ok(Keys(keys)) - } - } - d.deserialize_map(V) - } - } - recipher_frame::serde::from_slice::(frame) - .ok()? - .0 - .into_iter() - .nth(position) + let root = Frame::parse(frame).ok()?; + crate::refusal::object_keys(root)?.into_iter().nth(position) } /// The keys a field's spec reads ([`FieldSpecWire`]). @@ -9018,6 +8994,20 @@ mod tests { "the message" ); } + // A spec that is a typed null is a null too. + let ty = vitaminc_aead::plaintext::FixedType::new( + Some(vitaminc_aead::plaintext::Logical::Date), + vitaminc_aead::plaintext::Width::I32, + ) + .expect("fixed"); + let mut typed_null = vec![vitaminc_aead::frame::OBJECT, 1, 0, 0, 0]; + typed_null.extend_from_slice(&3u32.to_le_bytes()); + typed_null.extend_from_slice(b"age"); + vitaminc_aead::leaf::write_typed_null(ty, &mut typed_null); + let error = + super::super::plan(Protected::new(typed_null).as_protected_ref().as_deref()) + .expect_err("a typed null spec"); + expect_shape(&error, "Plan", Some("age"), None, Found::Null); // A spec that is an object of keys the spec does not take is not // refused as not an object, even where the frame holds a // passthrough the reader does not read. diff --git a/packages/stack-encrypt/src/refusal.rs b/packages/stack-encrypt/src/refusal.rs index 373eae630..b06c504fc 100644 --- a/packages/stack-encrypt/src/refusal.rs +++ b/packages/stack-encrypt/src/refusal.rs @@ -117,8 +117,9 @@ pub enum Error { }, /// A record plan is malformed: not one transport frame, not an object - /// of field specs, empty, missing or duplicating an output, carrying a key that is not - /// `"context"`, `"outputs"`, `"target"` or `"type"`, naming a type that + /// of field specs, empty, missing or duplicating an output, carrying a + /// key that is not `"context"`, `"outputs"`, `"target"` or `"type"`, + /// naming a type that /// is not one, asking for an index its declared type is not defined /// for, giving a field a context that is not a label a plan can /// seal it under, or declaring what no plan allows (two fields @@ -156,8 +157,8 @@ pub enum Error { }, /// A record source does not fit its plan: not an object (or an array of - /// them, the row then named), a field the plan does not name, a plan field the source does - /// not carry or carries twice, or a passthrough or a repeated map key + /// them, the row then named), a field the plan does not name, a plan + /// field the source does not carry or carries twice, or a passthrough or a repeated map key /// under a field the plan seals, or a value of another type than its /// field declares that does not convert to it exactly, or `undefined` /// for a field that declares a type. Also a query its field does not answer: an operator @@ -206,8 +207,8 @@ pub enum Error { }, /// A stored record does not fit its plan: not a map (or a sequence of - /// them, the row then named), a ciphertext-bearing field that is absent or given twice, or - /// has no `"c"` node or two of them, a repeated map key under `"c"`, a + /// them, the row then named), a ciphertext-bearing field that is absent + /// or given twice, or has no `"c"` node or two of them, a repeated map key under `"c"`, a /// passthrough under `"c"` — which would hand back unauthenticated /// bytes as if they had been opened — or a passthrough field that is /// absent, carries no `"passthrough"` node, or carries a value of @@ -885,6 +886,16 @@ impl Found { } } +/// The keys of an object frame, in order; `None` for a frame that is not an +/// object. Read with the probe, so a value the frame reader refuses to read, +/// such as a typed null, does not hide the keys beside it. +pub(crate) fn object_keys(frame: Frame<'_>) -> Option> { + let found = Cell::new(None); + let keys = RefCell::new(Vec::new()); + let _ = frame.visit(Probe::noting(&found, Some(&keys))); + (found.get() == Some(Found::Kind(ValueKind::Object))).then(|| keys.into_inner()) +} + impl fmt::Display for Found { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { From 990ea28f309e4a714f5b20ba9e19eed77ac718d3 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sat, 28 Nov 2026 02:42:13 +1100 Subject: [PATCH 05/14] chore(mutants): drop the exclusion for a visitor that no longer exists The plan parser no longer reads a refused plan's keys with a serde visitor, so the exclusion for that visitor's `expecting` matches nothing. The comment on the remaining visitors said a plan's root is refused with one fixed reason; it is refused as `not_a_frame`, or as `not_an_object` with the kind the frame reports. --- .cargo/mutants.toml | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/.cargo/mutants.toml b/.cargo/mutants.toml index 992e76a19..e3af2e279 100644 --- a/.cargo/mutants.toml +++ b/.cargo/mutants.toml @@ -155,15 +155,12 @@ exclude_re = [ 'stack-encrypt/src/dynamic/target\.rs:\d+:\d+: replace ::targets -> Vec with vec!\[\]$', # A serde visitor's `expecting` writes only the "expected ..." half of a # serde error's message, and no caller of these three reads that message: - # a context, statistics and a plan's root are each refused with one fixed - # `Reason` (`ContextKind`, `NotStats`, `NotAnObject`), and the plan's + # a context and statistics are each refused with one fixed `Reason` + # (`ContextKind`, `NotStats`), a plan's root with `NotAFrame` or with + # `NotAnObject` and the kind the frame reports, and the plan's # field-level reasons are read from the error's path, so writing nothing # refuses the same input with the same error. 'stack-encrypt/src/dynamic/(context|query|record)\.rs:\d+:\d+: replace for ContextVisitor|serde::Deserialize<\x27de> for Confidence>::deserialize:: for V|Deserialize<\x27de> for PlanWire>::deserialize:: for V)>::expecting -> fmt::Result with Ok\(Default::default\(\)\)$', - # The same for the visitor that reads a refused plan's keys back - # (`entry_key`): its error is discarded (`.ok()`), so its message is never - # read at all. - 'stack-encrypt/src/dynamic/record\.rs:\d+:\d+: replace entry_key:: for Keys>::deserialize:: for V>::expecting -> fmt::Result with Ok\(Default::default\(\)\)$', # The JSON index. `unhex` joins a high nibble shifted into the top four # bits with a low nibble below 16: the bits never overlap, so `^` is `|`. 'stack-encrypt/src/json/mod\.rs:\d+:\d+: replace \| with \^ in unhex$', From 706fc9fbec13473fc95dd94c93bb14d5a89f7fa5 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sat, 28 Nov 2026 02:42:13 +1100 Subject: [PATCH 06/14] fix(stack-encrypt): never name what a decrypted value opened as, and name only the field and row still open Review of the "not an object" errors found a privacy leak and four places where an error could name the wrong field or row, or none. - A decrypt that opened a field as another type than the plan declares reported what it opened as (`found`, and "field "doc" opened as an array"). The type tag is inside the AEAD envelope, so that is the plaintext's own metadata, such as which rows hold a null. The refusal is back to naming the field and the declared type alone, with no `found`. A kind is now named only for what the caller sent (a plan, a source, a query input) or for the stored record's own structure (a row that is a passthrough or a sealed leaf rather than a map, which the stored form shows without decrypting). stack-profile's payload policy, the raw-frame contract and the CHANGELOGs say so, and a test asserts a decrypt-side refusal has no `found` and names no kind. - A source failure named a field from when its entry began until the record ended, so a failure between two fields blamed the first. Each field's value is now written through a writer that marks the field finished when the value completes, so a failure between fields, or after a field's container ends, names no field. - The row was set when a batch element began and never cleared, so a failure after the last element, or between elements, named the last row; and an element the source began and dropped unwritten left no record and shifted the rows after it. Rows begun are counted, the row is cleared when its record is put, and a dropped element is refused as `unframeable` naming its row. - A frame-writer refusal that named no field became `Error::Internal`, which Go reports as an internal failure. It is the caller's input: a `Source` refusal, `unframeable`, with the row. - The row a refusal is in is now passed through for every refusal made while the source is split (a repeated key, a value its logical type does not admit, a value too deep or too long). A field's own misfit (missing, unknown, of another type) still names no row: adding one would change every Go refusal, since Go always sends a batch. The CHANGELOG, the rustdoc and the Go doc now say exactly which refusals name a row. Conformance cases changed back in place: record-reads-v1 authenticated-int32-as-int64, authenticated-int32-as-string, authenticated-int32-as-uint64 and authenticated-null-as-required, and record-raw-frames-v1 authenticated-int64 and authenticated-string, lose `found` and expect their payload from before this branch. row-not-map keeps `row` and `found`: the row is a passthrough in the stored form. --- .../stack-encrypt/raw-frames-contract.md | 4 +- .../v1/record-raw-frames-v1.cases.json | 6 +- .../v1/record-reads-v1.cases.json | 12 +- languages/golang/CHANGELOG.md | 5 +- languages/golang/internal/guest/diagnostic.go | 16 +- packages/stack-encrypt/CHANGELOG.md | 40 +-- packages/stack-encrypt/src/codes.rs | 12 - packages/stack-encrypt/src/dynamic/planned.rs | 1 - packages/stack-encrypt/src/dynamic/record.rs | 112 ++++--- packages/stack-encrypt/src/dynamic/source.rs | 273 ++++++++++++++++-- packages/stack-encrypt/src/plan/error.rs | 38 +-- packages/stack-encrypt/src/plan/values.rs | 1 - packages/stack-encrypt/src/refusal.rs | 20 +- packages/stack-profile/src/diagnostic.rs | 9 +- 14 files changed, 396 insertions(+), 153 deletions(-) diff --git a/conformance/stack-encrypt/raw-frames-contract.md b/conformance/stack-encrypt/raw-frames-contract.md index dc60b2416..9abc6040f 100644 --- a/conformance/stack-encrypt/raw-frames-contract.md +++ b/conformance/stack-encrypt/raw-frames-contract.md @@ -43,7 +43,9 @@ diagnostic. Within `authenticated`, two outcomes are distinguished. A leaf sealed as an `int32` and read as `int64` or `string` authenticates and then fails the declared type: `stack_encrypt::plan_field_type` naming the field and the -expected kind, as the read profile's authenticated cases do. A leaf moved +expected kind, as the read profile's authenticated cases do. It never names +the kind the leaf opened as: that is known only once the leaf is decrypted, +so the payload has no `found`. A leaf moved into another role (the single leaf under an empty-sequence tag) fails authentication itself: `stack_encrypt::aead`, which Go reports as `ErrAuthentication` carrying that code. Both runners compare the code and diff --git a/conformance/stack-encrypt/v1/record-raw-frames-v1.cases.json b/conformance/stack-encrypt/v1/record-raw-frames-v1.cases.json index 084f027c8..e98211d45 100644 --- a/conformance/stack-encrypt/v1/record-raw-frames-v1.cases.json +++ b/conformance/stack-encrypt/v1/record-raw-frames-v1.cases.json @@ -44,8 +44,7 @@ "code": "stack_encrypt::plan_field_type", "fields": { "expected": "int64", - "field": "value", - "found": "int32" + "field": "value" } } }, @@ -62,8 +61,7 @@ "code": "stack_encrypt::plan_field_type", "fields": { "expected": "string", - "field": "value", - "found": "int32" + "field": "value" } } }, diff --git a/conformance/stack-encrypt/v1/record-reads-v1.cases.json b/conformance/stack-encrypt/v1/record-reads-v1.cases.json index 5aeec0460..b0df0808b 100644 --- a/conformance/stack-encrypt/v1/record-reads-v1.cases.json +++ b/conformance/stack-encrypt/v1/record-reads-v1.cases.json @@ -453,8 +453,7 @@ "code": "stack_encrypt::plan_field_type", "fields": { "field": "value", - "expected": "int64", - "found": "int32" + "expected": "int64" } } } @@ -490,8 +489,7 @@ "code": "stack_encrypt::plan_field_type", "fields": { "field": "value", - "expected": "string", - "found": "int32" + "expected": "string" } } } @@ -527,8 +525,7 @@ "code": "stack_encrypt::plan_field_type", "fields": { "field": "value", - "expected": "uint64", - "found": "int32" + "expected": "uint64" } } } @@ -564,8 +561,7 @@ "code": "stack_encrypt::plan_field_type", "fields": { "field": "value", - "expected": "int32", - "found": "null" + "expected": "int32" } } } diff --git a/languages/golang/CHANGELOG.md b/languages/golang/CHANGELOG.md index 3692bd9a3..272cabb72 100644 --- a/languages/golang/CHANGELOG.md +++ b/languages/golang/CHANGELOG.md @@ -28,8 +28,9 @@ and `languages/golang/encrypt/encrypttest/vX.Y.Z` on the same commit. `"passthrough"`, `"sealed"` and so on. `Row` is the row of a batch it is in, from 0, and the message names it too, as in `row 2 of the records to decrypt is a passthrough value, not an object of stored - fields`. A field declared as one type that opens as another names what - it opened as in `Found` and in the message. + fields`. `Found` names only what the program sent or the stored row's + own structure: an error about a decrypted value never says what it + opened as. ### Changed diff --git a/languages/golang/internal/guest/diagnostic.go b/languages/golang/internal/guest/diagnostic.go index 89cfaee44..16ff5475c 100644 --- a/languages/golang/internal/guest/diagnostic.go +++ b/languages/golang/internal/guest/diagnostic.go @@ -131,9 +131,11 @@ func (d *Diagnostic) Reason() string { // Row is the row of a batch a refusal is about, counted from 0: a record // to encrypt or a stored record that is not an object of fields, or the row -// a value failed to be read in. ok is false for an error that names no row, -// such as one about a single record, and for a row that is negative, not a -// whole number, or past int. +// of a value that failed to be read or could not be written as a frame. A +// field's own refusal (missing, unknown, of another type) names the field +// and no row. ok is false for an error that names no row, such as one about +// a single record, and for a row that is negative, not a whole number, or +// past int. func (d *Diagnostic) Row() (row int, ok bool) { return nonNegativeInt(d.Fields["row"]) } @@ -141,10 +143,10 @@ func (d *Diagnostic) Row() (row int, ok bool) { // Found is what a refusal found where it expected an object, by its kind // and never its value: "null", "array", "string", "passthrough", "sealed" // (a sealed value where a stored record or row should be), another kind's -// schema name ("uint32", "object", ...), "undefined" or "unknown". A field -// declared as one type that opens as another names what it opened as the -// same way. "" for an error that names none. New kinds may appear: keep a -// fallback. +// schema name ("uint32", "object", ...), "undefined" or "unknown". It names +// only what the program sent or the stored row's own structure, never what +// a decrypted value opened as. "" for an error that names none. New kinds +// may appear: keep a fallback. func (d *Diagnostic) Found() string { found, _ := d.Fields["found"].(string) return found diff --git a/packages/stack-encrypt/CHANGELOG.md b/packages/stack-encrypt/CHANGELOG.md index 2e3388e07..c147bdbee 100644 --- a/packages/stack-encrypt/CHANGELOG.md +++ b/packages/stack-encrypt/CHANGELOG.md @@ -512,10 +512,19 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 value: `Error::found()`, the payload's `found` (`"null"`, `"array"`, `"string"`, `"uint32"`, `"passthrough"`, `"sealed"`, ...), and the message, as in `row 2 of the records to encrypt is null, not an - object of fields`. The new `dynamic::Found` names the kinds. - - A row of a batch to encrypt or decrypt is named by its position from - 0: `Error::row()`, the payload's `row`, and the message. The message - also says whether the record was to encrypt or to decrypt. + object of fields`. The new `dynamic::Found` names the kinds. A kind is + named only for what the caller sent, or for the stored record's own + structure (a row that is a passthrough or a sealed value rather than a + map). An error about a decrypted value never names what it opened as. + - A row of a batch that is not an object is named by its position from + 0: `Error::row()`, the payload's `row`, and the message, which also + says whether the record was to encrypt or to decrypt. So is the row of + a value that fails while it is read, or that the frame writer refuses + (a repeated key, a value its logical type does not admit, a value too + deep or too long). A field's own misfit (missing, unknown, of another + type) names the field and not the row. A row whose element the source + began and never wrote is refused as `unframeable`, naming the row, + rather than shifting the rows after it. - Bytes given as a plan that are not one transport frame (empty, cut short, JSON text, a repeated key, bytes after the value) have their own reason, `not_a_frame`. A frame that is not an object of field @@ -524,19 +533,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - A value that fails while it is read, such as a JSON document nested too deep, is the new `Error::SourceFailed`, with the code `stack_encrypt::dynamic_source_failed` and the reason `source_failed`. - It names the field and the row being read, and keeps the value's own - error as its cause. The cause is not in the message, because a host's - error can quote the value. Before, it was `not_an_object` with no - field. - - A typed field that opens as another type says what it opened as: - `PlanError::FieldType` has `found`, in its payload too, as in - `field "doc" opened as an array, not an object`. - - `Error::Plan` has a new `found` field, `Error::Source` and - `Error::Record` new `row` and `found` fields, and - `PlanError::FieldType` a new `found` field, so a match on them that names - every field needs `..`. Reason codes do not change, except the two new - ones. + It names the row being read, and the field while its value is being + written; a failure between two fields, or between two rows, names + neither. It keeps the value's own error as its cause. The cause is not + in the message, because a host's error can quote the value. Before, it + was `not_an_object` with no field. + + `Error::Plan` has a new `found` field, and `Error::Source` and + `Error::Record` new `row` and `found` fields, so a match on them that + names every field needs `..`. Reason codes do not change, except the two + new ones. - **`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/codes.rs b/packages/stack-encrypt/src/codes.rs index 12ab6bde6..d7b47ae44 100644 --- a/packages/stack-encrypt/src/codes.rs +++ b/packages/stack-encrypt/src/codes.rs @@ -184,7 +184,6 @@ mod tests { PlanError::FieldType { .. } => PlanError::FieldType { field: field(), expected: "int64", - found: None, }, PlanError::NoSuchField { .. } => PlanError::NoSuchField { field: field() }, PlanError::IndexOverlap { .. } => PlanError::IndexOverlap { @@ -527,20 +526,9 @@ mod tests { Box::new(PlanError::FieldType { field: "age".into(), expected: "int64", - found: None, }), json!({ "field": "age", "expected": "int64" }), ), - ( - Box::new(PlanError::FieldType { - field: "age".into(), - expected: "int64", - found: Some(crate::refusal::Found::Kind( - vitaminc_aead::plaintext::ValueKind::String, - )), - }), - json!({ "field": "age", "expected": "int64", "found": "string" }), - ), ( Box::new(PlanError::TwoContextSources { first: "the plan", diff --git a/packages/stack-encrypt/src/dynamic/planned.rs b/packages/stack-encrypt/src/dynamic/planned.rs index d69d1b518..8f38d5a04 100644 --- a/packages/stack-encrypt/src/dynamic/planned.rs +++ b/packages/stack-encrypt/src/dynamic/planned.rs @@ -1561,7 +1561,6 @@ fn field_type(field: &str, expected: &'static str) -> crate::Error { PlanError::FieldType { field: field.to_owned(), expected, - found: None, } .into() } diff --git a/packages/stack-encrypt/src/dynamic/record.rs b/packages/stack-encrypt/src/dynamic/record.rs index 30f7ec86c..c72c22c68 100644 --- a/packages/stack-encrypt/src/dynamic/record.rs +++ b/packages/stack-encrypt/src/dynamic/record.rs @@ -2259,11 +2259,13 @@ pub(super) fn source_rows(source: impl Encrypt, plan: &Plan) -> Result } /// A value refused while the source was split, as the source error that -/// names its field: a repeated key as [`Reason::RepeatedKey`], a scalar its -/// logical type does not admit as [`Reason::FieldType`], and anything else (too -/// deep or too long for a frame) as [`Reason::Unframeable`]. A failure of -/// the source's own is [`Error::SourceFailed`], with the field and the row -/// it was reading and its error as the cause. +/// names its field and the row of a batch it is in: a repeated key as +/// [`Reason::RepeatedKey`], a scalar its logical type does not admit as +/// [`Reason::FieldType`], and anything else (too deep or too long for a +/// frame, or a value the source never wrote) as [`Reason::Unframeable`], +/// naming no field when the source left a row of a batch unwritten. A +/// failure of the source's own is [`Error::SourceFailed`], with the field +/// and the row it was reading and its error as the cause. fn split_refusal(SplitRefusal { row, field, error }: SplitRefusal) -> Error { let reason = match error { FrameWriteError::Source(cause) => return Error::SourceFailed { field, row, cause }, @@ -2271,14 +2273,9 @@ fn split_refusal(SplitRefusal { row, field, error }: SplitRefusal) -> Error { FrameWriteError::Invalid => Reason::FieldType, _ => Reason::Unframeable, }; - // Only a field's frame writer refuses a value, and the split names - // the field it hands one to. - let Some(field) = field else { - return Error::Internal; - }; Error::Source { - field: Some(field), - row: None, + field, + row, reason, found: None, } @@ -2564,11 +2561,13 @@ pub(super) fn open_record( // opens as a plain null, as every frame carries one. let null = field.null.is_some() && value.frame().is_null(); if let Some(kind) = field.kind.filter(|_| !null) { + // The error names the declared type and never what the value + // opened as: that is known only once it is decrypted, and is + // the plaintext's own metadata. if !kind.holds(value.frame().kind()) { return Err(crate::PlanError::FieldType { field: field.name.clone(), expected: kind.name(), - found: Some(Found::of_frame(value.frame())), } .into()); } @@ -6184,14 +6183,13 @@ mod tests { PlanError::FieldType { field: "age".into(), expected: "int64", - found: Some(Found::Kind(ValueKind::UInt64)), }, - "the field, the declared type and what it opened as" + "the field and the declared type" ); assert_eq!( refused.to_string(), - r#"field "age" opened as a uint64, not an int64"#, - "the message says what the field opened as" + r#"field "age" is not an int64"#, + "the message names no kind the value opened as" ); let sealed = seal(&keyset, obj(vec![("age", Tree::UInt64(34))]), &untyped).await; @@ -6223,30 +6221,29 @@ mod tests { PlanError::FieldType { field: "age".into(), expected: "uint64", - found: Some(Found::Kind(ValueKind::Float64)), }, - "the row that opened as a float64" + "the field and the declared type" ); } /// A field declared as an object that opens as a list, a single - /// value or a null says what it opened as, by its kind and never its - /// value. + /// value or a null is refused naming the field and the declared type, + /// and never what it opened as: the kind of a value is known only + /// once it is decrypted, so it is the plaintext's own metadata. The + /// payload has no `found`, and the message names no kind. #[tokio::test] - async fn decrypt_says_what_an_object_field_opened_as() { + async fn decrypt_never_says_what_a_field_opened_as() { + use crate::ErrorPayload; let cipher = cipher().await; let keyset = cipher.default_keyset(); let untyped = plan(obj(vec![("doc", spec(label("doc"), &["c"]))])).expect("plan"); let as_object = plan(obj(vec![("doc", typed(label("doc"), &["c"], "object"))])).expect("plan"); - for (stored, found, text) in [ - ( - Tree::Array(vec![s("secret")]), - Found::Kind(ValueKind::Array), - "an array", - ), - (s("secret"), Found::Kind(ValueKind::String), "a string"), - (Tree::Null, Found::Null, "null"), + for (what, stored) in [ + ("a list", Tree::Array(vec![s("secret")])), + ("a string", s("secret")), + ("a null", Tree::Null), + ("a uint32", Tree::UInt32(7)), ] { let sealed = seal(&keyset, obj(vec![("doc", stored)]), &untyped).await; let result = decrypt(&cipher, sealed, &as_object, None) @@ -6258,17 +6255,23 @@ mod tests { PlanError::FieldType { field: "doc".into(), expected: "object", - found: Some(found), }, - "{text}" + "{what}" + ); + let payload = refused.payload(); + assert_eq!( + serde_json::Value::Object(payload.clone()), + serde_json::json!({ "field": "doc", "expected": "object" }), + "{what}: the payload has no found" ); let message = refused.to_string(); assert_eq!( - message, - format!(r#"field "doc" opened as {text}, not an object"#), - "the message names the field and the kind" + message, r#"field "doc" is not an object"#, + "{what}: the message names no kind" ); - assert!(!message.contains("secret"), "no value: {message}"); + for kind in ["list", "array", "string", "null", "uint32", "secret"] { + assert!(!message.contains(kind), "{what}: {kind} in {message}"); + } } } @@ -9196,6 +9199,13 @@ mod tests { error, }) }; + let in_row = |row, error| { + split_refusal(SplitRefusal { + row: Some(row), + field: Some("age".to_owned()), + error, + }) + }; let fault = |error| refusal(Some("age"), error); expect( &fault(FrameWriteError::DuplicateKey), @@ -9212,9 +9222,34 @@ mod tests { for error in [FrameWriteError::TooDeep, FrameWriteError::Unwritten] { expect(&fault(error), "Source", Some("age"), Reason::Unframeable); } + // A refusal in a row of a batch names the row, in the payload + // and the message. + let error = in_row(3, FrameWriteError::DuplicateKey); + expect(&error, "Source", Some("age"), Reason::RepeatedKey); + assert_eq!(error.row(), Some(3), "the row: {error}"); + assert_eq!(error.payload()["row"], 3, "the payload's row: {error}"); + assert!( + error.to_string().ends_with(r#" (row 3, field "age")"#), + "the message names the row: {error}" + ); + // A row the source left unwritten names no field, and is still + // the caller's input, not this module's bug. + let unwritten = split_refusal(SplitRefusal { + row: Some(1), + field: None, + error: FrameWriteError::Unwritten, + }); + expect(&unwritten, "Source", None, Reason::Unframeable); + assert_eq!(unwritten.row(), Some(1), "the row left unwritten"); assert!( - matches!(refusal(None, FrameWriteError::Invalid), Error::Internal), - "a value refused outside any field" + matches!(unwritten.into_crate(), crate::Error::Input(_)), + "an input refusal" + ); + expect( + &refusal(None, FrameWriteError::Invalid), + "Source", + None, + Reason::FieldType, ); } @@ -9495,7 +9530,6 @@ mod tests { P::FieldType { field: field(), expected: "int64", - found: None, } .into(), some("age"), diff --git a/packages/stack-encrypt/src/dynamic/source.rs b/packages/stack-encrypt/src/dynamic/source.rs index 3d684ef5c..2aebe324b 100644 --- a/packages/stack-encrypt/src/dynamic/source.rs +++ b/packages/stack-encrypt/src/dynamic/source.rs @@ -33,7 +33,7 @@ use std::cell::{Cell, RefCell}; -use vitaminc_aead::frame::{FrameWriteError, FrameWriter, OwnedFrame}; +use vitaminc_aead::frame::{FrameMap, FrameSeq, FrameWriteError, FrameWriter, OwnedFrame}; use vitaminc_aead::plaintext::{ Encrypt, EncryptRef, FixedType, Logical, MapSink, Physical, SeqSink, Sink, ValueKind, }; @@ -76,16 +76,25 @@ pub(super) fn split_source(source: P) -> Result>, field: RefCell>, } +impl Place { + /// The field being written is finished. + fn field_done(&self) { + *self.field.borrow_mut() = None; + } +} + /// The place shared by every sink in a split. type Open<'f> = &'f Place; @@ -106,13 +115,17 @@ impl PutRecord for TopRecord { } } -/// The next record of a batch. -struct BatchRecord<'s>(&'s mut Vec); +/// The next record of a batch. Putting it finishes its row. +struct BatchRecord<'s> { + records: &'s mut Vec, + open: Open<'s>, +} impl PutRecord for BatchRecord<'_> { type Ok = (); fn put(self, record: SourceRecord) { - self.0.push(record); + self.records.push(record); + self.open.row.set(None); } } @@ -141,6 +154,7 @@ impl<'f> Sink for TopSink<'f> { Ok(BatchSink { open: self.0, records: Vec::new(), + begun: 0, }) } @@ -153,10 +167,25 @@ impl<'f> Sink for TopSink<'f> { } } -/// A batch: one record for each element. +/// A batch: one record for each element. `begun` counts the elements the +/// source began, so an element whose sink it dropped unwritten, leaving no +/// record, is refused rather than shifting the rows after it. struct BatchSink<'f> { open: Open<'f>, records: Vec, + begun: usize, +} + +impl BatchSink<'_> { + /// Refuse a batch whose last element begun put no record: its sink was + /// dropped unwritten. + fn check_written(&self) -> Result<(), FrameWriteError> { + if self.records.len() == self.begun { + return Ok(()); + } + self.open.row.set(Some(self.records.len())); + Err(FrameWriteError::Unwritten) + } } impl<'f> SeqSink for BatchSink<'f> { @@ -168,14 +197,20 @@ impl<'f> SeqSink for BatchSink<'f> { Self: 's; fn element(&mut self) -> Result, FrameWriteError> { - self.open.row.set(Some(self.records.len())); + self.check_written()?; + self.open.row.set(Some(self.begun)); + self.begun += 1; Ok(ElementSink { open: self.open, - record: BatchRecord(&mut self.records), + record: BatchRecord { + records: &mut self.records, + open: self.open, + }, }) } fn end(self) -> Result { + self.check_written()?; Ok(SplitSource::Batch(self.records)) } } @@ -328,15 +363,15 @@ impl<'f, O> RecordMap<'f, O> { } } -impl MapSink for RecordMap<'_, O> { +impl<'f, O: PutRecord> MapSink for RecordMap<'f, O> { type Ok = O::Ok; type Error = FrameWriteError; type Entry<'s> - = FrameWriter<'s> + = FieldWriter<'s, 'f> where Self: 's; - fn entry(&mut self, key: &str) -> Result, FrameWriteError> { + fn entry(&mut self, key: &str) -> Result, FrameWriteError> { *self.open.field.borrow_mut() = Some(key.to_owned()); self.entries.push((key.to_owned(), Buffer::new())); let buffer = match self.entries.last_mut() { @@ -344,13 +379,13 @@ impl MapSink for RecordMap<'_, O> { // Pushed on the line above. None => unreachable!(), }; - Ok(FrameWriter::new(buffer)) + Ok(FieldWriter { + writer: FrameWriter::new(buffer), + open: self.open, + }) } fn end(self) -> Result { - // The record's values are written: a failure after this is not one - // of its fields'. - *self.open.field.borrow_mut() = None; let mut record = Vec::with_capacity(self.entries.len()); for (key, buffer) in self.entries { // A source that dropped an entry's sink without writing to it @@ -365,6 +400,104 @@ impl MapSink for RecordMap<'_, O> { } } +/// One field's value, written into its own frame. It forwards to the frame +/// writer, and once the value is complete it marks the field finished, so a +/// source that fails after one field's value and before the next names +/// neither. +struct FieldWriter<'s, 'f> { + writer: FrameWriter<'s>, + open: Open<'f>, +} + +impl<'s, 'f> Sink for FieldWriter<'s, 'f> { + type Ok = (); + type Error = FrameWriteError; + type Seq = FieldSeq<'s, 'f>; + type Map = FieldMap<'s, 'f>; + + fn scalar(self, logical: Option, value: Physical<'_>) -> Result<(), FrameWriteError> { + self.writer.scalar(logical, value)?; + self.open.field_done(); + Ok(()) + } + + fn typed_null(self, ty: FixedType) -> Result<(), FrameWriteError> { + self.writer.typed_null(ty)?; + self.open.field_done(); + Ok(()) + } + + fn seq(self, len: Option) -> Result, FrameWriteError> { + Ok(FieldSeq { + inner: self.writer.seq(len)?, + open: self.open, + }) + } + + fn map(self, len: Option) -> Result, FrameWriteError> { + Ok(FieldMap { + inner: self.writer.map(len)?, + open: self.open, + }) + } + + fn passthrough(self, value: &P) -> Result<(), FrameWriteError> { + self.writer.passthrough(value)?; + self.open.field_done(); + Ok(()) + } +} + +/// A field's value that is a sequence: finished when the sequence ends. +struct FieldSeq<'s, 'f> { + inner: FrameSeq<'s>, + open: Open<'f>, +} + +impl<'s> SeqSink for FieldSeq<'s, '_> { + type Ok = (); + type Error = FrameWriteError; + type Element<'e> + = FrameWriter<'e> + where + Self: 'e; + + fn element(&mut self) -> Result, FrameWriteError> { + self.inner.element() + } + + fn end(self) -> Result<(), FrameWriteError> { + self.inner.end()?; + self.open.field_done(); + Ok(()) + } +} + +/// A field's value that is a map: finished when the map ends. +struct FieldMap<'s, 'f> { + inner: FrameMap<'s>, + open: Open<'f>, +} + +impl<'s> MapSink for FieldMap<'s, '_> { + type Ok = (); + type Error = FrameWriteError; + type Entry<'e> + = FrameWriter<'e> + where + Self: 'e; + + fn entry(&mut self, key: &str) -> Result, FrameWriteError> { + self.inner.entry(key) + } + + fn end(self) -> Result<(), FrameWriteError> { + self.inner.end()?; + self.open.field_done(); + Ok(()) + } +} + #[cfg(test)] mod tests { use super::*; @@ -606,7 +739,109 @@ mod tests { after.error ); assert_eq!(after.field, None, "no field is being read"); - assert_eq!(after.row, Some(1), "the last row begun"); + assert_eq!(after.row, None, "every row begun is finished"); + } + + /// Where a source fails decides what the refusal names: a field only + /// while its value is being written, and a row only while it is being + /// read. A failure between two fields, after a field's container ends, + /// or between two rows names neither. + #[test] + fn a_source_failure_names_only_the_field_and_row_still_open() { + /// Where the source fails, in a batch of records. + #[derive(Clone, Copy, Debug)] + enum At { + /// In row 0, after `age` is written and before `email` begins. + BetweenFields, + /// In row 0, inside `tags`, a list, after its first element. + InsideAList, + /// In row 0, after `tags`, a map, has ended. + AfterAMap, + /// After row 0 is finished and before row 1 begins. + BetweenRows, + } + impl Encrypt for &At { + fn visit(self, sink: S) -> Result { + let fail = || { + ::source(SourceError::msg( + "getter threw", + )) + }; + let one = || Raw(None, Physical::Int(Int::I32(1))); + let mut seq = sink.seq(Some(2))?; + let mut map = seq.element()?.map(Some(2))?; + one().visit(map.entry("age")?)?; + match self { + At::BetweenFields => Err(fail()), + At::InsideAList => { + let mut list = map.entry("tags")?.seq(Some(2))?; + one().visit(list.element()?)?; + Err(fail()) + } + At::AfterAMap => { + let mut inner = map.entry("tags")?.map(Some(1))?; + one().visit(inner.entry("k")?)?; + inner.end()?; + Err(fail()) + } + At::BetweenRows => { + one().visit(map.entry("email")?)?; + map.end()?; + Err(fail()) + } + } + } + } + for (at, field, row) in [ + (At::BetweenFields, None, Some(0)), + (At::InsideAList, Some("tags"), Some(0)), + (At::AfterAMap, None, Some(0)), + (At::BetweenRows, None, None), + ] { + let failed = split_source(&at).err().expect("refused"); + assert!( + matches!(failed.error, FrameWriteError::Source(_)), + "{at:?}: {:?}", + failed.error + ); + assert_eq!(failed.field.as_deref(), field, "{at:?}: the field"); + assert_eq!(failed.row, row, "{at:?}: the row"); + } + } + + /// A batch element whose sink the source dropped unwritten leaves no + /// record: the batch is refused naming that row, before or at its end, + /// rather than shifting the rows after it. + #[test] + fn a_batch_element_left_unwritten_is_refused_naming_its_row() { + /// A batch of two rows whose row `dropped` is begun and dropped. + struct DropsARow { + dropped: usize, + } + impl Encrypt for &DropsARow { + fn visit(self, sink: S) -> Result { + let mut seq = sink.seq(Some(2))?; + for row in 0..2 { + let element = seq.element()?; + if row != self.dropped { + let mut map = element.map(Some(1))?; + Raw(None, Physical::Int(Int::I32(1))).visit(map.entry("a")?)?; + map.end()?; + } + } + seq.end() + } + } + for dropped in [0, 1] { + let refused = split_source(&DropsARow { dropped }).err().expect("refused"); + assert!( + matches!(refused.error, FrameWriteError::Unwritten), + "row {dropped}: {:?}", + refused.error + ); + assert_eq!(refused.row, Some(dropped), "the row left unwritten"); + assert_eq!(refused.field, None, "no field is being written"); + } } /// An entry whose sink the source dropped unwritten has no frame: the diff --git a/packages/stack-encrypt/src/plan/error.rs b/packages/stack-encrypt/src/plan/error.rs index 225e9cafa..dd551a0ad 100644 --- a/packages/stack-encrypt/src/plan/error.rs +++ b/packages/stack-encrypt/src/plan/error.rs @@ -1,6 +1,5 @@ //! Why a plan was refused. use crate::op::Op; -use crate::refusal::Found; use crate::LabelError; /// Why a plan was refused: when it was parsed, or when it was run against a @@ -103,9 +102,8 @@ pub enum PlanError { field: String, }, /// A field is not of the type the plan declares for it, so the plan - /// cannot resolve how to seal, index or read it. A field that opens - /// as another type says what it opened as. - #[error("{}", field_type_text(field, expected, *found))] + /// cannot resolve how to seal, index or read it. + #[error("field {field:?} is not {article} {expected}", article = article(expected))] #[diagnostic( code(stack_encrypt::plan_field_type), help("Give the field a value of the type the plan declares. A row stored as another type opens only after it is re-encrypted as the declared one.") @@ -115,9 +113,6 @@ pub enum PlanError { field: String, /// The type the plan declares. expected: &'static str, - /// What the field opened as, when it was opened: a stored row - /// sealed as another type than the plan now declares. - found: Option, }, /// The plan has no field of that name. #[error("the plan has no field {field:?}")] @@ -234,20 +229,10 @@ impl crate::ErrorPayload for PlanError { Self::DuplicateIndex { at, index } => { payload([("field", at.as_str().into()), ("index", (*index).into())]) } - Self::FieldType { - field, - expected, - found, - } => { - let mut fields = payload([ - ("field", field.as_str().into()), - ("expected", (*expected).into()), - ]); - if let Some(found) = found { - let _ = fields.insert("found".to_owned(), found.as_str().into()); - } - fields - } + Self::FieldType { field, expected } => payload([ + ("field", field.as_str().into()), + ("expected", (*expected).into()), + ]), Self::IndexOverlap { at, first, @@ -267,16 +252,6 @@ impl crate::ErrorPayload for PlanError { } } -/// `field "age" is not an int64`, or, for a field that was opened, -/// `field "age" opened as a string, not an int64`. -fn field_type_text(field: &str, expected: &str, found: Option) -> String { - let article = article(expected); - match found { - Some(found) => format!("field {field:?} opened as {found}, not {article} {expected}"), - None => format!("field {field:?} is not {article} {expected}"), - } -} - /// The indefinite article for a type's name, as it is read aloud: "an" before /// a vowel sound (`an int8`, `an i64`, `an object`), and "a" otherwise. A name /// starting with `u` is read as "you" (`a uint8`, `a u32`), so it takes "a". @@ -297,7 +272,6 @@ mod tests { PlanError::FieldType { field: "f".to_owned(), expected, - found: None, } .to_string() }; diff --git a/packages/stack-encrypt/src/plan/values.rs b/packages/stack-encrypt/src/plan/values.rs index bd54bf632..5ef093483 100644 --- a/packages/stack-encrypt/src/plan/values.rs +++ b/packages/stack-encrypt/src/plan/values.rs @@ -103,7 +103,6 @@ impl FieldValues { PlanError::FieldType { field: name.to_string(), expected: type_name::(), - found: None, } .into() }) diff --git a/packages/stack-encrypt/src/refusal.rs b/packages/stack-encrypt/src/refusal.rs index b06c504fc..2c782e2f2 100644 --- a/packages/stack-encrypt/src/refusal.rs +++ b/packages/stack-encrypt/src/refusal.rs @@ -65,9 +65,14 @@ use crate::target::IndexSpec; /// Where a plan, a record to encrypt or a stored record is not the object /// the operation takes, the error says what it found instead: its kind /// ([`Found`]), never the value. It is in the message, in -/// [`found`](Self::found) and in the payload (`found`). A row of a batch is -/// named by its position, from 0: in the message, in [`row`](Self::row) and -/// in the payload (`row`). +/// [`found`](Self::found) and in the payload (`found`). The kind is always +/// one the caller sent, or one the stored record's own structure shows; an +/// error about a decrypted value never names what it opened as. Where the +/// error is about one row of a batch's shape, or about a value the source +/// failed or the frame writer refused while the rows were read, it names +/// the row by its position, from 0: in the message, in [`row`](Self::row) +/// and in the payload (`row`). A field's own misfit (missing, unknown, of +/// another type) names the field and not the row. /// /// Not every variant has a [`Reason`]. [`Context`](Error::Context), /// [`Plan`](Error::Plan), [`Source`](Error::Source), @@ -176,7 +181,7 @@ pub enum Error { /// The source field at fault, if the fault is one field's. field: Option, /// The row of a batch at fault, from 0, if the fault is one row's - /// shape. + /// shape or a value the frame writer refused as the rows were read. row: Option, /// What was wrong with the source. reason: Reason, @@ -458,9 +463,10 @@ impl Error { } /// The row of a batch an input error is about, from 0: a row of a - /// record source or a stored record that is not an object, or the row - /// a source failed in. `None` for a single record, and for every other - /// error. + /// record source or a stored record that is not an object, the row a + /// source failed in, or the row of a value the frame writer refused as + /// the source's rows were read. `None` for a single record, and for + /// every other error. pub fn row(&self) -> Option { match self { Self::Source { row, .. } diff --git a/packages/stack-profile/src/diagnostic.rs b/packages/stack-profile/src/diagnostic.rs index f2bdb0631..b1469cfb6 100644 --- a/packages/stack-profile/src/diagnostic.rs +++ b/packages/stack-profile/src/diagnostic.rs @@ -58,9 +58,12 @@ //! //! - Keyset IDs and names; counts and lengths; index names and kinds. //! - Schema field names from a plan or Go struct, rather than field values. -//! - A value's kind, such as null, an array or a uint32, rather than the -//! value, and the position of a row in a batch. The kind is what a schema -//! declares, and a frame carries it in the clear. +//! - The kind of a value the caller sent, such as null, an array or a +//! uint32, rather than the value, or the kind of a node in a stored +//! record's own structure (a passthrough, a sealed value, a list), which +//! the stored form shows without decrypting; and the position of a row in +//! a batch. Never the kind of a decrypted value: that is known only once +//! it is opened, so it is the plaintext's own metadata. //! - Request kinds and HTTP status codes for ZeroKMS, CipherStash's //! key-management service. //! - Workspace IDs, workspace resource names (CRNs), and regions. From 533f2572ca6a28f33c66d886c28466174541d533 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sat, 28 Nov 2026 04:02:11 +1100 Subject: [PATCH 07/14] fix(stack-encrypt): keep a host's error out of Debug, and tidy the refusal paths Review of the "not an object" errors found a new leak and some loose ends: - `SourceFailed` kept the host's `SourceError` as its cause, and the derived `Debug` printed it, so `{:?}`, `tracing::error!(?err)` or a panic from `.unwrap()` showed text that can quote the value. `Error` now has a hand-written `Debug`: every other variant prints as the derive did, and the cause prints as `SourceError(..)`. `source()` still reaches it. The test asserts the marker text is absent from `{:?}`, `{:#?}`, the message and the payload. - A known logical type over a value it does not admit (a date over a null) was named "a value of a type this build does not know". Only a logical type this build does not know is `unknown` now; any other is named by the value's physical kind. - A writer's refusal with no field to name kept a field's reason (`repeated_key`, `field_type`) it could not attribute. With no field it is `unframeable`, with the row. - The frame-walking sinks behind `Found` (`of_frame`, `of_entry`, `object_keys`, the probe and the lookup) are used only by the dynamic interface, and compiled as dead code without it. They now live in `dynamic::found`. - `split_source` names its shared place `place`, without an alias. - Thirty-two literal `Error::{Plan, Source}` builds that set no row and no kind use `bad_plan`/`bad_source` with `in_field`. - A source refusal only a query's input meets (an operator, a range, a term, statistics, a null query, a JSON operator's input) said "record source does not fit the plan", though no record or plan was involved. It says "query input does not fit the field". - Two Go doc comments left long by a partial reflow are rewrapped. --- languages/golang/encrypt/errors.go | 7 +- languages/golang/internal/guest/diagnostic.go | 6 +- packages/stack-encrypt/CHANGELOG.md | 11 +- packages/stack-encrypt/src/dynamic/found.rs | 296 ++++++++++++++ packages/stack-encrypt/src/dynamic/mod.rs | 1 + packages/stack-encrypt/src/dynamic/query.rs | 75 +--- packages/stack-encrypt/src/dynamic/record.rs | 238 ++++++------ packages/stack-encrypt/src/dynamic/source.rs | 57 ++- packages/stack-encrypt/src/refusal.rs | 362 +++++++----------- 9 files changed, 603 insertions(+), 450 deletions(-) create mode 100644 packages/stack-encrypt/src/dynamic/found.rs diff --git a/languages/golang/encrypt/errors.go b/languages/golang/encrypt/errors.go index 26eb85e36..c1da56976 100644 --- a/languages/golang/encrypt/errors.go +++ b/languages/golang/encrypt/errors.go @@ -98,9 +98,10 @@ var ErrStorageVersion = vcffi.ErrUnsupportedVersion // grammar's words and the byte offset in the predicate where it starts. // // What one may carry is fixed: keyset ids and names, field names, counts, -// row positions, value kinds, index kinds, ZeroKMS request kinds and HTTP statuses, and a refused -// predicate's construct and offset. Never plaintext, key material, -// tokens, ciphertext or term bytes, or the values of an encryption context. +// row positions, value kinds, index kinds, ZeroKMS request kinds and HTTP +// statuses, and a refused predicate's construct and offset. Never +// plaintext, key material, tokens, ciphertext or term bytes, or the values +// of an encryption context. // // Errors the client raises itself carry none: a closed client ([ErrState]), // a guest that did not return, [ErrMemoryLock], and an argument refused diff --git a/languages/golang/internal/guest/diagnostic.go b/languages/golang/internal/guest/diagnostic.go index 16ff5475c..860628e8f 100644 --- a/languages/golang/internal/guest/diagnostic.go +++ b/languages/golang/internal/guest/diagnostic.go @@ -25,9 +25,9 @@ import ( // keyset ids and names, field names, counts, row positions, value kinds, // index kinds, ZeroKMS request kinds and HTTP statuses, workspace ids, CRNs // and regions, profile file paths, and for a refused predicate the -// construct in the grammar's words and a byte offset. Never plaintext, key material, tokens, ciphertext or -// term bytes, or a context's values: a stored context's length and parts -// at most. +// construct in the grammar's words and a byte offset. Never plaintext, key +// material, tokens, ciphertext or term bytes, or a context's values: a +// stored context's length and parts at most. // // A guest built before se_last_error, or one whose error does not decode, // returns the bare sentinel instead: the detail is never allowed to hide diff --git a/packages/stack-encrypt/CHANGELOG.md b/packages/stack-encrypt/CHANGELOG.md index c147bdbee..662476481 100644 --- a/packages/stack-encrypt/CHANGELOG.md +++ b/packages/stack-encrypt/CHANGELOG.md @@ -535,9 +535,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 `stack_encrypt::dynamic_source_failed` and the reason `source_failed`. It names the row being read, and the field while its value is being written; a failure between two fields, or between two rows, names - neither. It keeps the value's own error as its cause. The cause is not - in the message, because a host's error can quote the value. Before, it - was `not_an_object` with no field. + neither. It keeps the value's own error as its cause, reached through + `source()`. The cause is not in the message, and `Debug` shows it as + `SourceError(..)`, because a host's error can quote the value. Before, + it was `not_an_object` with no field. + - A source refusal only a query's input meets (an operator, a range, a + term, statistics, a null query, a JSON operator's input) now says + `query input does not fit the field`, where it said `record source + does not fit the plan`. `Error::Plan` has a new `found` field, and `Error::Source` and `Error::Record` new `row` and `found` fields, so a match on them that diff --git a/packages/stack-encrypt/src/dynamic/found.rs b/packages/stack-encrypt/src/dynamic/found.rs new file mode 100644 index 000000000..824b03fee --- /dev/null +++ b/packages/stack-encrypt/src/dynamic/found.rs @@ -0,0 +1,296 @@ +//! What a value an input error is about is, read from the value itself: +//! [`Found`] for a scalar a source describes, a frame, or one entry of an +//! object frame, and the keys of an object frame. The sinks here read past +//! every value and copy none of it. + +use std::cell::{Cell, RefCell}; + +use vitaminc_aead::frame::{Frame, FrameWriteError}; +use vitaminc_aead::plaintext::{ + Encrypt as _, EncryptRef, FixedType, Logical, MapSink, Physical, SeqSink, Sink, ValueKind, +}; + +use crate::refusal::Found; + +impl Found { + /// What a scalar is, from how it describes itself: its kind, or + /// `undefined`, or a logical type this build does not know. A logical + /// type over a value it does not admit is named by the value's own + /// physical kind, as null, a string, an int32 and so on. + pub(crate) fn scalar(logical: Option, value: &Physical<'_>) -> Self { + if let Some(kind) = ValueKind::of(logical, value) { + return Self::Kind(kind); + } + match logical { + Some(Logical::Undefined) => Self::Undefined, + Some(Logical::Unknown(_)) => Self::Unknown, + _ => ValueKind::of(None, value).map_or(Self::Null, Self::Kind), + } + } + + /// What a frame holds, reading no more of it than its first node. + pub(crate) fn of_frame(frame: Frame<'_>) -> Self { + if let Some(kind) = frame.kind() { + return Self::Kind(kind); + } + if frame.is_null() { + return Self::Null; + } + // A passthrough, `undefined` or a logical type this build does not + // know: one node, which the probe reads without walking inside it. + let found = Cell::new(None); + let _ = frame.visit(Probe::noting(&found, None)); + found.get().unwrap_or(Self::Unknown) + } + + /// What the entry under `key` holds, for a frame that is an object with + /// one, and the entry's own keys, in order, when it is an object too. + /// `None` for a frame that is not an object or has no such key. + pub(crate) fn of_entry(frame: Frame<'_>, key: &str) -> Option<(Self, Vec)> { + let found = Cell::new(None); + let keys = RefCell::new(Vec::new()); + let _ = frame.visit(Lookup { + key, + found: &found, + keys: &keys, + }); + found.get().map(|found| (found, keys.into_inner())) + } +} + +/// The keys of an object frame, in order; `None` for a frame that is not an +/// object. Read with the probe, so a value the frame reader refuses to read, +/// such as a typed null, does not hide the keys beside it. +pub(crate) fn object_keys(frame: Frame<'_>) -> Option> { + let found = Cell::new(None); + let keys = RefCell::new(Vec::new()); + let _ = frame.visit(Probe::noting(&found, Some(&keys))); + (found.get() == Some(Found::Kind(ValueKind::Object))).then(|| keys.into_inner()) +} + +/// A sink that reads past a value and keeps none of it: where it is given +/// a cell, it notes what kind of value the node is, and where it is given +/// a list, the keys of an object it is. Children are read past with +/// neither, so nothing inside a container is noted, and no value is copied. +struct Probe<'c> { + found: Option<&'c Cell>>, + keys: Option<&'c RefCell>>, +} + +impl<'c> Probe<'c> { + /// A probe that notes the node's kind, and its keys if `keys` is given. + fn noting(found: &'c Cell>, keys: Option<&'c RefCell>>) -> Self { + Self { + found: Some(found), + keys, + } + } + + /// A probe that reads past a node and notes nothing. + fn past() -> Self { + Self { + found: None, + keys: None, + } + } + + fn note(&self, found: Found) { + if let Some(cell) = self.found { + cell.set(Some(found)); + } + } +} + +impl<'c> Sink for Probe<'c> { + type Ok = (); + type Error = FrameWriteError; + type Seq = Probe<'c>; + type Map = Probe<'c>; + + fn scalar(self, logical: Option, value: Physical<'_>) -> Result<(), FrameWriteError> { + self.note(Found::scalar(logical, &value)); + Ok(()) + } + + fn typed_null(self, _: FixedType) -> Result<(), FrameWriteError> { + self.note(Found::Null); + Ok(()) + } + + fn seq(self, _: Option) -> Result, FrameWriteError> { + self.note(Found::Kind(ValueKind::Array)); + Ok(Probe::past()) + } + + fn map(self, _: Option) -> Result, FrameWriteError> { + self.note(Found::Kind(ValueKind::Object)); + // The map's entries are read with the keys list, to note their keys. + Ok(Probe { + found: None, + keys: self.keys, + }) + } + + fn passthrough(self, _: &P) -> Result<(), FrameWriteError> { + self.note(Found::Passthrough); + Ok(()) + } +} + +impl<'c> SeqSink for Probe<'c> { + type Ok = (); + type Error = FrameWriteError; + type Element<'e> + = Probe<'c> + where + Self: 'e; + + fn element(&mut self) -> Result, FrameWriteError> { + Ok(Probe::past()) + } + + fn end(self) -> Result<(), FrameWriteError> { + Ok(()) + } +} + +impl<'c> MapSink for Probe<'c> { + type Ok = (); + type Error = FrameWriteError; + type Entry<'e> + = Probe<'c> + where + Self: 'e; + + fn entry(&mut self, key: &str) -> Result, FrameWriteError> { + if let Some(keys) = self.keys { + keys.borrow_mut().push(key.to_owned()); + } + Ok(Probe::past()) + } + + fn end(self) -> Result<(), FrameWriteError> { + Ok(()) + } +} + +/// A sink that notes what kind of value one entry of an object is, and its +/// keys if it is an object, and reads past everything else. +struct Lookup<'k, 'c> { + key: &'k str, + found: &'c Cell>, + keys: &'c RefCell>, +} + +impl<'k, 'c> Sink for Lookup<'k, 'c> { + type Ok = (); + type Error = FrameWriteError; + type Seq = Probe<'c>; + type Map = Lookup<'k, 'c>; + + fn scalar(self, _: Option, _: Physical<'_>) -> Result<(), FrameWriteError> { + Ok(()) + } + + fn typed_null(self, _: FixedType) -> Result<(), FrameWriteError> { + Ok(()) + } + + fn seq(self, _: Option) -> Result, FrameWriteError> { + Ok(Probe::past()) + } + + fn map(self, _: Option) -> Result { + Ok(self) + } + + fn passthrough(self, _: &P) -> Result<(), FrameWriteError> { + Ok(()) + } +} + +impl<'c> MapSink for Lookup<'_, 'c> { + type Ok = (); + type Error = FrameWriteError; + type Entry<'e> + = Probe<'c> + where + Self: 'e; + + fn entry(&mut self, key: &str) -> Result, FrameWriteError> { + if key == self.key { + Ok(Probe::noting(self.found, Some(self.keys))) + } else { + Ok(Probe::past()) + } + } + + fn end(self) -> Result<(), FrameWriteError> { + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use vitaminc_aead::plaintext::{Int, Raw}; + + /// A scalar is named by its kind, `undefined`, or a logical type this + /// build does not know. A known logical type over a value it does not + /// admit is named by the value's own physical kind, never as unknown. + #[test] + fn a_scalar_is_named_by_what_it_is() { + let unknown = Logical::from_wire(200, 0).expect("an unknown logical type"); + for (logical, value, want) in [ + (None, Physical::Null, Found::Null), + (None, Physical::Text("x"), Found::Kind(ValueKind::String)), + ( + Some(Logical::Date), + Physical::Int(Int::I32(1)), + Found::Kind(ValueKind::Date), + ), + (Some(Logical::Undefined), Physical::Null, Found::Undefined), + (Some(unknown), Physical::Int(Int::U32(1)), Found::Unknown), + (Some(Logical::Date), Physical::Null, Found::Null), + ( + Some(Logical::Date), + Physical::Text("x"), + Found::Kind(ValueKind::String), + ), + ( + Some(Logical::Uuid), + Physical::Int(Int::I64(1)), + Found::Kind(ValueKind::Int64), + ), + ] { + assert_eq!( + Found::scalar(logical, &value), + want, + "{logical:?} over {value:?}" + ); + } + } + + /// Through a record source: a batch row that is a date over a null is + /// a null, not a value of a type this build does not know. + #[test] + fn a_row_that_is_a_known_logical_over_a_null_is_a_null() { + struct Rows; + impl vitaminc_aead::plaintext::Encrypt for &Rows { + fn visit(self, sink: S) -> Result { + let mut seq = sink.seq(Some(1))?; + Raw(Some(Logical::Date), Physical::Null).visit(seq.element()?)?; + seq.end() + } + } + let Ok(super::super::source::SplitSource::Batch(rows)) = + super::super::source::split_source(&Rows) + else { + panic!("a batch"); + }; + assert!( + matches!(rows.as_slice(), [Err(Found::Null)]), + "the row is a null" + ); + } +} diff --git a/packages/stack-encrypt/src/dynamic/mod.rs b/packages/stack-encrypt/src/dynamic/mod.rs index 06cc854f4..786e8c0b3 100644 --- a/packages/stack-encrypt/src/dynamic/mod.rs +++ b/packages/stack-encrypt/src/dynamic/mod.rs @@ -92,6 +92,7 @@ //! binding has to be taught, and an exhaustive match is how the compiler //! tells a binding author that. mod context; +mod found; mod json; mod json_query; mod kind; diff --git a/packages/stack-encrypt/src/dynamic/query.rs b/packages/stack-encrypt/src/dynamic/query.rs index ee2916237..29cf6a0be 100644 --- a/packages/stack-encrypt/src/dynamic/query.rs +++ b/packages/stack-encrypt/src/dynamic/query.rs @@ -425,12 +425,7 @@ fn answer<'p>( resolver: &(impl TargetResolver + ?Sized), ) -> Result, Error> { let found = find(plan, field)?; - let not_answered = || Error::Source { - field: Some(field.to_owned()), - reason: Reason::OperatorNotAnswered, - found: None, - row: None, - }; + let not_answered = || Error::bad_source(Reason::OperatorNotAnswered).in_field(field); let kind = found.field_type().ok_or_else(not_answered)?; let (operators, target) = answers(found, resolver)?; let index = operators @@ -450,11 +445,7 @@ pub(super) fn find<'p>(plan: &'p Plan, field: &str) -> Result<&'p FieldPlan, Err plan.fields() .iter() .find(|candidate| candidate.name() == field) - .ok_or_else(|| Error::Plan { - field: Some(field.to_owned()), - reason: Reason::NoSuchField, - found: None, - }) + .ok_or_else(|| Error::bad_plan(Reason::NoSuchField).in_field(field)) } /// Operators a field answers, each with the index that answers it. @@ -586,11 +577,7 @@ impl OperatorEntry { /// [`verify`] and [`target_limit`] derive nothing and take such a plan. fn has_context(plan: &Plan, field: &str) -> Result<(), Error> { if !plan.bindings().is_empty() { - return Err(Error::Plan { - field: Some(field.to_owned()), - reason: Reason::BindInQuery, - found: None, - }); + return Err(Error::bad_plan(Reason::BindInQuery).in_field(field)); } names_its_context(plan, field) } @@ -604,11 +591,7 @@ fn has_context(plan: &Plan, field: &str) -> Result<(), Error> { /// it again. fn names_its_context(plan: &Plan, field: &str) -> Result<(), Error> { match plan.context_field() { - Some(_) => Err(Error::Plan { - field: Some(field.to_owned()), - reason: Reason::QueryContextField, - found: None, - }), + Some(_) => Err(Error::bad_plan(Reason::QueryContextField).in_field(field)), None => Ok(()), } } @@ -624,24 +607,15 @@ fn names_its_context(plan: &Plan, field: &str) -> Result<(), Error> { fn read_input(answer: &Answer<'_>, operator: Op, input: impl Encrypt) -> Result { let name = answer.field.name(); if !operator.takes_pair() { - let input = OwnedFrame::of(input).map_err(|_| Error::Source { - field: Some(name.to_owned()), - reason: Reason::FieldType, - found: None, - row: None, - })?; + let input = OwnedFrame::of(input) + .map_err(|_| Error::bad_source(Reason::FieldType).in_field(name))?; // A null is found by its equality term, which a field that seals // its nulls stores beside each one (#1298); nothing else has one. if input.frame().is_null() { let sealed = answer.field.null() == Some(super::NullMode::Sealed); return match (sealed, &answer.index) { (true, IndexSpec::Equality) => Ok(Input::One(input)), - _ => Err(Error::Source { - field: Some(name.to_owned()), - reason: Reason::NullQuery, - found: None, - row: None, - }), + _ => Err(Error::bad_source(Reason::NullQuery).in_field(name)), }; } return read(answer.kind, input.frame()) @@ -658,12 +632,7 @@ fn read_input(answer: &Answer<'_>, operator: Op, input: impl Encrypt) -> Result< } fn not_a_range(field: &str) -> Error { - Error::Source { - field: Some(field.to_owned()), - reason: Reason::NotARange, - found: None, - row: None, - } + Error::bad_source(Reason::NotARange).in_field(field) } /// What a query of `input` through `index` is refused for before any term @@ -871,12 +840,7 @@ fn json_options<'p>(answer: &Answer<'p>) -> Result<&'p crate::json::JsonOptions, } fn json_input(field: &str) -> Error { - Error::Source { - field: Some(field.to_owned()), - reason: Reason::JsonInput, - found: None, - row: None, - } + Error::bad_source(Reason::JsonInput).in_field(field) } /// A JSON operator's term: the operand [`json_query`](super::json_query) @@ -1201,12 +1165,7 @@ fn probabilistic( // probabilistic operator, so the index says which this is. match answer.index { IndexSpec::Match(options) => Ok((options, target)), - _ => Err(Error::Source { - field: Some(field.to_owned()), - reason: Reason::ExactOperator, - found: None, - row: None, - }), + _ => Err(Error::bad_source(Reason::ExactOperator).in_field(field)), } } @@ -1259,12 +1218,7 @@ pub fn verify( _ => Err(None), }, )) - .map_err(|_| Error::Source { - field: Some(field.to_owned()), - reason: Reason::FieldType, - found: None, - row: None, - }) + .map_err(|_| Error::bad_source(Reason::FieldType).in_field(field)) }) .collect() } @@ -1306,12 +1260,7 @@ pub fn target_limit( } else { query_bits(term, &options) }; - let bits = bits.ok_or_else(|| Error::Source { - field: Some(field.to_owned()), - reason: Reason::NotAQueryTerm, - found: None, - row: None, - })?; + let bits = bits.ok_or_else(|| Error::bad_source(Reason::NotAQueryTerm).in_field(field))?; Ok(match_limit(bits, &options, None, want, stats)) } diff --git a/packages/stack-encrypt/src/dynamic/record.rs b/packages/stack-encrypt/src/dynamic/record.rs index c72c22c68..6a0126dbe 100644 --- a/packages/stack-encrypt/src/dynamic/record.rs +++ b/packages/stack-encrypt/src/dynamic/record.rs @@ -312,11 +312,7 @@ impl FieldPlan { outputs: Vec, ) -> Result { let name = name.into(); - let refuse = |reason| Error::Plan { - field: Some(name.clone()), - reason, - found: None, - }; + let refuse = |reason| Error::bad_plan(reason).in_field(&name); if outputs.is_empty() { return Err(refuse(Reason::NoOutputs)); } @@ -376,11 +372,7 @@ impl FieldPlan { let name = name.into(); let target = target.into(); if target.is_empty() { - return Err(Error::Plan { - field: Some(name), - reason: Reason::InvalidTarget, - found: None, - }); + return Err(Error::bad_plan(Reason::InvalidTarget).in_field(&name)); } let (label, extension) = field_context(&name, context.get())?; Ok(Self { @@ -429,11 +421,7 @@ impl FieldPlan { for output in &self.outputs { if let Output::Term(index) = output { if let Some(reason) = not_admitted(field_type, index) { - return Err(Error::Plan { - field: Some(self.name.clone()), - reason, - found: None, - }); + return Err(Error::bad_plan(reason).in_field(&self.name)); } } } @@ -543,11 +531,8 @@ impl FieldPlan { let Some((_, prefix)) = segments.split_last() else { return Err(Error::Internal); }; - Label::new(prefix).map_err(|_| Error::Plan { - field: Some(self.name.clone()), - reason: Reason::ContextNotLabel, - found: None, - }) + Label::new(prefix) + .map_err(|_| Error::bad_plan(Reason::ContextNotLabel).in_field(&self.name)) } /// What the output adapters need of the field: no context, which is the @@ -649,11 +634,7 @@ fn field_context( name: &str, piece: &ContextPiece<'_>, ) -> Result<(Label, Vec>), Error> { - split_context(piece).ok_or_else(|| Error::Plan { - field: Some(name.to_owned()), - reason: Reason::ContextNotLabel, - found: None, - }) + split_context(piece).ok_or_else(|| Error::bad_plan(Reason::ContextNotLabel).in_field(name)) } /// A refusal of the lowering or the engine's own check, as the field it @@ -759,11 +740,7 @@ impl Plan { // `prefix` refuses a one-segment label, which has nothing to // sit under; a longer one must sit under the first field's. if field.prefix()? != context { - return Err(Error::Plan { - field: Some(field.name.clone()), - reason: Reason::MixedContexts, - found: None, - }); + return Err(Error::bad_plan(Reason::MixedContexts).in_field(&field.name)); } } for field in fields.iter_mut().filter(|field| field.is_target()) { @@ -807,19 +784,13 @@ impl Plan { (None, false) => None, (None, true) => Some(TargetOptions::Json(Default::default())), (Some(TargetOptions::Json(options)), true) => { - options.check().map_err(|_| Error::Plan { - field: Some(field.name.clone()), - reason: Reason::InvalidTarget, - found: None, + options.check().map_err(|_| { + Error::bad_plan(Reason::InvalidTarget).in_field(&field.name) })?; Some(TargetOptions::Json(options)) } (Some(_), false) => { - return Err(Error::Plan { - field: Some(field.name.clone()), - reason: Reason::TargetOptions, - found: None, - }) + return Err(Error::bad_plan(Reason::TargetOptions).in_field(&field.name)) } }; // A null has an equality term and no other, so a sealed null @@ -830,11 +801,7 @@ impl Plan { .iter() .any(|index| index != IndexSpec::Equality.key()) { - return Err(Error::Plan { - field: Some(field.name.clone()), - reason: Reason::SealedNullIndex, - found: None, - }); + return Err(Error::bad_plan(Reason::SealedNullIndex).in_field(&field.name)); } } Self::build(Context::Label(context), fields) @@ -865,11 +832,7 @@ impl Plan { fields: Vec, ) -> Result { let context_field = context_field.into(); - let refuse = |reason| Error::Plan { - field: Some(context_field.clone()), - reason, - found: None, - }; + let refuse = |reason| Error::bad_plan(reason).in_field(&context_field); let Some(field) = fields.iter().find(|field| field.name == context_field) else { return Err(refuse(Reason::NoSuchField)); }; @@ -884,11 +847,7 @@ impl Plan { .iter() .find(|field| field.label.segments().count() != 1) { - return Err(Error::Plan { - field: Some(field.name.clone()), - reason: Reason::ContextNotLabel, - found: None, - }); + return Err(Error::bad_plan(Reason::ContextNotLabel).in_field(&field.name)); } // A target field's label must be a column, `
/`, // which a context field's one-segment identity is not: the table @@ -925,11 +884,7 @@ impl Plan { }; let extension = first.extension.clone(); for (at, field) in fields.iter().enumerate() { - let refuse = |reason| Error::Plan { - field: Some(field.name.clone()), - reason, - found: None, - }; + let refuse = |reason| Error::bad_plan(reason).in_field(&field.name); if fields[..at].iter().any(|prior| prior.name == field.name) { return Err(refuse(Reason::DuplicateField)); } @@ -1357,11 +1312,8 @@ pub fn plan_with( recipher_frame::serde::from_slice(frame).map_err(|e| plan_refusal(&e, frame))?; let mut fields: Vec = Vec::with_capacity(wire.fields.len()); for (name, spec) in wire.fields { - let spec = FieldSpec::try_from(spec).map_err(|reason| Error::Plan { - field: Some(name.clone()), - reason, - found: None, - })?; + let spec = + FieldSpec::try_from(spec).map_err(|reason| Error::bad_plan(reason).in_field(&name))?; let context = super::context::non_empty(spec.context.0).map_err(|e| e.in_field(&name))?; let field = match spec.what { What::Outputs(outputs) => FieldPlan::new(name, context, outputs)?, @@ -1452,7 +1404,7 @@ impl<'de> Deserialize<'de> for PlanWire { /// when it is not an object of that many entries. fn entry_key(frame: &[u8], position: usize) -> Option { let root = Frame::parse(frame).ok()?; - crate::refusal::object_keys(root)?.into_iter().nth(position) + super::found::object_keys(root)?.into_iter().nth(position) } /// The keys a field's spec reads ([`FieldSpecWire`]). @@ -1683,11 +1635,7 @@ fn plan_refusal(error: &recipher_frame::serde::Error, frame: &[u8]) -> Error { } }, }; - Error::Plan { - field: Some(field.clone()), - reason, - found: None, - } + Error::bad_plan(reason).in_field(field) } /// Encrypt a record — or a batch of records — per a plan. @@ -1826,32 +1774,17 @@ pub fn query<'a, K: 'static>( .fields .iter() .find(|candidate| candidate.name == field) - .ok_or_else(|| Error::Plan { - field: Some(field.to_owned()), - reason: Reason::NoSuchField, - found: None, - })?; - let name = field.target().ok_or_else(|| Error::Plan { - field: Some(field.name.clone()), - reason: Reason::NotATarget, - found: None, - })?; - let value = OwnedFrame::of(value).map_err(|_| Error::Source { - field: Some(field.name.clone()), - reason: Reason::FieldType, - found: None, - row: None, - })?; + .ok_or_else(|| Error::bad_plan(Reason::NoSuchField).in_field(field))?; + let name = field + .target() + .ok_or_else(|| Error::bad_plan(Reason::NotATarget).in_field(&field.name))?; + let value = OwnedFrame::of(value) + .map_err(|_| Error::bad_source(Reason::FieldType).in_field(&field.name))?; // A null is queried by the term a field that seals its nulls stores // beside each (#1298), through the type's equality index alone. let value = if value.frame().is_null() { if field.null != Some(NullMode::Sealed) || *index != IndexSpec::Equality { - return Err(Error::Source { - field: Some(field.name.clone()), - reason: Reason::NullQuery, - found: None, - row: None, - }); + return Err(Error::bad_source(Reason::NullQuery).in_field(&field.name)); } value } else { @@ -2098,12 +2031,7 @@ enum Children<'a, T> { impl RecordTree for StackCipherText { fn misfit(field: &str, reason: Reason) -> Error { - Error::Record { - field: Some(field.to_owned()), - row: None, - reason, - found: None, - } + Error::bad_record(reason).in_field(field) } fn is_passthrough(&self) -> bool { @@ -2262,15 +2190,20 @@ pub(super) fn source_rows(source: impl Encrypt, plan: &Plan) -> Result /// names its field and the row of a batch it is in: a repeated key as /// [`Reason::RepeatedKey`], a scalar its logical type does not admit as /// [`Reason::FieldType`], and anything else (too deep or too long for a -/// frame, or a value the source never wrote) as [`Reason::Unframeable`], -/// naming no field when the source left a row of a batch unwritten. A -/// failure of the source's own is [`Error::SourceFailed`], with the field -/// and the row it was reading and its error as the cause. +/// frame, or a value the source never wrote) as [`Reason::Unframeable`]. +/// A refusal that names no field (a row the source left unwritten, or a +/// writer's refusal the source kept and returned after the field ended) +/// cannot say whose value it was, so it is [`Reason::Unframeable`] with the +/// row. A failure of the source's own is [`Error::SourceFailed`], with the +/// field and the row it was reading and its error as the cause. fn split_refusal(SplitRefusal { row, field, error }: SplitRefusal) -> Error { - let reason = match error { + let error = match error { FrameWriteError::Source(cause) => return Error::SourceFailed { field, row, cause }, - FrameWriteError::DuplicateKey => Reason::RepeatedKey, - FrameWriteError::Invalid => Reason::FieldType, + error => error, + }; + let reason = match (error, field.is_some()) { + (FrameWriteError::DuplicateKey, true) => Reason::RepeatedKey, + (FrameWriteError::Invalid, true) => Reason::FieldType, _ => Reason::Unframeable, }; Error::Source { @@ -2282,12 +2215,7 @@ fn split_refusal(SplitRefusal { row, field, error }: SplitRefusal) -> Error { } fn source_row(mut row: Vec<(String, OwnedFrame)>, plan: &Plan) -> Result { - let misfit = |field: &str, reason| Error::Source { - field: Some(field.to_owned()), - row: None, - reason, - found: None, - }; + let misfit = |field: &str, reason| Error::bad_source(reason).in_field(field); let mut values = FieldValues::new(); let mut targets = Vec::new(); let mut absent = Absent::new(); @@ -2355,12 +2283,7 @@ fn source_row(mut row: Vec<(String, OwnedFrame)>, plan: &Plan) -> Result Result { - let misfit = |reason| Error::Source { - field: Some(field.name.clone()), - reason, - found: None, - row: None, - }; + let misfit = |reason| Error::bad_source(reason).in_field(&field.name); let value = match field.field_type { Some(declared) => convert(declared, value.frame()) .map_err(|error| error.in_field(&field.name))? @@ -9189,7 +9112,9 @@ mod tests { } /// A refusal from the split names its field, by its cause. One that - /// names no field and is not the source's own is this module's bug. + /// names no field (a row left unwritten, or a source that kept a + /// writer's refusal and returned it after the field) is the + /// caller's input too: `unframeable`, with the row. #[test] fn a_split_refusal_names_its_field_and_cause() { let refusal = |field: Option<&str>, error| { @@ -9245,12 +9170,13 @@ mod tests { matches!(unwritten.into_crate(), crate::Error::Input(_)), "an input refusal" ); - expect( - &refusal(None, FrameWriteError::Invalid), - "Source", - None, - Reason::FieldType, - ); + for error in [ + FrameWriteError::Invalid, + FrameWriteError::DuplicateKey, + FrameWriteError::TooDeep, + ] { + expect(&refusal(None, error), "Source", None, Reason::Unframeable); + } } /// A source that fails as it is read is refused as @@ -9302,6 +9228,22 @@ mod tests { ); let shown = format!("{message} {fields:?}"); assert!(!shown.contains("marker-value"), "no cause text: {shown}"); + // `Debug`, plain and pretty, shows the field and the row and + // not the cause's text: a log line or a panic does not leak it. + for debug in [format!("{error:?}"), format!("{error:#?}")] { + assert!( + !debug.contains("marker-value"), + "no cause text in Debug: {debug}" + ); + for part in ["SourceFailed", "\"email\"", "SourceError(..)"] { + assert!(debug.contains(part), "{part} in Debug: {debug}"); + } + } + assert_eq!( + format!("{error:?}"), + r#"SourceFailed { field: Some("email"), row: Some(1), cause: SourceError(..) }"#, + "Debug" + ); assert!( matches!(error.into_crate(), crate::Error::Input(_)), "an input error" @@ -9568,6 +9510,54 @@ mod tests { } } + /// A refusal only a query's input meets says so; one a record source + /// meets, or a value of another type in either, says it is the + /// record source that does not fit. + #[test] + fn a_query_refusal_names_the_query_input() { + use Reason::*; + for reason in [ + UnknownOperator, + OperatorNotAnswered, + NotARange, + ExactOperator, + NotAQueryTerm, + NotStats, + NullQuery, + JsonInput, + JsonSyntax, + JsonDuplicateKey, + JsonIntegerRange, + JsonPathPosition, + JsonPathWildcard, + JsonPathNoWildcard, + JsonNoPredicates, + JsonWildcardBoundZero, + JsonUnknownPredicateOp, + ] { + let error = Error::bad_source(reason).in_field("age"); + assert_eq!( + error.to_string(), + format!(r#"query input does not fit the field: {reason} (field "age")"#), + "{reason:?}" + ); + } + for reason in [ + FieldMissing, + UnknownField, + FieldType, + Passthrough, + Unframeable, + ] { + let error = Error::bad_source(reason).in_field("age"); + assert_eq!( + error.to_string(), + format!(r#"record source does not fit the plan: {reason} (field "age")"#), + "{reason:?}" + ); + } + } + /// `in_field` names the field only where none is named yet. #[test] fn in_field_fills_only_an_unnamed_field() { diff --git a/packages/stack-encrypt/src/dynamic/source.rs b/packages/stack-encrypt/src/dynamic/source.rs index 2aebe324b..8ca044cb0 100644 --- a/packages/stack-encrypt/src/dynamic/source.rs +++ b/packages/stack-encrypt/src/dynamic/source.rs @@ -95,9 +95,6 @@ impl Place { } } -/// The place shared by every sink in a split. -type Open<'f> = &'f Place; - /// Where a finished record goes: returned to the caller, or added to a /// batch. trait PutRecord { @@ -118,19 +115,19 @@ impl PutRecord for TopRecord { /// The next record of a batch. Putting it finishes its row. struct BatchRecord<'s> { records: &'s mut Vec, - open: Open<'s>, + place: &'s Place, } impl PutRecord for BatchRecord<'_> { type Ok = (); fn put(self, record: SourceRecord) { self.records.push(record); - self.open.row.set(None); + self.place.row.set(None); } } /// The top of a source. -struct TopSink<'f>(Open<'f>); +struct TopSink<'f>(&'f Place); impl<'f> Sink for TopSink<'f> { type Ok = SplitSource; @@ -152,7 +149,7 @@ impl<'f> Sink for TopSink<'f> { fn seq(self, _: Option) -> Result, FrameWriteError> { Ok(BatchSink { - open: self.0, + place: self.0, records: Vec::new(), begun: 0, }) @@ -171,7 +168,7 @@ impl<'f> Sink for TopSink<'f> { /// source began, so an element whose sink it dropped unwritten, leaving no /// record, is refused rather than shifting the rows after it. struct BatchSink<'f> { - open: Open<'f>, + place: &'f Place, records: Vec, begun: usize, } @@ -183,7 +180,7 @@ impl BatchSink<'_> { if self.records.len() == self.begun { return Ok(()); } - self.open.row.set(Some(self.records.len())); + self.place.row.set(Some(self.records.len())); Err(FrameWriteError::Unwritten) } } @@ -198,13 +195,13 @@ impl<'f> SeqSink for BatchSink<'f> { fn element(&mut self) -> Result, FrameWriteError> { self.check_written()?; - self.open.row.set(Some(self.begun)); + self.place.row.set(Some(self.begun)); self.begun += 1; Ok(ElementSink { - open: self.open, + place: self.place, record: BatchRecord { records: &mut self.records, - open: self.open, + place: self.place, }, }) } @@ -218,7 +215,7 @@ impl<'f> SeqSink for BatchSink<'f> { /// One element of a batch. A map is a record. Anything else is not a /// record, and the sink reads past its content. struct ElementSink<'f, 's> { - open: Open<'f>, + place: &'f Place, record: BatchRecord<'s>, } @@ -245,7 +242,7 @@ impl<'f, 's> Sink for ElementSink<'f, 's> { } fn map(self, _: Option) -> Result>, FrameWriteError> { - Ok(RecordMap::new(self.open, self.record)) + Ok(RecordMap::new(self.place, self.record)) } fn passthrough(self, _: &P) -> Result<(), FrameWriteError> { @@ -346,7 +343,7 @@ impl MapSink for Discard { /// One record's fields, each value written into its own frame. struct RecordMap<'f, O> { - open: Open<'f>, + place: &'f Place, out: O, // The keys are field names. Field names are not secret, so they are // not wiped. @@ -354,9 +351,9 @@ struct RecordMap<'f, O> { } impl<'f, O> RecordMap<'f, O> { - fn new(open: Open<'f>, out: O) -> Self { + fn new(place: &'f Place, out: O) -> Self { Self { - open, + place, out, entries: Vec::new(), } @@ -372,7 +369,7 @@ impl<'f, O: PutRecord> MapSink for RecordMap<'f, O> { Self: 's; fn entry(&mut self, key: &str) -> Result, FrameWriteError> { - *self.open.field.borrow_mut() = Some(key.to_owned()); + *self.place.field.borrow_mut() = Some(key.to_owned()); self.entries.push((key.to_owned(), Buffer::new())); let buffer = match self.entries.last_mut() { Some((_, buffer)) => buffer, @@ -381,7 +378,7 @@ impl<'f, O: PutRecord> MapSink for RecordMap<'f, O> { }; Ok(FieldWriter { writer: FrameWriter::new(buffer), - open: self.open, + place: self.place, }) } @@ -391,7 +388,7 @@ impl<'f, O: PutRecord> MapSink for RecordMap<'f, O> { // A source that dropped an entry's sink without writing to it // left no frame. let value = OwnedFrame::from_buffer(buffer).map_err(|_| { - *self.open.field.borrow_mut() = Some(key.clone()); + *self.place.field.borrow_mut() = Some(key.clone()); FrameWriteError::Unwritten })?; record.push((key, value)); @@ -406,7 +403,7 @@ impl<'f, O: PutRecord> MapSink for RecordMap<'f, O> { /// neither. struct FieldWriter<'s, 'f> { writer: FrameWriter<'s>, - open: Open<'f>, + place: &'f Place, } impl<'s, 'f> Sink for FieldWriter<'s, 'f> { @@ -417,33 +414,33 @@ impl<'s, 'f> Sink for FieldWriter<'s, 'f> { fn scalar(self, logical: Option, value: Physical<'_>) -> Result<(), FrameWriteError> { self.writer.scalar(logical, value)?; - self.open.field_done(); + self.place.field_done(); Ok(()) } fn typed_null(self, ty: FixedType) -> Result<(), FrameWriteError> { self.writer.typed_null(ty)?; - self.open.field_done(); + self.place.field_done(); Ok(()) } fn seq(self, len: Option) -> Result, FrameWriteError> { Ok(FieldSeq { inner: self.writer.seq(len)?, - open: self.open, + place: self.place, }) } fn map(self, len: Option) -> Result, FrameWriteError> { Ok(FieldMap { inner: self.writer.map(len)?, - open: self.open, + place: self.place, }) } fn passthrough(self, value: &P) -> Result<(), FrameWriteError> { self.writer.passthrough(value)?; - self.open.field_done(); + self.place.field_done(); Ok(()) } } @@ -451,7 +448,7 @@ impl<'s, 'f> Sink for FieldWriter<'s, 'f> { /// A field's value that is a sequence: finished when the sequence ends. struct FieldSeq<'s, 'f> { inner: FrameSeq<'s>, - open: Open<'f>, + place: &'f Place, } impl<'s> SeqSink for FieldSeq<'s, '_> { @@ -468,7 +465,7 @@ impl<'s> SeqSink for FieldSeq<'s, '_> { fn end(self) -> Result<(), FrameWriteError> { self.inner.end()?; - self.open.field_done(); + self.place.field_done(); Ok(()) } } @@ -476,7 +473,7 @@ impl<'s> SeqSink for FieldSeq<'s, '_> { /// A field's value that is a map: finished when the map ends. struct FieldMap<'s, 'f> { inner: FrameMap<'s>, - open: Open<'f>, + place: &'f Place, } impl<'s> MapSink for FieldMap<'s, '_> { @@ -493,7 +490,7 @@ impl<'s> MapSink for FieldMap<'s, '_> { fn end(self) -> Result<(), FrameWriteError> { self.inner.end()?; - self.open.field_done(); + self.place.field_done(); Ok(()) } } diff --git a/packages/stack-encrypt/src/refusal.rs b/packages/stack-encrypt/src/refusal.rs index 2c782e2f2..6033e9bcd 100644 --- a/packages/stack-encrypt/src/refusal.rs +++ b/packages/stack-encrypt/src/refusal.rs @@ -20,13 +20,9 @@ allow(dead_code, rustdoc::broken_intra_doc_links) )] -use std::cell::{Cell, RefCell}; use std::fmt; -use vitaminc_aead::frame::{Frame, FrameWriteError}; -use vitaminc_aead::plaintext::{ - Encrypt as _, EncryptRef, FixedType, Logical, MapSink, Physical, SeqSink, Sink, ValueKind, -}; +use vitaminc_aead::plaintext::ValueKind; use crate::target::IndexSpec; @@ -84,7 +80,11 @@ use crate::target::IndexSpec; /// [`UntypedIndex`](Error::UntypedIndex) the field (`field`), `Target` and /// `Cipher` carry the payload of the error they hold, and `Internal` carries /// none. A binding reads `reason` when it is there, and does not require it. -#[derive(Debug, thiserror::Error, miette::Diagnostic)] +/// +/// `Debug` shows every field as a derived `Debug` would, except the cause of +/// [`SourceFailed`](Error::SourceFailed), which it shows as `SourceError(..)`: +/// a host's error can quote the value it failed on. +#[derive(thiserror::Error, miette::Diagnostic)] #[non_exhaustive] pub enum Error { /// A value used as an encryption context is not one — a boolean, float, @@ -172,10 +172,7 @@ pub enum Error { /// values to verify that holds a value of another type, or statistics /// or a term that are not what [`target_limit`](crate::dynamic::target_limit) reads — the same shape of /// refusal as a mistyped field, naming the field. - #[error( - "record source does not fit the plan: {}", - misfit_text(Subject::Source, *reason, *found, *row, field) - )] + #[error("{}", source_text(*reason, *found, *row, field))] #[diagnostic(code(stack_encrypt::dynamic_source))] Source { /// The source field at fault, if the fault is one field's. @@ -194,8 +191,9 @@ pub enum Error { /// of its own as it described itself, such as a host getter that threw, /// or a JSON document nested too deep. The value's own error is the /// cause ([`source`](std::error::Error::source)). It is not in the - /// message, because a host's error can quote the value it failed on. - /// Its reason is [`Reason::SourceFailed`]. + /// message, because a host's error can quote the value it failed on, + /// nor in `Debug`, which shows it as `SourceError(..)`. Its reason is + /// [`Reason::SourceFailed`]. #[error("record source failed while it was read{}", place_text(*row, field))] #[diagnostic( code(stack_encrypt::dynamic_source_failed), @@ -290,6 +288,85 @@ pub enum Error { Cipher(#[from] crate::Error), } +impl fmt::Debug for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Context { field, reason } => f + .debug_struct("Context") + .field("field", field) + .field("reason", reason) + .finish(), + Self::Term { field, kind } => f + .debug_struct("Term") + .field("field", field) + .field("kind", kind) + .finish(), + Self::Plan { + field, + reason, + found, + } => f + .debug_struct("Plan") + .field("field", field) + .field("reason", reason) + .field("found", found) + .finish(), + Self::UntypedIndex { field } => f + .debug_struct("UntypedIndex") + .field("field", field) + .finish(), + Self::Source { + field, + row, + reason, + found, + } => f + .debug_struct("Source") + .field("field", field) + .field("row", row) + .field("reason", reason) + .field("found", found) + .finish(), + // The cause is the host's own error, which can quote the value + // it failed on: it is reached through `source()`, never shown. + Self::SourceFailed { field, row, .. } => f + .debug_struct("SourceFailed") + .field("field", field) + .field("row", row) + .field("cause", &format_args!("SourceError(..)")) + .finish(), + Self::Record { + field, + row, + reason, + found, + } => f + .debug_struct("Record") + .field("field", field) + .field("row", row) + .field("reason", reason) + .field("found", found) + .finish(), + Self::Predicate { + field, + reason, + construct, + at, + } => f + .debug_struct("Predicate") + .field("field", field) + .field("reason", reason) + .field("construct", construct) + .field("at", at) + .finish(), + Self::Internal => f.write_str("Internal"), + #[cfg(feature = "dynamic")] + Self::Target(error) => f.debug_tuple("Target").field(error).finish(), + Self::Cipher(error) => f.debug_tuple("Cipher").field(error).finish(), + } + } +} + /// ` (field "age")`, or nothing: the tail of an input error's message. fn in_field_text(field: &Option) -> String { field @@ -308,6 +385,55 @@ fn place_text(row: Option, field: &Option) -> String { } } +/// A source error's message: "query input does not fit the field" for a +/// refusal only a query's input meets ([`answers_a_query`]), and "record +/// source does not fit the plan" for the rest. +fn source_text( + reason: Reason, + found: Option, + row: Option, + field: &Option, +) -> String { + let what = if answers_a_query(reason) { + "query input does not fit the field" + } else { + "record source does not fit the plan" + }; + format!( + "{what}: {}", + misfit_text(Subject::Source, reason, found, row, field) + ) +} + +/// Whether a source refusal's reason is one only a query's input meets: an +/// operator, a range, a term, statistics, a null query, or a JSON +/// operator's input. A value that cannot be read as the field's type is +/// [`Reason::FieldType`] for a query and a record alike, and keeps the +/// record's words. +fn answers_a_query(reason: Reason) -> bool { + use Reason::*; + matches!( + reason, + UnknownOperator + | OperatorNotAnswered + | NotARange + | ExactOperator + | NotAQueryTerm + | NotStats + | NullQuery + | JsonInput + | JsonSyntax + | JsonDuplicateKey + | JsonIntegerRange + | JsonPathPosition + | JsonPathWildcard + | JsonPathNoWildcard + | JsonNoPredicates + | JsonWildcardBoundZero + | JsonUnknownPredicateOp + ) +} + /// What a plan, source or stored-record error is about. #[derive(Clone, Copy)] enum Subject { @@ -375,7 +501,6 @@ impl Error { } /// A stored-record error with no field named yet. - #[cfg(test)] pub(crate) fn bad_record(reason: Reason) -> Self { Self::Record { field: None, @@ -851,55 +976,6 @@ impl Found { Self::Unknown => "unknown", } } - - /// What a scalar is, from how it describes itself. - pub(crate) fn scalar(logical: Option, value: &Physical<'_>) -> Self { - match (ValueKind::of(logical, value), logical, value) { - (Some(kind), _, _) => Self::Kind(kind), - (None, Some(Logical::Undefined), _) => Self::Undefined, - (None, None, Physical::Null) => Self::Null, - (None, _, _) => Self::Unknown, - } - } - - /// What a frame holds, reading no more of it than its first node. - pub(crate) fn of_frame(frame: Frame<'_>) -> Self { - if let Some(kind) = frame.kind() { - return Self::Kind(kind); - } - if frame.is_null() { - return Self::Null; - } - // A passthrough, `undefined` or a logical type this build does not - // know: one node, which the probe reads without walking inside it. - let found = Cell::new(None); - let _ = frame.visit(Probe::noting(&found, None)); - found.get().unwrap_or(Self::Unknown) - } - - /// What the entry under `key` holds, for a frame that is an object with - /// one, and the entry's own keys, in order, when it is an object too. - /// `None` for a frame that is not an object or has no such key. - pub(crate) fn of_entry(frame: Frame<'_>, key: &str) -> Option<(Self, Vec)> { - let found = Cell::new(None); - let keys = RefCell::new(Vec::new()); - let _ = frame.visit(Lookup { - key, - found: &found, - keys: &keys, - }); - found.get().map(|found| (found, keys.into_inner())) - } -} - -/// The keys of an object frame, in order; `None` for a frame that is not an -/// object. Read with the probe, so a value the frame reader refuses to read, -/// such as a typed null, does not hide the keys beside it. -pub(crate) fn object_keys(frame: Frame<'_>) -> Option> { - let found = Cell::new(None); - let keys = RefCell::new(Vec::new()); - let _ = frame.visit(Probe::noting(&found, Some(&keys))); - (found.get() == Some(Found::Kind(ValueKind::Object))).then(|| keys.into_inner()) } impl fmt::Display for Found { @@ -917,165 +993,3 @@ impl fmt::Display for Found { } } } - -/// A sink that reads past a value and keeps none of it: where it is given -/// a cell, it notes what kind of value the node is, and where it is given -/// a list, the keys of an object it is. Children are read past with -/// neither, so nothing inside a container is noted, and no value is copied. -struct Probe<'c> { - found: Option<&'c Cell>>, - keys: Option<&'c RefCell>>, -} - -impl<'c> Probe<'c> { - /// A probe that notes the node's kind, and its keys if `keys` is given. - fn noting(found: &'c Cell>, keys: Option<&'c RefCell>>) -> Self { - Self { - found: Some(found), - keys, - } - } - - /// A probe that reads past a node and notes nothing. - fn past() -> Self { - Self { - found: None, - keys: None, - } - } - - fn note(&self, found: Found) { - if let Some(cell) = self.found { - cell.set(Some(found)); - } - } -} - -impl<'c> Sink for Probe<'c> { - type Ok = (); - type Error = FrameWriteError; - type Seq = Probe<'c>; - type Map = Probe<'c>; - - fn scalar(self, logical: Option, value: Physical<'_>) -> Result<(), FrameWriteError> { - self.note(Found::scalar(logical, &value)); - Ok(()) - } - - fn typed_null(self, _: FixedType) -> Result<(), FrameWriteError> { - self.note(Found::Null); - Ok(()) - } - - fn seq(self, _: Option) -> Result, FrameWriteError> { - self.note(Found::Kind(ValueKind::Array)); - Ok(Probe::past()) - } - - fn map(self, _: Option) -> Result, FrameWriteError> { - self.note(Found::Kind(ValueKind::Object)); - // The map's entries are read with the keys list, to note their keys. - Ok(Probe { - found: None, - keys: self.keys, - }) - } - - fn passthrough(self, _: &P) -> Result<(), FrameWriteError> { - self.note(Found::Passthrough); - Ok(()) - } -} - -impl<'c> SeqSink for Probe<'c> { - type Ok = (); - type Error = FrameWriteError; - type Element<'e> - = Probe<'c> - where - Self: 'e; - - fn element(&mut self) -> Result, FrameWriteError> { - Ok(Probe::past()) - } - - fn end(self) -> Result<(), FrameWriteError> { - Ok(()) - } -} - -impl<'c> MapSink for Probe<'c> { - type Ok = (); - type Error = FrameWriteError; - type Entry<'e> - = Probe<'c> - where - Self: 'e; - - fn entry(&mut self, key: &str) -> Result, FrameWriteError> { - if let Some(keys) = self.keys { - keys.borrow_mut().push(key.to_owned()); - } - Ok(Probe::past()) - } - - fn end(self) -> Result<(), FrameWriteError> { - Ok(()) - } -} - -/// A sink that notes what kind of value one entry of an object is, and its -/// keys if it is an object, and reads past everything else. -struct Lookup<'k, 'c> { - key: &'k str, - found: &'c Cell>, - keys: &'c RefCell>, -} - -impl<'k, 'c> Sink for Lookup<'k, 'c> { - type Ok = (); - type Error = FrameWriteError; - type Seq = Probe<'c>; - type Map = Lookup<'k, 'c>; - - fn scalar(self, _: Option, _: Physical<'_>) -> Result<(), FrameWriteError> { - Ok(()) - } - - fn typed_null(self, _: FixedType) -> Result<(), FrameWriteError> { - Ok(()) - } - - fn seq(self, _: Option) -> Result, FrameWriteError> { - Ok(Probe::past()) - } - - fn map(self, _: Option) -> Result { - Ok(self) - } - - fn passthrough(self, _: &P) -> Result<(), FrameWriteError> { - Ok(()) - } -} - -impl<'c> MapSink for Lookup<'_, 'c> { - type Ok = (); - type Error = FrameWriteError; - type Entry<'e> - = Probe<'c> - where - Self: 'e; - - fn entry(&mut self, key: &str) -> Result, FrameWriteError> { - if key == self.key { - Ok(Probe::noting(self.found, Some(self.keys))) - } else { - Ok(Probe::past()) - } - } - - fn end(self) -> Result<(), FrameWriteError> { - Ok(()) - } -} From fcd4fc958bd351ddda715d22aefc4fe1c3a01ffd Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sat, 28 Nov 2026 19:01:02 +1100 Subject: [PATCH 08/14] docs(stack-encrypt): say in plain words what an input error names The doc comments on `Error`, `Reason` and `Found`, and on the helpers that find the kind of a value, packed several ideas into each sentence and used terms they did not explain. A reader who was not part of the work could not follow them. The comments now use short sentences and lists. They explain a term where it first appears, such as "record source", "transport frame" and "passthrough". They state the rule for when an error names a kind of value: only when the engine can read the kind without decrypting anything. Only comments change. No code, message text or reason code changes. --- packages/stack-encrypt/src/dynamic/found.rs | 103 ++++-- packages/stack-encrypt/src/refusal.rs | 331 +++++++++++++------- 2 files changed, 289 insertions(+), 145 deletions(-) diff --git a/packages/stack-encrypt/src/dynamic/found.rs b/packages/stack-encrypt/src/dynamic/found.rs index 824b03fee..61b2dc976 100644 --- a/packages/stack-encrypt/src/dynamic/found.rs +++ b/packages/stack-encrypt/src/dynamic/found.rs @@ -1,7 +1,21 @@ -//! What a value an input error is about is, read from the value itself: -//! [`Found`] for a scalar a source describes, a frame, or one entry of an -//! object frame, and the keys of an object frame. The sinks here read past -//! every value and copy none of it. +//! Finds the kind of a value for an input error, without copying the value. +//! +//! An input error names the kind of value that the caller passed, as a +//! [`Found`]. This module reads that kind from three places: +//! +//! - A scalar, as a record source describes it ([`Found::scalar`]). +//! - A frame ([`Found::of_frame`]). A frame is the binary encoding of one +//! value. +//! - One entry of a frame that is an object ([`Found::of_entry`]). +//! +//! The module also lists the keys of a frame that is an object +//! ([`object_keys`]). +//! +//! The code reads each value through vitaminc's [`Sink`] trait. A value +//! describes itself by calling the methods of a `Sink`. The two sinks in +//! this module are [`Probe`] and [`Lookup`]. Both sinks record the kind of +//! a value and the keys of an object. Neither sink copies any part of a +//! value. use std::cell::{Cell, RefCell}; @@ -13,10 +27,15 @@ use vitaminc_aead::plaintext::{ use crate::refusal::Found; impl Found { - /// What a scalar is, from how it describes itself: its kind, or - /// `undefined`, or a logical type this build does not know. A logical - /// type over a value it does not admit is named by the value's own - /// physical kind, as null, a string, an int32 and so on. + /// The kind of a scalar, from the logical type and the physical value + /// that the scalar reports. + /// + /// The result is the scalar's [`ValueKind`], [`Found::Undefined`], or + /// [`Found::Unknown`] for a logical type that this build does not + /// define. A logical type can come with a physical value that the type + /// does not allow, such as a date with a string value. The result is + /// then the kind of the physical value, such as a null, a string, or an + /// int32. pub(crate) fn scalar(logical: Option, value: &Physical<'_>) -> Self { if let Some(kind) = ValueKind::of(logical, value) { return Self::Kind(kind); @@ -28,7 +47,8 @@ impl Found { } } - /// What a frame holds, reading no more of it than its first node. + /// The kind of the value in a frame. Reads only the first node of the + /// frame. pub(crate) fn of_frame(frame: Frame<'_>) -> Self { if let Some(kind) = frame.kind() { return Self::Kind(kind); @@ -36,16 +56,21 @@ impl Found { if frame.is_null() { return Self::Null; } - // A passthrough, `undefined` or a logical type this build does not - // know: one node, which the probe reads without walking inside it. + // The frame is a passthrough, `undefined`, or a scalar of a logical + // type that this build does not define. Each is one node. `Probe` + // records the kind of the node and reads nothing inside it. let found = Cell::new(None); let _ = frame.visit(Probe::noting(&found, None)); found.get().unwrap_or(Self::Unknown) } - /// What the entry under `key` holds, for a frame that is an object with - /// one, and the entry's own keys, in order, when it is an object too. - /// `None` for a frame that is not an object or has no such key. + /// The kind of the value under `key` in a frame that is an object. + /// + /// When that value is an object too, the result also lists its keys, in + /// order. For a value of any other kind, the list of keys is empty. + /// + /// Returns `None` when the frame is not an object, or has no entry + /// under `key`. pub(crate) fn of_entry(frame: Frame<'_>, key: &str) -> Option<(Self, Vec)> { let found = Cell::new(None); let keys = RefCell::new(Vec::new()); @@ -58,9 +83,13 @@ impl Found { } } -/// The keys of an object frame, in order; `None` for a frame that is not an -/// object. Read with the probe, so a value the frame reader refuses to read, -/// such as a typed null, does not hide the keys beside it. +/// The keys of a frame that is an object, in order. Returns `None` when +/// the frame is not an object. +/// +/// The function reads the frame with [`Probe`], and not with the serde +/// frame reader. The serde frame reader returns an error at a value that it +/// does not read. An example is a typed null: a null that records a type. +/// `Probe` reads every value, so the function returns every key. pub(crate) fn object_keys(frame: Frame<'_>) -> Option> { let found = Cell::new(None); let keys = RefCell::new(Vec::new()); @@ -68,17 +97,22 @@ pub(crate) fn object_keys(frame: Frame<'_>) -> Option> { (found.get() == Some(Found::Kind(ValueKind::Object))).then(|| keys.into_inner()) } -/// A sink that reads past a value and keeps none of it: where it is given -/// a cell, it notes what kind of value the node is, and where it is given -/// a list, the keys of an object it is. Children are read past with -/// neither, so nothing inside a container is noted, and no value is copied. +/// A [`Sink`] that reads a value and copies no part of it. +/// +/// - With `found` set, the probe stores the kind of the value there. +/// - With `keys` set, the probe adds the keys of the value there, when the +/// value is an object. +/// +/// The probe reads the children of a list or an object with neither set. +/// So the probe records nothing about a value inside a container. struct Probe<'c> { found: Option<&'c Cell>>, keys: Option<&'c RefCell>>, } impl<'c> Probe<'c> { - /// A probe that notes the node's kind, and its keys if `keys` is given. + /// A probe that stores the kind of the value in `found`. With `keys` + /// given, the probe also stores the keys of an object there. fn noting(found: &'c Cell>, keys: Option<&'c RefCell>>) -> Self { Self { found: Some(found), @@ -86,7 +120,7 @@ impl<'c> Probe<'c> { } } - /// A probe that reads past a node and notes nothing. + /// A probe that reads a value and records nothing. fn past() -> Self { Self { found: None, @@ -124,7 +158,8 @@ impl<'c> Sink for Probe<'c> { fn map(self, _: Option) -> Result, FrameWriteError> { self.note(Found::Kind(ValueKind::Object)); - // The map's entries are read with the keys list, to note their keys. + // The probe for the entries has the `keys` list, so that it records + // each key. Ok(Probe { found: None, keys: self.keys, @@ -174,8 +209,11 @@ impl<'c> MapSink for Probe<'c> { } } -/// A sink that notes what kind of value one entry of an object is, and its -/// keys if it is an object, and reads past everything else. +/// A [`Sink`] for an object that records one entry: the entry under `key`. +/// +/// The sink stores the kind of the value of that entry in `found`. When +/// the value is an object, the sink stores its keys in `keys`. The sink +/// reads every other entry and records nothing about it. struct Lookup<'k, 'c> { key: &'k str, found: &'c Cell>, @@ -235,9 +273,11 @@ mod tests { use super::*; use vitaminc_aead::plaintext::{Int, Raw}; - /// A scalar is named by its kind, `undefined`, or a logical type this - /// build does not know. A known logical type over a value it does not - /// admit is named by the value's own physical kind, never as unknown. + /// [`Found::scalar`] returns the kind of a scalar, `Undefined`, or + /// `Unknown` for a logical type that this build does not define. For a + /// known logical type with a physical value that the type does not + /// allow, the result is the kind of the physical value. The result is + /// never `Unknown`. #[test] fn a_scalar_is_named_by_what_it_is() { let unknown = Logical::from_wire(200, 0).expect("an unknown logical type"); @@ -271,8 +311,9 @@ mod tests { } } - /// Through a record source: a batch row that is a date over a null is - /// a null, not a value of a type this build does not know. + /// The same rule applies through a record source. A row of a batch has + /// the logical type date and a null value. `split_source` reports the + /// row as a null, and not as `Unknown`. #[test] fn a_row_that_is_a_known_logical_over_a_null_is_a_null() { struct Rows; diff --git a/packages/stack-encrypt/src/refusal.rs b/packages/stack-encrypt/src/refusal.rs index 6033e9bcd..2242266b5 100644 --- a/packages/stack-encrypt/src/refusal.rs +++ b/packages/stack-encrypt/src/refusal.rs @@ -58,32 +58,55 @@ use crate::target::IndexSpec; /// [`read`](crate::dynamic::read)); [`in_field`](Self::in_field) names it /// from the caller's side. /// -/// Where a plan, a record to encrypt or a stored record is not the object -/// the operation takes, the error says what it found instead: its kind -/// ([`Found`]), never the value. It is in the message, in -/// [`found`](Self::found) and in the payload (`found`). The kind is always -/// one the caller sent, or one the stored record's own structure shows; an -/// error about a decrypted value never names what it opened as. Where the -/// error is about one row of a batch's shape, or about a value the source -/// failed or the frame writer refused while the rows were read, it names -/// the row by its position, from 0: in the message, in [`row`](Self::row) -/// and in the payload (`row`). A field's own misfit (missing, unknown, of -/// another type) names the field and not the row. +/// Some operations take an object: a plan, a record to encrypt, or a +/// stored record to decrypt. When the caller passes another kind of value, +/// the error names that kind as a [`Found`]. For example, the error says +/// that the record is a null or an array. The error never includes the +/// value. The kind is in the message, in [`found`](Self::found), and in the +/// payload field `found`. /// -/// Not every variant has a [`Reason`]. [`Context`](Error::Context), -/// [`Plan`](Error::Plan), [`Source`](Error::Source), -/// [`SourceFailed`](Error::SourceFailed), [`Record`](Error::Record) and -/// [`Predicate`](Error::Predicate) do: it is -/// in the message, in [`reason`](Self::reason) and in the payload +/// An error names a kind only when the engine can read that kind without +/// decrypting anything. There are two such kinds: +/// +/// - The kind of a value the caller sent. +/// - The kind of a node in the unencrypted structure of a stored record, +/// such as a list, an encrypted value, or a passthrough. A passthrough +/// is a value stored without encryption. +/// +/// An error about a decrypted value never names the kind that the value +/// decrypted to. That kind was inside the ciphertext, so the kind is part +/// of the plaintext. +/// +/// When the input is a batch, some errors name the row by its position, +/// counted from 0. The row is in the message, in [`row`](Self::row), and in +/// the payload field `row`. An error names the row in any of these cases: +/// +/// - The row is not an object. +/// - A value in the row returned an error of its own while the engine read +/// it ([`SourceFailed`](Error::SourceFailed)). +/// - The engine could not copy a value in the row. For example, the value +/// repeats a map key, does not fit its logical type, or is nested too +/// deep. +/// +/// An error from comparing the fields of a row with the plan names the +/// field and no row. Examples are a missing field, a field that the plan +/// does not name, and a value of another type than the field declares. +/// +/// Not every variant has a [`Reason`]. These variants have one: +/// [`Context`](Error::Context), [`Plan`](Error::Plan), +/// [`Source`](Error::Source), [`SourceFailed`](Error::SourceFailed), +/// [`Record`](Error::Record), and [`Predicate`](Error::Predicate). The +/// reason is in the message, in [`reason`](Self::reason), and in the payload /// (`reason`). The others carry their own payload fields instead: /// [`Term`](Error::Term) names the index it was asked for (`index`), /// [`UntypedIndex`](Error::UntypedIndex) the field (`field`), `Target` and /// `Cipher` carry the payload of the error they hold, and `Internal` carries /// none. A binding reads `reason` when it is there, and does not require it. /// -/// `Debug` shows every field as a derived `Debug` would, except the cause of -/// [`SourceFailed`](Error::SourceFailed), which it shows as `SourceError(..)`: -/// a host's error can quote the value it failed on. +/// `Debug` prints every field as a derived `Debug` would, with one +/// exception. For [`SourceFailed`](Error::SourceFailed), `Debug` prints the +/// cause as `SourceError(..)`. The cause is an error from the caller's own +/// code. The text of that error can include the value that failed. #[derive(thiserror::Error, miette::Diagnostic)] #[non_exhaustive] pub enum Error { @@ -121,14 +144,23 @@ pub enum Error { kind: IndexSpec, }, - /// A record plan is malformed: not one transport frame, not an object - /// of field specs, empty, missing or duplicating an output, carrying a - /// key that is not `"context"`, `"outputs"`, `"target"` or `"type"`, - /// naming a type that - /// is not one, asking for an index its declared type is not defined - /// for, giving a field a context that is not a label a plan can - /// seal it under, or declaring what no plan allows (two fields - /// under one identity, fields under different contexts). + /// A record plan is malformed. The [`Reason`] names the rule that the + /// plan breaks. For example: + /// + /// - The bytes are not one transport frame. A transport frame is the + /// binary encoding of one value. + /// - The plan is not an object of field specs, or the plan is empty. A + /// field spec is the entry that describes one field. + /// - A field has no output, or lists an output twice. + /// - A field spec has a key that is not `"context"`, `"outputs"`, + /// `"target"`, or `"type"`. + /// - A field names a type that does not exist. + /// - A field asks for an index that is not defined for its declared + /// type. + /// - A field's context is not a label that a plan can encrypt the field + /// under. + /// - The plan declares two fields under one identity, or fields under + /// different contexts. No plan allows either. #[error( "record plan is malformed: {}", misfit_text(Subject::Plan, *reason, *found, None, field) @@ -139,8 +171,9 @@ pub enum Error { field: Option, /// What was wrong with the plan. reason: Reason, - /// What the plan, or the field's spec, is instead of an object: - /// set with [`Reason::NotAnObject`]. + /// The kind of value that the plan or the field spec is, when it + /// is not an object. `Some` only when `reason` is + /// [`Reason::NotAnObject`]. found: Option, }, @@ -161,64 +194,100 @@ pub enum Error { field: String, }, - /// A record source does not fit its plan: not an object (or an array of - /// them, the row then named), a field the plan does not name, a plan - /// field the source does not carry or carries twice, or a passthrough or a repeated map key - /// under a field the plan seals, or a value of another type than its - /// field declares that does not convert to it exactly, or `undefined` - /// for a field that declares a type. Also a query its field does not answer: an operator - /// the field's type does not answer, an input that cannot be read as the - /// field's type ([`read`](crate::dynamic::read)) or is not the pair a range takes, a page of - /// values to verify that holds a value of another type, or statistics - /// or a term that are not what [`target_limit`](crate::dynamic::target_limit) reads — the same shape of - /// refusal as a mistyped field, naming the field. + /// A record source, or the input of a query, does not match the plan. + /// + /// A record source is the value that the caller asks to encrypt: one + /// record, or an array of records. A record source gets this error in + /// any of these cases: + /// + /// - The source is not an object or an array of objects. For an array, + /// the error names the row that is not an object. + /// - The source has a field that the plan does not name. + /// - The source lacks a field that the plan names, or has that field + /// twice. + /// - A field that the plan encrypts contains a passthrough, or a map + /// that repeats a key. A passthrough is a value marked to be stored + /// without encryption. + /// - A value has another type than its field declares, with no exact + /// conversion to that type. + /// - A field that declares a type has the value `undefined`. + /// + /// The input of a query also gets this error. The error names the + /// field. The cases are: + /// + /// - The field's type does not support the operator. + /// - The input cannot be read as the field's type + /// ([`read`](crate::dynamic::read)), or is not the pair of values + /// that a range takes. + /// - A page of values to verify contains a value of another type. + /// - The statistics or the term are not the ones that + /// [`target_limit`](crate::dynamic::target_limit) reads. #[error("{}", source_text(*reason, *found, *row, field))] #[diagnostic(code(stack_encrypt::dynamic_source))] Source { /// The source field at fault, if the fault is one field's. field: Option, - /// The row of a batch at fault, from 0, if the fault is one row's - /// shape or a value the frame writer refused as the rows were read. + /// The position of the row in a batch, counted from 0. `Some` when + /// the row is not an object, or when the engine could not copy a + /// value in the row. 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`]. + /// 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`]. found: Option, }, - /// A record source failed while it was read: a value reported a failure - /// of its own as it described itself, such as a host getter that threw, - /// or a JSON document nested too deep. The value's own error is the - /// cause ([`source`](std::error::Error::source)). It is not in the - /// message, because a host's error can quote the value it failed on, - /// nor in `Debug`, which shows it as `SourceError(..)`. Its reason is - /// [`Reason::SourceFailed`]. + /// A value in the record source returned an error of its own while the + /// engine read it. + /// + /// Examples are a property getter in the caller's language that throws, + /// and a JSON document that is nested too deep. The value's error is + /// the cause of this error, and + /// [`source`](std::error::Error::source) returns it. + /// + /// The message and `Debug` leave the cause out, because the text of the + /// caller's error can include the value. `Debug` prints the cause as + /// `SourceError(..)`. The reason is [`Reason::SourceFailed`]. #[error("record source failed while it was read{}", place_text(*row, field))] #[diagnostic( code(stack_encrypt::dynamic_source_failed), help("The value's own error is this error's cause. It is left out of the message, because it can quote the value.") )] SourceFailed { - /// The field whose value was being read, if one was. + /// The field whose value the engine was reading. `None` when the + /// error happened outside the value of any field. field: Option, - /// The row of a batch being read, from 0, if the source is a batch. + /// The position of the row that the engine was reading, counted + /// from 0. `None` when the source is one record, or when the error + /// happened between two rows. row: Option, - /// The value's own error. + /// The error that the value returned. #[source] cause: vitaminc_aead::plaintext::SourceError, }, - /// A stored record does not fit its plan: not a map (or a sequence of - /// them, the row then named), a ciphertext-bearing field that is absent - /// or given twice, or has no `"c"` node or two of them, a repeated map key under `"c"`, a - /// passthrough under `"c"` — which would hand back unauthenticated - /// bytes as if they had been opened — or a passthrough field that is - /// absent, carries no `"passthrough"` node, or carries a value of - /// another type than it declares. A sealed field that opens to a value - /// of another type than it declares fails the pending instead - /// ([`PlanError::FieldType`](crate::PlanError::FieldType)): the type tag - /// is inside the AEAD envelope. + /// A stored record to decrypt does not match the plan, in one of these + /// ways: + /// + /// - The record is not a map or a sequence of maps. For a sequence, the + /// error names the row that is not a map. + /// - A field with a ciphertext output is absent, or is given twice. + /// - A field with a ciphertext output has no `"c"` node, or has two. + /// The `"c"` node contains the ciphertext. + /// - A map under `"c"` repeats a key. + /// - A passthrough is under `"c"`. A passthrough is an unencrypted + /// value. The engine refuses it, because the caller would get + /// unauthenticated bytes back as if the engine had decrypted them. + /// - A passthrough field is absent, has no `"passthrough"` node, or has + /// a value of another type than the field declares. + /// + /// An encrypted field can decrypt to a value of another type than the + /// field declares. That fault is not this error, because the type tag + /// is inside the ciphertext. The [`Pending`](crate::Pending) operation + /// fails with [`PlanError::FieldType`](crate::PlanError::FieldType) + /// instead. #[error( "stored record does not fit the plan: {}", misfit_text(Subject::Record, *reason, *found, *row, field) @@ -227,13 +296,14 @@ pub enum Error { Record { /// The stored field at fault, if the fault is one field's. field: Option, - /// The row of a batch at fault, from 0, if the fault is one row's - /// shape. + /// The position of the row in a batch, counted from 0. `Some` when + /// the row is not a map. row: Option, /// What was wrong with the stored record. reason: Reason, - /// What the stored record, or the row, is instead of an object of - /// stored fields: set with [`Reason::NotAnObject`]. + /// The kind of node that the stored record or the row is, when it + /// is not a map of stored fields. `Some` only when `reason` is + /// [`Reason::NotAnObject`]. found: Option, }, @@ -327,8 +397,9 @@ impl fmt::Debug for Error { .field("reason", reason) .field("found", found) .finish(), - // The cause is the host's own error, which can quote the value - // it failed on: it is reached through `source()`, never shown. + // The cause comes from the caller's code, and its text can + // include the value that failed. `Debug` prints a placeholder + // for the cause. A caller gets the cause from `source()`. Self::SourceFailed { field, row, .. } => f .debug_struct("SourceFailed") .field("field", field) @@ -375,8 +446,10 @@ fn in_field_text(field: &Option) -> String { .unwrap_or_default() } -/// ` (row 2, field "age")`, ` (row 2)`, ` (field "age")`, or nothing: the -/// tail of an error that can name a row of a batch. +/// The end of the message of an error that can name a row and a field. +/// +/// The text is ` (row 2, field "age")`, ` (row 2)`, ` (field "age")`, or an +/// empty string when the error names neither. fn place_text(row: Option, field: &Option) -> String { match (row, field.as_deref()) { (Some(row), Some(field)) => format!(" (row {row}, field {field:?})"), @@ -385,9 +458,12 @@ fn place_text(row: Option, field: &Option) -> String { } } -/// A source error's message: "query input does not fit the field" for a -/// refusal only a query's input meets ([`answers_a_query`]), and "record -/// source does not fit the plan" for the rest. +/// The message of an [`Error::Source`]. +/// +/// The message starts with "query input does not fit the field" when only +/// the input of a query can cause the reason ([`answers_a_query`]). For +/// every other reason, the message starts with "record source does not fit +/// the plan". fn source_text( reason: Reason, found: Option, @@ -405,11 +481,14 @@ fn source_text( ) } -/// Whether a source refusal's reason is one only a query's input meets: an -/// operator, a range, a term, statistics, a null query, or a JSON -/// operator's input. A value that cannot be read as the field's type is -/// [`Reason::FieldType`] for a query and a record alike, and keeps the -/// record's words. +/// Returns `true` when only the input of a query can cause `reason`. +/// +/// Those reasons are about an operator, a range, a term, statistics, a +/// null query, or the input of a JSON operator. +/// +/// [`Reason::FieldType`] returns `false`. A query and a record both get +/// that reason for a value that cannot be read as the field's type. So the +/// message for that reason keeps the wording for a record. fn answers_a_query(reason: Reason) -> bool { use Reason::*; matches!( @@ -434,7 +513,8 @@ fn answers_a_query(reason: Reason) -> bool { ) } -/// What a plan, source or stored-record error is about. +/// The input that an error message is about: the plan, the record source, +/// or the stored record. #[derive(Clone, Copy)] enum Subject { Plan, @@ -442,9 +522,14 @@ enum Subject { Record, } -/// The body of a plan, source or stored-record error's message. With -/// [`Found`], a sentence that says what was there, where, and what the -/// operation takes; without, the reason and where it was. +/// 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. fn misfit_text( subject: Subject, reason: Reason, @@ -587,11 +672,18 @@ impl Error { } } - /// The row of a batch an input error is about, from 0: a row of a - /// record source or a stored record that is not an object, the row a - /// source failed in, or the row of a value the frame writer refused as - /// the source's rows were read. `None` for a single record, and for - /// every other error. + /// The position of the row in a batch that the error is about, counted + /// from 0. + /// + /// `Some` in any of these cases: + /// + /// - A row of a record source or of a stored record is not an object. + /// - A value in the row returned an error of its own + /// ([`SourceFailed`](Error::SourceFailed)). + /// - The engine could not copy a value in the row of a record source. + /// + /// `None` when the input is one record and not a batch, and for every + /// other error. pub fn row(&self) -> Option { match self { Self::Source { row, .. } @@ -601,9 +693,12 @@ 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. + /// 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. pub fn found(&self) -> Option { match self { Self::Plan { found, .. } | Self::Source { found, .. } | Self::Record { found, .. } => { @@ -691,9 +786,9 @@ reasons! { #[non_exhaustive] pub enum Reason { /// A plan, field spec, source or stored record is not an object (a - /// map), or a list of them, where one is expected. The error says - /// what it is instead ([`Error::found`]), and which row of a batch - /// ([`Error::row`]). + /// map), or a list of them, where one is expected. + /// [`Error::found`] returns the kind of that value. For a batch, + /// [`Error::row`] returns the position of the row. NotAnObject => "not_an_object", "not an object where one is expected"; /// A context value is of a kind a context cannot hold: a boolean, /// float, null, object or passthrough. @@ -915,11 +1010,12 @@ reasons! { /// than the engine reads, or names a path with more steps than a /// document has levels. JsonPredicateTooDeep => "json_predicate_too_deep", "the predicate nests too deep"; - /// Bytes given as a plan are not one transport frame: empty, cut - /// short, holding a repeated key at any depth, or with bytes after - /// the value. A plan sent as JSON text is refused so. + /// The bytes given as a plan are not one transport frame. A + /// transport frame is the binary encoding of one value. The bytes + /// are empty, end early, repeat a key at any depth, or continue + /// after the value ends. A plan sent as JSON text gets this reason. NotAFrame => "not_a_frame", "the bytes are not one transport frame"; - /// A value failed while it was read, with an error of its own + /// 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"; } @@ -938,34 +1034,41 @@ impl fmt::Display for Reason { } } -/// What an input error found where it expected an object: a value's kind, -/// never the value. A binding reads [`as_str`](Self::as_str), the name in -/// the payload's `found` field; `Display` is the phrase the message uses. +/// The kind of value that the caller passed where the operation takes an +/// object. +/// +/// A `Found` names the kind of a value and never contains the value. +/// [`as_str`](Self::as_str) returns the name in the payload field `found`, +/// for a binding to read. `Display` writes the phrase that the error +/// message uses, such as "a passthrough value". /// -/// `#[non_exhaustive]`: a kind added later is not a break, and a binding -/// that switches on one keeps a fallback. +/// The enum is `#[non_exhaustive]`, so a later version can add a kind +/// without a breaking change. A binding that matches on the kind needs a +/// fallback case. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum Found { - /// A null, plain or typed: `"null"`. + /// A null, with or without a declared type. The name is `"null"`. Null, - /// JavaScript's `undefined`: `"undefined"`. + /// JavaScript's `undefined`. The name is `"undefined"`. Undefined, - /// A passthrough, a value that travels in the clear: `"passthrough"`. + /// A passthrough: a value marked to be stored without encryption. The + /// name is `"passthrough"`. Passthrough, - /// A sealed value where a stored record or a row of one should be: a - /// ciphertext leaf, or the marker of a sealed empty list or map. - /// `"sealed"`. + /// An encrypted value in the place of a stored record or of a row. The + /// value is one ciphertext, or the marker of an encrypted empty list or + /// map. The name is `"sealed"`. Sealed, - /// A value of this kind: its schema name, such as `"string"`, - /// `"uint32"` or `"array"`. + /// A value of this [`ValueKind`]. The name is the schema name of the + /// kind, such as `"string"`, `"uint32"`, or `"array"`. Kind(ValueKind), - /// A scalar of a logical type this build does not know: `"unknown"`. + /// A scalar whose logical type this build does not define. The name is + /// `"unknown"`. Unknown, } impl Found { - /// The name a binding reports in its payload's `found` field. + /// The name of the kind, as the payload field `found` contains it. pub fn as_str(self) -> &'static str { match self { Self::Null => "null", From cd14dd1121ce6e2041760b54b88e9d544c5d3e6f Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sat, 28 Nov 2026 19:01:03 +1100 Subject: [PATCH 09/14] docs(stack-encrypt): rewrite the record source comments in plain language The comments on the code that splits a record source into fields, and on the code that turns a split error into the caller's error, were hard to follow. They used long sentences, and words such as "refusal", "place" and "the open field" with no explanation. The comments now say what each item does, when it returns an error, and what that error names. Parallel cases are lists. The same applies to the test comments, the `uuid` feature comment in Cargo.toml and one comment in the cargo-mutants configuration. Only comments change. --- .cargo/mutants.toml | 18 ++- packages/stack-encrypt/Cargo.toml | 6 +- packages/stack-encrypt/src/dynamic/record.rs | 162 +++++++++++-------- packages/stack-encrypt/src/dynamic/source.rs | 157 +++++++++++------- 4 files changed, 211 insertions(+), 132 deletions(-) diff --git a/.cargo/mutants.toml b/.cargo/mutants.toml index e3af2e279..d07251da8 100644 --- a/.cargo/mutants.toml +++ b/.cargo/mutants.toml @@ -153,13 +153,17 @@ exclude_re = [ # the empty list (`dynamic::target::NoTargets`), which a test asserts on # and `resolve` turns into `TargetError::NoTargets`; `vec![]` is the body. 'stack-encrypt/src/dynamic/target\.rs:\d+:\d+: replace ::targets -> Vec with vec!\[\]$', - # A serde visitor's `expecting` writes only the "expected ..." half of a - # serde error's message, and no caller of these three reads that message: - # a context and statistics are each refused with one fixed `Reason` - # (`ContextKind`, `NotStats`), a plan's root with `NotAFrame` or with - # `NotAnObject` and the kind the frame reports, and the plan's - # field-level reasons are read from the error's path, so writing nothing - # refuses the same input with the same error. + # A serde visitor's `expecting` writes only the "expected ..." part of + # the message of a serde error. No caller of these three visitors reads + # that message: + # - A context is refused with the fixed `Reason` `ContextKind`. + # - Statistics are refused with the fixed `Reason` `NotStats`. + # - The root of a plan is refused with `NotAFrame`, or with `NotAnObject` + # and the kind of value in the frame. + # - The reasons for one field of a plan are read from the path of the + # error. + # So a mutant that writes nothing refuses the same input with the same + # error. 'stack-encrypt/src/dynamic/(context|query|record)\.rs:\d+:\d+: replace for ContextVisitor|serde::Deserialize<\x27de> for Confidence>::deserialize:: for V|Deserialize<\x27de> for PlanWire>::deserialize:: for V)>::expecting -> fmt::Result with Ok\(Default::default\(\)\)$', # The JSON index. `unhex` joins a high nibble shifted into the top four # bits with a low nibble below 16: the bits never overlap, so `^` is `|`. diff --git a/packages/stack-encrypt/Cargo.toml b/packages/stack-encrypt/Cargo.toml index ff205035d..4f617651a 100644 --- a/packages/stack-encrypt/Cargo.toml +++ b/packages/stack-encrypt/Cargo.toml @@ -150,9 +150,9 @@ rust_decimal = ["vitaminc-aead/rust_decimal", "vitaminc-ore/rust_decimal"] # `value::Uuid`: vitaminc's wipeable uuid, built from the uuid crate's # `Uuid`, sealed as one leaf with an equality term. On by default. It turns # on no order term: an order index takes no uuid, so `vitaminc-ore/uuid` -# stays off. `dynamic` does not need it: the dynamic path admits a uuid -# (`ValueKind::Uuid`), and seals and indexes one without this feature. The -# feature adds only the typed `value::Uuid`. +# stays off. `dynamic` does not need this feature. The dynamic path +# accepts a uuid (`ValueKind::Uuid`), and encrypts and indexes it, with the +# feature off. The feature adds only the type `value::Uuid`. uuid = ["vitaminc-aead/uuid"] # `stack_encrypt::kms::FakeDataKeySource`: the in-memory key source for tests # with no ZeroKMS, so a caller's dev-dependency on stack-encrypt is enough and diff --git a/packages/stack-encrypt/src/dynamic/record.rs b/packages/stack-encrypt/src/dynamic/record.rs index 6a0126dbe..124d10228 100644 --- a/packages/stack-encrypt/src/dynamic/record.rs +++ b/packages/stack-encrypt/src/dynamic/record.rs @@ -238,9 +238,11 @@ pub enum NullMode { /// opens as a null. An equality index stores a null's term beside it, /// the one term every null of the field shares, so an `eq` query of a /// null finds the absent rows; no other index has a term for a null. - /// Only for a field of a declared type of fixed width (a boolean, a - /// number, a date, a timestamp, a decimal or a UUID) whose indexes are - /// equality alone; a target field takes it when its EQL type's are. + /// A field can use this mode only when it declares a type of fixed + /// width. Those types are a boolean, a number, a date, a timestamp, a + /// decimal, and a UUID. Equality must also be the only index of the + /// field. For a target field, equality must be the only index of its + /// EQL type. Sealed, /// `"sql"`: a null, or a row with no entry for the field, produces /// nothing: the stored record has no entry for the field, so the host @@ -1242,10 +1244,10 @@ pub fn plan(frame: vitaminc_protected::ProtectedRef<'_, [u8]>) -> Result Error { _ => None, }; let Some(field) = field else { - // The root: not one frame, or a frame that is not an object. + // The error is at the root of the plan. Either the bytes are not + // one frame, or the frame is not an object. return match Frame::parse(frame) { Err(_) => Error::bad_plan(Reason::NotAFrame), Ok(root) => Error::Plan { @@ -1608,13 +1611,19 @@ fn plan_refusal(error: &recipher_frame::serde::Error, frame: &[u8]) -> Error { // key an error inside a spec's value is placed under (an unknown // key is never on the path). Some(_) => Reason::UnknownType, - // The spec itself: not an object at all, a key it does not know, or - // a missing context. Read from the spec's kind and its own keys, not - // the error's wording, so a reworded message cannot change the - // reason. An object of known keys refused at its own level lacks - // its context: a value under a key is refused under that key, a - // frame never holds a repeated key, and the outputs-or-target rule - // is checked after parsing. + // The error is at the field spec itself. There are three possible + // causes: the spec is not an object, the spec has a key that a spec + // does not take, or the spec has no context. The code decides + // between them from the kind of the spec and from its keys. The + // code does not read the text of the error, so a change to that + // text cannot change the reason. + // + // An object with only known keys must lack its context, because + // nothing else fails at this level: + // - An error in the value under a key is reported under that key. + // - A frame never contains a repeated key. + // - The rule that a spec has outputs or a target is checked after + // parsing. None => match Frame::parse(frame) .ok() .and_then(|root| Found::of_entry(root, field)) @@ -2186,16 +2195,30 @@ pub(super) fn source_rows(source: impl Encrypt, plan: &Plan) -> Result } } -/// A value refused while the source was split, as the source error that -/// names its field and the row of a batch it is in: a repeated key as -/// [`Reason::RepeatedKey`], a scalar its logical type does not admit as -/// [`Reason::FieldType`], and anything else (too deep or too long for a -/// frame, or a value the source never wrote) as [`Reason::Unframeable`]. -/// A refusal that names no field (a row the source left unwritten, or a -/// writer's refusal the source kept and returned after the field ended) -/// cannot say whose value it was, so it is [`Reason::Unframeable`] with the -/// row. A failure of the source's own is [`Error::SourceFailed`], with the -/// field and the row it was reading and its error as the cause. +/// Converts the error from [`split_source`] into the [`Error`] that the +/// caller gets. The result keeps the field and the row that the split +/// names. +/// +/// An error that the source returned becomes [`Error::SourceFailed`], with +/// the source's error as its cause. +/// +/// An error from the frame writer becomes [`Error::Source`]. When the +/// split names a field, the reason is: +/// +/// - [`Reason::RepeatedKey`] for a map that repeats a key. +/// - [`Reason::FieldType`] for a scalar that its logical type does not +/// allow. +/// - [`Reason::Unframeable`] for anything else. Examples are a value that +/// is nested too deep or is too long for a frame, and a value that the +/// source never wrote. +/// +/// When the split names no field, the reason is always +/// [`Reason::Unframeable`], with the row, because the error cannot name +/// the value at fault. That happens in two cases: +/// +/// - The source started a row and never wrote it. +/// - The source kept an error from the frame writer and returned it after +/// the field ended. fn split_refusal(SplitRefusal { row, field, error }: SplitRefusal) -> Error { let error = match error { FrameWriteError::Source(cause) => return Error::SourceFailed { field, row, cause }, @@ -2484,9 +2507,9 @@ pub(super) fn open_record( // opens as a plain null, as every frame carries one. let null = field.null.is_some() && value.frame().is_null(); if let Some(kind) = field.kind.filter(|_| !null) { - // The error names the declared type and never what the value - // opened as: that is known only once it is decrypted, and is - // the plaintext's own metadata. + // The error names the type that the field declares. The error + // never names the kind that the value decrypted to. That kind + // was inside the ciphertext, so it is part of the plaintext. if !kind.holds(value.frame().kind()) { return Err(crate::PlanError::FieldType { field: field.name.clone(), @@ -2573,8 +2596,8 @@ pub(super) fn record_rows(tree: StackCipherText, plan: &Plan) -> Result Found { match tree { CipherText::Sequence(_) => Found::Kind(ValueKind::Array), @@ -6149,11 +6172,12 @@ mod tests { ); } - /// A field declared as an object that opens as a list, a single - /// value or a null is refused naming the field and the declared type, - /// and never what it opened as: the kind of a value is known only - /// once it is decrypted, so it is the plaintext's own metadata. The - /// payload has no `found`, and the message names no kind. + /// A field is declared as an object, and its stored value decrypts + /// to a list, a scalar, or a null. The error names the field and the + /// declared 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. The payload has no `found`, and the message + /// names no kind. #[tokio::test] async fn decrypt_never_says_what_a_field_opened_as() { use crate::ErrorPayload; @@ -8820,9 +8844,10 @@ mod tests { } } - /// A refusal of a value that is not the object the operation takes: - /// the variant, the field, the row of a batch and what was found, in - /// the accessors, the payload and the message. + /// Checks an error about a value that is not the object that the + /// operation takes. The checks cover the variant, the field, the row + /// of a batch and the kind of the value. The row and the kind are + /// checked in the accessors, the payload, and the message. fn expect_shape( error: &Error, variant: &str, @@ -8857,9 +8882,9 @@ mod tests { } } - /// Bytes that are not one frame are not a plan: empty, cut short, - /// JSON text, or a frame whose spec repeats a key, which no frame - /// holds. + /// Bytes that are not one frame are not a plan. The cases are empty + /// bytes, bytes that are cut short, JSON text, and bytes whose field + /// spec repeats a key. A frame never contains a repeated key. #[test] fn bytes_that_are_not_a_frame_are_not_a_plan() { let mut repeated = vec![vitaminc_aead::frame::OBJECT, 1, 0, 0, 0]; @@ -8889,8 +8914,8 @@ mod tests { } } - /// A plan, or a field's spec, that is a frame but not an object - /// says what it is instead. + /// When a plan or a field spec is a frame and not an object, the + /// error names the kind of value that it is. #[test] fn a_plan_or_spec_that_is_not_an_object_says_what_it_is() { for (value, found) in [ @@ -8920,7 +8945,7 @@ mod tests { "the message" ); } - // A spec that is a typed null is a null too. + // A field spec that is a typed null is reported as a null too. let ty = vitaminc_aead::plaintext::FixedType::new( Some(vitaminc_aead::plaintext::Logical::Date), vitaminc_aead::plaintext::Width::I32, @@ -8934,9 +8959,10 @@ mod tests { super::super::plan(Protected::new(typed_null).as_protected_ref().as_deref()) .expect_err("a typed null spec"); expect_shape(&error, "Plan", Some("age"), None, Found::Null); - // A spec that is an object of keys the spec does not take is not - // refused as not an object, even where the frame holds a - // passthrough the reader does not read. + // A field spec can be an object with a key that a spec does not + // take. The reason is then the one for an unknown key, and not + // `NotAnObject`. That is so even when the frame contains a + // passthrough. The frame reader does not read a passthrough. let error = plan(obj(vec![( "age", obj(vec![ @@ -9111,10 +9137,12 @@ mod tests { check_source(Tree::Object(distinct), &plan).expect("distinct keys in a passthrough"); } - /// A refusal from the split names its field, by its cause. One that - /// names no field (a row left unwritten, or a source that kept a - /// writer's refusal and returned it after the field) is the - /// caller's input too: `unframeable`, with the row. + /// An error from the split that names a field gets its reason from + /// its cause. An error that names no field is also an error in the + /// caller's input, with the reason `unframeable` and the row. There + /// are two causes. The source left a row unwritten. Or the source + /// kept an error from the frame writer and returned it after the + /// field ended. #[test] fn a_split_refusal_names_its_field_and_cause() { let refusal = |field: Option<&str>, error| { @@ -9147,8 +9175,8 @@ mod tests { for error in [FrameWriteError::TooDeep, FrameWriteError::Unwritten] { expect(&fault(error), "Source", Some("age"), Reason::Unframeable); } - // A refusal in a row of a batch names the row, in the payload - // and the message. + // An error in a row of a batch names the row, in the payload + // and in the message. let error = in_row(3, FrameWriteError::DuplicateKey); expect(&error, "Source", Some("age"), Reason::RepeatedKey); assert_eq!(error.row(), Some(3), "the row: {error}"); @@ -9157,8 +9185,9 @@ mod tests { error.to_string().ends_with(r#" (row 3, field "age")"#), "the message names the row: {error}" ); - // A row the source left unwritten names no field, and is still - // the caller's input, not this module's bug. + // An error for a row that the source left unwritten names no + // field. The error is still about the caller's input. The error + // is not a bug in this module. let unwritten = split_refusal(SplitRefusal { row: Some(1), field: None, @@ -9179,14 +9208,16 @@ mod tests { } } - /// A source that fails as it is read is refused as - /// [`Error::SourceFailed`], naming the field and the row it was - /// reading, with its own error as the cause and not in the message. + /// When a source returns an error of its own, the caller gets + /// [`Error::SourceFailed`]. The error names the field and the row + /// that the engine was reading. The source's error is the cause. + /// The message leaves the cause out. #[test] fn a_source_that_fails_names_its_field_and_row_and_keeps_its_cause() { use vitaminc_aead::plaintext::SourceError; const SECRET: &str = "the getter saw marker-value"; - /// A batch of two records whose second fails in its `email`. + /// A batch of two records. The source returns an error inside + /// `email` in the second record. struct Fails; impl Encrypt for &Fails { fn visit(self, sink: S) -> Result { @@ -9228,8 +9259,9 @@ mod tests { ); let shown = format!("{message} {fields:?}"); assert!(!shown.contains("marker-value"), "no cause text: {shown}"); - // `Debug`, plain and pretty, shows the field and the row and - // not the cause's text: a log line or a panic does not leak it. + // The plain form and the pretty form of `Debug` both print the + // field and the row. Neither form prints the text of the cause. + // So a log line or a panic message does not leak that text. for debug in [format!("{error:?}"), format!("{error:#?}")] { assert!( !debug.contains("marker-value"), @@ -9510,9 +9542,11 @@ mod tests { } } - /// A refusal only a query's input meets says so; one a record source - /// meets, or a value of another type in either, says it is the - /// record source that does not fit. + /// When only the input of a query can cause the reason, the message + /// says that the query input does not fit the field. For a reason + /// that a record source can cause, the message says that the record + /// source does not fit the plan. That includes a value of another + /// type. A query and a record can both cause that reason. #[test] fn a_query_refusal_names_the_query_input() { use Reason::*; diff --git a/packages/stack-encrypt/src/dynamic/source.rs b/packages/stack-encrypt/src/dynamic/source.rs index 8ca044cb0..f0944ec74 100644 --- a/packages/stack-encrypt/src/dynamic/source.rs +++ b/packages/stack-encrypt/src/dynamic/source.rs @@ -17,19 +17,23 @@ //! * A sequence is a batch. Each element of the sequence is one record. //! * Anything else is not a record: a single value, a null, a passthrough //! value, or a sequence inside a batch. The entry for that value is the -//! kind of value it is ([`Found`]). Nothing inside the value is copied or -//! checked. +//! kind of the value, as a [`Found`]. Nothing inside the value is copied +//! or checked. //! //! This module does not compare the fields with the plan. The caller, //! `record::source_rows`, refuses a value that is not a record, a missing //! field, an extra field, and a value of the wrong type. //! -//! [`split_source`] fails when the frame writer refuses a field's value, -//! such as a date out of range or a map that repeats a key, or when the -//! source fails to describe itself, such as a host getter that throws. The -//! error names the field whose value was being written, and the row of a -//! batch, so the caller can report where it happened. A source that fails -//! outside any field's value names no field. +//! [`split_source`] returns an error in two cases: +//! +//! * The split cannot write a field's value into a frame. Examples are a +//! date out of range, and a map that repeats a key. +//! * The value returns an error of its own while the split reads it. An +//! example is a property getter in the caller's language that throws. +//! +//! The error names the row of a batch and the field whose value the split +//! was writing. So the caller can report where the error happened. An +//! error that happens outside the value of any field names no field. use std::cell::{Cell, RefCell}; @@ -41,9 +45,13 @@ use vitaminc_protected::Buffer; use crate::refusal::Found; -/// One record's fields, each name with its value in a frame of its own, in -/// the order the source lists them. The kind of value the source gave -/// instead, when it is not a map, so is not a record. +/// One entry of the result: a record, or the kind of a value that is not +/// a record. +/// +/// `Ok` contains the fields of one record, in the order the source lists +/// them. Each field is a name and a value. Each value is in a frame of its +/// own. `Err` contains the kind of a value that is not a map, so is not a +/// record. pub(super) type SourceRecord = Result, Found>; /// A source split by [`split_source`]: one record, or a batch of them. @@ -54,9 +62,15 @@ pub(super) enum SplitSource { Batch(Vec), } -/// Why [`split_source`] failed: the error from the frame writer, or the -/// source's own, the row of a batch the split was in, and the field whose -/// value it was writing, if it was writing one. +/// Why [`split_source`] failed, and where. +/// +/// - `error` is the error from [`FrameWriter`], or the error that the +/// source returned. `FrameWriter` writes a value into a frame. +/// - `row` is the position of the row that the split was reading, counted +/// from 0. `None` when the source is not a batch, or the split was +/// between two rows. +/// - `field` is the field whose value the split was writing. `None` when +/// the split was not writing the value of a field. #[derive(Debug)] pub(super) struct SplitRefusal { pub(super) row: Option, @@ -76,12 +90,18 @@ pub(super) fn split_source(source: P) -> Result>, @@ -89,7 +109,7 @@ struct Place { } impl Place { - /// The field being written is finished. + /// Clears the field, because the source has finished writing its value. fn field_done(&self) { *self.field.borrow_mut() = None; } @@ -112,7 +132,8 @@ impl PutRecord for TopRecord { } } -/// The next record of a batch. Putting it finishes its row. +/// The next record of a batch. [`put`](PutRecord::put) adds the record to +/// the batch and clears the row in [`Place`], because the row is finished. struct BatchRecord<'s> { records: &'s mut Vec, place: &'s Place, @@ -164,9 +185,13 @@ impl<'f> Sink for TopSink<'f> { } } -/// A batch: one record for each element. `begun` counts the elements the -/// source began, so an element whose sink it dropped unwritten, leaving no -/// record, is refused rather than shifting the rows after it. +/// A batch: one record for each element. +/// +/// `begun` counts the elements that the source started. A source can start +/// an element and then drop its sink without writing a value. That element +/// leaves no record, so every later row would move up one position. The +/// split returns an error for that batch instead +/// ([`check_written`](Self::check_written)). struct BatchSink<'f> { place: &'f Place, records: Vec, @@ -174,8 +199,9 @@ struct BatchSink<'f> { } impl BatchSink<'_> { - /// Refuse a batch whose last element begun put no record: its sink was - /// dropped unwritten. + /// Returns an error when the last element that the source started left + /// no record, because the source dropped its sink without writing a + /// value. The error names the row of that element. fn check_written(&self) -> Result<(), FrameWriteError> { if self.records.len() == self.begun { return Ok(()); @@ -253,7 +279,8 @@ impl<'f, 's> Sink for ElementSink<'f, 's> { /// A batch element that is a sequence, so is not a record. The source still /// describes its elements, and [`Discard`] reads past them without copying -/// them. When the sequence ends, the batch notes that it was an array. +/// them. When the sequence ends, the batch records that the element was an +/// array. struct NotARecord<'s> { record: BatchRecord<'s>, } @@ -397,10 +424,11 @@ impl<'f, O: PutRecord> MapSink for RecordMap<'f, O> { } } -/// One field's value, written into its own frame. It forwards to the frame -/// writer, and once the value is complete it marks the field finished, so a -/// source that fails after one field's value and before the next names -/// neither. +/// Writes the value of one field into a frame of its own. +/// +/// The writer passes every call on to [`FrameWriter`]. When the value is +/// complete, the writer clears the field in [`Place`]. So an error after +/// the value of one field and before the next names no field. struct FieldWriter<'s, 'f> { writer: FrameWriter<'s>, place: &'f Place, @@ -445,7 +473,8 @@ impl<'s, 'f> Sink for FieldWriter<'s, 'f> { } } -/// A field's value that is a sequence: finished when the sequence ends. +/// A field's value that is a sequence. The field is finished when the +/// sequence ends. struct FieldSeq<'s, 'f> { inner: FrameSeq<'s>, place: &'f Place, @@ -470,7 +499,8 @@ impl<'s> SeqSink for FieldSeq<'s, '_> { } } -/// A field's value that is a map: finished when the map ends. +/// A field's value that is a map. The field is finished when the map +/// ends. struct FieldMap<'s, 'f> { inner: FrameMap<'s>, place: &'f Place, @@ -515,8 +545,8 @@ mod tests { ) } - /// A record's fields as their frames' bytes, in source order, or what - /// the value was instead of a record. + /// The fields of a record as the bytes of their frames, in source + /// order. For a value that is not a record, the kind of that value. fn bytes(record: &SourceRecord) -> Result)>, Found> { record.as_ref().map_err(|found| *found).map(|entries| { entries @@ -556,8 +586,9 @@ mod tests { ); } - /// A value that is not a map is not a record: the split notes what - /// kind of value it is, at the top or as an element of a batch. + /// A value that is not a map is not a record. The split reports the + /// kind of that value, at the top of the source and as an element of a + /// batch. #[test] fn a_sequence_is_a_batch_and_what_is_not_a_map_is_not_a_record() { let ty = FixedType::new(Some(Logical::Date), Width::I32).expect("fixed"); @@ -622,8 +653,8 @@ mod tests { ); } - /// A refusal names the field whose value the writer refused, and the - /// row of a batch it is in. + /// When the frame writer refuses a value, the error names the field of + /// that value. For a batch, the error also names the row. #[test] fn a_refusal_names_the_field_and_row_being_written() { let refused = |source: &Tree| split_source(source).err().expect("refused"); @@ -677,13 +708,15 @@ mod tests { ); } - /// A source that fails as it describes itself keeps its own error, and - /// the split names the field and the row it was reading. A failure - /// after a record's fields are written names no field. + /// When a source returns an error of its own, the split keeps that + /// error. The split also names the field and the row that it was + /// reading. An error after the fields of a record are written names no + /// field. #[test] fn a_source_failure_names_the_field_and_row_it_was_reading() { - /// Describes a batch of `rows` records of one field `a`, and fails - /// in the last one: inside `a`'s value, or after the record ends. + /// A batch of `rows` records, each with one field `a`. The source + /// returns an error in the last record: inside the value of `a`, or + /// after the record ends. struct Fails { rows: usize, after_the_record: bool, @@ -739,22 +772,28 @@ mod tests { assert_eq!(after.row, None, "every row begun is finished"); } - /// Where a source fails decides what the refusal names: a field only - /// while its value is being written, and a row only while it is being - /// read. A failure between two fields, after a field's container ends, - /// or between two rows names neither. + /// The place where a source returns an error decides what the error + /// names. The error names a field only while the split is writing the + /// value of that field. The error names a row only while the split is + /// reading that row. An error names no field when it happens between + /// two fields, or after the list or map of a field ends. An error + /// between two rows names no field and no row. #[test] fn a_source_failure_names_only_the_field_and_row_still_open() { - /// Where the source fails, in a batch of records. + /// The place in a batch of records where the source returns an + /// error. #[derive(Clone, Copy, Debug)] enum At { - /// In row 0, after `age` is written and before `email` begins. + /// The error happens in row 0, after `age` is written and before + /// `email` starts. BetweenFields, - /// In row 0, inside `tags`, a list, after its first element. + /// The error happens in row 0, inside the list `tags`, after its + /// first element. InsideAList, - /// In row 0, after `tags`, a map, has ended. + /// The error happens in row 0, after the map `tags` has ended. AfterAMap, - /// After row 0 is finished and before row 1 begins. + /// The error happens after row 0 is finished, before row 1 + /// starts. BetweenRows, } impl Encrypt for &At { @@ -806,12 +845,14 @@ mod tests { } } - /// A batch element whose sink the source dropped unwritten leaves no - /// record: the batch is refused naming that row, before or at its end, - /// rather than shifting the rows after it. + /// A source can start a batch element and drop its sink without + /// writing a value. That element leaves no record. The split returns an + /// error that names the row, when the next element starts or when the + /// batch ends. The split does not move the later rows up one position. #[test] fn a_batch_element_left_unwritten_is_refused_naming_its_row() { - /// A batch of two rows whose row `dropped` is begun and dropped. + /// A batch of two rows. The source starts row `dropped` and drops + /// its sink without writing a value. struct DropsARow { dropped: usize, } From 4740a05a71793cb9cb610db36e713e626019a90c Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sat, 28 Nov 2026 19:01:03 +1100 Subject: [PATCH 10/14] docs(golang): rewrite the Diagnostic row and kind docs in plain language The Go doc comments for `Diagnostic.Row` and `Diagnostic.Found`, the list of details a Diagnostic can contain, and the CHANGELOG entry each packed several rules into one sentence. They are now short sentences and lists. `Found` lists its kinds and says what "passthrough", "sealed", "undefined" and "unknown" mean. The guest's status comment says why each input error is named one by one. Only comments and Markdown change. --- languages/golang/CHANGELOG.md | 21 +++--- languages/golang/encrypt/errors.go | 33 ++++++---- languages/golang/encrypt/guest/src/status.rs | 15 +++-- languages/golang/internal/guest/diagnostic.go | 65 +++++++++++++------ .../golang/internal/guest/diagnostic_test.go | 5 +- 5 files changed, 89 insertions(+), 50 deletions(-) diff --git a/languages/golang/CHANGELOG.md b/languages/golang/CHANGELOG.md index 272cabb72..91a657e56 100644 --- a/languages/golang/CHANGELOG.md +++ b/languages/golang/CHANGELOG.md @@ -22,15 +22,18 @@ and `languages/golang/encrypt/encrypttest/vX.Y.Z` on the same commit. `[16]byte` (`github.com/google/uuid.UUID`, say), which is converted to one. `stashgen` does not yet map a Go type to it. -- `Diagnostic.Row` and `Diagnostic.Found` (#1985). A plan, a record or a - stored row that is not an object now says what it is instead, by its - kind and never its value: `Found` is `"null"`, `"array"`, `"string"`, - `"passthrough"`, `"sealed"` and so on. `Row` is the row of a batch it - is in, from 0, and the message names it too, as in `row 2 of the - records to decrypt is a passthrough value, not an object of stored - fields`. `Found` names only what the program sent or the stored row's - own structure: an error about a decrypted value never says what it - opened as. +- `Diagnostic.Row` and `Diagnostic.Found` (#1985). The two accessors give + more detail for an error about a plan, a record, or a stored row that is + not an object: + - `Found` is the kind of value that the engine got, such as `"null"`, + `"array"`, `"string"`, `"passthrough"`, or `"sealed"`. `Found` never + contains the value. + - `Row` is the position of the row in a batch, counted from 0. The + message names the row too, as in `row 2 of the records to decrypt is + a passthrough value, not an object of stored fields`. + - `Found` names a kind only for a value that the program sent, or for a + node in the unencrypted structure of a stored row. An error about a + decrypted value never names the kind that the value decrypted to. ### Changed diff --git a/languages/golang/encrypt/errors.go b/languages/golang/encrypt/errors.go index c1da56976..90158ae44 100644 --- a/languages/golang/encrypt/errors.go +++ b/languages/golang/encrypt/errors.go @@ -89,19 +89,28 @@ var ErrStorageVersion = vcffi.ErrUnsupportedVersion // "stack_kms::keyset_not_found", ...; stable), Message (what Error // returns after the sentinel's text), Help, URL, Severity, Fields (the // structured fields, by name) and Causes (the errors behind it, outermost -// first). Accessors read the fields a caller branches on: ExpectedKeyset -// and FoundKeyset on an [ErrForeignKeyset] (each a [KeysetID]'s bytes); -// Field and Reason on a refused plan, record or value; Row and Found on a -// plan, record or row that is not an object, the row of a batch from 0 and -// what was there by its kind ("null", "array", "string", ...); and -// Construct and At on a refused Match predicate, the construct in the -// grammar's words and the byte offset in the predicate where it starts. +// first). Accessors read the fields a caller branches on: // -// What one may carry is fixed: keyset ids and names, field names, counts, -// row positions, value kinds, index kinds, ZeroKMS request kinds and HTTP -// statuses, and a refused predicate's construct and offset. Never -// plaintext, key material, tokens, ciphertext or term bytes, or the values -// of an encryption context. +// - ExpectedKeyset and FoundKeyset, on an [ErrForeignKeyset]. Each is the +// bytes of a [KeysetID]. +// - Field and Reason, on a refused plan, record, or value. +// - Row and Found, on a plan, a record, or a row that is not an object. +// Row is the position of the row in a batch, counted from 0. Found is +// the kind of value that was there, such as "null", "array", or +// "string". +// - Construct and At, on a refused Match predicate. Construct is the +// construct in the grammar's words. At is the byte offset in the +// predicate where the construct starts. +// +// A Diagnostic contains only these details: +// +// - keyset ids and names, field names, and counts +// - row positions, and the kinds of values +// - index kinds, ZeroKMS request kinds, and HTTP statuses +// - the construct and the offset of a refused predicate +// +// A Diagnostic never contains plaintext, key material, tokens, ciphertext +// bytes, term bytes, or the values of an encryption context. // // Errors the client raises itself carry none: a closed client ([ErrState]), // a guest that did not return, [ErrMemoryLock], and an argument refused diff --git a/languages/golang/encrypt/guest/src/status.rs b/languages/golang/encrypt/guest/src/status.rs index 61f307948..46d664c07 100644 --- a/languages/golang/encrypt/guest/src/status.rs +++ b/languages/golang/encrypt/guest/src/status.rs @@ -165,12 +165,15 @@ pub fn status_for_error(error: &stack_encrypt::Error) -> u32 { /// A dynamic-path error as a status code. /// -/// The split the library draws is the one the ABI needs: `Context`, `Term`, -/// `Plan`, `UntypedIndex`, `Source`, `SourceFailed`, `Record` and -/// `Predicate` are each a statement about the caller's input, decided -/// before any key is minted or retrieved, so they are -/// [`STATUS_ENCODING`] — named one by one, because that verdict is the -/// host's to act on and must be given deliberately. `Cipher` defers to +/// The library separates errors about the caller's input from every other +/// error, and the ABI needs the same separation. `Context`, `Term`, `Plan`, +/// `UntypedIndex`, `Source`, `SourceFailed`, `Record`, and `Predicate` are +/// each about the caller's input. The library decides each one before any +/// key is minted or retrieved. So each one is [`STATUS_ENCODING`]. The +/// match names them one by one, because the host acts on that status, so +/// the choice must be deliberate. +/// +/// `Cipher` defers to /// [`status_for_error`]; `Internal` is the library's own invariant failing /// — a slot count that did not line up, a re-proof that could not fail — /// and is [`STATUS_INTERNAL`], never a verdict on the input. diff --git a/languages/golang/internal/guest/diagnostic.go b/languages/golang/internal/guest/diagnostic.go index 860628e8f..973aa98ef 100644 --- a/languages/golang/internal/guest/diagnostic.go +++ b/languages/golang/internal/guest/diagnostic.go @@ -21,13 +21,20 @@ import ( // var d *encrypt.Diagnostic // if errors.As(err, &d) { log.Print(d.Code, d.Help) } // -// What it may carry is the rule written on stack-profile's ErrorPayload: -// keyset ids and names, field names, counts, row positions, value kinds, -// index kinds, ZeroKMS request kinds and HTTP statuses, workspace ids, CRNs -// and regions, profile file paths, and for a refused predicate the -// construct in the grammar's words and a byte offset. Never plaintext, key -// material, tokens, ciphertext or term bytes, or a context's values: a -// stored context's length and parts at most. +// A Diagnostic contains only the details that the rule on stack-profile's +// ErrorPayload allows: +// +// - keyset ids and names, field names, and counts +// - row positions, and the kinds of values +// - index kinds, ZeroKMS request kinds, and HTTP statuses +// - workspace ids, CRNs, and regions +// - profile file paths +// - for a refused predicate, the construct in the grammar's words and a +// byte offset +// +// A Diagnostic never contains plaintext, key material, tokens, ciphertext +// bytes, term bytes, or the values of a context. For a stored context, a +// Diagnostic contains at most its length and its number of parts. // // A guest built before se_last_error, or one whose error does not decode, // returns the bare sentinel instead: the detail is never allowed to hide @@ -129,24 +136,40 @@ func (d *Diagnostic) Reason() string { return reason } -// Row is the row of a batch a refusal is about, counted from 0: a record -// to encrypt or a stored record that is not an object of fields, or the row -// of a value that failed to be read or could not be written as a frame. A -// field's own refusal (missing, unknown, of another type) names the field -// and no row. ok is false for an error that names no row, such as one about -// a single record, and for a row that is negative, not a whole number, or -// past int. +// Row is the position of the row in a batch that the error is about, +// counted from 0. An error names a row in any of these cases: +// +// - A record to encrypt, or a stored record, is not an object of fields. +// - A value in the row returned an error while the engine read it. +// - The engine could not encode a value in the row. +// +// An error about one field of a record names the field and no row. Examples +// are a missing field, an unknown field, and a value of another type. +// +// Row returns ok as false when the error names no row, such as an error +// about a single record. Row also returns ok as false for a row that is +// negative, is not a whole number, or is too large for an int. func (d *Diagnostic) Row() (row int, ok bool) { return nonNegativeInt(d.Fields["row"]) } -// Found is what a refusal found where it expected an object, by its kind -// and never its value: "null", "array", "string", "passthrough", "sealed" -// (a sealed value where a stored record or row should be), another kind's -// schema name ("uint32", "object", ...), "undefined" or "unknown". It names -// only what the program sent or the stored row's own structure, never what -// a decrypted value opened as. "" for an error that names none. New kinds -// may appear: keep a fallback. +// Found is the kind of value that the engine got where it takes an object. +// Found names the kind and never contains the value. The kinds are: +// +// - "null", "array", "string", or the schema name of another kind, such +// as "uint32" or "object" +// - "passthrough", for a value stored without encryption +// - "sealed", for an encrypted value in the place of a stored record or +// of a row +// - "undefined", for JavaScript's undefined +// - "unknown", for a value of a type that this build does not define +// +// Found names a kind only for a value that the program sent, or for a node +// in the unencrypted structure of a stored row. Found never names the kind +// that a value decrypted to. +// +// Found is "" when the error names no kind. A later version can add a kind, +// so keep a fallback case. func (d *Diagnostic) Found() string { found, _ := d.Fields["found"].(string) return found diff --git a/languages/golang/internal/guest/diagnostic_test.go b/languages/golang/internal/guest/diagnostic_test.go index 357e77a4f..614db9227 100644 --- a/languages/golang/internal/guest/diagnostic_test.go +++ b/languages/golang/internal/guest/diagnostic_test.go @@ -319,8 +319,9 @@ func TestConstructAndAtReadARefusedPredicate(t *testing.T) { } } -// A refusal of a value that is not an object reads its row of a batch and -// what it found, as decoded; an error with neither gives none. +// Row and Found read the row and the kind from the decoded fields of an +// error about a value that is not an object. For an error with neither +// field, Row returns ok false and Found returns "". func TestRowAndFoundReadARefusedShape(t *testing.T) { d := &guest.Diagnostic{Fields: map[string]any{"reason": "not_an_object", "row": uint64(2), "found": "null"}} if row, ok := d.Row(); !ok || row != 2 { From 1144c4c03294f7f1f665eea048f3750657b9f22c Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sat, 28 Nov 2026 19:01:03 +1100 Subject: [PATCH 11/14] docs(stack-encrypt): rewrite the changelog entry for input errors The CHANGELOG entry for errors about input that is not an object was hard to follow. It now starts with what a caller must change to upgrade, then lists each change in short sentences, and explains "field spec", "transport frame" and "typed null" where they first appear. The payload policy in stack-profile and the raw-frames contract say the same rule in the same words: an error names a kind only when the kind can be read without decrypting anything. Only comments and Markdown change. --- .../stack-encrypt/raw-frames-contract.md | 6 +- packages/stack-encrypt/CHANGELOG.md | 112 +++++++++++------- packages/stack-profile/src/diagnostic.rs | 15 ++- 3 files changed, 80 insertions(+), 53 deletions(-) diff --git a/conformance/stack-encrypt/raw-frames-contract.md b/conformance/stack-encrypt/raw-frames-contract.md index 9abc6040f..d40d3fb40 100644 --- a/conformance/stack-encrypt/raw-frames-contract.md +++ b/conformance/stack-encrypt/raw-frames-contract.md @@ -43,9 +43,9 @@ diagnostic. Within `authenticated`, two outcomes are distinguished. A leaf sealed as an `int32` and read as `int64` or `string` authenticates and then fails the declared type: `stack_encrypt::plan_field_type` naming the field and the -expected kind, as the read profile's authenticated cases do. It never names -the kind the leaf opened as: that is known only once the leaf is decrypted, -so the payload has no `found`. A leaf moved +expected kind, as the read profile's authenticated cases do. The diagnostic +never names the kind that the leaf decrypted to. That kind was inside the +ciphertext, so the payload has no `found` field. A leaf moved into another role (the single leaf under an empty-sequence tag) fails authentication itself: `stack_encrypt::aead`, which Go reports as `ErrAuthentication` carrying that code. Both runners compare the code and diff --git a/packages/stack-encrypt/CHANGELOG.md b/packages/stack-encrypt/CHANGELOG.md index 662476481..5f97efcda 100644 --- a/packages/stack-encrypt/CHANGELOG.md +++ b/packages/stack-encrypt/CHANGELOG.md @@ -504,50 +504,74 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Breaking -- **A record refused as "not an object" says what it found, and where** - (#1985). Before, a plan, a field's spec, a record to encrypt or a stored - record that was not an object was refused as `not_an_object` with no - more detail, and most of them named no field and no row. Now: - - The error says what was there instead, by its kind and never its - value: `Error::found()`, the payload's `found` (`"null"`, `"array"`, - `"string"`, `"uint32"`, `"passthrough"`, `"sealed"`, ...), and the - message, as in `row 2 of the records to encrypt is null, not an - object of fields`. The new `dynamic::Found` names the kinds. A kind is - named only for what the caller sent, or for the stored record's own - structure (a row that is a passthrough or a sealed value rather than a - map). An error about a decrypted value never names what it opened as. - - A row of a batch that is not an object is named by its position from - 0: `Error::row()`, the payload's `row`, and the message, which also - says whether the record was to encrypt or to decrypt. So is the row of - a value that fails while it is read, or that the frame writer refuses - (a repeated key, a value its logical type does not admit, a value too - deep or too long). A field's own misfit (missing, unknown, of another - type) names the field and not the row. A row whose element the source - began and never wrote is refused as `unframeable`, naming the row, - rather than shifting the rows after it. - - Bytes given as a plan that are not one transport frame (empty, cut - short, JSON text, a repeated key, bytes after the value) have their - own reason, `not_a_frame`. A frame that is not an object of field - specs keeps `not_an_object`, with what it is. A field's spec that is a - typed null now names its field, where it named none. - - A value that fails while it is read, such as a JSON document nested - too deep, is the new `Error::SourceFailed`, with the code - `stack_encrypt::dynamic_source_failed` and the reason `source_failed`. - It names the row being read, and the field while its value is being - written; a failure between two fields, or between two rows, names - neither. It keeps the value's own error as its cause, reached through - `source()`. The cause is not in the message, and `Debug` shows it as - `SourceError(..)`, because a host's error can quote the value. Before, - it was `not_an_object` with no field. - - A source refusal only a query's input meets (an operator, a range, a - term, statistics, a null query, a JSON operator's input) now says - `query input does not fit the field`, where it said `record source - does not fit the plan`. - - `Error::Plan` has a new `found` field, and `Error::Source` and - `Error::Record` new `row` and `found` fields, so a match on them that - names every field needs `..`. Reason codes do not change, except the two - new ones. +- **An error about input that is not an object names the kind of value + and the row** (#1985). The input is a plan, a field spec, a record to + encrypt, or a stored record. A field spec is the entry in a plan that + describes one field. Before, the engine refused each one with the reason + `not_an_object` and no more detail. Most of those errors named no field + and no row. + + To upgrade, add `..` to a match that names every field of `Error::Plan`, + `Error::Source`, or `Error::Record`. `Error::Plan` has a new `found` + field. `Error::Source` and `Error::Record` have new `row` and `found` + fields. The existing reason codes keep their names. The two new codes + are `not_a_frame` and `source_failed`. + + The changes are: + - The error names the kind of value that the engine got, and never + includes the value. The kind is in `Error::found()`, in the payload + field `found`, and in the message. An example of the message is + `row 2 of the records to encrypt is null, not an object of fields`. + The new `dynamic::Found` lists the kinds, such as `"null"`, `"array"`, + `"string"`, `"uint32"`, `"passthrough"`, and `"sealed"`. + - An error names a kind only when the engine can read the kind without + decrypting anything. That is the kind of a value the caller sent, or + the kind of a node in the unencrypted structure of a stored record. + An example of the second is a row that is a passthrough or an + encrypted value, and not a map. An error about a decrypted value never + names the kind that the value decrypted to. + - An error about a row of a batch names the row by its position, counted + from 0. The position is in `Error::row()`, in the payload field `row`, + and in the message. The message also says whether the record was to + encrypt or to decrypt. An error names the row in any of these cases: + - The row is not an object. + - A value in the row returns an error of its own while the engine + reads it. + - The engine cannot copy a value in the row. The cause is a value + that repeats a map key, does not fit its logical type, is nested too + deep, or is too long. + - An error from comparing a field with the plan names the field and not + the row. Examples are a missing field, a field that the plan does not + name, and a value of another type. + - A source can start a row of a batch and never write it. The engine + refuses that batch with the reason `unframeable`, and the error names + the row. The engine does not move the later rows up one position. + - Bytes given as a plan that are not one transport frame get the new + reason `not_a_frame`. A transport frame is the binary encoding of one + value. The bytes are empty, are cut short, are JSON text, repeat a + key, or continue after the value ends. A frame that is not an object + of field specs keeps the reason `not_an_object`, and the error names + the kind of value in the frame. + - An error about a field spec that is a typed null names the field. + Before, the error named no field. A typed null is a null that records + a type. + - A value that returns an error of its own while the engine reads it + gets the new `Error::SourceFailed`. An example is a JSON document that + is nested too deep. The code is `stack_encrypt::dynamic_source_failed`. + The reason is `source_failed`. Before, the reason was `not_an_object`, + and the error named no field. + - The error names the row that the engine was reading, and the field + whose value the engine was writing. An error between two fields + names no field. An error between two rows names no field and no row. + - The value's error is the cause, and `source()` returns it. The + message leaves the cause out, and `Debug` prints the cause as + `SourceError(..)`, because the text of the caller's error can + include the value. + - The message of an `Error::Source` starts with `query input does not + fit the field` when only the input of a query can cause the reason. + Before, that message started with `record source does not fit the + plan`. Those reasons are about an operator, a range, a term, + statistics, a null query, or the input of a JSON operator. - **`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-profile/src/diagnostic.rs b/packages/stack-profile/src/diagnostic.rs index b1469cfb6..322ae7155 100644 --- a/packages/stack-profile/src/diagnostic.rs +++ b/packages/stack-profile/src/diagnostic.rs @@ -58,12 +58,15 @@ //! //! - Keyset IDs and names; counts and lengths; index names and kinds. //! - Schema field names from a plan or Go struct, rather than field values. -//! - The kind of a value the caller sent, such as null, an array or a -//! uint32, rather than the value, or the kind of a node in a stored -//! record's own structure (a passthrough, a sealed value, a list), which -//! the stored form shows without decrypting; and the position of a row in -//! a batch. Never the kind of a decrypted value: that is known only once -//! it is opened, so it is the plaintext's own metadata. +//! - The kind of a value, such as null, an array, or a uint32, rather than +//! the value. Report a kind only when it can be read without decrypting +//! anything. One such kind is the kind of a value the caller sent. The +//! other is the kind of a node in the unencrypted structure of a stored +//! record. Examples of such a node are a list, an encrypted value, and a +//! value stored without encryption. Never report the kind that a value +//! decrypted to. That kind was inside the ciphertext, so it is part of +//! the plaintext. +//! - The position of a row in a batch. //! - Request kinds and HTTP status codes for ZeroKMS, CipherStash's //! key-management service. //! - Workspace IDs, workspace resource names (CRNs), and regions. From 1788adb369db4006e000773403b1a9868361ee05 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sat, 28 Nov 2026 19:28:41 +1100 Subject: [PATCH 12/14] docs(stack-encrypt): list every key a field spec accepts The doc on Error::Plan named four keys. The plan reader also accepts "null", as the doc on Reason::UnknownKey already says. --- packages/stack-encrypt/src/refusal.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/stack-encrypt/src/refusal.rs b/packages/stack-encrypt/src/refusal.rs index 2242266b5..cb11c2fa1 100644 --- a/packages/stack-encrypt/src/refusal.rs +++ b/packages/stack-encrypt/src/refusal.rs @@ -153,7 +153,7 @@ pub enum Error { /// field spec is the entry that describes one field. /// - A field has no output, or lists an output twice. /// - A field spec has a key that is not `"context"`, `"outputs"`, - /// `"target"`, or `"type"`. + /// `"target"`, `"type"`, or `"null"`. /// - A field names a type that does not exist. /// - A field asks for an index that is not defined for its declared /// type. From 3625e78096c5448a9a5fbf810e4a82e1f4428a1e Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sat, 28 Nov 2026 21:02:05 +1100 Subject: [PATCH 13/14] fix(stack-encrypt): say what the caller passed in the input error messages The messages of the dynamic input errors used the names in the code, such as "record source", "sealed value", and "transport frame". The developer who gets one of these errors did not write those names. The messages now name what the developer passed: the record to encrypt, the record to decrypt, or the query input. Only the text of the messages changes. The codes, the reason names, the payload fields, and the variants stay the same. - An error with a `found` kind has a message of one sentence. An example is "row 2 of the records to encrypt is null, not an object of fields". That message no longer starts with "record source does not fit the plan". The start repeated what the sentence says. - The other messages of `Error::Source` start with the input that the reason is about. A record and a query can both cause a value of another type, or an `undefined` value. For those two reasons, the message names both inputs when the error has no row. - The message of `Error::Record` starts with "the record to decrypt does not match the plan". - The message of `Error::SourceFailed` says that a value in the record to encrypt returned an error. The help text says why the message leaves the cause out. - The message for plan bytes that are not a frame says what a transport frame is. - A message says "an encrypted value" for the kind `sealed`, and "a type this build does not define" for an unknown logical type. No message includes a value, the text of a cause, or the kind that a value decrypted to. The tests that pin the cause text and the `Debug` output still pass unchanged. --- packages/stack-encrypt/CHANGELOG.md | 32 +++- packages/stack-encrypt/src/dynamic/record.rs | 168 ++++++++++++++++--- packages/stack-encrypt/src/refusal.rs | 115 +++++++++---- 3 files changed, 252 insertions(+), 63 deletions(-) diff --git a/packages/stack-encrypt/CHANGELOG.md b/packages/stack-encrypt/CHANGELOG.md index 5f97efcda..e63e1efed 100644 --- a/packages/stack-encrypt/CHANGELOG.md +++ b/packages/stack-encrypt/CHANGELOG.md @@ -520,10 +520,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 The changes are: - The error names the kind of value that the engine got, and never includes the value. The kind is in `Error::found()`, in the payload - field `found`, and in the message. An example of the message is - `row 2 of the records to encrypt is null, not an object of fields`. + field `found`, and in the message. The message is one sentence, such + as `row 2 of the records to encrypt is null, not an object of fields`. The new `dynamic::Found` lists the kinds, such as `"null"`, `"array"`, - `"string"`, `"uint32"`, `"passthrough"`, and `"sealed"`. + `"string"`, `"uint32"`, `"passthrough"`, and `"sealed"`. The message + says `an encrypted value` for the kind `"sealed"`. - An error names a kind only when the engine can read the kind without decrypting anything. That is the kind of a value the caller sent, or the kind of a node in the unencrypted structure of a stored record. @@ -567,11 +568,26 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 message leaves the cause out, and `Debug` prints the cause as `SourceError(..)`, because the text of the caller's error can include the value. - - The message of an `Error::Source` starts with `query input does not - fit the field` when only the input of a query can cause the reason. - Before, that message started with `record source does not fit the - plan`. Those reasons are about an operator, a range, a term, - statistics, a null query, or the input of a JSON operator. + - The message of an `Error::Source` names the input that the reason is + about. Before, every such message started with `record source does not + fit the plan`. Now the message starts with one of these: + - `the query input does not match the field`, when only the input of a + query can cause the reason. Those reasons are about an operator, a + range, a term, statistics, a null query, or the input of a JSON + operator. + - `the record to encrypt or the query input does not match the plan`, + for a value of another type and for an `undefined` value, when the + error names no row. A record and a query can both cause those + reasons. + - `the record to encrypt does not match the plan`, for every other + reason. + - The message of an `Error::Record` starts with `the record to decrypt + does not match the plan`. Before, that message started with `stored + record does not fit the plan`. + - The message of an `Error::SourceFailed` starts with `a value in the + record to encrypt returned an error while it was read`. The row and + the field follow. For an error that names no field, the message starts + with `the record to encrypt`. - **`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/record.rs b/packages/stack-encrypt/src/dynamic/record.rs index 124d10228..754a8f6dc 100644 --- a/packages/stack-encrypt/src/dynamic/record.rs +++ b/packages/stack-encrypt/src/dynamic/record.rs @@ -8908,7 +8908,7 @@ mod tests { assert_eq!(error.found(), None, "no kind for bytes: {error}"); assert_eq!( error.to_string(), - "record plan is malformed: the bytes are not one transport frame", + "record plan is malformed: the plan bytes are not one transport frame, the binary encoding of one value", "the message" ); } @@ -8929,9 +8929,7 @@ mod tests { expect_shape(&error, "Plan", None, None, found); assert_eq!( error.to_string(), - format!( - "record plan is malformed: the plan is {found}, not an object of field specs" - ), + format!("the plan is {found}, not an object of field specs"), "the message" ); @@ -8939,9 +8937,7 @@ mod tests { expect_shape(&error, "Plan", Some("age"), None, found); assert_eq!( error.to_string(), - format!( - r#"record plan is malformed: the field's spec is {found}, not an object (field "age")"# - ), + format!(r#"the field's spec is {found}, not an object (field "age")"#), "the message" ); } @@ -9040,9 +9036,7 @@ mod tests { expect_shape(&error, "Source", None, Some(2), found); assert_eq!( error.to_string(), - format!( - "record source does not fit the plan: row 2 of the records to encrypt is {found}, not an object of fields" - ), + format!("row 2 of the records to encrypt is {found}, not an object of fields"), "the message" ); } @@ -9051,7 +9045,7 @@ mod tests { expect_shape(&error, "Source", None, None, Found::Passthrough); assert_eq!( error.to_string(), - "record source does not fit the plan: the record to encrypt is a passthrough value, not an object of fields", + "the record to encrypt is a passthrough value, not an object of fields", "the message" ); // A value that is not of its field's declared type is refused @@ -9242,7 +9236,8 @@ mod tests { assert_eq!(error.found(), None, "nothing was found"); let message = error.to_string(); assert_eq!( - message, r#"record source failed while it was read (row 1, field "email")"#, + message, + r#"a value in the record to encrypt returned an error while it was read (row 1, field "email")"#, "the message" ); let cause = std::error::Error::source(&error).expect("a cause"); @@ -9282,6 +9277,79 @@ mod tests { ); } + /// The message of an [`Error::SourceFailed`] says "a value in the + /// record to encrypt" only when the error names a field. The help + /// text says why the message leaves the cause out. Neither text + /// includes the text of the cause. + #[test] + fn a_source_failure_says_where_it_happened() { + use miette::Diagnostic; + use vitaminc_aead::plaintext::SourceError; + let failed = |row, field: Option<&str>| Error::SourceFailed { + field: field.map(str::to_owned), + row, + cause: SourceError::msg("the getter saw marker-value"), + }; + for (row, field, message) in [ + ( + Some(1), + Some("email"), + r#"a value in the record to encrypt returned an error while it was read (row 1, field "email")"#, + ), + ( + None, + Some("email"), + r#"a value in the record to encrypt returned an error while it was read (field "email")"#, + ), + ( + Some(1), + None, + "the record to encrypt returned an error while it was read (row 1)", + ), + ( + None, + None, + "the record to encrypt returned an error while it was read", + ), + ] { + let error = failed(row, field); + assert_eq!(error.to_string(), message, "{row:?} {field:?}"); + let help = error.help().expect("help").to_string(); + assert_eq!( + help, + "The error that the value returned is the cause of this error. The message leaves the cause out, because the text of the cause can include the value.", + "the help" + ); + assert!(!help.contains("marker-value"), "no cause text: {help}"); + } + assert_eq!( + Reason::SourceFailed.to_string(), + "a value returned an error while it was read", + "the reason" + ); + } + + /// The phrase that a message uses for each kind of value. The + /// phrase for an encrypted value does not use the name `sealed` + /// that the payload has. + #[test] + fn a_found_is_written_as_a_phrase() { + for (found, phrase) in [ + (Found::Null, "null"), + (Found::Undefined, "undefined"), + (Found::Passthrough, "a passthrough value"), + (Found::Sealed, "an encrypted value"), + (Found::Kind(ValueKind::Array), "an array"), + (Found::Kind(ValueKind::UInt32), "a uint32"), + ( + Found::Unknown, + "a value of a type this build does not define", + ), + ] { + assert_eq!(found.to_string(), phrase, "{found:?}"); + } + } + /// The source shapes the shared runtime corpus cannot build: its /// host projection has no passthrough, no repeated key and no /// non-object row. A missing field, an unknown field and a value @@ -9384,7 +9452,7 @@ mod tests { expect_shape(&error, "Record", None, None, Found::Sealed); assert_eq!( error.to_string(), - "stored record does not fit the plan: the record to decrypt is a sealed value, not an object of stored fields", + "the record to decrypt is an encrypted value, not an object of stored fields", "the message" ); for (what, stored, found) in [ @@ -9401,7 +9469,7 @@ mod tests { assert_eq!( error.to_string(), format!( - "stored record does not fit the plan: row 1 of the records to decrypt is {found}, not an object of stored fields" + "row 1 of the records to decrypt is {found}, not an object of stored fields" ), "{what}: the message" ); @@ -9542,11 +9610,16 @@ mod tests { } } - /// When only the input of a query can cause the reason, the message - /// says that the query input does not fit the field. For a reason - /// that a record source can cause, the message says that the record - /// source does not fit the plan. That includes a value of another - /// type. A query and a record can both cause that reason. + /// The start of the message of an [`Error::Source`] names the input + /// that the reason is about: + /// + /// - The query input, when only the input of a query can cause the + /// reason. + /// - The record to encrypt, when only a record can cause the reason. + /// - Both, when a query and a record can both cause the reason and + /// the error names no row. Those reasons are a value of another + /// type and an `undefined` value. With a row, the message names + /// the record, because only a record has rows. #[test] fn a_query_refusal_names_the_query_input() { use Reason::*; @@ -9572,24 +9645,75 @@ mod tests { let error = Error::bad_source(reason).in_field("age"); assert_eq!( error.to_string(), - format!(r#"query input does not fit the field: {reason} (field "age")"#), + format!(r#"the query input does not match the field: {reason} (field "age")"#), "{reason:?}" ); } for reason in [ FieldMissing, + FieldRepeated, UnknownField, - FieldType, + RepeatedKey, Passthrough, Unframeable, ] { let error = Error::bad_source(reason).in_field("age"); assert_eq!( error.to_string(), - format!(r#"record source does not fit the plan: {reason} (field "age")"#), + format!( + r#"the record to encrypt does not match the plan: {reason} (field "age")"# + ), + "{reason:?}" + ); + } + for reason in [FieldType, Undefined] { + let error = Error::bad_source(reason).in_field("age"); + assert_eq!( + error.to_string(), + format!( + r#"the record to encrypt or the query input does not match the plan: {reason} (field "age")"# + ), "{reason:?}" ); + let in_a_row = Error::Source { + field: Some("age".to_owned()), + row: Some(2), + reason, + found: None, + }; + assert_eq!( + in_a_row.to_string(), + format!( + r#"the record to encrypt does not match the plan: {reason} (row 2, field "age")"# + ), + "{reason:?} in a row" + ); } + // A reason that only a record can cause names the record with or + // without a row. + let unwritten = Error::Source { + field: None, + row: Some(1), + reason: Unframeable, + found: None, + }; + assert_eq!( + unwritten.to_string(), + format!("the record to encrypt does not match the plan: {Unframeable} (row 1)"), + "a row that the source never wrote" + ); + assert_eq!( + Error::bad_record(NoCiphertextNode) + .in_field("email") + .to_string(), + r#"the record to decrypt does not match the plan: no "c" node (field "email")"#, + "a stored record" + ); + assert_eq!( + Error::bad_plan(NoFields).to_string(), + "record plan is malformed: the plan has no fields", + "a plan" + ); } /// `in_field` names the field only where none is named yet. diff --git a/packages/stack-encrypt/src/refusal.rs b/packages/stack-encrypt/src/refusal.rs index cb11c2fa1..6242be4b1 100644 --- a/packages/stack-encrypt/src/refusal.rs +++ b/packages/stack-encrypt/src/refusal.rs @@ -162,8 +162,8 @@ pub enum Error { /// - The plan declares two fields under one identity, or fields under /// different contexts. No plan allows either. #[error( - "record plan is malformed: {}", - misfit_text(Subject::Plan, *reason, *found, None, field) + "{}", + misfit_text("record plan is malformed", Subject::Plan, *reason, *found, None, field) )] #[diagnostic(code(stack_encrypt::dynamic_plan))] Plan { @@ -250,10 +250,10 @@ pub enum Error { /// The message and `Debug` leave the cause out, because the text of the /// caller's error can include the value. `Debug` prints the cause as /// `SourceError(..)`. The reason is [`Reason::SourceFailed`]. - #[error("record source failed while it was read{}", place_text(*row, field))] + #[error("{}", source_failed_text(*row, field))] #[diagnostic( code(stack_encrypt::dynamic_source_failed), - help("The value's own error is this error's cause. It is left out of the message, because it can quote the value.") + help("The error that the value returned is the cause of this error. The message leaves the cause out, because the text of the cause can include the value.") )] SourceFailed { /// The field whose value the engine was reading. `None` when the @@ -289,8 +289,15 @@ pub enum Error { /// fails with [`PlanError::FieldType`](crate::PlanError::FieldType) /// instead. #[error( - "stored record does not fit the plan: {}", - misfit_text(Subject::Record, *reason, *found, *row, field) + "{}", + misfit_text( + "the record to decrypt does not match the plan", + Subject::Record, + *reason, + *found, + *row, + field + ) )] #[diagnostic(code(stack_encrypt::dynamic_record))] Record { @@ -458,12 +465,40 @@ fn place_text(row: Option, field: &Option) -> String { } } +/// The message of an [`Error::SourceFailed`]. +/// +/// With a field, the message starts with "a value in the record to +/// encrypt". Without a field, the error happened outside the value of any +/// field, so the message starts with "the record to encrypt". +fn source_failed_text(row: Option, field: &Option) -> String { + let what = match field { + Some(_) => "a value in the record to encrypt", + None => "the record to encrypt", + }; + format!( + "{what} returned an error while it was read{}", + place_text(row, field) + ) +} + /// The message of an [`Error::Source`]. /// -/// The message starts with "query input does not fit the field" when only -/// the input of a query can cause the reason ([`answers_a_query`]). For -/// every other reason, the message starts with "record source does not fit -/// the plan". +/// The start of the message names the input that the reason is about. +/// There are three cases: +/// +/// - Only the input of a query can cause the reason +/// ([`answers_a_query`]). The message starts with "the query input does +/// not match the field". +/// - A record and a query can both cause the reason +/// ([`either_input_can_cause`]), and the error names no row. The message +/// starts with "the record to encrypt or the query input does not match +/// the plan". +/// - Every other error is about a record. That includes an error that +/// names a row, because only a record has rows. The message starts with +/// "the record to encrypt does not match the plan". +/// +/// The message of an error with a [`Found`] has no such start. That message +/// is the sentence that [`misfit_text`] writes. fn source_text( reason: Reason, found: Option, @@ -471,14 +506,22 @@ fn source_text( field: &Option, ) -> String { let what = if answers_a_query(reason) { - "query input does not fit the field" + "the query input does not match the field" + } else if row.is_none() && either_input_can_cause(reason) { + "the record to encrypt or the query input does not match the plan" } else { - "record source does not fit the plan" + "the record to encrypt does not match the plan" }; - format!( - "{what}: {}", - misfit_text(Subject::Source, reason, found, row, field) - ) + misfit_text(what, Subject::Source, reason, found, row, field) +} + +/// Returns `true` when a record and a query can both cause `reason`. +/// +/// Those reasons are the ones in an error from +/// [`read`](crate::dynamic::read). A record and a query both call `read` to +/// convert a value to the type of its field. +fn either_input_can_cause(reason: Reason) -> bool { + matches!(reason, Reason::FieldType | Reason::Undefined) } /// Returns `true` when only the input of a query can cause `reason`. @@ -486,9 +529,9 @@ fn source_text( /// Those reasons are about an operator, a range, a term, statistics, a /// null query, or the input of a JSON operator. /// -/// [`Reason::FieldType`] returns `false`. A query and a record both get -/// that reason for a value that cannot be read as the field's type. So the -/// message for that reason keeps the wording for a record. +/// [`Reason::FieldType`] and [`Reason::Undefined`] return `false`. A query +/// and a record both get those reasons for a value that cannot be read as +/// the field's type ([`either_input_can_cause`]). fn answers_a_query(reason: Reason) -> bool { use Reason::*; matches!( @@ -522,15 +565,21 @@ enum Subject { Record, } -/// The main part of the message of an error about a plan, a record -/// source, or a stored record. +/// The message of an error about a plan, a record source, or a stored +/// 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. /// -/// 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. +/// 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, reason: Reason, found: Option, @@ -538,9 +587,9 @@ fn misfit_text( field: &Option, ) -> String { let Some(found) = found else { - return format!("{reason}{}", place_text(row, field)); + return format!("{what}: {reason}{}", place_text(row, field)); }; - let what = match (subject, row, field) { + let input = match (subject, row, field) { (Subject::Plan, _, None) => "the plan".to_owned(), (Subject::Plan, _, Some(_)) => "the field's spec".to_owned(), (Subject::Source, None, _) => "the record to encrypt".to_owned(), @@ -554,7 +603,7 @@ fn misfit_text( (Subject::Source, _) => "an object of fields", (Subject::Record, _) => "an object of stored fields", }; - format!("{what} is {found}, not {expected}{}", in_field_text(field)) + format!("{input} is {found}, not {expected}{}", in_field_text(field)) } impl Error { @@ -1014,10 +1063,10 @@ reasons! { /// transport frame is the binary encoding of one value. The bytes /// are empty, end early, repeat a key at any depth, or continue /// after the value ends. A plan sent as JSON text gets this reason. - NotAFrame => "not_a_frame", "the bytes are not one transport frame"; + NotAFrame => "not_a_frame", "the plan bytes are not one transport frame, the binary encoding of one value"; /// 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"; + SourceFailed => "source_failed", "a value returned an error while it was read"; } } @@ -1087,12 +1136,12 @@ impl fmt::Display for Found { Self::Null => f.write_str("null"), Self::Undefined => f.write_str("undefined"), Self::Passthrough => f.write_str("a passthrough value"), - Self::Sealed => f.write_str("a sealed value"), + Self::Sealed => f.write_str("an encrypted value"), Self::Kind(kind) => { let name = kind.name(); write!(f, "{} {name}", crate::plan::article(name)) } - Self::Unknown => f.write_str("a value of a type this build does not know"), + Self::Unknown => f.write_str("a value of a type this build does not define"), } } } From 8f823d96739dcc3cd07712b1fbd3794c11acbee7 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sat, 28 Nov 2026 22:59:14 +1100 Subject: [PATCH 14/14] refactor(stack-encrypt, aead): hide a source error's text in its own Debug The text of a SourceError comes from the caller's own code, and it can include the value that failed. So `dynamic::Error` had a hand-written Debug that matched on every variant, only to print the cause of SourceFailed as `SourceError(..)`. The placeholder now comes from SourceError itself, in vitaminc-aead. SourceError has a small Debug that prints `SourceError(..)` and nothing of the error it wraps. A type that contains a SourceError can derive Debug again. `dynamic::Error` derives Debug, and the hand-written impl is gone. The Debug output of each variant of `dynamic::Error` is the same as before, in the plain form and the pretty form. A test that formatted one value of each variant gave the same bytes before and after the change. Three errors in vitaminc-aead contain a SourceError, and they print the placeholder now too: `EncryptError::Source`, `DecodeError::Source`, and `FrameWriteError::Source`. Before, their derived Debug printed the caller's text. `Display`, `inner()`, and `source()` are unchanged. A caller that needs the text reads it through one of them on purpose. --- packages/stack-encrypt/src/refusal.rs | 90 ++----------------- packages/vitaminc-aead/CHANGELOG.md | 8 ++ packages/vitaminc-aead/src/plaintext/mod.rs | 24 ++++- .../vitaminc-aead/src/plaintext/sources.rs | 32 +++++++ 4 files changed, 68 insertions(+), 86 deletions(-) diff --git a/packages/stack-encrypt/src/refusal.rs b/packages/stack-encrypt/src/refusal.rs index 6242be4b1..dd5deaa10 100644 --- a/packages/stack-encrypt/src/refusal.rs +++ b/packages/stack-encrypt/src/refusal.rs @@ -103,11 +103,11 @@ use crate::target::IndexSpec; /// `Cipher` carry the payload of the error they hold, and `Internal` carries /// none. A binding reads `reason` when it is there, and does not require it. /// -/// `Debug` prints every field as a derived `Debug` would, with one -/// exception. For [`SourceFailed`](Error::SourceFailed), `Debug` prints the -/// cause as `SourceError(..)`. The cause is an error from the caller's own -/// code. The text of that error can include the value that failed. -#[derive(thiserror::Error, miette::Diagnostic)] +/// `Debug` prints no text from the caller's own code. The cause of a +/// [`SourceFailed`](Error::SourceFailed) is a +/// [`SourceError`](vitaminc_aead::plaintext::SourceError), and its `Debug` +/// prints `SourceError(..)`. +#[derive(Debug, thiserror::Error, miette::Diagnostic)] #[non_exhaustive] pub enum Error { /// A value used as an encryption context is not one — a boolean, float, @@ -365,86 +365,6 @@ pub enum Error { Cipher(#[from] crate::Error), } -impl fmt::Debug for Error { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::Context { field, reason } => f - .debug_struct("Context") - .field("field", field) - .field("reason", reason) - .finish(), - Self::Term { field, kind } => f - .debug_struct("Term") - .field("field", field) - .field("kind", kind) - .finish(), - Self::Plan { - field, - reason, - found, - } => f - .debug_struct("Plan") - .field("field", field) - .field("reason", reason) - .field("found", found) - .finish(), - Self::UntypedIndex { field } => f - .debug_struct("UntypedIndex") - .field("field", field) - .finish(), - Self::Source { - field, - row, - reason, - found, - } => f - .debug_struct("Source") - .field("field", field) - .field("row", row) - .field("reason", reason) - .field("found", found) - .finish(), - // The cause comes from the caller's code, and its text can - // include the value that failed. `Debug` prints a placeholder - // for the cause. A caller gets the cause from `source()`. - Self::SourceFailed { field, row, .. } => f - .debug_struct("SourceFailed") - .field("field", field) - .field("row", row) - .field("cause", &format_args!("SourceError(..)")) - .finish(), - Self::Record { - field, - row, - reason, - found, - } => f - .debug_struct("Record") - .field("field", field) - .field("row", row) - .field("reason", reason) - .field("found", found) - .finish(), - Self::Predicate { - field, - reason, - construct, - at, - } => f - .debug_struct("Predicate") - .field("field", field) - .field("reason", reason) - .field("construct", construct) - .field("at", at) - .finish(), - Self::Internal => f.write_str("Internal"), - #[cfg(feature = "dynamic")] - Self::Target(error) => f.debug_tuple("Target").field(error).finish(), - Self::Cipher(error) => f.debug_tuple("Cipher").field(error).finish(), - } - } -} - /// ` (field "age")`, or nothing: the tail of an input error's message. fn in_field_text(field: &Option) -> String { field diff --git a/packages/vitaminc-aead/CHANGELOG.md b/packages/vitaminc-aead/CHANGELOG.md index 7549ee1f9..f03bb0d49 100644 --- a/packages/vitaminc-aead/CHANGELOG.md +++ b/packages/vitaminc-aead/CHANGELOG.md @@ -42,6 +42,14 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). The decrypt sink of `OwnedFrame` writes through them, reporting `DecodeError`. - `DecodeError` implements `From`: a scalar its logical type does not admit is `DecodeError::Expected`, a source's failure is `DecodeError::Source`, and any other refusal is `DecodeError::Source` with the writer's error as its source. +### Security + +- `plaintext::SourceError` prints `SourceError(..)` in `Debug`, and none of the error it wraps. + The wrapped error comes from the caller's code, and its text can include the value that failed. + Before, `Debug` printed that text, so `{:?}`, a log line, or a panic from `unwrap` could print the value. + The errors that contain a `SourceError` now print the same placeholder in `Debug`: `EncryptError::Source`, `DecodeError::Source`, and `FrameWriteError::Source`. + `Display`, `inner`, and `source()` are unchanged, so a caller that needs the text still gets it. + ## [0.10.0] - 2026-11-19 ### Wire format diff --git a/packages/vitaminc-aead/src/plaintext/mod.rs b/packages/vitaminc-aead/src/plaintext/mod.rs index 90b77871b..146d42523 100644 --- a/packages/vitaminc-aead/src/plaintext/mod.rs +++ b/packages/vitaminc-aead/src/plaintext/mod.rs @@ -282,10 +282,32 @@ pub trait Error: Sized { /// Transparent: it displays as the wrapped error, and its `source()` is the /// wrapped error's, so a reporter that walks the chain sees what lies behind /// a failed getter. -#[derive(Debug, thiserror::Error)] +/// +/// `Debug` prints `SourceError(..)` and none of the wrapped error. The +/// wrapped error comes from the caller's code, and its text can include the +/// value that failed. So an error type that contains a `SourceError` can +/// derive `Debug`, and `{:?}`, a log line, or a panic from `unwrap` prints no +/// value. A caller that needs the text asks for it on purpose: through +/// `Display`, [`inner`](Self::inner), or `source()`. +/// +/// ``` +/// use vitaminc_aead::plaintext::SourceError; +/// +/// let error = SourceError::msg("the getter saw 4111 1111 1111 1111"); +/// assert_eq!(format!("{error:?}"), "SourceError(..)"); +/// assert_eq!(error.to_string(), "the getter saw 4111 1111 1111 1111"); +/// ``` +#[derive(thiserror::Error)] #[error(transparent)] pub struct SourceError(Box); +/// Prints a placeholder for the wrapped error, in both `{:?}` and `{:#?}`. +impl core::fmt::Debug for SourceError { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + f.write_str("SourceError(..)") + } +} + impl SourceError { /// A source error from any error type. pub fn new(error: impl core::error::Error + Send + Sync + 'static) -> Self { diff --git a/packages/vitaminc-aead/src/plaintext/sources.rs b/packages/vitaminc-aead/src/plaintext/sources.rs index 3248aaeb2..6b5245012 100644 --- a/packages/vitaminc-aead/src/plaintext/sources.rs +++ b/packages/vitaminc-aead/src/plaintext/sources.rs @@ -805,6 +805,38 @@ mod tests { assert!(SourceError::msg("plain").source().is_none()); } + /// `Debug` prints a placeholder and none of the wrapped error's text, in + /// the plain form and the pretty form. A type that contains a + /// `SourceError` and derives `Debug` prints the placeholder in the same + /// place. + #[test] + fn a_source_error_prints_no_text_in_debug() { + #[derive(Debug)] + #[allow(dead_code, reason = "only `Debug` reads the fields")] + struct Holder { + row: usize, + cause: SourceError, + } + + let error = SourceError::msg("the getter saw marker-value"); + assert_eq!(format!("{error:?}"), "SourceError(..)"); + assert_eq!(format!("{error:#?}"), "SourceError(..)"); + assert_eq!(error.to_string(), "the getter saw marker-value"); + + let holder = Holder { + row: 2, + cause: error, + }; + assert_eq!( + format!("{holder:?}"), + "Holder { row: 2, cause: SourceError(..) }" + ); + assert_eq!( + format!("{holder:#?}"), + "Holder {\n row: 2,\n cause: SourceError(..),\n}" + ); + } + #[test] fn byte_strings_are_byte_leaves_not_sequences() { assert_eq!(