From efcd81f7a5405318b15f3f3a9f55d7474ef529ba Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Tue, 24 Nov 2026 21:23:06 +1100 Subject: [PATCH] refactor(recipher-js): an error is its diagnostic and nothing else The addon described every error twice. It sorted each engine error into one of nine kinds with a match that sent any new engine variant to `internal`, the TypeScript listed the same kinds again, and the SDK's own 39 errors were string literals at each place they were raised, tied together only by a test that scanned the source. The diagnostic's code already says what an error is, more exactly than a kind, and every language SDK meets the same choice. So `kind` is gone. The SDK's own errors are one enum that derives `thiserror::Error` and `miette::Diagnostic`, with the code, message and help on each variant, as the engine declares its errors, and an error is raised by naming a variant. One function turns any diagnostic, the engine's, the value bridge's or the SDK's own, into the object JavaScript receives. A test builds one of every variant, through a match with no wildcard, and checks each code's form and that none is used twice. Removing a property changes the outcome's shape, so the binding interface moves to 4. Closes #1800. --- .../typescript/packages/recipher-js/README.md | 16 +- .../__tests__/addon/records.test.ts | 12 +- .../recipher-js/__tests__/addon/value.test.ts | 13 +- .../__tests__/addon/values.test.ts | 9 +- .../__tests__/unit/binding.test.ts | 16 +- .../recipher-js/__tests__/unit/error.test.ts | 26 +- .../packages/recipher-js/crate/Cargo.toml | 8 +- .../packages/recipher-js/crate/src/cipher.rs | 144 ++--- .../recipher-js/crate/src/ciphertext.rs | 43 +- .../recipher-js/crate/src/engine_tests.rs | 3 +- .../packages/recipher-js/crate/src/error.rs | 492 +++++++++++------- .../packages/recipher-js/crate/src/js.rs | 90 +--- .../packages/recipher-js/crate/src/json.rs | 139 ++--- .../packages/recipher-js/crate/src/lib.rs | 4 +- .../packages/recipher-js/crate/src/outcome.rs | 13 +- .../packages/recipher-js/crate/src/record.rs | 274 ++++------ .../recipher-js/crate/src/record_tests.rs | 9 +- .../packages/recipher-js/crate/src/value.rs | 17 +- .../packages/recipher-js/native.d.ts | 34 +- .../packages/recipher-js/src/binding.ts | 16 +- .../packages/recipher-js/src/cipher.ts | 8 +- .../packages/recipher-js/src/error.ts | 88 ++-- .../packages/recipher-js/src/index.ts | 1 - .../packages/recipher-js/src/record.ts | 4 +- .../packages/recipher-js/src/testing.ts | 19 +- .../packages/recipher-js/src/values.ts | 4 +- .../packages/recipher-js/type-tests/result.ts | 52 +- 27 files changed, 656 insertions(+), 898 deletions(-) diff --git a/languages/typescript/packages/recipher-js/README.md b/languages/typescript/packages/recipher-js/README.md index 509531b69..3670ec2e1 100644 --- a/languages/typescript/packages/recipher-js/README.md +++ b/languages/typescript/packages/recipher-js/README.md @@ -55,8 +55,7 @@ defines, read and built by the `recipher-value-napi` crate (`value-napi/`): the integer `5n`. - A plain object is refused. Wrap it in `json(..)`. - `VcUuid` is exported, but the engine's value model does not hold a UUID - yet, so encrypting one is an `Err` of kind `value`, code - `recipher::uuid`. + yet, so encrypting one is an `Err` with the code `recipher::uuid`. - vitaminc's rules apply: a `Map`, a `Set`, a class instance, a sparse array, a typed array other than a `Uint8Array`, a string with an unpaired surrogate, and a property named `__proto__`, `constructor` or @@ -85,8 +84,8 @@ const opened = await cipher.decrypt(sealed.unwrap()) and are refused. So is a document nested deeper than 127 levels. - A property named `__proto__`, `constructor` or `prototype` cannot be encrypted, and a document another SDK wrote with one opens as an `Err` - of kind `open`, code `recipher::reserved_key`: vitaminc does not build - those properties in JavaScript. + with the code `recipher::reserved_key`: vitaminc does not build those + properties in JavaScript. - **Read a stored document back with `kinds.json`.** The bytes do not say a value is JSON. `Ciphertext.fromBytes(bytes, kinds.json)` opens it as the document. With no kind it opens as its JSON text, and `JSON.parse` @@ -173,12 +172,12 @@ This holds for a method passed on its own (`ciphertexts.map(cipher.decrypt)` keeps its cipher), for an argument of the wrong type, and when the native build is missing. -A `RecipherError` is the engine's diagnostic, as a value: +A `RecipherError` is a diagnostic, as a value. Most come from the engine. +The SDK's own have a `recipher::` code. Switch on `code`: ```ts const opened = await cipher.decrypt(damaged) if (opened.isErr()) { - opened.error.kind // 'open' opened.error.code // 'stack_encrypt::aead' opened.error.message // 'AEAD operation failed (wrong key, AAD mismatch, or malformed ciphertext)' opened.error.help // 'Open the value under the context it was sealed with. ...' @@ -187,12 +186,11 @@ if (opened.isErr()) { | Property | What it holds | | --- | --- | -| `kind` | The closed set to switch on: `declaration`, `value`, `credential`, `zerokms`, `foreign_keyset`, `context_mismatch`, `open`, `cancelled` or `internal`. | -| `code` | Stable, and finer than the kind: the engine's code (`stack_encrypt::aead`), vitaminc's for a value it refused (`ERR_INTEGER_RANGE`), or the SDK's own (`recipher::not_a_ciphertext`). | +| `code` | Stable, and what to switch on: the engine's code (`stack_encrypt::aead`), vitaminc's for a value it refused (`ERR_INTEGER_RANGE`), or the SDK's own (`recipher::not_a_ciphertext`). | | `message` | What went wrong, in one line. | | `help` | What to do about it, where the error knows. | | `url` | A documentation page for the error, where it has one. | -| `severity` | `error`, unless the engine's diagnostic states `warning` or `advice`. | +| `severity` | `error`, unless the diagnostic states `warning` or `advice`. | | `fields` | The error's structured fields, by `snake_case` name: a refused declaration's `reason`, a ZeroKMS failure's `request_kind`. | | `field` | The field at fault, where one is known. | | `record` | The record at fault, where one is. | diff --git a/languages/typescript/packages/recipher-js/__tests__/addon/records.test.ts b/languages/typescript/packages/recipher-js/__tests__/addon/records.test.ts index 32a3d70f0..113c2d0ac 100644 --- a/languages/typescript/packages/recipher-js/__tests__/addon/records.test.ts +++ b/languages/typescript/packages/recipher-js/__tests__/addon/records.test.ts @@ -174,7 +174,6 @@ describe('one field', () => { // differs. The key service refuses the key, which it binds to the // field path the value was sealed under. const result = await c.decryptField(pair, 'a', row.b) - expect(result.err()?.kind).toBe('zerokms') expect(result.err()?.code).toBe('stack_kms::retrieve_key_failed') // A row opened under a record of another name is refused the same way. @@ -244,7 +243,6 @@ describe('refusals', () => { const result = await c .defaultKeyset() .encrypt(user, { ...ada, age: 2n ** 40n }) - expect(result.err()?.kind).toBe('value') expect(result.err()?.code).toBe('recipher::field_type') expect(result.err()?.field).toBe('age') expect(result.err()?.record).toBe('users') @@ -281,13 +279,13 @@ describe('refusals', () => { n: encrypt(kinds.int32, { index: ['match'] }), }) const checked = checkDeclarations([bad]) - expect(checked.err()?.kind).toBe('declaration') + expect(checked.err()?.code).toBe('stack_encrypt::dynamic_plan') expect(checked.err()?.field).toBe('n') expect(checked.err()?.record).toBe('bad') const c = await cipher() const result = await c.defaultKeyset().encrypt(bad, { n: 1n }) - expect(result.err()?.kind).toBe('declaration') + expect(result.err()?.code).toBe('stack_encrypt::dynamic_plan') }) it('Cipher.create refuses a bad declaration before it looks for credentials', async () => { @@ -295,7 +293,7 @@ describe('refusals', () => { flag: encrypt(kinds.boolean, { index: ['ore'] }), }) const result = await Cipher.create({ records: [user, bad] }) - expect(result.err()?.kind).toBe('declaration') + expect(result.err()?.code).toBe('stack_encrypt::dynamic_plan') expect(result.err()?.record).toBe('bad') }) @@ -304,7 +302,7 @@ describe('refusals', () => { const checked = checkDeclarations([ record(name, { x: encrypt(kinds.string) }), ]) - expect(checked.err()?.kind).toBe('declaration') + expect(checked.err()?.code).toBe('recipher::record_name') expect(checked.err()?.record).toBe(name) expect(checked.err()?.field).toBeUndefined() expect(checked.err()?.message).toContain('record name') @@ -350,6 +348,6 @@ describe('refusals', () => { ...stored, email: { ...stored.email, ciphertext }, }) - expect(result.err()?.kind).toBe('open') + expect(result.err()?.code).toBe('stack_encrypt::aead') }) }) diff --git a/languages/typescript/packages/recipher-js/__tests__/addon/value.test.ts b/languages/typescript/packages/recipher-js/__tests__/addon/value.test.ts index 826852c39..24b77be72 100644 --- a/languages/typescript/packages/recipher-js/__tests__/addon/value.test.ts +++ b/languages/typescript/packages/recipher-js/__tests__/addon/value.test.ts @@ -77,11 +77,9 @@ describe('one string, with no context', () => { }) describe('failures are values', () => { - const kindOf = (error: RecipherError | undefined) => error?.kind - it('refuses bytes that are not a ciphertext, without quoting them', () => { const result = Ciphertext.fromBytes(new TextEncoder().encode('plain text')) - expect(kindOf(result.err())).toBe('open') + expect(result.err()?.code).toBe('stack_encrypt::leaf_version') expect(result.err()?.message).not.toContain('plain text') }) @@ -92,7 +90,6 @@ describe('failures are values', () => { bytes[last] = (bytes[last] ?? 0) ^ 0x01 const opened = await c.decrypt(Ciphertext.fromBytes(bytes).unwrap()) const error = opened.err() - expect(kindOf(error)).toBe('open') expect(error?.code).toBe('stack_encrypt::aead') expect(error?.message).toBe( 'AEAD operation failed (wrong key, AAD mismatch, or malformed ciphertext)', @@ -121,7 +118,6 @@ describe('failures are values', () => { it('refuses a string with an unpaired surrogate, with a code of its own', async () => { const result = await (await cipher()).defaultKeyset().encrypt('\uD800') - expect(result.err()?.kind).toBe('value') expect(result.err()?.code).toBe('recipher::unpaired_surrogate') }) @@ -171,7 +167,7 @@ describe('no call throws', () => { const decrypt = Object.getOwnPropertyDescriptor(Cipher.prototype, 'decrypt') const method = decrypt?.get?.call({}) as (value: unknown) => unknown const result = (await method('x')) as { err(): RecipherError | undefined } - expect(result.err()?.kind).toBe('internal') + expect(result.err()?.code).toBe('recipher::native_threw') }) it('arguments of every wrong type resolve to an Err', async () => { @@ -208,7 +204,6 @@ describe('no call throws', () => { }, } const result = await keyset.encrypt(hostile as never) - expect(result.err()?.kind).toBe('value') expect(result.err()?.code).toBe('recipher::threw') expect(result.err()?.message).not.toContain('4111') }) @@ -247,8 +242,8 @@ describe('Cipher.create', () => { } }) - it('resolves to a credential error, and does not throw, with no credentials', async () => { + it('resolves to a configuration error, and does not throw, with no credentials', async () => { const result = await Cipher.create() - expect(result.err()?.kind).toBe('credential') + expect(result.err()?.code).toBe('stack_encrypt::config') }) }) diff --git a/languages/typescript/packages/recipher-js/__tests__/addon/values.test.ts b/languages/typescript/packages/recipher-js/__tests__/addon/values.test.ts index 6cf14b4e2..98845d331 100644 --- a/languages/typescript/packages/recipher-js/__tests__/addon/values.test.ts +++ b/languages/typescript/packages/recipher-js/__tests__/addon/values.test.ts @@ -156,7 +156,7 @@ describe('an array of values', () => { const keyset = (await cipher()).defaultKeyset() // @ts-expect-error: an array inside an array is not a value. const result = await keyset.encrypt(['fine', ['nested']]) - expect(result.err()?.kind).toBe('value') + expect(result.err()?.code).toBe('recipher::not_a_scalar') }) }) @@ -224,7 +224,6 @@ describe('a JSON document', () => { expect((await keyset.encrypt(json(nested(127) as any))).isOk()).toBe(true) // biome-ignore lint/suspicious/noExplicitAny: a nested array of any depth. const deep = await keyset.encrypt(json(nested(128) as any)) - expect(deep.err()?.kind).toBe('value') expect(deep.err()?.code).toBe('recipher::too_deep') }) @@ -249,14 +248,12 @@ describe('a JSON document', () => { const keyset = c.defaultKeyset() for (const text of ['{"constructor":1}', '{"prototype":1}']) { const refused = await keyset.encrypt(json(JSON.parse(text))) - expect(refused.err()?.kind).toBe('value') expect(refused.err()?.code).toBe('recipher::reserved_key') // A document another SDK wrote, sealed as the engine seals one: as its // JSON text. const sealed = (await keyset.encrypt(text)).unwrap() const stored = Ciphertext.fromBytes(sealed.toBytes(), kinds.json).unwrap() const opened = await c.decrypt(stored) - expect(opened.err()?.kind).toBe('open') expect(opened.err()?.code).toBe('recipher::reserved_key') } }) @@ -286,7 +283,6 @@ describe('a ciphertext read back with a kind', () => { const sealed = (await c.defaultKeyset().encrypt('text')).unwrap() const stored = Ciphertext.fromBytes(sealed.toBytes(), kinds.int64).unwrap() const opened = await c.decrypt(stored) - expect(opened.err()?.kind).toBe('open') expect(opened.err()?.code).toBe('recipher::opened_type') }) @@ -304,7 +300,6 @@ describe('refusals', () => { const uuid = new VcUuid('123e4567-e89b-12d3-a456-426614174000') // @ts-expect-error: a UUID is not a scalar of the engine's value model. const result = await keyset.encrypt(uuid) - expect(result.err()?.kind).toBe('value') expect(result.err()?.code).toBe('recipher::uuid') expect(result.err()?.message).toContain('UUID') }) @@ -313,7 +308,6 @@ describe('refusals', () => { const keyset = (await cipher()).defaultKeyset() const result = await keyset.encrypt(2n ** 128n) expect(result.isErr()).toBe(true) - expect(result.err()?.kind).toBe('value') expect(result.err()?.code).toBe('ERR_INTEGER_RANGE') expect(result.err()?.message).not.toContain(String(2n ** 128n)) }) @@ -365,7 +359,6 @@ describe('refusals', () => { }, } const result = await keyset.encrypt(json(document)) - expect(result.err()?.kind).toBe('value') expect(result.err()?.code).toBe('recipher::threw') expect(result.err()?.message).not.toContain('4111') }) diff --git a/languages/typescript/packages/recipher-js/__tests__/unit/binding.test.ts b/languages/typescript/packages/recipher-js/__tests__/unit/binding.test.ts index daeadb866..bd91a1f40 100644 --- a/languages/typescript/packages/recipher-js/__tests__/unit/binding.test.ts +++ b/languages/typescript/packages/recipher-js/__tests__/unit/binding.test.ts @@ -41,17 +41,16 @@ describe('load', () => { expect(load(requiring(fakeBuild()), '/x/recipher.node').isOk()).toBe(true) }) - it('is an internal Err, not a throw, when the build does not load', () => { + it('is an Err, not a throw, when the build does not load', () => { const loaded = load(() => { throw new Error('ENOENT: no such file') }, '/x/recipher.node') - expect(loaded.err()?.kind).toBe('internal') expect(loaded.err()?.code).toBe('recipher::load') expect(loaded.err()?.message).toContain('build:debug') expect(loaded.err()?.message).not.toContain('ENOENT') }) - it('is an internal Err when the build lacks an export', () => { + it('is an Err when the build lacks an export', () => { for (const name of [ 'Cipher', 'Keyset', @@ -75,12 +74,11 @@ describe('load', () => { expect(load(requiring(null), '/x').err()?.code).toBe('recipher::load') }) - it('is an internal Err when the build implements another interface', () => { + it('is an Err when the build implements another interface', () => { const loaded = load( requiring(fakeBuild({ bindingInterface: () => BINDING_INTERFACE + 1 })), '/x/recipher.node', ) - expect(loaded.err()?.kind).toBe('internal') expect(loaded.err()?.code).toBe('recipher::binding_interface') const throwing = load( requiring( @@ -102,7 +100,6 @@ describe('settle', () => { const failed = settle(() => ({ ok: false, error: { - kind: 'value', code: 'recipher::x', message: 'no', severity: 'error', @@ -114,17 +111,17 @@ describe('settle', () => { expect(failed.err()?.code).toBe('recipher::x') }) - it('turns a throw or a rejection into an internal Err, keeping no text', async () => { + it('turns a throw or a rejection into an Err, keeping no text', async () => { const thrown = settle(() => { throw new TypeError('card 4111 1111 1111 1111') }) - expect(thrown.err()?.code).toBe('recipher::threw') + expect(thrown.err()?.code).toBe('recipher::native_threw') expect(thrown.err()?.message).not.toContain('4111') const rejected = await settleAsync(() => Promise.reject(new Error('card 4111')), ) - expect(rejected.err()?.code).toBe('recipher::threw') + expect(rejected.err()?.code).toBe('recipher::native_threw') expect(rejected.err()?.message).not.toContain('4111') }) @@ -194,7 +191,6 @@ describe('adapt', () => { describe('the classes of a build that did not load', () => { const error = new RecipherError({ - kind: 'internal', code: 'recipher::load', message: 'did not load', }) diff --git a/languages/typescript/packages/recipher-js/__tests__/unit/error.test.ts b/languages/typescript/packages/recipher-js/__tests__/unit/error.test.ts index d20e26dae..0fea95e70 100644 --- a/languages/typescript/packages/recipher-js/__tests__/unit/error.test.ts +++ b/languages/typescript/packages/recipher-js/__tests__/unit/error.test.ts @@ -2,34 +2,31 @@ import { describe, expect, it } from 'vitest' import { fromNative, RecipherError } from '../../src/error' describe('RecipherError', () => { - it('is frozen and prints its kind, code and message', () => { + it('is frozen and prints its code and message', () => { const error = new RecipherError({ - kind: 'open', code: 'stack_encrypt::aead', message: 'did not open', }) expect(Object.isFrozen(error)).toBe(true) expect(String(error)).toBe( - 'RecipherError(open, stack_encrypt::aead): did not open', + 'RecipherError(stack_encrypt::aead): did not open', ) }) it('prints its help on a line of its own', () => { const error = new RecipherError({ - kind: 'open', code: 'stack_encrypt::aead', message: 'did not open', help: 'check the context', }) expect(error.message).toBe('did not open') expect(String(error)).toBe( - 'RecipherError(open, stack_encrypt::aead): did not open\nhelp: check the context', + 'RecipherError(stack_encrypt::aead): did not open\nhelp: check the context', ) }) it('keeps the help, URL, fields and causes of a native error', () => { const read = fromNative({ - kind: 'zerokms', code: 'stack_kms::x', message: 'refused', help: 'try again', @@ -54,28 +51,29 @@ describe('RecipherError', () => { expect(Object.isFrozen(read.causes)).toBe(true) }) - it('reads a native error, and refuses one of an unknown kind or shape', () => { + it('reads a native error, and refuses one of an unknown shape', () => { const read = fromNative({ - kind: 'zerokms', code: 'stack_kms::x', message: 'refused', help: null, field: 'email', }) - expect(read.kind).toBe('zerokms') + expect(read.code).toBe('stack_kms::x') + expect(read.message).toBe('refused') expect(read.field).toBe('email') expect(read.help).toBeUndefined() // An error that states no severity, or an unknown one, is an error. expect(read.severity).toBe('error') expect( - fromNative({ kind: 'open', code: 'c', message: 'm', severity: 'loud' }) - .severity, + fromNative({ code: 'c', message: 'm', severity: 'loud' }).severity, ).toBe('error') expect(read.fields).toEqual({}) expect(read.causes).toEqual([]) - expect(fromNative({ kind: 'surprise' }).kind).toBe('internal') - expect(fromNative(null).kind).toBe('internal') - expect(fromNative('text').kind).toBe('internal') + // An error with no code or no message is not one the native build + // writes. + for (const shape of [{ message: 'm' }, { code: 'c' }, null, 'text']) { + expect(fromNative(shape).code).toBe('recipher::outcome') + } }) }) diff --git a/languages/typescript/packages/recipher-js/crate/Cargo.toml b/languages/typescript/packages/recipher-js/crate/Cargo.toml index 07b6325d9..d2fad4c24 100644 --- a/languages/typescript/packages/recipher-js/crate/Cargo.toml +++ b/languages/typescript/packages/recipher-js/crate/Cargo.toml @@ -42,8 +42,11 @@ vitaminc-aead = "0.10.0" # `OpaqueDebug`, and the protected buffer a frame is held in. The version # the engine resolves. vitaminc-protected = "0.10.0" -# For the engine error's diagnostic: its code, help, URL and causes. +# Every error is a miette diagnostic: the engine's, the value bridge's, and +# the SDK's own, which derive `Diagnostic` and `thiserror::Error`. The +# versions the engine resolves. miette = "7.5.0" +thiserror = "1.0.56" # For the structured fields of an engine error (`ErrorPayload::payload`). serde_json = "1" # The engine's opaque path wipes a value it did not seal. The version the @@ -56,9 +59,6 @@ serde = { version = "1", features = ["derive"] } [dev-dependencies] stack-encrypt = { path = "../../../../../packages/stack-encrypt", default-features = false, features = ["dynamic", "http", "test-support"] } tokio = { version = "1", features = ["rt", "macros"] } -# The probe errors the cause-chain test builds. The version the engine -# resolves. -thiserror = "1.0.56" # The values the engine-interop tests seal through the engine's typed API, # and the types the counting key source names. The versions the engine # resolves. diff --git a/languages/typescript/packages/recipher-js/crate/src/cipher.rs b/languages/typescript/packages/recipher-js/crate/src/cipher.rs index bac4620f8..994c2ef26 100644 --- a/languages/typescript/packages/recipher-js/crate/src/cipher.rs +++ b/languages/typescript/packages/recipher-js/crate/src/cipher.rs @@ -17,7 +17,7 @@ use stack_encrypt::{CipherRef, DecryptFrom, EncryptInto, KeysetCipher, StackCiph use vitaminc_protected::OpaqueDebug; use crate::ciphertext::Ciphertext; -use crate::error::{ErrorKind, RecipherErrorFields}; +use crate::error::{Error, RecipherErrorFields}; use crate::js; use crate::json::Json; use crate::outcome::{not_made, refused, spawn, Outcome}; @@ -73,13 +73,12 @@ impl Cipher { /// A cipher over ZeroKMS, with the credentials the engine finds: the /// `CS_*` variables, then the profile `stash auth login` writes. /// - /// Resolves to a failure of kind `credential` when there are none or - /// they are refused, and of kind `zerokms` when ZeroKMS refuses to load - /// the default keyset. + /// Resolves to the engine's error when there are no credentials, when + /// they are refused, or when ZeroKMS refuses to load the default keyset. /// /// `options.records` are declarations to check now, before any /// credential is looked for: a declaration the engine refuses is a - /// failure of kind `declaration`, naming the record. + /// failure naming the record. // Configurable, as an instance method is, so the package's TypeScript // can wrap it (`adapt`). #[napi(configurable = true, ts_return_type = "Promise>")] @@ -218,17 +217,15 @@ impl Keyset { if many { return instances.into_unknown(env).map_err(not_made); } - instances.pop().ok_or_else(|| { - RecipherErrorFields::internal("recipher::outcome", "the engine sealed no value") - }) + instances.pop().ok_or_else(|| Error::NoResult.into()) }, ) } /// Open a ciphertext sealed under this keyset, or an array of them. A - /// ciphertext of another keyset is a failure of kind `foreign_keyset`, - /// before any key is requested. With a record first, open its stored - /// row, or an array of them. + /// ciphertext of another keyset is a failure with the code + /// `stack_encrypt::foreign_keyset`, before any key is requested. With a + /// record first, open its stored row, or an array of them. #[napi(ts_return_type = "Promise>")] pub fn decrypt<'e>( &self, @@ -293,7 +290,7 @@ impl Keyset { /// who knows the seed. /// /// Only a build with the `testing` feature has one; any other resolves to -/// a failure of kind `internal`, code `recipher::no_testing`. +/// a failure with the code `recipher::no_testing`. #[napi(ts_return_type = "Promise>")] pub fn create_testing<'e>( env: &'e Env, @@ -301,14 +298,7 @@ pub fn create_testing<'e>( ) -> napi::Result>> { let seed = crate::ciphertext::bytes_of(seed).and_then(|bytes| <[u8; 32]>::try_from(bytes).ok()); let Some(seed) = seed else { - return refused( - env, - RecipherErrorFields::new( - ErrorKind::Value, - "recipher::testing_seed", - "a test cipher's seed is a Uint8Array of 32 bytes", - ), - ); + return refused(env, Error::TestingSeed.into()); }; testing(env, seed) } @@ -331,17 +321,7 @@ fn testing(env: &Env, seed: [u8; 32]) -> napi::Result> #[cfg(not(feature = "testing"))] fn testing(env: &Env, _seed: [u8; 32]) -> napi::Result>> { - refused(env, no_testing()) -} - -/// The failure of `createTesting` in a build without the test cipher. -#[cfg_attr(feature = "testing", allow(dead_code))] -fn no_testing() -> RecipherErrorFields { - RecipherErrorFields::internal( - "recipher::no_testing", - "this native build has no test cipher. Build it with \ - `pnpm --filter @cipherstash/recipher build:debug`.", - ) + refused(env, Error::NoTesting.into()) } /// A new cipher's JavaScript value. @@ -380,17 +360,7 @@ fn open<'e>( for value in values { match Ciphertext::of(env, value) { Some(ciphertext) => ciphertexts.push(ciphertext), - None => { - return refused( - env, - RecipherErrorFields::new( - ErrorKind::Value, - "recipher::not_a_ciphertext", - "decrypt takes a Ciphertext, or an array of them; read stored bytes \ - with Ciphertext.fromBytes", - ), - ) - } + None => return refused(env, Error::NotACiphertext.into()), } } let sealed = ciphertexts @@ -419,9 +389,7 @@ fn open<'e>( if many { return values.into_unknown(env).map_err(not_made); } - values.pop().ok_or_else(|| { - RecipherErrorFields::internal("recipher::outcome", "the engine opened no value") - }) + values.pop().ok_or_else(|| Error::NoResult.into()) }, ) } @@ -437,9 +405,8 @@ fn one_value(env: &Env, value: Unknown<'_>) -> Outcome<(OneValue, Option(env: &'e Env, records: Unknown<'_>) -> napi::Result> { let checked = check(env, records); @@ -471,11 +438,7 @@ fn records_of_options<'e>(env: &Env, options: Option>) -> Outcome) -> Outcome> { if !js::is_record(env, &record) { - return Err(RecipherErrorFields::new( - ErrorKind::Declaration, - "recipher::not_a_record", - "a record is declared with record(..)", - )); + return Err(Error::NotARecord.into()); } RecordPlan::of(&js::read(env, record)?) } @@ -498,37 +461,23 @@ fn one_or_array<'e>( if many { return values.into_unknown(env).map_err(not_made); } - values.pop().ok_or_else(|| { - RecipherErrorFields::internal("recipher::outcome", "the engine returned no result") - }) + values.pop().ok_or_else(|| Error::NoResult.into()) } /// A row of `plan`'s record, read and each field read as its kind. A value /// vitaminc refuses is named by the field it was read from. fn read_row(env: &Env, plan: &RecordPlan, row: Unknown<'_>) -> Outcome { - let not_a_row = || { - let mut error = RecipherErrorFields::new( - ErrorKind::Value, - "recipher::not_a_row", - "a row is an object of the record's fields", - ); - error.record = Some(plan.name().to_owned()); - error - }; + let not_a_row = || RecipherErrorFields::from(Error::NotARow).in_record(plan.name()); if row.get_type().ok() != Some(napi::ValueType::Object) || row.is_array().unwrap_or(false) { return Err(not_a_row()); } - let frame = js::read(env, row).map_err(|mut error| { - error.record = Some(plan.name().to_owned()); - error.field = plan - .field_names() - .find(|name| { - js::property(env, row, name) - .map(|value| value.is_some_and(|value| js::read(env, value).is_err())) - .unwrap_or(true) - }) - .map(str::to_owned); - error + let frame = js::read(env, row).map_err(|error| { + let field = plan.field_names().find(|name| { + js::property(env, row, name) + .map(|value| value.is_some_and(|value| js::read(env, value).is_err())) + .unwrap_or(true) + }); + error.in_record(plan.name()).at_field(field) })?; crate::record::conform_row(plan, &frame) } @@ -586,12 +535,7 @@ fn open_rows_of<'e>( let (many, rows) = one_or_many(env, stored)?; let rows = rows .into_iter() - .map(|row| { - js::read(env, row).map_err(|mut error| { - error.record = Some(plan.name().to_owned()); - error - }) - }) + .map(|row| js::read(env, row).map_err(|error| error.in_record(plan.name()))) .collect::>>()?; Ok((plan, many, rows)) }; @@ -627,15 +571,8 @@ fn field_plan_of( field: Unknown<'_>, ) -> Outcome<(Arc, String)> { let plan = plan_of(env, record)?; - let name = js::string(field).ok_or_else(|| { - let mut error = RecipherErrorFields::new( - ErrorKind::Declaration, - "recipher::no_field", - "a field is named by a string", - ); - error.record = Some(plan.name().to_owned()); - error - })?; + let name = js::string(field) + .ok_or_else(|| RecipherErrorFields::from(Error::NoField).in_record(plan.name()))?; Ok((plan.field(&name)?, name)) } @@ -653,11 +590,8 @@ fn seal_field<'e>( let rows = values .into_iter() .map(|value| { - let value = js::read(env, value).map_err(|mut error| { - error.record = Some(plan.name().to_owned()); - error.field = Some(name.clone()); - error - })?; + let value = js::read(env, value) + .map_err(|error| error.in_record(plan.name()).at_field(Some(&name)))?; crate::record::conform_row(&plan, &one_field_row(&name, &value)?) }) .collect::>>()?; @@ -701,11 +635,8 @@ fn open_field<'e>( let rows = values .into_iter() .map(|value| { - let value = js::read(env, value).map_err(|mut error| { - error.record = Some(plan.name().to_owned()); - error.field = Some(name.clone()); - error - })?; + let value = js::read(env, value) + .map_err(|error| error.in_record(plan.name()).at_field(Some(&name)))?; one_field_row(&name, &value) }) .collect::>>()?; @@ -752,11 +683,7 @@ where .await .map_err(|error| match error { // No ciphertext exists yet, so this is the value, not damage. - stack_encrypt::Error::Aead => RecipherErrorFields::new( - ErrorKind::Value, - "recipher::not_sealed", - "the engine could not seal the value as given", - ), + stack_encrypt::Error::Aead => Error::NotSealed.into(), error => RecipherErrorFields::engine(&error), }) } @@ -781,9 +708,8 @@ mod tests { #[test] fn a_build_without_the_test_cipher_says_how_to_get_one() { - let error = no_testing(); - assert_eq!(error.kind, ErrorKind::Internal); + let error = RecipherErrorFields::from(Error::NoTesting); assert_eq!(error.code, "recipher::no_testing"); - assert!(error.message.contains("build:debug")); + assert!(error.help.is_some_and(|help| help.contains("build:debug"))); } } diff --git a/languages/typescript/packages/recipher-js/crate/src/ciphertext.rs b/languages/typescript/packages/recipher-js/crate/src/ciphertext.rs index 23af7480f..d52aca1d9 100644 --- a/languages/typescript/packages/recipher-js/crate/src/ciphertext.rs +++ b/languages/typescript/packages/recipher-js/crate/src/ciphertext.rs @@ -11,7 +11,7 @@ use stack_encrypt::dynamic::{read, ValueFrame, ValueKind}; use stack_encrypt::AsProtectedRef; use vitaminc_protected::OpaqueDebug; -use crate::error::{ErrorKind, RecipherErrorFields}; +use crate::error::{Error, RecipherErrorFields}; use crate::js; use crate::outcome::{failed, not_made, settle, Outcome}; @@ -57,8 +57,9 @@ impl Ciphertext { /// /// # Errors /// - /// A failure of kind `open` for a value sealed as another type, or for - /// one named JSON that is not a JSON document. + /// `recipher::opened_type` for a value sealed as another type, and + /// `recipher::not_a_document` for one named JSON that is not a JSON + /// document. pub(crate) fn opened(&self, value: ValueFrame) -> Outcome { match self.opens_as { None => Ok(value), @@ -87,19 +88,12 @@ impl Ciphertext { kind: Option>, ) -> napi::Result> { let Some(bytes) = bytes_of(bytes) else { - return failed( - env, - RecipherErrorFields::new( - ErrorKind::Value, - "recipher::not_bytes", - "a ciphertext is read from a Uint8Array", - ), - ); + return failed(env, Error::NotBytes.into()); }; let outcome = kind_of(env, kind).and_then(|opens_as| { stack_encrypt::Ciphertext::from_bytes(&bytes) .map(|sealed| Ciphertext::new(sealed, opens_as)) - .map_err(|error| RecipherErrorFields::diagnostic(ErrorKind::Open, &error, None)) + .map_err(|error| RecipherErrorFields::engine(&error)) }); settle(env, outcome, |env, ciphertext| { Ok(ciphertext @@ -134,24 +128,17 @@ fn kind_of(env: &Env, value: Option>) -> Outcome> else { return Ok(None); }; - let not_a_kind = || { - RecipherErrorFields::new( - ErrorKind::Value, - "recipher::not_a_kind", - "a ciphertext opens as one of `kinds`, such as `kinds.string`", - ) - }; - let frame = js::read(env, value).map_err(|_| not_a_kind())?; + let frame = js::read(env, value).map_err(|_| Error::NotAKind)?; let argument: KindArgument = stack_encrypt::dynamic::frame::serde::from_slice(frame.as_protected_ref().risky_ref()) - .map_err(|_| not_a_kind())?; - argument + .map_err(|_| Error::NotAKind)?; + let kind = argument .name .parse::() .ok() .filter(|kind| !matches!(kind, ValueKind::Array | ValueKind::Object)) - .map(Some) - .ok_or_else(not_a_kind) + .ok_or(Error::NotAKind)?; + Ok(Some(kind)) } /// Whether `kind` is an integer kind. @@ -175,13 +162,7 @@ fn integer(kind: ValueKind) -> bool { /// width, or a float of another width, converted by the engine's `read` /// when the conversion is exact; anything else refused. fn as_kind(kind: ValueKind, value: ValueFrame) -> Outcome { - let refused = || { - RecipherErrorFields::new( - ErrorKind::Open, - "recipher::opened_type", - format!("the value opened, but it was not sealed as the kind named, {kind}"), - ) - }; + let refused = || RecipherErrorFields::from(Error::OpenedType { kind }); let opened = value.kind(); if opened == Some(kind) { return Ok(value); diff --git a/languages/typescript/packages/recipher-js/crate/src/engine_tests.rs b/languages/typescript/packages/recipher-js/crate/src/engine_tests.rs index 92c883536..deb24d5bf 100644 --- a/languages/typescript/packages/recipher-js/crate/src/engine_tests.rs +++ b/languages/typescript/packages/recipher-js/crate/src/engine_tests.rs @@ -17,7 +17,6 @@ use uuid::Uuid; use crate::cipher::{seal, unseal}; use crate::ciphertext::Ciphertext; -use crate::error::ErrorKind; use crate::value::OneValue; const SEED: [u8; 32] = [7; 32]; @@ -179,7 +178,7 @@ async fn an_altered_ciphertext_does_not_open() { bytes[last] ^= 0x01; let altered = stack_encrypt::Ciphertext::from_bytes(&bytes).unwrap(); let error = unseal(&engine().await, vec![altered]).await.unwrap_err(); - assert_eq!(error.kind, ErrorKind::Open); + assert_eq!(error.code, "stack_encrypt::aead"); assert!(!error.message.contains("intact")); } diff --git a/languages/typescript/packages/recipher-js/crate/src/error.rs b/languages/typescript/packages/recipher-js/crate/src/error.rs index 563699efb..79fcd1457 100644 --- a/languages/typescript/packages/recipher-js/crate/src/error.rs +++ b/languages/typescript/packages/recipher-js/crate/src/error.rs @@ -1,52 +1,191 @@ //! Every failure the addon reports, as the object JavaScript receives. //! -//! A failure is a [`RecipherErrorFields`]: an [`ErrorKind`] a caller switches -//! on, and the engine's diagnostic as it stands: its stable code, message, -//! help, documentation URL, severity, structured fields and causes. An engine error is -//! mapped here, once, by its variant. The engine's errors never hold a -//! plaintext, a key, a token or a ciphertext, and nothing here adds one. +//! An error is a miette diagnostic: the engine's, the value bridge's +//! [`Refusal`](recipher_value_napi::Refusal), or one of the SDK's own in +//! [`Error`]. [`RecipherErrorFields::diagnostic`] turns any of them into a +//! [`RecipherErrorFields`]: its code, message, help, documentation URL, +//! severity, structured fields and causes. No error here holds a plaintext, +//! a key, a token or a ciphertext. //! //! A cause that is one of the engine's own diagnostics gives its code and //! message. A cause from another library gives [`UNDESCRIBED_CAUSE`] and //! nothing else: its message is text the engine does not vouch for, and is //! never copied. -use std::error::Error; +use std::error::Error as StdError; use miette::Diagnostic; use napi_derive::napi; +use stack_encrypt::dynamic::ValueKind; use stack_encrypt::ErrorPayload; -/// The closed set of things that can go wrong, for a caller to switch on. -#[napi(string_enum = "snake_case")] -#[derive(Clone, Debug, PartialEq, Eq)] -pub enum ErrorKind { - /// A declaration the engine refused. - Declaration, - /// A value the SDK or the engine refused: a type it does not encrypt, - /// or a value outside what its type holds. +/// The SDK's own errors: what the addon refuses before the engine sees it, +/// and what goes wrong between the engine and JavaScript. +#[derive(Debug, thiserror::Error, Diagnostic)] +pub(crate) enum Error { + /// `undefined` given as a value. + #[error("`undefined` is not a value")] + #[diagnostic( + code(recipher::undefined), + help("Use `null` for a value that is not there.") + )] + Undefined, + /// A `VcUuid`, which the engine's value model does not hold. + #[error("a UUID cannot be encrypted yet: the engine's value model does not hold one")] + #[diagnostic(code(recipher::uuid), help("Encrypt its text instead."))] + Uuid, + /// A value outside the engine's value model, or one Node-API failed to + /// read. + #[error("the value cannot be encrypted: it is not one the engine reads")] + #[diagnostic(code(recipher::value))] Value, - /// No credentials, or credentials that were refused. - Credential, - /// ZeroKMS refused a request, or could not be reached. - Zerokms, - /// A value sealed under another keyset than the one asked to open it. - ForeignKeyset, - /// A value opened under another context than the one it was sealed - /// under, found before any key was requested. - ContextMismatch, - /// A ciphertext that did not open: damaged, altered, not a ciphertext, - /// or holding a value of another type than the one asked for. - Open, - /// The call was cancelled before it finished. - Cancelled, - /// A failure that is not the caller's to fix: the native build did not - /// load, or the engine or the addon did something the SDK does not - /// expect. - Internal, + /// A getter of the application's threw while the value was read. + #[error( + "reading the value threw. The thrown error is not kept, because its message may hold the value" + )] + #[diagnostic(code(recipher::threw))] + Threw, + /// An array inside an array, given as one value. + #[error("an array inside an array is not a value")] + #[diagnostic(code(recipher::not_a_scalar), help("Wrap it in json(..)."))] + NotAScalar, + /// An object given as one value. + #[error("an object is not a value")] + #[diagnostic(code(recipher::plain_object), help("Wrap it in json(..)."))] + PlainObject, + /// A value that is not a JSON document the engine seals. + #[error("the value is not a JSON document the engine seals: {what}")] + #[diagnostic(code(recipher::not_json))] + NotJson { what: &'static str }, + /// A JSON document nested deeper than the engine's parser reads. + #[error( + "the value is not a JSON document the engine seals: it is nested deeper than 127 levels of arrays and objects" + )] + #[diagnostic(code(recipher::too_deep))] + JsonTooDeep, + /// The engine refused to seal a value as it was given. + #[error("the engine could not seal the value as given")] + #[diagnostic(code(recipher::not_sealed))] + NotSealed, + /// `decrypt` given something that is not a `Ciphertext`. + #[error("decrypt takes a Ciphertext, or an array of them")] + #[diagnostic( + code(recipher::not_a_ciphertext), + help("Read stored bytes with Ciphertext.fromBytes.") + )] + NotACiphertext, + /// `Ciphertext.fromBytes` given something that is not bytes. + #[error("a ciphertext is read from a Uint8Array")] + #[diagnostic(code(recipher::not_bytes))] + NotBytes, + /// A kind that is not one of `kinds`. + #[error("a ciphertext opens as one of `kinds`, such as `kinds.string`")] + #[diagnostic(code(recipher::not_a_kind))] + NotAKind, + /// A ciphertext that opened as another kind than the one named. + #[error("the value opened, but it was not sealed as the kind named, {kind}")] + #[diagnostic(code(recipher::opened_type))] + OpenedType { kind: ValueKind }, + /// A ciphertext named JSON that opened as text that is not JSON. + #[error("the value opened, but it is not a JSON document")] + #[diagnostic(code(recipher::not_a_document))] + NotADocument, + /// A test cipher's seed that is not 32 bytes. + #[error("a test cipher's seed is a Uint8Array of 32 bytes")] + #[diagnostic(code(recipher::testing_seed))] + TestingSeed, + /// `createTesting` in a build without the test cipher. + // A build with the test cipher never raises it. + #[cfg_attr(feature = "testing", allow(dead_code))] + #[error("this native build has no test cipher")] + #[diagnostic( + code(recipher::no_testing), + help("Build it with `pnpm --filter @cipherstash/recipher build:debug`.") + )] + NoTesting, + /// A declaration that `record(..)` did not make. + #[error("the value is not a record")] + #[diagnostic( + code(recipher::not_a_record), + help("Declare a record with record(..).") + )] + NotARecord, + /// A field declared with something other than `encrypt(..)` or + /// `passthrough()`. + #[error("a field is declared with encrypt(..) or passthrough()")] + #[diagnostic(code(recipher::declaration))] + Declaration, + /// A field named with a name the engine reserves. + #[error("the field's name is one the engine reserves")] + #[diagnostic(code(recipher::reserved_field), help("Name the field something else."))] + ReservedField, + /// A field's kind that is not one of `kinds`. + #[error("`{name}` is not one of `kinds`")] + #[diagnostic(code(recipher::kind))] + Kind { name: String }, + /// A field's index that is not one the SDK names. + #[error("`{name}` is not an index")] + #[diagnostic(code(recipher::index))] + Index { name: String }, + /// A field's null mode that is not one the engine has. + #[error("`{mode}` is not a null mode")] + #[diagnostic(code(recipher::null), help("A null mode is `sealed` or `sql`."))] + Null { mode: String }, + /// A field path that could not be written as a context. + #[error("the field path could not be written")] + #[diagnostic(code(recipher::context))] + Context, + /// A record name the engine refuses as a segment of a field path. + #[error("the record name is not a plain segment of a field path")] + #[diagnostic( + code(recipher::record_name), + help("Use a record name that is not empty and holds no character the engine refuses in a field path, such as `/`.") + )] + RecordName, + /// A field named that the record does not seal: no such field, a + /// passthrough field, or a name that is not a string. + #[error("the record declares no sealed field of that name")] + #[diagnostic( + code(recipher::no_field), + help("Name a field the record declares with encrypt(..). A passthrough field has no ciphertext.") + )] + NoField, + /// A row that is not an object of the record's fields. + #[error("a row is an object of the record's fields")] + #[diagnostic(code(recipher::not_a_row))] + NotARow, + /// A row's value that is not of its field's kind. + #[error("the value is not of the field's kind, {kind}, or does not fit it")] + #[diagnostic(code(recipher::field_type))] + FieldType { kind: ValueKind }, + /// A stored row that does not have the record's shape. + #[error("the stored row does not have the record's shape: {what}")] + #[diagnostic(code(recipher::not_a_stored_row))] + NotAStoredRow { what: &'static str }, + /// A stored row from the engine that the SDK cannot read. + #[error("the engine's stored row does not have the shape the SDK reads: {what}")] + #[diagnostic( + code(recipher::engine_result), + help("Report this as a bug in @cipherstash/recipher.") + )] + EngineResult { what: &'static str }, + /// A call whose engine work returned no result. + #[error("the engine returned no result")] + #[diagnostic( + code(recipher::outcome), + help("Report this as a bug in @cipherstash/recipher.") + )] + NoResult, + /// A result that could not be made into a JavaScript value. + #[error("the result could not be given to JavaScript")] + #[diagnostic( + code(recipher::build_value), + help("Report this as a bug in @cipherstash/recipher.") + )] + BuildValue, } -/// How serious a failure is, as the engine's diagnostic states it. +/// How serious a failure is, as the diagnostic states it. #[napi(string_enum = "snake_case")] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Severity { @@ -72,9 +211,7 @@ impl From for Severity { #[napi(object)] #[derive(Clone, Debug, PartialEq, Eq)] pub struct RecipherErrorFields { - /// What kind of failure it is. - pub kind: ErrorKind, - /// Stable: the engine's diagnostic code, such as `stack_encrypt::aead`, + /// Stable: the diagnostic's code, such as `stack_encrypt::aead`, /// vitaminc's code for a value it refused, such as `ERR_INTEGER_RANGE`, /// or the SDK's own, such as `recipher::not_a_ciphertext`. pub code: String, @@ -84,8 +221,7 @@ pub struct RecipherErrorFields { pub help: Option, /// A documentation page for the error, where it has one. pub url: Option, - /// How serious it is: `error` unless the engine's diagnostic says - /// otherwise. + /// How serious it is: `error` unless the diagnostic says otherwise. pub severity: Severity, /// The error's structured fields, by `snake_case` name: a refused /// plan's `field` and `reason`, a ZeroKMS failure's `request_kind`. @@ -123,7 +259,7 @@ enum Cause<'a> { /// One of the engine's errors, reached as a diagnostic source. Ours(&'a dyn Diagnostic), /// Anything reached as a plain source. - Foreign(&'a (dyn Error + 'static)), + Foreign(&'a (dyn StdError + 'static)), } /// The cause after a diagnostic: its diagnostic source, or else its plain @@ -165,51 +301,16 @@ fn causes_of(error: &dyn Diagnostic) -> Vec { } impl RecipherErrorFields { - /// The engine's reason token, such as `no_fields`, where the error's - /// fields hold one. - pub(crate) fn reason(&self) -> Option<&str> { - self.fields - .get("reason") - .and_then(serde_json::Value::as_str) - } - - /// A failure of the SDK's own, with no help, fields or causes. - pub(crate) fn new(kind: ErrorKind, code: &str, message: impl Into) -> Self { - Self { - kind, - code: code.to_owned(), - message: message.into(), - help: None, - url: None, - severity: Severity::Error, - fields: serde_json::Map::new(), - causes: Vec::new(), - field: None, - record: None, - } - } - - /// The failure for an engine error, of the kind its variant names. - pub(crate) fn engine(error: &stack_encrypt::Error) -> Self { - Self::diagnostic(kind_of(error), error, Some(error.payload())) - } - - /// The failure for a diagnostic of `kind`, with the structured fields of - /// `payload` where there is one. + /// The failure for any diagnostic, with the structured fields of + /// `payload` where there is one. `field` is the payload's `field`, where + /// it names one. pub(crate) fn diagnostic( - kind: ErrorKind, error: &dyn Diagnostic, payload: Option>, ) -> Self { let fields = payload.unwrap_or_default(); - let text_of = |key: &str| { - fields - .get(key) - .and_then(serde_json::Value::as_str) - .map(str::to_owned) - }; Self { - kind, + // Every error the addon reports has a code; this is never seen. code: error .code() .map_or_else(|| "recipher::unknown".to_owned(), |code| code.to_string()), @@ -217,49 +318,56 @@ impl RecipherErrorFields { help: error.help().map(|help| help.to_string()), url: error.url().map(|url| url.to_string()), severity: error.severity().map_or(Severity::Error, Severity::from), - field: text_of("field"), + field: fields + .get("field") + .and_then(serde_json::Value::as_str) + .map(str::to_owned), causes: causes_of(error), fields, record: None, } } - /// An `internal` failure: something the SDK does not expect happened. - pub(crate) fn internal(code: &str, message: impl Into) -> Self { - Self::new(ErrorKind::Internal, code, message) + /// The failure for an engine error, with its structured fields. + pub(crate) fn engine(error: &E) -> Self { + Self::diagnostic(error, Some(error.payload())) + } + + /// This failure, naming the record at fault. + pub(crate) fn in_record(mut self, record: &str) -> Self { + self.record = Some(record.to_owned()); + self + } + + /// This failure, naming the field at fault, or none. + pub(crate) fn at_field(mut self, field: Option<&str>) -> Self { + self.field = field.map(str::to_owned); + self + } + + /// The engine's reason token, such as `no_fields`, where the error's + /// fields hold one. + pub(crate) fn reason(&self) -> Option<&str> { + self.fields + .get("reason") + .and_then(serde_json::Value::as_str) } } -/// The kind of an engine error. -fn kind_of(error: &stack_encrypt::Error) -> ErrorKind { - use stack_encrypt::Error; - match error { - Error::Kms(stack_encrypt::kms::Error::Auth(_)) | Error::Config(_) => ErrorKind::Credential, - Error::Kms(_) | Error::KeysetLoad { .. } | Error::NoKeyset => ErrorKind::Zerokms, - Error::Aead | Error::OpenedType { .. } => ErrorKind::Open, - Error::ForeignKeyset { .. } => ErrorKind::ForeignKeyset, - Error::ContextMismatch { .. } => ErrorKind::ContextMismatch, - Error::Input(_) | Error::Blob(_) | Error::Term(_) => ErrorKind::Value, - Error::Plan(_) => ErrorKind::Declaration, - // A decrypt target that did not open a field it declares, a - // destination that takes no such output, and two pendings confined - // to different keysets are each a fault in the code that drove the - // engine (here, this addon), never in the caller's ciphertext. - Error::NotOpened | Error::UnsupportedShape | Error::KeysetMismatch { .. } => { - ErrorKind::Internal - } - _ => ErrorKind::Internal, +impl From for RecipherErrorFields { + fn from(error: Error) -> Self { + Self::diagnostic(&error, None) } } #[cfg(test)] mod tests { - use super::{ErrorCause, ErrorKind, RecipherErrorFields, Severity, UNDESCRIBED_CAUSE}; + use super::{Error, ErrorCause, RecipherErrorFields, Severity, UNDESCRIBED_CAUSE}; + use stack_encrypt::dynamic::ValueKind; #[test] - fn an_aead_failure_is_an_open_failure_with_the_engine_code() { + fn an_aead_failure_keeps_the_engine_code_message_and_help() { let error = RecipherErrorFields::engine(&stack_encrypt::Error::Aead); - assert_eq!(error.kind, ErrorKind::Open); assert_eq!(error.code, "stack_encrypt::aead"); // The message is the engine's one line. Its help is a field of // its own, never appended. @@ -303,7 +411,7 @@ mod tests { ] .into_iter() .collect(); - let error = RecipherErrorFields::diagnostic(ErrorKind::Value, &outer, Some(payload)); + let error = RecipherErrorFields::diagnostic(&outer, Some(payload)); assert_eq!(error.code, "probe::outer"); assert_eq!(error.message, "outer"); assert_eq!(error.help.as_deref(), Some("try again")); @@ -331,99 +439,107 @@ mod tests { } #[test] - fn a_fault_in_driving_the_engine_is_internal() { - for error in [ - stack_encrypt::Error::NotOpened, - stack_encrypt::Error::UnsupportedShape, - ] { - assert_eq!( - RecipherErrorFields::engine(&error).kind, - ErrorKind::Internal - ); - } + fn an_error_of_the_sdks_own_has_its_code_message_and_help() { + let error = RecipherErrorFields::from(Error::Undefined); + assert_eq!(error.code, "recipher::undefined"); + assert_eq!(error.message, "`undefined` is not a value"); + assert_eq!( + error.help.as_deref(), + Some("Use `null` for a value that is not there.") + ); + assert_eq!(error.severity, Severity::Error); + assert!(error.fields.is_empty() && error.causes.is_empty()); } - /// Every code the SDK gives an error of its own, in order. A caller - /// branches on a code and a documentation page is written for each, so - /// a new one is added here by hand. - const SDK_CODES: &[&str] = &[ - "recipher::binding_interface", - "recipher::build_value", - "recipher::changed_while_read", - "recipher::context", - "recipher::declaration", - "recipher::engine_result", - "recipher::field_type", - "recipher::index", - "recipher::kind", - "recipher::load", - "recipher::no_field", - "recipher::no_testing", - "recipher::not_a_ciphertext", - "recipher::not_a_document", - "recipher::not_a_kind", - "recipher::not_a_record", - "recipher::not_a_row", - "recipher::not_a_scalar", - "recipher::not_a_stored_row", - "recipher::not_a_value", - "recipher::not_bytes", - "recipher::not_json", - "recipher::not_plain", - "recipher::not_sealed", - "recipher::null", - "recipher::opened_type", - "recipher::outcome", - "recipher::plain_object", - "recipher::reserved_field", - "recipher::reserved_key", - "recipher::sparse_array", - "recipher::testing_seed", - "recipher::threw", - "recipher::too_deep", - "recipher::undefined", - "recipher::unknown", - "recipher::unpaired_surrogate", - "recipher::uuid", - "recipher::value", - ]; - - /// The `recipher::` codes written in the files of `dir`, as string - /// literals in either quote. - fn codes_written_in(dir: &std::path::Path, found: &mut std::collections::BTreeSet) { - for entry in std::fs::read_dir(dir).unwrap() { - let path = entry.unwrap().path(); - if path.is_dir() { - codes_written_in(&path, found); - continue; - } - let text = std::fs::read_to_string(&path).unwrap(); - for quote in ['"', '\''] { - let start = format!("{quote}recipher::"); - for (at, _) in text.match_indices(&start) { - let literal = &text[at + 1..]; - let end = literal.find(quote).unwrap(); - let _ = found.insert(literal[..end].to_owned()); - } + /// One of every variant of [`Error`]. The match has no wildcard, so a + /// variant added without a row here does not compile. + fn every_error() -> Vec { + let name = || "x".to_owned(); + let all = vec![ + Error::Undefined, + Error::Uuid, + Error::Value, + Error::Threw, + Error::NotAScalar, + Error::PlainObject, + Error::NotJson { what: "bytes" }, + Error::JsonTooDeep, + Error::NotSealed, + Error::NotACiphertext, + Error::NotBytes, + Error::NotAKind, + Error::OpenedType { + kind: ValueKind::String, + }, + Error::NotADocument, + Error::TestingSeed, + Error::NoTesting, + Error::NotARecord, + Error::Declaration, + Error::ReservedField, + Error::Kind { name: name() }, + Error::Index { name: name() }, + Error::Null { mode: name() }, + Error::Context, + Error::RecordName, + Error::NoField, + Error::NotARow, + Error::FieldType { + kind: ValueKind::Int8, + }, + Error::NotAStoredRow { what: "x" }, + Error::EngineResult { what: "x" }, + Error::NoResult, + Error::BuildValue, + ]; + for error in &all { + match error { + Error::Undefined + | Error::Uuid + | Error::Value + | Error::Threw + | Error::NotAScalar + | Error::PlainObject + | Error::NotJson { .. } + | Error::JsonTooDeep + | Error::NotSealed + | Error::NotACiphertext + | Error::NotBytes + | Error::NotAKind + | Error::OpenedType { .. } + | Error::NotADocument + | Error::TestingSeed + | Error::NoTesting + | Error::NotARecord + | Error::Declaration + | Error::ReservedField + | Error::Kind { .. } + | Error::Index { .. } + | Error::Null { .. } + | Error::Context + | Error::RecordName + | Error::NoField + | Error::NotARow + | Error::FieldType { .. } + | Error::NotAStoredRow { .. } + | Error::EngineResult { .. } + | Error::NoResult + | Error::BuildValue => {} } } + all } #[test] - fn every_sdk_code_is_well_formed_and_listed() { - let package = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join(".."); - let mut found = std::collections::BTreeSet::new(); - codes_written_in(&package.join("crate/src"), &mut found); - codes_written_in(&package.join("src"), &mut found); - for code in &found { + fn every_error_has_a_recipher_code_of_its_own() { + let mut codes = std::collections::BTreeSet::new(); + for error in every_error() { + let code = RecipherErrorFields::from(error).code; assert!( - stack_encrypt::diagnostic::is_code_of("recipher", code), + stack_encrypt::diagnostic::is_code_of("recipher", &code), "{code} is not `recipher::` and a snake_case name" ); + assert!(codes.insert(code.clone()), "{code} is used twice"); } - assert_eq!( - found.iter().map(String::as_str).collect::>(), - SDK_CODES - ); } } diff --git a/languages/typescript/packages/recipher-js/crate/src/js.rs b/languages/typescript/packages/recipher-js/crate/src/js.rs index 61ebbe239..450d8fcdc 100644 --- a/languages/typescript/packages/recipher-js/crate/src/js.rs +++ b/languages/typescript/packages/recipher-js/crate/src/js.rs @@ -7,8 +7,9 @@ //! converts a value itself. //! //! When the bridge refuses a value it says which rule the value broke, and -//! for a scalar it also throws into JavaScript. [`read`] turns either into a [`RecipherErrorFields`] of kind `value`, so a -//! call that reads a value returns an outcome rather than throwing. What a +//! for a scalar it also throws into JavaScript. [`read`] turns either into a +//! [`RecipherErrorFields`], so a call that reads a value returns an outcome +//! rather than throwing. What a //! getter of the application's threw is caught and dropped, never copied: //! its message may hold the value. @@ -21,51 +22,34 @@ use stack_encrypt::AsProtectedRef; use vitaminc_aead::Frame; use vitaminc_protected::Controlled; -use crate::error::{ErrorKind, RecipherErrorFields}; +use crate::error::{Error, RecipherErrorFields}; use crate::outcome::not_made; /// Read a JavaScript value into the engine's value model. /// /// # Errors /// -/// A failure of kind `value`: `undefined`, a value vitaminc refused or that -/// threw while it was read, or one outside the engine's value model, such -/// as a `VcUuid`. +/// `recipher::undefined`, `recipher::uuid` for a `VcUuid`, `recipher::value` +/// for another value outside the engine's value model, `recipher::threw` +/// when reading it threw, or the bridge's code for a value it refused. pub fn read(env: &Env, value: Unknown<'_>) -> Result { if value.get_type().ok() == Some(ValueType::Undefined) { - return Err(RecipherErrorFields::new( - ErrorKind::Value, - "recipher::undefined", - "`undefined` is not a value; use `null` for a value that is not there", - )); + return Err(Error::Undefined.into()); } let uuid = is_uuid(env, &value); let frame = JsRef::new(value) .to_frame() .map_err(|error| refused(env, &error))?; - ValueFrame::from_bytes(frame.as_protected_ref()).map_err(|error| { - if uuid { - return RecipherErrorFields::new( - ErrorKind::Value, - "recipher::uuid", - "a UUID cannot be encrypted yet: the engine's value model does not hold \ - one. Encrypt its text instead", - ); - } - RecipherErrorFields::new( - ErrorKind::Value, - "recipher::value", - format!("the value cannot be encrypted: {error}"), - ) - }) + ValueFrame::from_bytes(frame.as_protected_ref()) + .map_err(|_| RecipherErrorFields::from(if uuid { Error::Uuid } else { Error::Value })) } /// The elements of `value` when it is an array, or `None` when it is not. /// /// # Errors /// -/// A failure of kind `value` when an element cannot be read, such as one -/// behind a getter that throws. +/// The bridge's refusal, or `recipher::threw`, when an element cannot be +/// read, such as one behind a getter that throws. pub fn elements<'e>( env: &Env, value: Unknown<'e>, @@ -87,14 +71,12 @@ pub fn elements<'e>( /// /// # Errors /// -/// A failure of kind `open` for a value JavaScript cannot hold as it was -/// sealed (a map key vitaminc does not build), and of kind `internal` for -/// any other failure. +/// `recipher::reserved_key` for a value JavaScript cannot hold as it was +/// sealed (a map key vitaminc does not build), and `recipher::build_value` +/// for any other failure. pub fn build(env: &Env, value: ValueFrame) -> Result, RecipherErrorFields> { let bytes = value.into_inner(); - let frame = Frame::parse(bytes.risky_ref()).map_err(|_| { - RecipherErrorFields::internal("recipher::build_value", "an opened value is not a frame") - })?; + let frame = Frame::parse(bytes.risky_ref()).map_err(|_| Error::BuildValue)?; JsBuilder::build(env, frame).map_err(|error| not_built(env, &error)) } @@ -103,17 +85,10 @@ fn not_built(env: &Env, fault: &JsFault) -> RecipherErrorFields { if fault.status() == Status::PendingException { let _ = take_exception(env); } - if let Some(refusal @ Refusal::ReservedKey) = fault.refusal() { - return RecipherErrorFields::diagnostic(ErrorKind::Open, &refusal, None); + match fault.refusal() { + Some(refusal @ Refusal::ReservedKey) => RecipherErrorFields::diagnostic(&refusal, None), + _ => Error::BuildValue.into(), } - RecipherErrorFields::internal( - "recipher::build_value", - format!( - "the opened value could not be given to JavaScript ({}). Report this as a bug \ - in @cipherstash/recipher.", - fault.status() - ), - ) } /// Whether `value` is one of vitaminc's `VcUuid`s. @@ -127,8 +102,8 @@ fn is_uuid(env: &Env, value: &Unknown<'_>) -> bool { /// /// # Errors /// -/// A failure of kind `value` when reading it throws, as a getter may; what -/// it threw is dropped. +/// `recipher::threw` when reading it throws, as a getter may; what it threw +/// is dropped. pub(crate) fn property<'e>( env: &Env, value: Unknown<'e>, @@ -176,13 +151,7 @@ pub(crate) fn second_without_record( let plain = Wrappers::get(env) .and_then(|wrappers| wrappers.is_plain(*first)) .unwrap_or(false); - plain.then(|| { - RecipherErrorFields::new( - ErrorKind::Declaration, - "recipher::not_a_record", - "the first argument is not a record: a record is declared with record(..)", - ) - }) + plain.then(|| Error::NotARecord.into()) } /// The text of a JavaScript string, or `None` for any other value. @@ -239,18 +208,9 @@ fn refused(env: &Env, fault: &JsFault) -> RecipherErrorFields { let _ = take_exception(env); } match fault.refusal() { - Some(refusal) => RecipherErrorFields::diagnostic(ErrorKind::Value, &refusal, None), - None if fault.status() == Status::PendingException => RecipherErrorFields::new( - ErrorKind::Value, - "recipher::threw", - "reading the value threw. The thrown error is not kept, because its \ - message may hold the value", - ), - None => RecipherErrorFields::new( - ErrorKind::Value, - "recipher::value", - "the value cannot be encrypted: it could not be read", - ), + Some(refusal) => RecipherErrorFields::diagnostic(&refusal, None), + None if fault.status() == Status::PendingException => Error::Threw.into(), + None => Error::Value.into(), } } diff --git a/languages/typescript/packages/recipher-js/crate/src/json.rs b/languages/typescript/packages/recipher-js/crate/src/json.rs index 8f83c39d9..cd03d964c 100644 --- a/languages/typescript/packages/recipher-js/crate/src/json.rs +++ b/languages/typescript/packages/recipher-js/crate/src/json.rs @@ -38,7 +38,7 @@ use stack_encrypt::{Encrypt, EncryptRef}; use vitaminc_protected::OpaqueDebug; use zeroize::Zeroizing; -use crate::error::{ErrorKind, RecipherErrorFields}; +use crate::error::{Error, RecipherErrorFields}; use crate::js; /// The deepest a document nests: the engine's parser reads 127 levels of @@ -111,39 +111,13 @@ pub fn json_document(env: &Env, document: Unknown<'_>) -> Json { } } -/// Why a value is not a JSON document. Each message is fixed text, with no -/// part of the value in it. -#[derive(Debug)] -enum NotJson { - /// A value of a kind JSON has no form for. - Kind(&'static str), - /// Nested deeper than the engine's parser reads. - TooDeep, - /// The source failed while it was read. - Source, -} - -impl SinkError for NotJson { +/// The JSON sink's error is the SDK's: [`Error::NotJson`] or +/// [`Error::JsonTooDeep`], each fixed text with no part of the value in it. +impl SinkError for Error { fn source(_: SourceError) -> Self { - Self::Source - } -} - -impl NotJson { - fn error(&self) -> RecipherErrorFields { - let (code, reason) = match self { - Self::Kind(what) => ("recipher::not_json", *what), - Self::TooDeep => ( - "recipher::too_deep", - "it is nested deeper than 127 levels of arrays and objects", - ), - Self::Source => ("recipher::not_json", "it could not be read"), - }; - RecipherErrorFields::new( - ErrorKind::Value, - code, - format!("the value is not a JSON document the engine seals: {reason}"), - ) + Self::NotJson { + what: "it could not be read", + } } } @@ -155,31 +129,20 @@ pub(crate) fn document(frame: &ValueFrame) -> Result Result { - let document = read_json(frame).map_err(|_| { - RecipherErrorFields::new( - ErrorKind::Open, - "recipher::not_a_document", - "the value opened, but it is not a JSON document", - ) - })?; - ValueFrame::of(&FromJson(document.value())).map_err(|_| { - RecipherErrorFields::internal( - "recipher::build_value", - "an opened JSON document could not be written as a frame", - ) - }) + let document = read_json(frame).map_err(|_| Error::NotADocument)?; + ValueFrame::of(&FromJson(document.value())).map_err(|_| Error::BuildValue.into()) } /// Where a built value goes. trait Out { type Ok; - fn put(self, value: Value) -> Result; + fn put(self, value: Value) -> Result; } /// The value is the result. @@ -187,7 +150,7 @@ struct Root; impl Out for Root { type Ok = Value; - fn put(self, value: Value) -> Result { + fn put(self, value: Value) -> Result { Ok(value) } } @@ -197,7 +160,7 @@ struct Element<'s>(&'s mut Vec); impl Out for Element<'_> { type Ok = (); - fn put(self, value: Value) -> Result<(), NotJson> { + fn put(self, value: Value) -> Result<(), Error> { self.0.push(value); Ok(()) } @@ -213,7 +176,7 @@ struct Member<'s> { impl Out for Member<'_> { type Ok = (); - fn put(mut self, value: Value) -> Result<(), NotJson> { + fn put(mut self, value: Value) -> Result<(), Error> { let key = std::mem::take(&mut *self.key); let _ = self.object.insert(key, value); Ok(()) @@ -228,9 +191,11 @@ struct ToJson { } /// A JSON number for a float, by the rules in the module docs. -fn float(value: f64) -> Result { +fn float(value: f64) -> Result { if !value.is_finite() { - return Err(NotJson::Kind("a number that is not finite")); + return Err(Error::NotJson { + what: "a number that is not finite", + }); } let magnitude = value.abs(); if value.fract() == 0.0 && magnitude <= MAX_SAFE as f64 { @@ -239,18 +204,20 @@ fn float(value: f64) -> Result { return Ok(Value::Number(Number::from(value as i64))); } if value.fract() == 0.0 && magnitude < TWO_TO_64 { - return Err(NotJson::Kind( - "a whole number between 2^53 and 2^64 held as a number, whose digits may not be \ + return Err(Error::NotJson { + what: "a whole number between 2^53 and 2^64 held as a number, whose digits may not be \ the ones meant; use a bigint", - )); + }); } Number::from_f64(value) .map(Value::Number) - .ok_or(NotJson::Kind("a number that is not finite")) + .ok_or(Error::NotJson { + what: "a number that is not finite", + }) } /// A JSON number for an integer, refused outside the 64-bit range. -fn integer(value: Int) -> Result { +fn integer(value: Int) -> Result { let wide = match value { Int::I8(n) => i128::from(n), Int::I16(n) => i128::from(n), @@ -269,17 +236,17 @@ fn integer(value: Int) -> Result { if let Ok(n) = u64::try_from(wide) { return Ok(Value::Number(Number::from(n))); } - Err(NotJson::Kind( - "a bigint outside the 64-bit range (below -2^63 or above 2^64 - 1)", - )) + Err(Error::NotJson { + what: "a bigint outside the 64-bit range (below -2^63 or above 2^64 - 1)", + }) } impl ToJson { /// The depth of a container opened here, refused past the limit. - fn nested(&self) -> Result { + fn nested(&self) -> Result { let depth = self.depth + 1; if depth > MAX_DEPTH { - return Err(NotJson::TooDeep); + return Err(Error::JsonTooDeep); } Ok(depth) } @@ -287,11 +254,11 @@ impl ToJson { impl Sink for ToJson { type Ok = O::Ok; - type Error = NotJson; + type Error = Error; type Seq = JsonArray; type Map = JsonObject; - fn scalar(self, ty: Option, value: Physical<'_>) -> Result { + fn scalar(self, ty: Option, value: Physical<'_>) -> Result { let value = match (ty, value) { (None, Physical::Null) => Value::Null, (None, Physical::Bool(b)) => Value::Bool(b), @@ -299,22 +266,22 @@ impl Sink for ToJson { (None, Physical::Float(Float::F64(n))) => float(n)?, (None, Physical::Float(Float::F32(n))) => float(f64::from(n))?, (None, Physical::Int(n)) => integer(n)?, - (None, Physical::Bytes(_)) => return Err(NotJson::Kind("bytes")), - (Some(Logical::Undefined), _) => return Err(NotJson::Kind("undefined")), + (None, Physical::Bytes(_)) => return Err(Error::NotJson { what: "bytes" }), + (Some(Logical::Undefined), _) => return Err(Error::NotJson { what: "undefined" }), (Some(_), _) => { - return Err(NotJson::Kind( - "a date, a timestamp, a decimal or a UUID; write it as text", - )) + return Err(Error::NotJson { + what: "a date, a timestamp, a decimal or a UUID; write it as text", + }) } }; self.out.put(value) } - fn typed_null(self, _: FixedType) -> Result { + fn typed_null(self, _: FixedType) -> Result { self.out.put(Value::Null) } - fn seq(self, len: Option) -> Result, NotJson> { + fn seq(self, len: Option) -> Result, Error> { let depth = self.nested()?; Ok(JsonArray { out: Some(self.out), @@ -323,7 +290,7 @@ impl Sink for ToJson { }) } - fn map(self, _: Option) -> Result, NotJson> { + fn map(self, _: Option) -> Result, Error> { let depth = self.nested()?; Ok(JsonObject { out: Some(self.out), @@ -332,8 +299,10 @@ impl Sink for ToJson { }) } - fn passthrough(self, _: &P) -> Result { - Err(NotJson::Kind("a passthrough")) + fn passthrough(self, _: &P) -> Result { + Err(Error::NotJson { + what: "a passthrough", + }) } } @@ -354,24 +323,26 @@ impl Drop for JsonArray { impl SeqSink for JsonArray { type Ok = O::Ok; - type Error = NotJson; + type Error = Error; type Element<'s> = ToJson> where Self: 's; - fn element(&mut self) -> Result>, NotJson> { + fn element(&mut self) -> Result>, Error> { Ok(ToJson { out: Element(&mut self.items), depth: self.depth, }) } - fn end(mut self) -> Result { + fn end(mut self) -> Result { let items = std::mem::take(&mut self.items); match self.out.take() { Some(out) => out.put(Value::Array(items)), - None => Err(NotJson::Source), + None => Err(Error::NotJson { + what: "it could not be read", + }), } } } @@ -393,13 +364,13 @@ impl Drop for JsonObject { impl MapSink for JsonObject { type Ok = O::Ok; - type Error = NotJson; + type Error = Error; type Entry<'s> = ToJson> where Self: 's; - fn entry(&mut self, key: &str) -> Result>, NotJson> { + fn entry(&mut self, key: &str) -> Result>, Error> { Ok(ToJson { out: Member { object: &mut self.members, @@ -409,11 +380,13 @@ impl MapSink for JsonObject { }) } - fn end(mut self) -> Result { + fn end(mut self) -> Result { let members = std::mem::take(&mut self.members); match self.out.take() { Some(out) => out.put(Value::Object(members)), - None => Err(NotJson::Source), + None => Err(Error::NotJson { + what: "it could not be read", + }), } } } diff --git a/languages/typescript/packages/recipher-js/crate/src/lib.rs b/languages/typescript/packages/recipher-js/crate/src/lib.rs index 0564dcbe3..d80bd5c64 100644 --- a/languages/typescript/packages/recipher-js/crate/src/lib.rs +++ b/languages/typescript/packages/recipher-js/crate/src/lib.rs @@ -50,7 +50,7 @@ mod record_tests; pub use cipher::{check_declarations, create_testing, Cipher, Keyset}; pub use ciphertext::Ciphertext; -pub use error::{ErrorKind, RecipherErrorFields}; +pub use error::RecipherErrorFields; pub use json::{json_document, Json}; use napi::bindgen_prelude::{JsObjectValue, Object, Unknown}; @@ -59,7 +59,7 @@ use napi_derive::napi; /// The version of the interface between the package's TypeScript and this /// build. -pub const BINDING_INTERFACE: u32 = 3; +pub const BINDING_INTERFACE: u32 = 4; /// The version of the interface between the package's TypeScript and this /// build. The TypeScript refuses a build that reports another. diff --git a/languages/typescript/packages/recipher-js/crate/src/outcome.rs b/languages/typescript/packages/recipher-js/crate/src/outcome.rs index 3119cac81..1091a7e2b 100644 --- a/languages/typescript/packages/recipher-js/crate/src/outcome.rs +++ b/languages/typescript/packages/recipher-js/crate/src/outcome.rs @@ -5,7 +5,7 @@ use std::future::Future; use napi::bindgen_prelude::{JsObjectValue, Object, PromiseRaw, ToNapiValue, Unknown}; use napi::Env; -use crate::error::RecipherErrorFields; +use crate::error::{Error, RecipherErrorFields}; /// What a call's work comes to before JavaScript sees it. pub(crate) type Outcome = Result; @@ -37,15 +37,8 @@ pub(crate) fn settle<'e, T>( /// The failure for a value napi could not make, which is never the /// caller's to fix. -pub(crate) fn not_made(error: napi::Error) -> RecipherErrorFields { - RecipherErrorFields::internal( - "recipher::build_value", - format!( - "the result could not be given to JavaScript ({}). Report this as a bug in \ - @cipherstash/recipher.", - error.status - ), - ) +pub(crate) fn not_made(_: napi::Error) -> RecipherErrorFields { + Error::BuildValue.into() } /// A failure, as an outcome object. diff --git a/languages/typescript/packages/recipher-js/crate/src/record.rs b/languages/typescript/packages/recipher-js/crate/src/record.rs index 668b14a14..76eb8bafa 100644 --- a/languages/typescript/packages/recipher-js/crate/src/record.rs +++ b/languages/typescript/packages/recipher-js/crate/src/record.rs @@ -31,11 +31,11 @@ use stack_encrypt::dynamic::{ use stack_encrypt::kms::{DataKeySource, IndexKeySource}; use stack_encrypt::target::IndexSpec; use stack_encrypt::{ - AsProtectedRef, CipherRef, CipherText, Controlled, DecryptFrom, EncryptInto, ErrorPayload as _, - KeysetCipher, PassthroughFrame, StackCipherText, + AsProtectedRef, CipherRef, CipherText, Controlled, DecryptFrom, EncryptInto, KeysetCipher, + PassthroughFrame, StackCipherText, }; -use crate::error::{ErrorKind, RecipherErrorFields}; +use crate::error::{Error, RecipherErrorFields}; use crate::frames::{bytes_of, entries, Entry, Map}; use crate::outcome::Outcome; @@ -149,14 +149,6 @@ struct KindDeclaration { name: String, } -/// A failure of the declaration of `record`, at `field` when there is one. -fn refused(record: &str, field: Option<&str>, code: &str, message: String) -> RecipherErrorFields { - let mut error = RecipherErrorFields::new(ErrorKind::Declaration, code, message); - error.record = Some(record.to_owned()); - error.field = field.map(str::to_owned); - error -} - /// The plans built so far, by the declaration's frame bytes. A declaration /// holds no secret. static PLANS: LazyLock, Arc>>> = @@ -168,8 +160,8 @@ impl RecordPlan { /// /// # Errors /// - /// A failure of kind `declaration`, naming the record and, where there - /// is one, the field. + /// `recipher::not_a_record`, or a refusal of the declaration naming the + /// record and, where there is one, the field. pub(crate) fn of(frame: &ValueFrame) -> Outcome> { let key = frame.risky_ref().to_vec(); if let Some(plan) = PLANS @@ -180,19 +172,10 @@ impl RecordPlan { return Ok(Arc::clone(plan)); } let declaration: Declaration = - stack_encrypt::dynamic::frame::serde::from_slice(frame.risky_ref()).map_err(|_| { - RecipherErrorFields::new( - ErrorKind::Declaration, - "recipher::not_a_record", - "a record is declared with record(..)", - ) - })?; + stack_encrypt::dynamic::frame::serde::from_slice(frame.risky_ref()) + .map_err(|_| Error::NotARecord)?; if declaration.tag != "record" { - return Err(RecipherErrorFields::new( - ErrorKind::Declaration, - "recipher::not_a_record", - "a record is declared with record(..)", - )); + return Err(Error::NotARecord.into()); } let plan = Arc::new(Self::build(declaration.name, declaration.fields.0)?); // Another call may have built the same plan meanwhile: the first one @@ -255,24 +238,13 @@ impl RecordPlan { /// /// # Errors /// - /// A failure of kind `declaration` for a name the record does not - /// declare, or that it passes through. + /// `recipher::no_field` for a name the record does not declare, or that + /// it passes through. pub(crate) fn field(&self, name: &str) -> Outcome> { self.alone.get(name).cloned().ok_or_else(|| { - let passthrough = self.fields.iter().any(|field| field.name == name); - refused( - &self.name, - Some(name), - "recipher::no_field", - if passthrough { - format!( - "the record `{}` passes this field through: it has no ciphertext", - self.name - ) - } else { - format!("the record `{}` declares no such field", self.name) - }, - ) + RecipherErrorFields::from(Error::NoField) + .in_record(&self.name) + .at_field(Some(name)) }) } } @@ -283,51 +255,38 @@ fn field_of( name: String, declaration: FieldDeclaration, ) -> Outcome<(Field, FieldPlan)> { - let at = |code: &str, message: String| refused(record, Some(&name), code, message); + let at = |error: Error| { + RecipherErrorFields::from(error) + .in_record(record) + .at_field(Some(&name)) + }; if RESERVED.contains(&name.as_str()) { - return Err(at( - "recipher::reserved_field", - format!("`{name}` is a name the engine reserves; name the field something else"), - )); + return Err(at(Error::ReservedField)); } let passthrough = match declaration.tag.as_str() { "sealed" => false, "passthrough" => true, - _ => { - return Err(at( - "recipher::declaration", - "a field is declared with encrypt(..) or passthrough()".to_owned(), - )) - } + _ => return Err(at(Error::Declaration)), }; - let kind = match &declaration.kind { - Some(kind) => Some(kind.name.parse::().map_err(|_| { - at( - "recipher::kind", - format!("`{}` is not one of `kinds`", kind.name), - ) - })?), + let kind = match declaration.kind { + Some(kind) => Some( + kind.name + .parse::() + .map_err(|_| at(Error::Kind { name: kind.name }))?, + ), None => None, }; let mut indexes = Vec::with_capacity(declaration.index.len()); - for index in &declaration.index { - indexes.push( - index_named(index) - .ok_or_else(|| at("recipher::index", format!("`{index}` is not an index")))?, - ); + for index in declaration.index { + indexes.push(index_named(&index).ok_or_else(|| at(Error::Index { name: index }))?); } - let null = match declaration.null.as_deref() { + let null = match declaration.null { None => None, Some(mode) => Some( [NullMode::Sealed, NullMode::Sql] .into_iter() .find(|known| known.name() == mode) - .ok_or_else(|| { - at( - "recipher::null", - format!("`{mode}` is not a null mode: `sealed` or `sql`"), - ) - })?, + .ok_or_else(|| at(Error::Null { mode }))?, ), }; let outputs = if passthrough { @@ -337,12 +296,7 @@ fn field_of( .chain(indexes.iter().cloned().map(Output::Term)) .collect() }; - let field_context = field_path(record, &name).ok_or_else(|| { - at( - "recipher::context", - "the field path could not be written".to_owned(), - ) - })?; + let field_context = field_path(record, &name).ok_or_else(|| at(Error::Context))?; let mut plan = FieldPlan::new(name.clone(), field_context, outputs) .map_err(|error| engine_refused(record, &error))?; if let Some(kind) = kind { @@ -375,24 +329,13 @@ fn field_path( } /// The engine's refusal of a declaration of `record`. When the engine says -/// a context is not a label, the record's name or the field's is at fault, -/// and the record's is tried alone to say which. +/// a context is not a label, the record's name or the field's is at fault. +/// The record's is tried alone to say which: the engine names the field +/// either way. fn engine_refused(record: &str, error: &stack_encrypt::dynamic::Error) -> RecipherErrorFields { - let mut refused = - RecipherErrorFields::diagnostic(ErrorKind::Declaration, error, Some(error.payload())); - refused.record = Some(record.to_owned()); + let refused = RecipherErrorFields::engine(error).in_record(record); if refused.reason() == Some("context_not_label") && !plain_segment(record) { - refused.field = None; - refused.message = format!( - "the record name `{record}` is not a plain segment of a field path: it is \ - empty, or holds a character the engine refuses in one" - ); - } else if refused.reason() == Some("context_not_label") { - refused.message = format!( - "the field name is not a plain segment of a field path: it is empty, or holds \ - a character the engine refuses in one. {}", - refused.message - ); + return RecipherErrorFields::from(Error::RecordName).in_record(record); } refused } @@ -404,34 +347,16 @@ fn plain_segment(record: &str) -> bool { .is_some_and(|context| FieldPlan::new("field", context, vec![Output::Ciphertext]).is_ok()) } -/// A failure of a row of `plan`'s record. -fn row_refused( - plan: &RecordPlan, - field: Option<&str>, - code: &str, - message: &str, -) -> RecipherErrorFields { - let mut error = RecipherErrorFields::new(ErrorKind::Value, code, message.to_owned()); - error.record = Some(plan.name.clone()); - error.field = field.map(str::to_owned); - error -} - /// A row's fields, each read as its field's kind, in the row's order. /// /// # Errors /// -/// A failure of kind `value` for a row that is not an object, or a value -/// that is not of its field's kind or does not fit it, naming the field. +/// `recipher::not_a_row` for a row that is not an object, and +/// `recipher::field_type` for a value that is not of its field's kind or +/// does not fit it, naming the field. pub(crate) fn conform_row(plan: &RecordPlan, row: &ValueFrame) -> Outcome { - let values = entries(row).ok_or_else(|| { - row_refused( - plan, - None, - "recipher::not_a_row", - "a row is an object of the record's fields", - ) - })?; + let not_a_row = || RecipherErrorFields::from(Error::NotARow).in_record(&plan.name); + let values = entries(row).ok_or_else(not_a_row)?; let mut conformed: Vec<(String, ValueFrame)> = Vec::with_capacity(values.len()); for (name, value) in values { let kind = plan @@ -442,12 +367,9 @@ pub(crate) fn conform_row(plan: &RecordPlan, row: &ValueFrame) -> Outcome read(kind, &value).map_err(|_| { - row_refused( - plan, - Some(&name), - "recipher::field_type", - &format!("the value is not of the field's kind, {kind}, or does not fit it"), - ) + RecipherErrorFields::from(Error::FieldType { kind }) + .in_record(&plan.name) + .at_field(Some(&name)) })?, _ => value, }; @@ -457,14 +379,7 @@ pub(crate) fn conform_row(plan: &RecordPlan, row: &ValueFrame) -> Outcome, K>(keyset) .await - .map_err(|error| with_record(&plan, RecipherErrorFields::engine(&error)))?; + .map_err(|error| RecipherErrorFields::engine(&error).in_record(&plan.name))?; stored .into_iter() .map(|row| stored_row(&plan, row)) @@ -501,8 +416,8 @@ where /// /// # Errors /// -/// A failure of kind `value` for a stored row of another shape, naming the -/// field, and the engine's refusal of one that does not open. +/// `recipher::not_a_stored_row` for a stored row of another shape, naming +/// the field, and the engine's refusal of one that does not open. pub(crate) async fn open_rows<'c, K>( cipher: impl Into>, plan: Arc, @@ -521,30 +436,16 @@ where .collect(); Vec::::decrypt_from(planned, cipher) .await - .map_err(|error| with_record(&plan, RecipherErrorFields::engine(&error))) -} - -/// `error`, naming the record. -fn with_record(plan: &RecordPlan, mut error: RecipherErrorFields) -> RecipherErrorFields { - error.record = Some(plan.name.clone()); - error -} - -/// A failure in the engine's result: a bug, never the caller's input. -fn engine_fault(what: &str) -> RecipherErrorFields { - RecipherErrorFields::internal( - "recipher::engine_result", - format!( - "the engine's stored row does not have the shape the SDK reads: {what}. Report \ - this as a bug in @cipherstash/recipher." - ), - ) + .map_err(|error| RecipherErrorFields::engine(&error).in_record(&plan.name)) } /// The stored row the engine returned, as the frame the SDK hands back. fn stored_row(plan: &RecordPlan, tree: StackCipherText) -> Outcome { let CipherText::Map(entries) = tree else { - return Err(engine_fault("a row is not a map of fields")); + return Err(Error::EngineResult { + what: "a row is not a map of fields", + } + .into()); }; let mut fields: Vec<(&str, Entry<'_>)> = Vec::with_capacity(plan.fields.len()); for field in &plan.fields { @@ -554,14 +455,20 @@ fn stored_row(plan: &RecordPlan, tree: StackCipherText) -> Outcome { continue; }; let CipherText::Map(outputs) = outputs else { - return Err(engine_fault("a field is not a map of outputs")); + return Err(Error::EngineResult { + what: "a field is not a map of outputs", + } + .into()); }; if field.passthrough { let Some((_, CipherText::Passthrough(PassthroughFrame(frame)))) = outputs .iter() .find(|(key, _)| key == Output::Passthrough.key()) else { - return Err(engine_fault("a passthrough field has no passthrough")); + return Err(Error::EngineResult { + what: "a passthrough field has no passthrough", + } + .into()); }; fields.push((field.name.as_str(), Entry::Frame(frame))); continue; @@ -574,28 +481,35 @@ fn stored_row(plan: &RecordPlan, tree: StackCipherText) -> Outcome { stored.push((CIPHERTEXT, Entry::Bytes(bytes))); } (Some(Output::Term(index)), CipherText::Passthrough(PassthroughFrame(term))) => { - let name = index_name(&index) - .ok_or_else(|| engine_fault("an index the SDK does not name"))?; + let name = index_name(&index).ok_or(Error::EngineResult { + what: "an index the SDK does not name", + })?; stored.push((name, Entry::Frame(term))); } - _ => return Err(engine_fault("an output of an unexpected shape")), + _ => { + return Err(Error::EngineResult { + what: "an output of an unexpected shape", + } + .into()) + } } } fields.push((field.name.as_str(), Entry::Map(Map(stored)))); } - ValueFrame::of(&Map(fields)) - .map_err(|_| engine_fault("the stored row could not be written as a frame")) + ValueFrame::of(&Map(fields)).map_err(|_| { + Error::EngineResult { + what: "the stored row could not be written as a frame", + } + .into() + }) } /// The engine's stored record for a stored row the SDK handed back. fn stored_tree(plan: &RecordPlan, row: &ValueFrame) -> Outcome { - let misfit = |field: Option<&str>, what: &str| { - row_refused( - plan, - field, - "recipher::not_a_stored_row", - &format!("the stored row does not have the record's shape: {what}"), - ) + let misfit = |field: Option<&str>, what: &'static str| { + RecipherErrorFields::from(Error::NotAStoredRow { what }) + .in_record(&plan.name) + .at_field(field) }; let stored = entries(row) .ok_or_else(|| misfit(None, "a stored row is an object of the record's fields"))?; @@ -631,11 +545,9 @@ fn stored_tree(plan: &RecordPlan, row: &ValueFrame) -> Outcome if key == CIPHERTEXT { let ciphertext = stack_encrypt::Ciphertext::from_bytes(&bytes).map_err(|error| { - let mut error = - RecipherErrorFields::diagnostic(ErrorKind::Open, &error, None); - error.record = Some(plan.name.clone()); - error.field = Some(name.clone()); - error + RecipherErrorFields::engine(&error) + .in_record(&plan.name) + .at_field(Some(&name)) })?; nodes.push(( Output::Ciphertext.key().to_owned(), @@ -665,11 +577,17 @@ fn stored_tree(plan: &RecordPlan, row: &ValueFrame) -> Outcome /// The value of the field `name` in a one-field row, or a null when the /// row has none (a null stored as SQL `NULL`). pub(crate) fn field_value(row: &ValueFrame, name: &str) -> Outcome { - let entries = - entries(row).ok_or_else(|| engine_fault("a one-field row is not a map of fields"))?; + let entries = entries(row).ok_or(Error::EngineResult { + what: "a one-field row is not a map of fields", + })?; match entries.into_iter().find(|(key, _)| key == name) { Some((_, value)) => Ok(value), - None => ValueFrame::of(&Null).map_err(|_| engine_fault("a null could not be written")), + None => ValueFrame::of(&Null).map_err(|_| { + Error::EngineResult { + what: "a null could not be written", + } + .into() + }), } } @@ -684,6 +602,10 @@ impl stack_encrypt::Encrypt for &Null { /// A one-field row: `{ name: value }`. pub(crate) fn one_field_row(name: &str, value: &ValueFrame) -> Outcome { - ValueFrame::of(&Map(vec![(name, Entry::Value(value))])) - .map_err(|_| engine_fault("a one-field row could not be written")) + ValueFrame::of(&Map(vec![(name, Entry::Value(value))])).map_err(|_| { + Error::EngineResult { + what: "a one-field row could not be written", + } + .into() + }) } diff --git a/languages/typescript/packages/recipher-js/crate/src/record_tests.rs b/languages/typescript/packages/recipher-js/crate/src/record_tests.rs index 279d67aac..3f602a9c4 100644 --- a/languages/typescript/packages/recipher-js/crate/src/record_tests.rs +++ b/languages/typescript/packages/recipher-js/crate/src/record_tests.rs @@ -16,7 +16,6 @@ use stack_encrypt::kms::{ use stack_encrypt::{AsProtectedRef, StackCipher}; use uuid::Uuid; -use crate::error::ErrorKind; use crate::frames::{bytes_of, entries, Entry, Map}; use crate::outcome::Outcome; use crate::record::{conform_row, field_value, one_field_row, open_rows, seal_rows, RecordPlan}; @@ -220,7 +219,6 @@ fn an_integer_is_read_at_its_fields_width_and_refused_outside_it() { )])) .unwrap(); let refused = conform_row(&small, &too_big).unwrap_err(); - assert_eq!(refused.kind, ErrorKind::Value); assert_eq!(refused.code, "recipher::field_type"); assert_eq!(refused.field.as_deref(), Some("n")); assert_eq!(refused.record.as_deref(), Some("t")); @@ -234,7 +232,7 @@ fn the_engine_refuses_a_declaration_naming_the_record_and_the_field() { "fields": { "n": { "type": "sealed", "kind": { "name": "int32" }, "index": ["match"] } }, })) .unwrap_err(); - assert_eq!(refused.kind, ErrorKind::Declaration); + assert_eq!(refused.code, "stack_encrypt::dynamic_plan"); assert_eq!(refused.field.as_deref(), Some("n")); assert_eq!(refused.record.as_deref(), Some("t")); @@ -255,7 +253,7 @@ fn a_json_field_needs_the_eql_extension() { "fields": { "doc": { "type": "sealed", "kind": { "name": "json" } } }, })) .unwrap_err(); - assert_eq!(refused.kind, ErrorKind::Declaration); + assert_eq!(refused.code, "stack_encrypt::dynamic_plan"); assert_eq!(refused.reason(), Some("json_needs_target")); } @@ -267,6 +265,7 @@ fn a_bad_record_name_is_the_records_fault_and_a_bad_field_name_the_fields() { "fields": { "x": { "type": "sealed", "kind": { "name": "string" } } }, })) .unwrap_err(); + assert_eq!(bad_record.code, "recipher::record_name"); assert_eq!(bad_record.record.as_deref(), Some("a/b")); assert_eq!(bad_record.field, None); @@ -276,7 +275,9 @@ fn a_bad_record_name_is_the_records_fault_and_a_bad_field_name_the_fields() { "fields": { "a/b": { "type": "sealed", "kind": { "name": "string" } } }, })) .unwrap_err(); + assert_eq!(bad_field.reason(), Some("context_not_label")); assert_eq!(bad_field.field.as_deref(), Some("a/b")); + assert_eq!(bad_field.record.as_deref(), Some("users")); } /// A deterministic key source that counts the key requests it is sent. diff --git a/languages/typescript/packages/recipher-js/crate/src/value.rs b/languages/typescript/packages/recipher-js/crate/src/value.rs index 9b34926ae..9f5e8a304 100644 --- a/languages/typescript/packages/recipher-js/crate/src/value.rs +++ b/languages/typescript/packages/recipher-js/crate/src/value.rs @@ -6,7 +6,7 @@ use stack_encrypt::json::JsonPlaintext; use stack_encrypt::Encrypt; use vitaminc_protected::OpaqueDebug; -use crate::error::{ErrorKind, RecipherErrorFields}; +use crate::error::{Error, RecipherErrorFields}; /// A value checked to be one leaf: one scalar of the value model, or a JSON /// document. The engine seals it through its opaque scalar path, as Rust's @@ -34,19 +34,12 @@ impl OneValue { /// /// # Errors /// - /// A failure of kind `value` for an array or an object. + /// `recipher::not_a_scalar` for an array, `recipher::plain_object` for an + /// object. pub(crate) fn scalar(value: ValueFrame) -> Result { match value.kind() { - Some(ValueKind::Array) => Err(RecipherErrorFields::new( - ErrorKind::Value, - "recipher::not_a_scalar", - "an array inside an array is not a value; wrap it in json(..)", - )), - Some(ValueKind::Object) => Err(RecipherErrorFields::new( - ErrorKind::Value, - "recipher::plain_object", - "an object is not a value: wrap it in json(..)", - )), + Some(ValueKind::Array) => Err(Error::NotAScalar.into()), + Some(ValueKind::Object) => Err(Error::PlainObject.into()), _ => Ok(Self(Some(Leaf::Scalar(value)))), } } diff --git a/languages/typescript/packages/recipher-js/native.d.ts b/languages/typescript/packages/recipher-js/native.d.ts index 3e9268254..c950b881a 100644 --- a/languages/typescript/packages/recipher-js/native.d.ts +++ b/languages/typescript/packages/recipher-js/native.d.ts @@ -17,13 +17,12 @@ export declare class Cipher { * A cipher over ZeroKMS, with the credentials the engine finds: the * `CS_*` variables, then the profile `stash auth login` writes. * - * Resolves to a failure of kind `credential` when there are none or - * they are refused, and of kind `zerokms` when ZeroKMS refuses to load - * the default keyset. + * Resolves to the engine's error when there are no credentials, when + * they are refused, or when ZeroKMS refuses to load the default keyset. * * `options.records` are declarations to check now, before any * credential is looked for: a declaration the engine refuses is a - * failure of kind `declaration`, naming the record. + * failure naming the record. */ static create(options?: unknown | undefined | null): Promise> /** @@ -114,9 +113,9 @@ export declare class Keyset { encrypt(first: unknown, second?: unknown | undefined | null): Promise> /** * Open a ciphertext sealed under this keyset, or an array of them. A - * ciphertext of another keyset is a failure of kind `foreign_keyset`, - * before any key is requested. With a record first, open its stored - * row, or an array of them. + * ciphertext of another keyset is a failure with the code + * `stack_encrypt::foreign_keyset`, before any key is requested. With a + * record first, open its stored row, or an array of them. */ decrypt(first: unknown, second?: unknown | undefined | null): Promise> /** @@ -142,9 +141,8 @@ export declare function bindingInterface(): number /** * Check declarations with the engine, with no credentials and no - * request: for a test or a CI step. The first refusal is the failure, of - * kind `declaration`, naming the record and, where there is one, the - * field. + * request: for a test or a CI step. The first refusal is the failure, + * naming the record and, where there is one, the field. */ export declare function checkDeclarations(records: unknown): Outcome @@ -156,7 +154,7 @@ export declare function checkDeclarations(records: unknown): Outcome * who knows the seed. * * Only a build with the `testing` feature has one; any other resolves to - * a failure of kind `internal`, code `recipher::no_testing`. + * a failure with the code `recipher::no_testing`. */ export declare function createTesting(seed: unknown): Promise> @@ -171,9 +169,6 @@ export interface ErrorCause { message: string } -/** The closed set of things that can go wrong, for a caller to switch on. */ -export type ErrorKind = 'declaration' | 'value' | 'credential' | 'zerokms' | 'foreign_keyset' | 'context_mismatch' | 'open' | 'cancelled' | 'internal' - /** * A JSON document, to encrypt as one ciphertext: a plain object, an array, * text, a number, a `bigint`, a boolean or `null`, nested at most 127 @@ -186,10 +181,8 @@ export declare function json(document: unknown): Json /** A failure, as JavaScript receives it. */ export interface RecipherErrorFields { - /** What kind of failure it is. */ - kind: ErrorKind /** - * Stable: the engine's diagnostic code, such as `stack_encrypt::aead`, + * Stable: the diagnostic's code, such as `stack_encrypt::aead`, * vitaminc's code for a value it refused, such as `ERR_INTEGER_RANGE`, * or the SDK's own, such as `recipher::not_a_ciphertext`. */ @@ -200,10 +193,7 @@ export interface RecipherErrorFields { help?: string /** A documentation page for the error, where it has one. */ url?: string - /** - * How serious it is: `error` unless the engine's diagnostic says - * otherwise. - */ + /** How serious it is: `error` unless the diagnostic says otherwise. */ severity: Severity /** * The error's structured fields, by `snake_case` name: a refused @@ -222,5 +212,5 @@ export interface RecipherErrorFields { record?: string } -/** How serious a failure is, as the engine's diagnostic states it. */ +/** How serious a failure is, as the diagnostic states it. */ export type Severity = 'error' | 'warning' | 'advice' diff --git a/languages/typescript/packages/recipher-js/src/binding.ts b/languages/typescript/packages/recipher-js/src/binding.ts index f0e92bfcb..7e92526a7 100644 --- a/languages/typescript/packages/recipher-js/src/binding.ts +++ b/languages/typescript/packages/recipher-js/src/binding.ts @@ -31,11 +31,11 @@ import { dirname, join } from 'node:path' import { fileURLToPath } from 'node:url' import type * as Native from '../native' import type { Outcome } from '../native' -import { fromNative, internal, type RecipherError } from './error' +import { fromNative, type RecipherError, sdkError } from './error' import { err, ok, type Result } from './result' /** The binding interface this TypeScript speaks. */ -export const BINDING_INTERFACE = 3 +export const BINDING_INTERFACE = 4 /** What the native build exports. */ export type Binding = typeof Native @@ -69,7 +69,7 @@ export function load( exported = require(path) } catch { return err( - internal( + sdkError( 'recipher::load', `the native build of @cipherstash/recipher did not load from ${path}. ` + 'Build it with `pnpm --filter @cipherstash/recipher build:debug`.', @@ -84,7 +84,7 @@ export function load( ) ) { return err( - internal( + sdkError( 'recipher::load', 'the native build of @cipherstash/recipher does not export its classes', ), @@ -100,7 +100,7 @@ export function load( } if (version !== BINDING_INTERFACE) { return err( - internal( + sdkError( 'recipher::binding_interface', `the native build implements binding interface ${String(version)}, ` + `and this TypeScript needs ${BINDING_INTERFACE}`, @@ -118,8 +118,8 @@ export const binding: Result = load( /** The error of a native call that threw or rejected, which it never should. */ function threw(): RecipherError { - return internal( - 'recipher::threw', + return sdkError( + 'recipher::native_threw', 'a call into the native build threw. A method called on something that ' + 'is not its class does; otherwise, report this as a bug in @cipherstash/recipher.', ) @@ -129,7 +129,7 @@ function threw(): RecipherError { function fromOutcome(outcome: Outcome): Result { if (typeof outcome !== 'object' || outcome === null) { return err( - internal( + sdkError( 'recipher::outcome', 'the native build returned something that is not an outcome', ), diff --git a/languages/typescript/packages/recipher-js/src/cipher.ts b/languages/typescript/packages/recipher-js/src/cipher.ts index 4f4a69562..4d326f320 100644 --- a/languages/typescript/packages/recipher-js/src/cipher.ts +++ b/languages/typescript/packages/recipher-js/src/cipher.ts @@ -96,8 +96,8 @@ export interface Keyset { ): Promise[], RecipherError>> /** * Open a ciphertext sealed under this keyset, or an array of them in one - * key request. A ciphertext from another keyset is an `Err` of kind - * `foreign_keyset`, refused before any key is requested. + * key request. A ciphertext from another keyset is an `Err` with the code + * `stack_encrypt::foreign_keyset`, refused before any key is requested. */ decrypt(ciphertext: Ciphertext): Promise> decrypt( @@ -215,8 +215,8 @@ export interface CipherClass { /** * A cipher over ZeroKMS, with the credentials it finds: the `CS_*` * variables, then the profile that `stash auth login` writes. Resolves - * to an `Err` of kind `credential` when there are none, and of kind - * `declaration` when the engine refuses one of `options.records`. + * to an `Err` with the code `stack_encrypt::config` when there are none, + * and to the engine's refusal when it refuses one of `options.records`. */ create(options?: CipherOptions): Promise> } diff --git a/languages/typescript/packages/recipher-js/src/error.ts b/languages/typescript/packages/recipher-js/src/error.ts index a8b0c7d34..c88b4e79a 100644 --- a/languages/typescript/packages/recipher-js/src/error.ts +++ b/languages/typescript/packages/recipher-js/src/error.ts @@ -1,41 +1,23 @@ /** * `RecipherError`: every failure, as a value. * - * The native build defines the error's fields and its kinds - * (`RecipherErrorFields` and `ErrorKind`, in the generated `native.d.ts`). - * This class exists in TypeScript because an error has to exist when the - * native build did not load. + * The native build defines the error's fields (`RecipherErrorFields`, in the + * generated `native.d.ts`) and every error it reports. This class exists in + * TypeScript because an error has to exist when the native build did not + * load. */ -import type { - ErrorCause, - ErrorKind, - RecipherErrorFields, - Severity, -} from '../native' +import type { ErrorCause, RecipherErrorFields, Severity } from '../native' -export type { ErrorCause, ErrorKind, RecipherErrorFields, Severity } - -const KINDS: ReadonlySet = new Set([ - 'declaration', - 'value', - 'credential', - 'zerokms', - 'foreign_keyset', - 'context_mismatch', - 'open', - 'cancelled', - 'internal', -]) +export type { ErrorCause, RecipherErrorFields, Severity } /** * A failure, as a value. Every call that fails resolves to an `Err` holding * one; none throws. * - * - `kind` is the closed set to switch on. A `switch` that leaves a kind - * out does not compile when its default case is checked as `never`. - * - `code` is stable: the engine's diagnostic code, such as - * `stack_encrypt::aead`, vitaminc's code for a value it refused, such as - * `ERR_INTEGER_RANGE`, or the SDK's own, such as `recipher::load`. + * - `code` is stable, and is what to switch on: the engine's diagnostic + * code, such as `stack_encrypt::aead`, vitaminc's code for a value it + * refused, such as `ERR_INTEGER_RANGE`, or the SDK's own, such as + * `recipher::not_a_ciphertext`. * - `message` says what went wrong, in one line. * - `help` says what to do about it, and `url` is a documentation page for * the error, where the error has them. @@ -53,7 +35,6 @@ const KINDS: ReadonlySet = new Set([ * ciphertext. */ export class RecipherError { - readonly kind: ErrorKind readonly code: string readonly message: string readonly help: string | undefined @@ -65,10 +46,9 @@ export class RecipherError { readonly record: string | undefined constructor( - fields: Pick & + fields: Pick & Partial, ) { - this.kind = fields.kind this.code = fields.code this.message = fields.message this.help = fields.help @@ -83,46 +63,32 @@ export class RecipherError { Object.freeze(this) } - /** The kind, code and message, then the help where there is one. */ + /** The code and message, then the help where there is one. */ toString(): string { - const text = `RecipherError(${this.kind}, ${this.code}): ${this.message}` + const text = `RecipherError(${this.code}): ${this.message}` return this.help === undefined ? text : `${text}\nhelp: ${this.help}` } } /** * The error of a native outcome. The native build writes it, so this only - * checks that it has the shape and a known kind. + * checks that it has the shape. */ export function fromNative(error: unknown): RecipherError { - if (typeof error !== 'object' || error === null) { - return internal( + const { code, message, help, url, severity, fields, causes, field, record } = + typeof error === 'object' && error !== null + ? (error as Record) + : {} + if (typeof code !== 'string' || typeof message !== 'string') { + return sdkError( 'recipher::outcome', 'the native build returned an error of an unknown shape', ) } - const { - kind, + return new RecipherError({ code, message, - help, - url, - severity, - fields, - causes, - field, - record, - } = error as Record - if (typeof kind !== 'string' || !KINDS.has(kind)) { - return internal( - 'recipher::outcome', - 'the native build returned an error of an unknown kind', - ) - } - return new RecipherError({ - kind: kind as ErrorKind, - code: typeof code === 'string' ? code : 'recipher::unknown', - message: typeof message === 'string' ? message : '', + ...(typeof help === 'string' ? { help } : {}), ...(typeof url === 'string' ? { url } : {}), ...(severity === 'warning' || severity === 'advice' ? { severity } : {}), @@ -147,7 +113,11 @@ function causeOf(cause: unknown): ErrorCause[] { return [typeof code === 'string' ? { code, message } : { message }] } -/** An `internal` error of the SDK's own. */ -export function internal(code: string, message: string): RecipherError { - return new RecipherError({ kind: 'internal', code, message }) +/** + * An error the TypeScript raises itself, for a native build that did not + * load or did not answer as it should. Every other error is the native + * build's. + */ +export function sdkError(code: string, message: string): RecipherError { + return new RecipherError({ code, message }) } diff --git a/languages/typescript/packages/recipher-js/src/index.ts b/languages/typescript/packages/recipher-js/src/index.ts index b556e6e6a..84a737a10 100644 --- a/languages/typescript/packages/recipher-js/src/index.ts +++ b/languages/typescript/packages/recipher-js/src/index.ts @@ -28,7 +28,6 @@ export { } from './cipher' export { type ErrorCause, - type ErrorKind, RecipherError, type RecipherErrorFields, type Severity, diff --git a/languages/typescript/packages/recipher-js/src/record.ts b/languages/typescript/packages/recipher-js/src/record.ts index a288b3365..2b000bda2 100644 --- a/languages/typescript/packages/recipher-js/src/record.ts +++ b/languages/typescript/packages/recipher-js/src/record.ts @@ -184,8 +184,8 @@ export type SealedFieldName = /** * Check declarations with the engine, with no credentials and no request: - * for a test or a CI step. The first refusal is the `Err`, of kind - * `declaration`, naming the record and, where there is one, the field. + * for a test or a CI step. The first refusal is the `Err`, naming the + * record and, where there is one, the field. */ export function checkDeclarations( declarations: readonly RecordDeclaration[], diff --git a/languages/typescript/packages/recipher-js/src/testing.ts b/languages/typescript/packages/recipher-js/src/testing.ts index b4870f2aa..5705629fc 100644 --- a/languages/typescript/packages/recipher-js/src/testing.ts +++ b/languages/typescript/packages/recipher-js/src/testing.ts @@ -13,8 +13,8 @@ * seed: never use a test cipher for data you keep. */ import { type Cipher, classes } from './cipher' -import { RecipherError } from './error' -import { err, type Result } from './result' +import type { RecipherError } from './error' +import type { Result } from './result' /** The byte the seed of a test cipher is filled with when none is given. */ const DEFAULT_SEED_BYTE = 0x2a @@ -27,9 +27,9 @@ export interface TestCipherOptions { /** * A cipher over the engine's deterministic test keys. Resolves to an `Err` - * of kind `value` for a seed that is not 32 bytes, and of kind `internal` - * (code `recipher::no_testing`) when the native build has no test cipher: - * only the debug build (`build:debug`) has one. + * with the code `recipher::testing_seed` for a seed that is not 32 bytes, + * or one whose getter throws, and `recipher::no_testing` when the native + * build has no test cipher: only the debug build (`build:debug`) has one. */ export async function testCipher( options?: TestCipherOptions | null, @@ -38,13 +38,8 @@ export async function testCipher( try { seed = options?.seed ?? new Uint8Array(32).fill(DEFAULT_SEED_BYTE) } catch { - return err( - new RecipherError({ - kind: 'value', - code: 'recipher::testing_seed', - message: 'reading the options threw', - }), - ) + // Not a seed, so the native build refuses it as one. + seed = undefined } return classes.createTesting(seed) } diff --git a/languages/typescript/packages/recipher-js/src/values.ts b/languages/typescript/packages/recipher-js/src/values.ts index 73691ecf5..ac8d1f565 100644 --- a/languages/typescript/packages/recipher-js/src/values.ts +++ b/languages/typescript/packages/recipher-js/src/values.ts @@ -56,8 +56,8 @@ export interface VcDecimal { /** * A UUID. vitaminc's class. The engine's value model does not hold a UUID - * yet, so encrypting one is an `Err` of kind `value` (code - * `recipher::uuid`), and it is not a `Scalar`. + * yet, so encrypting one is an `Err` with the code `recipher::uuid`, and it + * is not a `Scalar`. */ export interface VcUuid { /** The UUID as hyphenated hex. */ diff --git a/languages/typescript/packages/recipher-js/type-tests/result.ts b/languages/typescript/packages/recipher-js/type-tests/result.ts index 09e644efb..6671e0029 100644 --- a/languages/typescript/packages/recipher-js/type-tests/result.ts +++ b/languages/typescript/packages/recipher-js/type-tests/result.ts @@ -1,12 +1,6 @@ // Compile-time tests: `pnpm run typecheck` compiles this file and nothing // runs it. Each `@ts-expect-error` is a line that must not compile. -import type { - Ciphertext, - ErrorKind, - Keyset, - RecipherError, - Result, -} from '../src/index' +import type { Ciphertext, Keyset, RecipherError, Result } from '../src/index' declare const sealed: Result, RecipherError> @@ -36,47 +30,15 @@ const bytes: Uint8Array | null = sealed .unwrapOr(null) void bytes -// A switch over the kinds covers every one, or the `never` does not compile. -function describe(kind: ErrorKind): string { - switch (kind) { - case 'declaration': - case 'value': - case 'credential': - case 'zerokms': - case 'foreign_keyset': - case 'context_mismatch': - case 'open': - case 'cancelled': - case 'internal': - return kind - default: { - const unhandled: never = kind - return unhandled - } - } +// An error is its diagnostic: a caller switches on its code, a string. +function describe(error: RecipherError): string { + const code: string = error.code + // @ts-expect-error: an error has no kind; its code says what it is. + void error.kind + return code } void describe -function missesOne(kind: ErrorKind): string { - switch (kind) { - case 'declaration': - case 'value': - case 'credential': - case 'zerokms': - case 'foreign_keyset': - case 'context_mismatch': - case 'open': - case 'cancelled': - return kind - default: { - // @ts-expect-error: `internal` is not handled. - const unhandled: never = kind - return unhandled - } - } -} -void missesOne - declare const keyset: Keyset // @ts-expect-error: a plain object is not a value. void keyset.encrypt({ name: 'Ada' })