Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 7 additions & 9 deletions languages/typescript/packages/recipher-js/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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`
Expand Down Expand Up @@ -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. ...'
Expand All @@ -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. |
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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')
Expand Down Expand Up @@ -281,21 +279,21 @@ 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 () => {
const bad = record('bad', {
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')
})

Expand All @@ -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')
Expand Down Expand Up @@ -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')
})
})
Original file line number Diff line number Diff line change
Expand Up @@ -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')
})

Expand All @@ -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)',
Expand Down Expand Up @@ -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')
})

Expand Down Expand Up @@ -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 () => {
Expand Down Expand Up @@ -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')
})
Expand Down Expand Up @@ -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')
})
})
Original file line number Diff line number Diff line change
Expand Up @@ -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')
})
})

Expand Down Expand Up @@ -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')
})

Expand All @@ -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')
}
})
Expand Down Expand Up @@ -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')
})

Expand All @@ -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')
})
Expand All @@ -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))
})
Expand Down Expand Up @@ -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')
})
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand All @@ -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(
Expand All @@ -102,7 +100,6 @@ describe('settle', () => {
const failed = settle(() => ({
ok: false,
error: {
kind: 'value',
code: 'recipher::x',
message: 'no',
severity: 'error',
Expand All @@ -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')
})

Expand Down Expand Up @@ -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',
})
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand All @@ -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')
}
})
})
8 changes: 4 additions & 4 deletions languages/typescript/packages/recipher-js/crate/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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.
Expand Down
Loading
Loading