diff --git a/languages/typescript/packages/recipher-js/Cargo.lock b/languages/typescript/packages/recipher-js/Cargo.lock index eb3a9efb8..72518b187 100644 --- a/languages/typescript/packages/recipher-js/Cargo.lock +++ b/languages/typescript/packages/recipher-js/Cargo.lock @@ -3792,6 +3792,7 @@ dependencies = [ "rust_decimal", "serde", "thiserror 2.0.21", + "uuid", "vitaminc-aead-derive 0.10.0", "vitaminc-context 0.10.0", "vitaminc-protected 0.10.0", diff --git a/languages/typescript/packages/recipher-js/README.md b/languages/typescript/packages/recipher-js/README.md index bc700809a..151b3b5a5 100644 --- a/languages/typescript/packages/recipher-js/README.md +++ b/languages/typescript/packages/recipher-js/README.md @@ -63,6 +63,7 @@ The value bridge converts JavaScript values in both directions: | an `RcTimestamp`, from `RcTimestamp.from('2026-11-23T01:02:03.000000001Z')` | a timestamp, in nanoseconds | `Date` when it is whole milliseconds, else `RcTimestamp` | | an `RcDate`, from `RcDate.from('2026-11-23')` | a calendar date | `RcDate` | | an `RcDecimal`, from `RcDecimal.from('1.50')` | a decimal, with its scale | `RcDecimal` | +| an `RcUuid`, from `RcUuid.from('123e4567-e89b-12d3-a456-426614174000')` | a universally unique identifier (UUID) | `RcUuid` | | `null` | refused: see [A declared kind](#a-declared-kind) | `null`, for a null stored another way, read with no kind or with `nullable(..)` | | `json(value)` | a JSON document, as its JSON text | the document, from the `Ciphertext` that `encrypt` returned or one read with `kinds.json` | @@ -95,9 +96,11 @@ The value bridge converts JavaScript values in both directions: `{ record }` in the options encrypts the object as a row of a record: see [Records](#records). `json(..)` encrypts the object as a JSON document. `opaque(..)`, for a whole object in the engine's own format, is not built yet. -- The package exports `RcUuid`, for a universally unique identifier (UUID). - This version of the SDK does not encrypt a UUID yet. - Encrypting an `RcUuid` is an `Err` with the code `recipher_js::uuid`. +- A UUID is an `RcUuid`, not a string. + A string that contains a UUID is encrypted as text. + The text of an `RcUuid` must be hyphenated hex, in upper or lower case. + `RcUuid.from` refuses other text, such as text in braces, with an `Err` with the code `ERR_INVALID_UUID`. + A decrypted `RcUuid` contains lowercase hyphenated hex, whatever case it was built with. - The value bridge refuses each of these values, with an error code for each: - a `Map` or a `Set`; - a class instance; @@ -151,7 +154,7 @@ const opened = (await cipher.decrypt(age)).unwrap() Store a value that is not there as a database `NULL`. TypeScript refuses `encrypt(null)` and `encrypt(null, { kind: kinds.int64 })` before the code runs. - Once the engine encrypts a typed null as one value, a `null` declared as `nullable(..)` of a fixed-width kind will encrypt. - A fixed-width kind is a boolean, an integer, a float, a decimal, a date, or a timestamp. + A fixed-width kind is a boolean, an integer, a float, a decimal, a date, a timestamp, or a UUID. The engine will encrypt the `null` padded to the size of a value, as a record field with `"null": "sealed"` stores one. Issue #2023 makes that engine change, and it has not merged yet. TypeScript already takes `encrypt(null, { kind: nullable(kinds.int64) })`. @@ -303,7 +306,7 @@ const sameEmail = (await cipher.decrypt(email, { record: UserRecord, field: 'ema - The package has an ECMAScript module (ESM) build and a CommonJS build. A declaration made by either build works with a cipher from the other. - Each encrypted field names its kind, by the engine's name for it. - The kinds are `kinds.string`, `kinds.boolean`, `kinds.int8` to `kinds.int128`, `kinds.uint8` to `kinds.uint128`, `kinds.float32`, `kinds.float64`, `kinds.decimal`, `kinds.date`, `kinds.timestamp`, and `kinds.bytes`. + The kinds are `kinds.string`, `kinds.boolean`, `kinds.int8` to `kinds.int128`, `kinds.uint8` to `kinds.uint128`, `kinds.float32`, `kinds.float64`, `kinds.decimal`, `kinds.date`, `kinds.timestamp`, `kinds.bytes`, and `kinds.uuid`. - An integer field accepts a `bigint` at every width. The field refuses a `bigint` outside its range. - A context is data that a ciphertext is bound to. @@ -315,6 +318,10 @@ const sameEmail = (await cipher.decrypt(email, { record: UserRecord, field: 'ema `equality` finds exact matches. `match` finds text matches. `ore` and `ope` compare order. + A field's kind decides which indexes the field accepts. + For example, a `kinds.uuid` field accepts `equality` only. + When the engine checks the declaration, it refuses any other index on that field. + The refusal has the reason `index_not_admitted` in `error.fields`. - The stored row has one object for each encrypted field. The object has a `ciphertext` property. The object also has one property for each index the field declares: `equality`, `match`, `ore`, or `ope`. 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 1fe664e3c..4dd75d1a3 100644 --- a/languages/typescript/packages/recipher-js/__tests__/addon/records.test.ts +++ b/languages/typescript/packages/recipher-js/__tests__/addon/records.test.ts @@ -10,6 +10,7 @@ import { passthrough, RcDate, RcDecimal, + RcUuid, record, } from '../../src/index' import { testCipher } from '../../src/testing' @@ -152,6 +153,152 @@ describe('a record', () => { }) }) +describe('a UUID field', () => { + const DeviceRecord = record('devices', { + id: encrypt(kinds.uuid, { index: ['equality'] }), + name: encrypt(kinds.string), + }) + const text = '123e4567-e89b-12d3-a456-426614174000' + + it('is stored, found by equality, and read back as an RcUuid', async () => { + const c = await cipher() + const keyset = c.defaultKeyset() + const row = { id: RcUuid.from(text).unwrap(), name: 'sensor' } + const stored = ( + await keyset.encrypt(row, { record: DeviceRecord }) + ).unwrap() + expect(Object.keys(stored.id).sort()).toEqual(['ciphertext', 'equality']) + + // A query term for the same UUID matches the stored term. A query term + // for another UUID does not. + const same = ( + await keyset.encrypt(RcUuid.from(text).unwrap(), { + record: DeviceRecord, + field: 'id', + }) + ).unwrap() + const other = ( + await keyset.encrypt( + RcUuid.from('123e4567-e89b-12d3-a456-426614174001').unwrap(), + { record: DeviceRecord, field: 'id' }, + ) + ).unwrap() + expect(Buffer.from(same.equality)).toEqual(Buffer.from(stored.id.equality)) + expect(Buffer.from(other.equality)).not.toEqual( + Buffer.from(stored.id.equality), + ) + + const opened = (await c.decrypt(stored, { record: DeviceRecord })).unwrap() + expect(opened.id).toBeInstanceOf(RcUuid) + expect(opened.id.value).toBe(text) + expect(opened.name).toBe('sensor') + }) + + it('refuses UUID text that is not hyphenated hex, naming the field', async () => { + const keyset = (await cipher()).defaultKeyset() + for (const bad of [ + '123e4567-e89b-12d3-a456-42661417400', + '{123e4567-e89b-12d3-a456-426614174000}', + '123e4567-e89b-12d3-a456-42661417400g', + ]) { + // `from` refuses the text, so no `RcUuid` holds it. + expect(RcUuid.from(bad).err()?.code, bad).toBe('ERR_INVALID_UUID') + // An object made without the constructor still passes `instanceof`, + // so the field's text is checked again when the row is encrypted. + const forged: RcUuid = Object.create(RcUuid.prototype) + Object.defineProperty(forged, 'value', { value: bad, enumerable: true }) + const result = await keyset.encrypt( + { + id: forged, + name: 'sensor', + }, + { record: DeviceRecord }, + ) + expect(result.isErr(), bad).toBe(true) + expect(result.err()?.code, bad).toBe('ERR_INVALID_UUID') + expect(result.err()?.field, bad).toBe('id') + expect(result.err()?.record, bad).toBe('devices') + } + }) + + it('stores and decrypts a null under each null setting, and refuses one by default', async () => { + const NullableDeviceRecord = record('nullable_devices', { + sealed: encrypt(kinds.uuid, { index: ['equality'], null: 'sealed' }), + sql: encrypt(kinds.uuid, { null: 'sql' }), + required: encrypt(kinds.uuid), + }) + const c = await cipher() + const keyset = c.defaultKeyset() + const id = RcUuid.from(text).unwrap() + + const empty = { sealed: null, sql: null, required: id } + const stored = ( + await keyset.encrypt(empty, { record: NullableDeviceRecord }) + ).unwrap() + // A sealed null is stored like a value, padded to a value's length. + // A SQL null is stored as null. + const full = ( + await keyset.encrypt( + { sealed: id, sql: id, required: id }, + { record: NullableDeviceRecord }, + ) + ).unwrap() + expect(stored.sealed).not.toBeNull() + expect(stored.sealed.ciphertext.length).toBe(full.sealed.ciphertext.length) + expect(Buffer.from(stored.sealed.equality)).not.toEqual( + Buffer.from(full.sealed.equality), + ) + expect(stored.sql).toBeNull() + + const opened = ( + await c.decrypt(stored, { record: NullableDeviceRecord }) + ).unwrap() + expect(opened.sealed).toBeNull() + expect(opened.sql).toBeNull() + expect(opened.required.value).toBe(text) + + // A field with the default null setting accepts no null. + const row = { sealed: id, sql: id, required: null } + // @ts-expect-error: `required` has no null setting, so it accepts no null. + const refused = await keyset.encrypt(row, { record: NullableDeviceRecord }) + expect(refused.err()?.code).toBe('stack_encrypt::dynamic_source') + expect(refused.err()?.field).toBe('required') + expect(refused.err()?.record).toBe('nullable_devices') + }) + + it('refuses the UUID as a string', async () => { + const keyset = (await cipher()).defaultKeyset() + const result = await keyset.encrypt( + { + // @ts-expect-error: a UUID field accepts an RcUuid, not its text. + id: text, + name: 'sensor', + }, + { record: DeviceRecord }, + ) + expect(result.isErr()).toBe(true) + expect(result.err()?.code).toBe('recipher_js::field_type') + expect(result.err()?.field).toBe('id') + expect(result.err()?.record).toBe('devices') + }) + + it('refuses an order index when the declaration is checked', async () => { + for (const index of ['ore', 'ope'] as const) { + const ordered = record('devices', { + id: encrypt(kinds.uuid, { index: [index] }), + }) + const checked = checkDeclarations([ordered]) + expect(checked.err()?.code).toBe('stack_encrypt::dynamic_plan') + expect(checked.err()?.fields.reason).toBe('index_not_admitted') + expect(checked.err()?.field).toBe('id') + expect(checked.err()?.record).toBe('devices') + + const result = await Cipher.create({ records: [ordered] }) + expect(result.err()?.fields.reason).toBe('index_not_admitted') + } + }) +}) + describe('one field', () => { it('encrypts alone to the form it has in a whole row', async () => { const c = await cipher() 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 124b2b646..d483786e9 100644 --- a/languages/typescript/packages/recipher-js/__tests__/addon/values.test.ts +++ b/languages/typescript/packages/recipher-js/__tests__/addon/values.test.ts @@ -39,7 +39,8 @@ async function encryptOne( | Date | RcDate | RcTimestamp - | RcDecimal, + | RcDecimal + | RcUuid, ) { return (await c.defaultKeyset().encrypt(value)).unwrap() } @@ -109,6 +110,22 @@ describe('every value in the mapping round-trips', () => { expect(price).toBeInstanceOf(RcDecimal) expect((price as RcDecimal).value).toBe('1.50') }) + + it('a UUID, as an RcUuid', async () => { + const id = await roundTrip( + RcUuid.from('123e4567-e89b-12d3-a456-426614174000').unwrap(), + ) + expect(id).toBeInstanceOf(RcUuid) + expect((id as RcUuid).value).toBe('123e4567-e89b-12d3-a456-426614174000') + }) + + it('a UUID built in uppercase, which decrypts as lowercase', async () => { + const id = await roundTrip( + RcUuid.from('123E4567-E89B-12D3-A456-426614174ABC').unwrap(), + ) + expect(id).toBeInstanceOf(RcUuid) + expect((id as RcUuid).value).toBe('123e4567-e89b-12d3-a456-426614174abc') + }) }) describe('a wrapper class', () => { @@ -695,6 +712,23 @@ describe('a ciphertext read back with a kind', () => { expect((await c.decrypt(maybe)).unwrap()).toBe(42n) }) + it('opens a UUID with kinds.uuid, and refuses its text', async () => { + const c = await cipher() + const keyset = c.defaultKeyset() + const text = '123e4567-e89b-12d3-a456-426614174000' + const sealed = (await keyset.encrypt(RcUuid.from(text).unwrap())).unwrap() + const stored = Ciphertext.fromBytes(sealed.toBytes(), kinds.uuid).unwrap() + const opened: RcUuid = (await c.decrypt(stored)).unwrap() + expect(opened.value).toBe(text) + + // The same UUID as a string is text, not a UUID. + const asText = (await keyset.encrypt(text)).unwrap() + const refused = await c.decrypt( + Ciphertext.fromBytes(asText.toBytes(), kinds.uuid).unwrap(), + ) + expect(refused.err()?.code).toBe('recipher_js::opened_type') + }) + it('refuses a value sealed as another type', async () => { const c = await cipher() const sealed = (await c.defaultKeyset().encrypt('text')).unwrap() @@ -933,6 +967,7 @@ describe('a declared kind', () => { nullable(kinds.boolean), nullable(kinds.timestamp), nullable(kinds.decimal), + nullable(kinds.uuid), ]) { const result = await keyset.encrypt(null, { kind }) expect(result.err()?.code, kind.name).toBe('recipher_js::null_value') @@ -1001,21 +1036,41 @@ describe('a declared kind', () => { } // The type checker takes any `{ name }` as a kind, so this check is // made when the call runs. - const unknown = await keyset.encrypt(34, { kind: { name: 'uuid' } }) + const unknown = await keyset.encrypt(34, { kind: { name: 'text' } }) expect(unknown.err()?.code).toBe('recipher_js::not_a_kind') }) }) describe('refusals', () => { - it('a UUID: this version of the SDK does not encrypt one yet', async () => { + it('UUID text that is not hyphenated hex, as an Err', async () => { const keyset = (await cipher()).defaultKeyset() - const uuid = RcUuid.from('123e4567-e89b-12d3-a456-426614174000').unwrap() - // @ts-expect-error: a UUID is not a `Scalar` in this version of the SDK. - const result = await keyset.encrypt(uuid) - expect(result.err()?.code).toBe('recipher_js::uuid') - expect(result.err()?.message).toContain( - 'this version of the SDK does not encrypt a UUID yet', - ) + for (const text of [ + // One digit short. + '123e4567-e89b-12d3-a456-42661417400', + // In braces. + '{123e4567-e89b-12d3-a456-426614174000}', + // A digit that is not hex. + '123e4567-e89b-12d3-a456-42661417400g', + ]) { + // `from` refuses the text, so no `RcUuid` holds it. + const made = RcUuid.from(text) + expect(made.err()?.code, text).toBe('ERR_INVALID_UUID') + expect(made.err()?.message, text).not.toContain(text) + // An object made without the constructor still passes `instanceof`, + // so `encrypt` checks the text again. + const forged: RcUuid = Object.create(RcUuid.prototype) + Object.defineProperty(forged, 'value', { value: text, enumerable: true }) + const pending = keyset.encrypt(forged) + // A synchronous throw would fail the line above. This line fails if + // `encrypt` returns a settled `Result` instead of a promise. `await` + // passes a value that is not a promise through unchanged, so the + // assertions below would still pass. + expect(pending, text).toBeInstanceOf(Promise) + const result = await pending + expect(result.isErr(), text).toBe(true) + expect(result.err()?.code, text).toBe('ERR_INVALID_UUID') + expect(result.err()?.message, text).not.toContain(text) + } }) it('a bigint outside 128 bits, with the code ERR_INTEGER_RANGE', async () => { diff --git a/languages/typescript/packages/recipher-js/crate/Cargo.toml b/languages/typescript/packages/recipher-js/crate/Cargo.toml index 2f1ffa8ef..3dda0d3c3 100644 --- a/languages/typescript/packages/recipher-js/crate/Cargo.toml +++ b/languages/typescript/packages/recipher-js/crate/Cargo.toml @@ -57,7 +57,9 @@ serde_json = "1" serde = { version = "1", features = ["derive"] } [dev-dependencies] -stack-encrypt = { path = "../../../../../packages/stack-encrypt", default-features = false, features = ["dynamic", "http", "test-support"] } +# `uuid` gives the tests the engine's UUID type. The tests encrypt and decrypt +# a UUID through the engine's typed API. +stack-encrypt = { path = "../../../../../packages/stack-encrypt", default-features = false, features = ["dynamic", "http", "test-support", "uuid"] } tokio = { version = "1", features = ["rt", "macros"] } # The values the engine-interop tests encrypt through the engine's typed API, # and the types the counting key source names. The versions the engine diff --git a/languages/typescript/packages/recipher-js/crate/src/ciphertext.rs b/languages/typescript/packages/recipher-js/crate/src/ciphertext.rs index 24694a0b8..76a79a55c 100644 --- a/languages/typescript/packages/recipher-js/crate/src/ciphertext.rs +++ b/languages/typescript/packages/recipher-js/crate/src/ciphertext.rs @@ -275,6 +275,7 @@ fn readable(kind: ValueKind) -> bool { | ValueKind::Date | ValueKind::Timestamp | ValueKind::Bytes + | ValueKind::Uuid | ValueKind::Json ) } @@ -388,12 +389,13 @@ mod tests { "date", "timestamp", "bytes", + "uuid", "json", ] { assert!(readable(name.parse::().unwrap()), "{name}"); } // The engine names these kinds, and no ciphertext decrypts as one. - for kind in [ValueKind::Uuid, ValueKind::Array, ValueKind::Object] { + for kind in [ValueKind::Array, ValueKind::Object] { assert!(!readable(kind), "{kind}"); } } @@ -431,6 +433,7 @@ mod tests { ValueKind::Decimal, ValueKind::Date, ValueKind::Timestamp, + ValueKind::Uuid, ValueKind::String, ValueKind::Bytes, ValueKind::Json, @@ -496,6 +499,7 @@ mod tests { "decimal", "date", "timestamp", + "uuid", ] ); } 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 3c054472f..2aaf5a116 100644 --- a/languages/typescript/packages/recipher-js/crate/src/engine_tests.rs +++ b/languages/typescript/packages/recipher-js/crate/src/engine_tests.rs @@ -13,7 +13,7 @@ use stack_encrypt::kms::{ IdentifiedBy, IndexKey, IndexKeySource, KeySourceKind, OwnIdentity, RetrieveKeyPayload, UnverifiedContext, }; -use stack_encrypt::value::{Decimal, Timestamp}; +use stack_encrypt::value::{Decimal, Timestamp, Uuid as EngineUuid}; use stack_encrypt::{Encrypt, StackCipher}; use uuid::Uuid; @@ -90,6 +90,9 @@ async fn the_sdk_opens_what_the_engine_sealed_of_every_type() { let decimal = Decimal::new(rust_decimal::Decimal::new(150, 2)); let timestamp_frame = OwnedFrame::of(×tamp).unwrap(); let decimal_frame = OwnedFrame::of(&decimal).unwrap(); + let id = EngineUuid::new(Uuid::from_u128(0x123e_4567_e89b_12d3_a456_4266_1417_4000)); + let uuid_frame = OwnedFrame::of(&id).unwrap(); + assert_eq!(uuid_frame.frame().kind(), Some(ValueKind::Uuid)); let cases: Vec<(stack_encrypt::Ciphertext, OwnedFrame)> = vec![ ( keyset.encrypt("text".to_owned()).await.unwrap(), @@ -109,6 +112,7 @@ async fn the_sdk_opens_what_the_engine_sealed_of_every_type() { ), (keyset.encrypt(timestamp).await.unwrap(), timestamp_frame), (keyset.encrypt(decimal).await.unwrap(), decimal_frame), + (keyset.encrypt(id).await.unwrap(), uuid_frame), ]; for (sealed, expected) in cases { let stored = stack_encrypt::Ciphertext::from_bytes(&sealed.to_bytes()).unwrap(); @@ -116,6 +120,23 @@ async fn the_sdk_opens_what_the_engine_sealed_of_every_type() { } } +/// The engine decrypts a UUID that the SDK encrypted. The ciphertext is +/// read back from its stored bytes. The engine decrypts it as the engine's +/// own UUID type. The other direction is a case of the test above. +#[tokio::test] +async fn the_engine_opens_a_uuid_the_sdk_sealed_from_its_stored_bytes() { + let id = Uuid::from_u128(0x123e_4567_e89b_12d3_a456_4266_1417_4000); + let sealed = sdk_seal(vec![one(EngineUuid::new(id))]).await.remove(0); + let stored = stack_encrypt::Ciphertext::from_bytes(&sealed.to_bytes()).unwrap(); + let opened: EngineUuid = engine() + .await + .default_keyset() + .decrypt(stored) + .await + .unwrap(); + assert_eq!(opened.to_uuid(), id); +} + #[tokio::test] async fn a_json_document_the_engine_sealed_opens_as_that_document() { let document = JsonPlaintext::from(serde_json::json!({"id": u64::MAX, "n": 5})); @@ -365,7 +386,12 @@ async fn a_null_with_no_declared_kind_is_refused_before_any_request() { #[tokio::test] async fn a_null_declared_nullable_of_a_fixed_width_kind_is_refused_until_2023() { let cipher = counting().await; - for kind in [ValueKind::Int64, ValueKind::Bool, ValueKind::Timestamp] { + for kind in [ + ValueKind::Int64, + ValueKind::Bool, + ValueKind::Timestamp, + ValueKind::Uuid, + ] { let declared = Declared { kind, nullable: true, diff --git a/languages/typescript/packages/recipher-js/crate/src/error.rs b/languages/typescript/packages/recipher-js/crate/src/error.rs index 79e8aa98a..8b0a468c2 100644 --- a/languages/typescript/packages/recipher-js/crate/src/error.rs +++ b/languages/typescript/packages/recipher-js/crate/src/error.rs @@ -43,11 +43,6 @@ pub(crate) enum Error { help("Check that the value is set: a misspelt property name gives `undefined`. Store a value that is not there as a database `NULL`.") )] Undefined, - /// An `RcUuid`. The engine accepts a UUID, but this version of the SDK - /// has no kind and no TypeScript type for one, so it refuses an `RcUuid`. - #[error("this version of the SDK does not encrypt a UUID yet")] - #[diagnostic(code(recipher_js::uuid), help("Encrypt the UUID as a string instead."))] - Uuid, /// A value outside the engine's value model, or a value that Node-API /// failed to read. #[error("the value cannot be encrypted: it is not one the engine reads")] @@ -718,7 +713,6 @@ mod tests { let name = || "x".to_owned(); let all = vec![ Error::Undefined, - Error::Uuid, Error::Value, Error::Threw, Error::NotAScalar, @@ -759,7 +753,6 @@ mod tests { for error in &all { match error { Error::Undefined - | Error::Uuid | Error::Value | Error::Threw | Error::NotAScalar @@ -803,7 +796,6 @@ mod tests { fn help_of(error: &Error) -> Option<&'static str> { match error { Error::Undefined => Some("Check that the value is set: a misspelt property name gives `undefined`. Store a value that is not there as a database `NULL`."), - Error::Uuid => Some("Encrypt the UUID as a string instead."), Error::NotAScalar => { Some("To encrypt the inner array as a JSON document, wrap it in `json(..)`.") } diff --git a/languages/typescript/packages/recipher-js/crate/src/js.rs b/languages/typescript/packages/recipher-js/crate/src/js.rs index 49b4fa8c9..510c5187f 100644 --- a/languages/typescript/packages/recipher-js/crate/src/js.rs +++ b/languages/typescript/packages/recipher-js/crate/src/js.rs @@ -47,7 +47,6 @@ use crate::outcome::settle; /// Returns one of these errors: /// /// - `recipher_js::undefined` for `undefined`; -/// - `recipher_js::uuid` for an `RcUuid`; /// - `recipher_js::value` when the bridge's bytes are not one well-formed /// frame the engine reads (`FrameError`); /// - `recipher_js::threw` when reading the value threw; @@ -56,9 +55,6 @@ pub fn read(env: &Env, value: Unknown<'_>) -> Result(env: &'e Env, name: &str, text: Unknown<'e>) -> napi::Result settle(env, made, |_, instance| Ok(instance)) } -/// Returns whether `value` is an `RcUuid`. -fn is_uuid(env: &Env, value: &Unknown<'_>) -> bool { - Wrappers::get(env) - .and_then(|wrappers| wrappers.classify(value)) - .is_ok_and(|wrapper| wrapper == Some(Wrapper::Uuid)) -} - /// Returns the property `name` of `value`. Returns `None` when `value` is not /// an object, or when the property is `undefined`. /// 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 af2023069..6657d72b6 100644 --- a/languages/typescript/packages/recipher-js/crate/src/record_tests.rs +++ b/languages/typescript/packages/recipher-js/crate/src/record_tests.rs @@ -248,6 +248,88 @@ fn the_engine_refuses_a_declaration_naming_the_record_and_the_field() { assert_eq!(unknown.code, "recipher_js::kind"); } +fn devices() -> Arc { + plan(json!({ + "type": "record", + "name": "devices", + "fields": { + "id": { "type": "sealed", "kind": { "name": "uuid" }, "index": ["equality"] }, + }, + })) + .unwrap() +} + +fn device_row(id: Uuid) -> OwnedFrame { + let id = OwnedFrame::of(stack_encrypt::value::Uuid::new(id)).unwrap(); + let frame = OwnedFrame::of(&Map(vec![("id", Entry::Value(&id))])).unwrap(); + conform_row(&devices(), &frame).unwrap() +} + +/// The `equality` term of the field `name` of a stored row. +fn equality_of(stored: &OwnedFrame, name: &str) -> Vec { + let field = field_value(stored, name).unwrap(); + let (_, term) = entries(&field) + .unwrap() + .into_iter() + .find(|(key, _)| key == "equality") + .unwrap(); + term.frame().as_bytes().to_vec() +} + +#[tokio::test] +async fn a_uuid_field_is_stored_found_by_equality_and_read_back() { + let cipher = engine().await; + let keyset = cipher.default_keyset(); + let id = Uuid::from_u128(0x123e_4567_e89b_12d3_a456_4266_1417_4000); + let other = Uuid::from_u128(0x123e_4567_e89b_12d3_a456_4266_1417_4001); + let stored = seal_rows(&keyset, devices(), vec![device_row(id)]) + .await + .unwrap() + .remove(0); + assert_eq!( + keys(&field_value(&stored, "id").unwrap()), + ["ciphertext", "equality"] + ); + + // A query for the same UUID derives the stored term. A query for + // another UUID does not. + let field = devices().field("id").unwrap(); + let query = |id: Uuid| { + let value = OwnedFrame::of(stack_encrypt::value::Uuid::new(id)).unwrap(); + conform_row(&field, &one_field_row("id", &value).unwrap()).unwrap() + }; + let found = seal_rows(&keyset, Arc::clone(&field), vec![query(id), query(other)]) + .await + .unwrap(); + assert_eq!(equality_of(&found[0], "id"), equality_of(&stored, "id")); + assert_ne!(equality_of(&found[1], "id"), equality_of(&stored, "id")); + + let opened = open_rows(&cipher, devices(), vec![stored]) + .await + .unwrap() + .remove(0); + let expected = OwnedFrame::of(stack_encrypt::value::Uuid::new(id)).unwrap(); + assert_eq!( + field_value(&opened, "id").unwrap().frame(), + expected.frame() + ); +} + +#[test] +fn an_order_index_on_a_uuid_field_is_refused_when_the_plan_is_built() { + for index in ["ore", "ope"] { + let refused = plan(json!({ + "type": "record", + "name": "t", + "fields": { "id": { "type": "sealed", "kind": { "name": "uuid" }, "index": [index] } }, + })) + .unwrap_err(); + assert_eq!(refused.code, "stack_encrypt::dynamic_plan", "{index}"); + assert_eq!(refused.reason(), Some("index_not_admitted"), "{index}"); + assert_eq!(refused.field.as_deref(), Some("id"), "{index}"); + } +} + #[test] fn a_field_of_a_nullable_kind_is_refused_naming_the_field() { for nullable in [json!(true), json!(false)] { diff --git a/languages/typescript/packages/recipher-js/src/kinds.ts b/languages/typescript/packages/recipher-js/src/kinds.ts index 75bbbfb63..e6f056394 100644 --- a/languages/typescript/packages/recipher-js/src/kinds.ts +++ b/languages/typescript/packages/recipher-js/src/kinds.ts @@ -18,6 +18,7 @@ import type { RcDate, RcDecimal, RcTimestamp, + RcUuid, } from './value-types' /** A kind: the type of a value, by the engine's name for it. */ @@ -124,6 +125,7 @@ export type FixedWidthName = | 'decimal' | 'date' | 'timestamp' + | 'uuid' /** * The values that `encrypt` takes with the declared kind `K`. A value of an @@ -203,5 +205,6 @@ export const kinds = Object.freeze({ date: kind<'date', RcDate>('date'), timestamp: kind<'timestamp', Date | RcTimestamp>('timestamp'), bytes: kind<'bytes', Uint8Array>('bytes'), + uuid: kind<'uuid', RcUuid>('uuid'), json: kind<'json', OpenedJson>('json'), }) diff --git a/languages/typescript/packages/recipher-js/src/value-types.ts b/languages/typescript/packages/recipher-js/src/value-types.ts index 2dfd711cc..453a16f09 100644 --- a/languages/typescript/packages/recipher-js/src/value-types.ts +++ b/languages/typescript/packages/recipher-js/src/value-types.ts @@ -34,12 +34,22 @@ export interface RcDecimal { } /** - * A universally unique identifier (UUID). - * This version of the SDK does not encrypt a UUID yet. Encrypting an `RcUuid` - * is an `Err` with the code `recipher_js::uuid`. `RcUuid` is not a `Scalar`. + * A universally unique identifier (UUID), such as + * `RcUuid.from('123e4567-e89b-12d3-a456-426614174000')`. + * + * The text must be hyphenated hex, in upper or lower case. `RcUuid.from` + * refuses other text with an `Err` with the code `ERR_INVALID_UUID`. + * Examples of other text are: + * + * - text in braces; + * - text of the wrong length; + * - text with a digit that is not hex. + * + * A decrypted `RcUuid` contains lowercase hyphenated hex, whatever case it + * was built with. */ export interface RcUuid { - /** The UUID as hyphenated hex. */ + /** The UUID as hyphenated hex: as given, or lowercase when decrypted. */ readonly value: string toJSON(): string readonly [wrapper]: 'RcUuid' @@ -64,6 +74,7 @@ export type Scalar = | RcTimestamp | RcDate | RcDecimal + | RcUuid /** * A JSON value. @@ -133,9 +144,11 @@ export type Opened = V extends string ? RcDate : V extends RcDecimal ? RcDecimal - : V extends JsonMarker - ? OpenedJson - : never + : V extends RcUuid + ? RcUuid + : V extends JsonMarker + ? OpenedJson + : never /** * Any type that a stored ciphertext read with no kind can decrypt to: any diff --git a/languages/typescript/packages/recipher-js/src/values.ts b/languages/typescript/packages/recipher-js/src/values.ts index 37f83d94d..5ee1e2a30 100644 --- a/languages/typescript/packages/recipher-js/src/values.ts +++ b/languages/typescript/packages/recipher-js/src/values.ts @@ -16,6 +16,7 @@ * | `RcTimestamp` | a timestamp, in nanoseconds | `Date` when it is whole milliseconds, else `RcTimestamp` | * | `RcDate` | a calendar date | `RcDate` | * | `RcDecimal` | a decimal, with its scale | `RcDecimal` | + * | `RcUuid` | a UUID | `RcUuid` | * | `null` | refused: see below | `null`, for a stored null | * | `json(value)` | a JSON document, as its text | the document | * @@ -153,9 +154,19 @@ export const RcDecimal: WrapperClass = wrapperClass('RcDecimal') export type RcDecimal = Types.RcDecimal /** - * A universally unique identifier (UUID). This version of the SDK does not - * encrypt a UUID yet. Encrypting an `RcUuid` is an `Err` with the code - * `recipher_js::uuid`. `RcUuid` is not a `Scalar`. + * A universally unique identifier (UUID), such as + * `RcUuid.from('123e4567-e89b-12d3-a456-426614174000')`. + * + * The text must be hyphenated hex, in upper or lower case. `RcUuid.from` + * refuses other text with an `Err` with the code `ERR_INVALID_UUID`. + * Examples of other text are: + * + * - text in braces; + * - text of the wrong length; + * - text with a digit that is not hex. + * + * A decrypted `RcUuid` contains lowercase hyphenated hex, whatever case it + * was built with. */ export const RcUuid: WrapperClass = wrapperClass('RcUuid') export type RcUuid = Types.RcUuid diff --git a/languages/typescript/packages/recipher-js/type-tests/records.ts b/languages/typescript/packages/recipher-js/type-tests/records.ts index 601572a5a..264913c51 100644 --- a/languages/typescript/packages/recipher-js/type-tests/records.ts +++ b/languages/typescript/packages/recipher-js/type-tests/records.ts @@ -7,6 +7,7 @@ import type { RcDate, RcDecimal, RcTimestamp, + RcUuid, RecipherError, Result, Stored, @@ -75,6 +76,7 @@ const all = record('all', { at: encrypt(kinds.timestamp), blob: encrypt(kinds.bytes), small: encrypt(kinds.uint8), + id: encrypt(kinds.uuid, { index: ['equality'] }), }) check< Exact< @@ -87,6 +89,7 @@ check< at: Date | RcTimestamp blob: Uint8Array small: bigint + id: RcUuid } > >() diff --git a/languages/typescript/packages/recipher-js/type-tests/values.ts b/languages/typescript/packages/recipher-js/type-tests/values.ts index 04d4f672b..2fd15f6be 100644 --- a/languages/typescript/packages/recipher-js/type-tests/values.ts +++ b/languages/typescript/packages/recipher-js/type-tests/values.ts @@ -56,6 +56,9 @@ check, RecipherError>>>() declare const price: RcDecimal const priced = await keyset.encrypt(price) check, RecipherError>>>() +declare const id: RcUuid +const identified = await keyset.encrypt(id) +check, RecipherError>>>() const document = await keyset.encrypt(json({ a: [1, 2n, null] })) check, RecipherError>>>() @@ -86,10 +89,6 @@ expectType(plainObject) // What `json(..)` returns is both. expectType(json({ a: 1 })) expectType(json({ a: 1 })) -// This version of the SDK does not encrypt a UUID yet. -declare const uuid: RcUuid -// @ts-expect-error: a UUID is not a value. -void keyset.encrypt(uuid) // @ts-expect-error: undefined is not a value. void keyset.encrypt(undefined) // With no kind, a null is refused. So is an array that contains one. @@ -106,6 +105,8 @@ void json({ d: new Date() }) // The wrapper types are distinct. // @ts-expect-error: an RcDate is not an RcDecimal. expectType(day) +// @ts-expect-error: an RcUuid is not an RcDate. +expectType(id) // A ciphertext read from stored bytes has the type of the kind named. A // kind from `kinds` is not nullable, as a Rust type that is not an `Option` @@ -114,6 +115,12 @@ expectType(day) declare const stored: Uint8Array const typed = Ciphertext.fromBytes(stored, kinds.int64) check, RecipherError>>>() +const typedUuid = Ciphertext.fromBytes(stored, kinds.uuid) +check, RecipherError>>>() +const maybeUuid = Ciphertext.fromBytes(stored, nullable(kinds.uuid)) +check< + Exact, RecipherError>> +>() const typedText = Ciphertext.fromBytes(stored, kinds.string) check, RecipherError>>>() const typedJson = Ciphertext.fromBytes(stored, kinds.json) @@ -166,6 +173,8 @@ check< // time. const absent = await keyset.encrypt(null, { kind: nullable(kinds.int64) }) check, RecipherError>>>() +const absentId = await keyset.encrypt(null, { kind: nullable(kinds.uuid) }) +check, RecipherError>>>() for (const kind of [ nullable(kinds.boolean), nullable(kinds.uint8), @@ -173,6 +182,7 @@ for (const kind of [ nullable(kinds.decimal), nullable(kinds.date), nullable(kinds.timestamp), + nullable(kinds.uuid), ]) { void keyset.encrypt(null, { kind }) } @@ -199,6 +209,8 @@ void keyset.encrypt(null, { kind: nullable(kinds.string) }) void keyset.encrypt(null, { kind: nullable(kinds.bytes) }) // @ts-expect-error: a null of a variable-width kind is not a value. void keyset.encrypt(null, { kind: nullable(kinds.json) }) +// @ts-expect-error: a plain kind takes no null. +void keyset.encrypt(null, { kind: kinds.uuid }) // @ts-expect-error: a null of a variable-width kind is not a value. void keyset.encrypt(null, { kind: kinds.string }) // A value of a variable-width nullable kind encrypts as the plain kind. diff --git a/packages/stack-encrypt/src/value.rs b/packages/stack-encrypt/src/value.rs index 92ed1a385..ecba56c10 100644 --- a/packages/stack-encrypt/src/value.rs +++ b/packages/stack-encrypt/src/value.rs @@ -116,7 +116,7 @@ pub use vitaminc_aead::Decimal; /// cannot be wiped. Hold a UUID you encrypt as this type. /// /// The dynamic path a language binding uses (`stack_encrypt::dynamic`) -/// does not take a UUID yet: it refuses one as a value outside its value -/// model. +/// takes a UUID as `ValueKind::Uuid`, and encrypts and indexes it. It does +/// not need this type or the `uuid` feature. #[cfg(feature = "uuid")] pub use vitaminc_aead::Uuid;