diff --git a/.cargo/mutants.toml b/.cargo/mutants.toml index 992e76a19e..d07251da8f 100644 --- a/.cargo/mutants.toml +++ b/.cargo/mutants.toml @@ -153,17 +153,18 @@ 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, statistics and a plan's root are each refused with one fixed - # `Reason` (`ContextKind`, `NotStats`, `NotAnObject`), 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 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$', diff --git a/conformance/stack-encrypt/declaration-grammar.md b/conformance/stack-encrypt/declaration-grammar.md index afdbbe447d..6ae67da0ec 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/raw-frames-contract.md b/conformance/stack-encrypt/raw-frames-contract.md index dc60b2416d..d40d3fb408 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. 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/conformance/stack-encrypt/v1/record-declarations-v1.cases.json b/conformance/stack-encrypt/v1/record-declarations-v1.cases.json index 2ec5851468..4367ba4fba 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,13 +3428,28 @@ "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", "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/conformance/stack-encrypt/v1/record-reads-v1.cases.json b/conformance/stack-encrypt/v1/record-reads-v1.cases.json index 7cdaad2a98..b0df0808b8 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" } } }, diff --git a/languages/golang/CHANGELOG.md b/languages/golang/CHANGELOG.md index 2396d56661..91a657e56e 100644 --- a/languages/golang/CHANGELOG.md +++ b/languages/golang/CHANGELOG.md @@ -22,6 +22,19 @@ 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). 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 - **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 15b9dc9313..90158ae441 100644 --- a/languages/golang/encrypt/errors.go +++ b/languages/golang/encrypt/errors.go @@ -89,16 +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; 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, -// 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/ops.rs b/languages/golang/encrypt/guest/src/ops.rs index 3eff02efb2..2374f4ac47 100644 --- a/languages/golang/encrypt/guest/src/ops.rs +++ b/languages/golang/encrypt/guest/src/ops.rs @@ -428,7 +428,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 570dd9e5b3..46d664c07f 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`, `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. @@ -189,6 +192,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 +437,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 +568,7 @@ mod tests { Error::Plan { field: age(), reason: Reason::DuplicateOutput, + found: None, }, ), ( @@ -574,14 +581,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 26ddf3403b..973aa98ef5 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, 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,6 +136,45 @@ func (d *Diagnostic) Reason() string { return reason } +// 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 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 +} + // 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 28f60b6871..614db92277 100644 --- a/languages/golang/internal/guest/diagnostic_test.go +++ b/languages/golang/internal/guest/diagnostic_test.go @@ -319,6 +319,31 @@ func TestConstructAndAtReadARefusedPredicate(t *testing.T) { } } +// 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 { + 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 399b28ef73..e63e1efed9 100644 --- a/packages/stack-encrypt/CHANGELOG.md +++ b/packages/stack-encrypt/CHANGELOG.md @@ -504,6 +504,91 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Breaking +- **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. 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"`. 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. + 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` 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). `dynamic::frame` re-exports both from vitaminc. A `Frame` is one value's diff --git a/packages/stack-encrypt/Cargo.toml b/packages/stack-encrypt/Cargo.toml index c9a28dfb04..4f617651a5 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 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/codes.rs b/packages/stack-encrypt/src/codes.rs index 10ced550ea..d7b47ae449 100644 --- a/packages/stack-encrypt/src/codes.rs +++ b/packages/stack-encrypt/src/codes.rs @@ -219,6 +219,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()), @@ -587,6 +592,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/found.rs b/packages/stack-encrypt/src/dynamic/found.rs new file mode 100644 index 0000000000..61b2dc9768 --- /dev/null +++ b/packages/stack-encrypt/src/dynamic/found.rs @@ -0,0 +1,337 @@ +//! 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}; + +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 { + /// 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); + } + match logical { + Some(Logical::Undefined) => Self::Undefined, + Some(Logical::Unknown(_)) => Self::Unknown, + _ => ValueKind::of(None, value).map_or(Self::Null, Self::Kind), + } + } + + /// 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); + } + if frame.is_null() { + return Self::Null; + } + // 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) + } + + /// 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()); + let _ = frame.visit(Lookup { + key, + found: &found, + keys: &keys, + }); + found.get().map(|found| (found, keys.into_inner())) + } +} + +/// 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()); + let _ = frame.visit(Probe::noting(&found, Some(&keys))); + (found.get() == Some(Found::Kind(ValueKind::Object))).then(|| keys.into_inner()) +} + +/// 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 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), + keys, + } + } + + /// A probe that reads a value and records 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 probe for the entries has the `keys` list, so that it records + // each key. + 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`] 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>, + 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}; + + /// [`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"); + 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:?}" + ); + } + } + + /// 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; + 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/json_query.rs b/packages/stack-encrypt/src/dynamic/json_query.rs index 98ed175602..76a96909a3 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 22ce22925d..8f38d5a044 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, }) }) } @@ -1953,7 +1957,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 +2024,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 56cdd9b1b6..29cf6a0be8 100644 --- a/packages/stack-encrypt/src/dynamic/query.rs +++ b/packages/stack-encrypt/src/dynamic/query.rs @@ -425,10 +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, - }; + 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 @@ -448,10 +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, - }) + .ok_or_else(|| Error::bad_plan(Reason::NoSuchField).in_field(field)) } /// Operators a field answers, each with the index that answers it. @@ -583,10 +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, - }); + return Err(Error::bad_plan(Reason::BindInQuery).in_field(field)); } names_its_context(plan, field) } @@ -600,10 +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, - }), + Some(_) => Err(Error::bad_plan(Reason::QueryContextField).in_field(field)), None => Ok(()), } } @@ -619,20 +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, - })?; + 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, - }), + _ => Err(Error::bad_source(Reason::NullQuery).in_field(name)), }; } return read(answer.kind, input.frame()) @@ -649,10 +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, - } + Error::bad_source(Reason::NotARange).in_field(field) } /// What a query of `input` through `index` is refused for before any term @@ -860,10 +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, - } + Error::bad_source(Reason::JsonInput).in_field(field) } /// A JSON operator's term: the operand [`json_query`](super::json_query) @@ -1188,10 +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, - }), + _ => Err(Error::bad_source(Reason::ExactOperator).in_field(field)), } } @@ -1244,10 +1218,7 @@ pub fn verify( _ => Err(None), }, )) - .map_err(|_| Error::Source { - field: Some(field.to_owned()), - reason: Reason::FieldType, - }) + .map_err(|_| Error::bad_source(Reason::FieldType).in_field(field)) }) .collect() } @@ -1289,10 +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, - })?; + 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 cb1686a52e..754a8f6dc8 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::{ @@ -236,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 or a decimal) 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 @@ -310,10 +314,7 @@ impl FieldPlan { outputs: Vec, ) -> Result { let name = name.into(); - let refuse = |reason| Error::Plan { - field: Some(name.clone()), - reason, - }; + let refuse = |reason| Error::bad_plan(reason).in_field(&name); if outputs.is_empty() { return Err(refuse(Reason::NoOutputs)); } @@ -373,10 +374,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, - }); + return Err(Error::bad_plan(Reason::InvalidTarget).in_field(&name)); } let (label, extension) = field_context(&name, context.get())?; Ok(Self { @@ -425,10 +423,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, - }); + return Err(Error::bad_plan(reason).in_field(&self.name)); } } } @@ -538,10 +533,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, - }) + 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 @@ -643,10 +636,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, - }) + 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 @@ -752,10 +742,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, - }); + return Err(Error::bad_plan(Reason::MixedContexts).in_field(&field.name)); } } for field in fields.iter_mut().filter(|field| field.is_target()) { @@ -799,17 +786,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, + 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, - }) + return Err(Error::bad_plan(Reason::TargetOptions).in_field(&field.name)) } }; // A null has an equality term and no other, so a sealed null @@ -820,10 +803,7 @@ impl Plan { .iter() .any(|index| index != IndexSpec::Equality.key()) { - return Err(Error::Plan { - field: Some(field.name.clone()), - reason: Reason::SealedNullIndex, - }); + return Err(Error::bad_plan(Reason::SealedNullIndex).in_field(&field.name)); } } Self::build(Context::Label(context), fields) @@ -854,10 +834,7 @@ impl Plan { fields: Vec, ) -> Result { let context_field = context_field.into(); - let refuse = |reason| Error::Plan { - field: Some(context_field.clone()), - reason, - }; + 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)); }; @@ -872,10 +849,7 @@ impl Plan { .iter() .find(|field| field.label.segments().count() != 1) { - return Err(Error::Plan { - field: Some(field.name.clone()), - reason: Reason::ContextNotLabel, - }); + 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 @@ -912,10 +886,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, - }; + 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)); } @@ -1273,10 +1244,10 @@ pub fn plan(frame: vitaminc_protected::ProtectedRef<'_, [u8]>) -> Result = 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, - })?; + 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)?, @@ -1436,55 +1405,13 @@ 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()?; + super::found::object_keys(root)?.into_iter().nth(position) } /// 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 +1581,16 @@ 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 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 { + field: None, + reason: Reason::NotAnObject, + found: Some(Found::of_frame(root)), + }, + }; }; let field = &field; if field == CONTEXT_FIELD { @@ -1676,24 +1611,40 @@ 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 - } - Some(_) => Reason::MissingContext, - None => Reason::NotAnObject, + // 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)) + { + 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), + } + } }, }; - Error::Plan { - field: Some(field.clone()), - reason, - } + Error::bad_plan(reason).in_field(field) } /// Encrypt a record — or a batch of records — per a plan. @@ -1832,26 +1783,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, - })?; - let name = field.target().ok_or_else(|| Error::Plan { - field: Some(field.name.clone()), - reason: Reason::NotATarget, - })?; - let value = OwnedFrame::of(value).map_err(|_| Error::Source { - field: Some(field.name.clone()), - reason: Reason::FieldType, - })?; + .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, - }); + return Err(Error::bad_source(Reason::NullQuery).in_field(&field.name)); } value } else { @@ -2008,7 +1950,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 +1995,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, + } } }) }; @@ -2088,10 +2040,7 @@ enum Children<'a, T> { impl RecordTree for StackCipherText { fn misfit(field: &str, reason: Reason) -> Error { - Error::Record { - field: Some(field.to_owned()), - reason, - } + Error::bad_record(reason).in_field(field) } fn is_passthrough(&self) -> bool { @@ -2226,41 +2175,70 @@ 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::, _>>()?, )), } } -/// 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); +/// 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 }, + error => error, }; - let reason = match error { - FrameWriteError::DuplicateKey => Reason::RepeatedKey, - FrameWriteError::Invalid => Reason::FieldType, + let reason = match (error, field.is_some()) { + (FrameWriteError::DuplicateKey, true) => Reason::RepeatedKey, + (FrameWriteError::Invalid, true) => Reason::FieldType, _ => Reason::Unframeable, }; Error::Source { - field: Some(field), + field, + row, 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()), - reason, - }; + 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(); @@ -2328,10 +2306,7 @@ fn source_row(mut row: Vec<(String, OwnedFrame)>, plan: &Plan) -> Result Result { - let misfit = |reason| Error::Source { - field: Some(field.name.clone()), - reason, - }; + 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))? @@ -2532,6 +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 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(), @@ -2596,18 +2574,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)), + } +} + +/// The kind of a stored node, for the error about a node that is not a map +/// of fields. +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 +3064,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 +3239,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 +3265,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 +4272,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 +4300,8 @@ mod tests { &refused, Error::Plan { field: None, - reason: Reason::EmptyBinding + reason: Reason::EmptyBinding, + .. } ), "{refused:?}" @@ -4320,7 +4324,8 @@ mod tests { &refused, Error::Plan { field: None, - reason: Reason::Bind + reason: Reason::Bind, + .. } ), "{refused:?}" @@ -4349,7 +4354,8 @@ mod tests { &refused, Error::Plan { field: None, - reason: Reason::EmptyBinding + reason: Reason::EmptyBinding, + .. } ), "{refused:?}" @@ -4371,7 +4377,8 @@ mod tests { &refused, Error::Plan { field: None, - reason: Reason::Bind + reason: Reason::Bind, + .. } ), "{refused:?}" @@ -5664,7 +5671,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 +5842,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 +6061,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 +6123,19 @@ 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", - } + }, + "the field and the declared type" + ); + assert_eq!( + refused.to_string(), + 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; @@ -6153,10 +6167,61 @@ mod tests { PlanError::FieldType { field: "age".into(), expected: "uint64", - } + }, + "the field and the declared type" ); } + /// 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; + 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 (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) + .expect("the shape fits") + .await; + let refused = plan_error(result.expect_err("refused")); + assert_eq!( + refused, + PlanError::FieldType { + field: "doc".into(), + expected: "object", + }, + "{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, r#"field "doc" is not an object"#, + "{what}: the message names no kind" + ); + for kind in ["list", "array", "string", "null", "uint32", "secret"] { + assert!(!message.contains(kind), "{what}: {kind} in {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 +6748,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 +6803,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 +7721,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 +7771,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 +7797,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 +7805,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,16 +8844,131 @@ mod tests { } } - /// Bytes that are not one frame are not a plan. + /// 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, + 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. 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() { - 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 plan bytes are not one transport frame, the binary encoding of one value", + "the message" + ); + } + } + + /// 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 [ + (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!("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#"the field's spec is {found}, not an object (field "age")"#), + "the message" + ); } + // 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, + ) + .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 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![ + ("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 @@ -8837,18 +9017,37 @@ 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!("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(), + "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,16 +9131,28 @@ 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. + /// 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| { split_refusal(SplitRefusal { + row: None, field: field.map(str::to_owned), 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), @@ -8958,14 +9169,187 @@ 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, + // 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}"); + 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}" + ); + // 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, + error: FrameWriteError::Unwritten, + }); + expect(&unwritten, "Source", None, Reason::Unframeable); + assert_eq!(unwritten.row(), Some(1), "the row left unwritten"); + assert!( + matches!(unwritten.into_crate(), crate::Error::Input(_)), + "an input refusal" + ); + for error in [ + FrameWriteError::Invalid, + FrameWriteError::DuplicateKey, + FrameWriteError::TooDeep, + ] { + expect(&refusal(None, error), "Source", None, Reason::Unframeable); + } + } + + /// 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. The source returns an error inside + /// `email` in the second record. + 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#"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"); + 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}"); + // 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"), + "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" + ); + } + + /// 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 @@ -8995,7 +9379,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 +9391,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 +9407,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 +9449,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(), + "the record to decrypt is an encrypted 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!( + "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. @@ -9181,6 +9610,112 @@ mod tests { } } + /// 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::*; + 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#"the query input does not match the field: {reason} (field "age")"#), + "{reason:?}" + ); + } + for reason in [ + FieldMissing, + FieldRepeated, + UnknownField, + RepeatedKey, + Passthrough, + Unframeable, + ] { + let error = Error::bad_source(reason).in_field("age"); + assert_eq!( + error.to_string(), + 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. #[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 e1f00a406f..f0944ec744 100644 --- a/packages/stack-encrypt/src/dynamic/source.rs +++ b/packages/stack-encrypt/src/dynamic/source.rs @@ -16,30 +16,43 @@ //! 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 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. 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. +//! [`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::RefCell; +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, + Encrypt, EncryptRef, FixedType, Logical, MapSink, Physical, SeqSink, Sink, ValueKind, }; use vitaminc_protected::Buffer; -/// 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>; +use crate::refusal::Found; + +/// 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. pub(super) enum SplitSource { @@ -49,10 +62,18 @@ 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, 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, pub(super) field: Option, pub(super) error: FrameWriteError, } @@ -61,21 +82,38 @@ 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>; +/// The current position of the split in the source. +/// +/// `row` is the row of a batch that the split is reading. `field` is the +/// field whose value the split is writing. +/// +/// The split sets each one when the source starts it, and clears it when +/// the source finishes it. So an error between two rows names no row, and +/// an error between two fields names no field. Every sink in one split +/// shares one `Place`. +/// +/// Field names are not secret. The plan and the stored record both contain +/// them unencrypted. So the code does not wipe the name. +#[derive(Default)] +struct Place { + row: Cell>, + field: RefCell>, +} + +impl Place { + /// Clears the field, because the source has finished writing its value. + fn field_done(&self) { + *self.field.borrow_mut() = None; + } +} /// Where a finished record goes: returned to the caller, or added to a /// batch. @@ -94,18 +132,23 @@ impl PutRecord for TopRecord { } } -/// The next record of a batch. -struct BatchRecord<'s>(&'s mut Vec); +/// 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, +} impl PutRecord for BatchRecord<'_> { type Ok = (); fn put(self, record: SourceRecord) { - self.0.push(record); + self.records.push(record); + 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; @@ -113,18 +156,23 @@ 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> { Ok(BatchSink { - open: self.0, + place: self.0, records: Vec::new(), + begun: 0, }) } @@ -133,14 +181,34 @@ impl<'f> Sink for TopSink<'f> { } fn passthrough(self, _: &P) -> Result { - Ok(SplitSource::One(None)) + Ok(SplitSource::One(Err(Found::Passthrough))) } } /// 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> { - open: Open<'f>, + place: &'f Place, records: Vec, + begun: usize, +} + +impl BatchSink<'_> { + /// 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(()); + } + self.place.row.set(Some(self.records.len())); + Err(FrameWriteError::Unwritten) + } } impl<'f> SeqSink for BatchSink<'f> { @@ -152,13 +220,20 @@ impl<'f> SeqSink for BatchSink<'f> { Self: 's; fn element(&mut self) -> Result, FrameWriteError> { + self.check_written()?; + self.place.row.set(Some(self.begun)); + self.begun += 1; Ok(ElementSink { - open: self.open, - record: BatchRecord(&mut self.records), + place: self.place, + record: BatchRecord { + records: &mut self.records, + place: self.place, + }, }) } fn end(self) -> Result { + self.check_written()?; Ok(SplitSource::Batch(self.records)) } } @@ -166,7 +241,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>, } @@ -176,13 +251,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(()) } @@ -193,18 +268,19 @@ 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> { - 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 records that the element was an +/// array. struct NotARecord<'s> { record: BatchRecord<'s>, } @@ -222,7 +298,7 @@ impl SeqSink for NotARecord<'_> { } fn end(self) -> Result<(), FrameWriteError> { - self.record.put(None); + self.record.put(Err(Found::Kind(ValueKind::Array))); Ok(()) } } @@ -294,7 +370,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. @@ -302,32 +378,35 @@ 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(), } } } -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> { - *self.open.borrow_mut() = Some(key.to_owned()); + fn entry(&mut self, key: &str) -> Result, FrameWriteError> { + *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, // Pushed on the line above. None => unreachable!(), }; - Ok(FrameWriter::new(buffer)) + Ok(FieldWriter { + writer: FrameWriter::new(buffer), + place: self.place, + }) } fn end(self) -> Result { @@ -336,12 +415,113 @@ impl MapSink for RecordMap<'_, 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.borrow_mut() = Some(key.clone()); + *self.place.field.borrow_mut() = Some(key.clone()); FrameWriteError::Unwritten })?; record.push((key, value)); } - Ok(self.out.put(Some(record))) + Ok(self.out.put(Ok(record))) + } +} + +/// 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, +} + +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.place.field_done(); + Ok(()) + } + + fn typed_null(self, ty: FixedType) -> Result<(), FrameWriteError> { + self.writer.typed_null(ty)?; + self.place.field_done(); + Ok(()) + } + + fn seq(self, len: Option) -> Result, FrameWriteError> { + Ok(FieldSeq { + inner: self.writer.seq(len)?, + place: self.place, + }) + } + + fn map(self, len: Option) -> Result, FrameWriteError> { + Ok(FieldMap { + inner: self.writer.map(len)?, + place: self.place, + }) + } + + fn passthrough(self, value: &P) -> Result<(), FrameWriteError> { + self.writer.passthrough(value)?; + self.place.field_done(); + Ok(()) + } +} + +/// 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, +} + +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.place.field_done(); + Ok(()) + } +} + +/// 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, +} + +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.place.field_done(); + Ok(()) } } @@ -350,7 +530,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 +545,10 @@ mod tests { ) } - /// A record's fields as their frames' bytes, in source order. - fn bytes(record: &SourceRecord) -> Option)>> { - record.as_ref().map(|entries| { + /// 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 .iter() .map(|(key, value)| (key.clone(), value.frame().as_bytes().to_vec())) @@ -396,14 +577,18 @@ 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 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"); @@ -413,6 +598,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 +609,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. + /// 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_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 +664,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 +699,187 @@ 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; + /// 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() { + /// 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, + } 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, None, "every row begun is finished"); + } + + /// 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() { + /// The place in a batch of records where the source returns an + /// error. + #[derive(Clone, Copy, Debug)] + enum At { + /// The error happens in row 0, after `age` is written and before + /// `email` starts. + BetweenFields, + /// The error happens in row 0, inside the list `tags`, after its + /// first element. + InsideAList, + /// The error happens in row 0, after the map `tags` has ended. + AfterAMap, + /// The error happens after row 0 is finished, before row 1 + /// starts. + 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 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. The source starts row `dropped` and drops + /// its sink without writing a value. + 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 @@ -513,9 +895,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 df4bcea1fb..dd551a0ad2 100644 --- a/packages/stack-encrypt/src/plan/error.rs +++ b/packages/stack-encrypt/src/plan/error.rs @@ -255,7 +255,7 @@ impl crate::ErrorPayload for PlanError { /// 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", diff --git a/packages/stack-encrypt/src/plan/mod.rs b/packages/stack-encrypt/src/plan/mod.rs index b1b184e89a..c8d718a99c 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/refusal.rs b/packages/stack-encrypt/src/refusal.rs index 6250a41305..dd5deaa10a 100644 --- a/packages/stack-encrypt/src/refusal.rs +++ b/packages/stack-encrypt/src/refusal.rs @@ -22,6 +22,8 @@ use std::fmt; +use vitaminc_aead::plaintext::ValueKind; + use crate::target::IndexSpec; /// What went wrong in a dynamic operation, or in the input of a typed JSON @@ -56,15 +58,55 @@ use crate::target::IndexSpec; /// [`read`](crate::dynamic::read)); [`in_field`](Self::in_field) names it /// from the caller's side. /// -/// 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 -/// in the message, in [`reason`](Self::reason) and in the payload +/// 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`. +/// +/// 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` 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 { @@ -102,20 +144,37 @@ 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 - /// `"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))] + /// 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"`, `"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. + /// - 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( + "{}", + misfit_text("record plan is malformed", 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, + /// 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, }, /// A record plan field has a term output (`"eq"`, `"match"`, `"ore"`, @@ -135,49 +194,124 @@ pub enum Error { field: String, }, - /// 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 - /// 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. - #[error( - "record source does not fit the plan: {reason}{}", - in_field_text(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 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, + /// 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 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("{}", source_failed_text(*row, field))] + #[diagnostic( + code(stack_encrypt::dynamic_source_failed), + 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 + /// error happened outside the value of any field. + field: Option, + /// 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 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), 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: {reason}{}", - in_field_text(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 { /// The stored field at fault, if the fault is one field's. field: Option, + /// 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, + /// 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, }, /// A `match` predicate is refused at a place in its text: text the @@ -239,6 +373,159 @@ fn in_field_text(field: &Option) -> String { .unwrap_or_default() } +/// 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:?})"), + (Some(row), None) => format!(" (row {row})"), + (None, _) => in_field_text(field), + } +} + +/// 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 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, + row: Option, + field: &Option, +) -> String { + let what = if answers_a_query(reason) { + "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 { + "the record to encrypt does not match the plan" + }; + 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`. +/// +/// Those reasons are about an operator, a range, a term, statistics, a +/// null query, or the input of a JSON operator. +/// +/// [`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!( + reason, + UnknownOperator + | OperatorNotAnswered + | NotARange + | ExactOperator + | NotAQueryTerm + | NotStats + | NullQuery + | JsonInput + | JsonSyntax + | JsonDuplicateKey + | JsonIntegerRange + | JsonPathPosition + | JsonPathWildcard + | JsonPathNoWildcard + | JsonNoPredicates + | JsonWildcardBoundZero + | JsonUnknownPredicateOp + ) +} + +/// The input that an error message is about: the plan, the record source, +/// or the stored record. +#[derive(Clone, Copy)] +enum Subject { + Plan, + Source, + 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. +/// +/// 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, + row: Option, + field: &Option, +) -> String { + let Some(found) = found else { + return format!("{what}: {reason}{}", place_text(row, field)); + }; + let input = match (subject, row, field) { + (Subject::Plan, _, None) => "the plan".to_owned(), + (Subject::Plan, _, Some(_)) => "the field's spec".to_owned(), + (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!("{input} 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 +540,7 @@ impl Error { Self::Plan { field: None, reason, + found: None, } } @@ -260,7 +548,9 @@ impl Error { pub(crate) fn bad_source(reason: Reason) -> Self { Self::Source { field: None, + row: None, reason, + found: None, } } @@ -268,7 +558,9 @@ impl Error { pub(crate) fn bad_record(reason: Reason) -> Self { Self::Record { field: None, + row: None, reason, + found: None, } } @@ -284,6 +576,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 +595,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 +632,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 +640,42 @@ impl 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, .. } + | Self::SourceFailed { row, .. } + | Self::Record { row, .. } => *row, + _ => None, + } + } + + /// 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, .. } => { + *found + } + _ => None, + } + } } impl crate::ErrorPayload for Error { @@ -366,6 +697,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 } } @@ -419,6 +756,8 @@ reasons! { 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. + /// [`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. @@ -596,7 +935,7 @@ reasons! { /// A field with `"null": "sealed"` declares no type, or one of no /// fixed width (text, bytes, a container), whose absence the length /// of its ciphertext would show. - SealedNullType => "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 @@ -640,6 +979,14 @@ 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"; + /// 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 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 returned an error while it was read"; } } @@ -655,3 +1002,66 @@ impl fmt::Display for Reason { f.write_str(Self::WORDS[*self as usize].1) } } + +/// 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". +/// +/// 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, with or without a declared type. The name is `"null"`. + Null, + /// JavaScript's `undefined`. The name is `"undefined"`. + Undefined, + /// A passthrough: a value marked to be stored without encryption. The + /// name is `"passthrough"`. + Passthrough, + /// 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 [`ValueKind`]. The name is the schema name of the + /// kind, such as `"string"`, `"uint32"`, or `"array"`. + Kind(ValueKind), + /// A scalar whose logical type this build does not define. The name is + /// `"unknown"`. + Unknown, +} + +impl Found { + /// The name of the kind, as the payload field `found` contains it. + 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", + } + } +} + +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("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 define"), + } + } +} diff --git a/packages/stack-encrypt/tests/planned.rs b/packages/stack-encrypt/tests/planned.rs index 68a2525019..bf45fb389c 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 c1b7903438..322ae71552 100644 --- a/packages/stack-profile/src/diagnostic.rs +++ b/packages/stack-profile/src/diagnostic.rs @@ -58,6 +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, 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. diff --git a/packages/vitaminc-aead/CHANGELOG.md b/packages/vitaminc-aead/CHANGELOG.md index 7549ee1f9f..f03bb0d492 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 90b77871ba..146d42523f 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 3248aaeb2f..6b5245012e 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!(