hayson-engine 0.25.0

Storage engine for hayson document databases — the embeddable core behind hayson-server, hayson-cli and hayson-browser
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
use std::collections::HashMap;

use aes_gcm::aead::{Aead, KeyInit, Payload};
use aes_gcm::{Aes256Gcm, Key, Nonce};
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use base64::Engine;
use rand::Rng;
use serde_json::Value;

use crate::errors::HaysonCipherError;
use crate::schema::{HaysonRecord, TableSchema};

const ENVELOPE_PREFIX: &str = "cypher";
const ENVELOPE_VERSION: &str = "v1";
const IV_BYTES: usize = 12;
const TAG_BYTES: usize = 16;
const KEY_BYTES: usize = 32;
/// The AAD field separator — TS's `String.fromCharCode(31)` (unit separator), not a visually
/// similar character. Ciphertexts must interop byte-for-byte with the TS engine, so this has to
/// match exactly.
const AAD_SEPARATOR: u8 = 0x1f;

/// What a read does when the key a stored value was written with is not on hand.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum MissingKeyPolicy {
    #[default]
    Throw,
    Omit,
    Raw,
}

/// Options for `Database::open` — key material and how reads behave when a value was written with
/// a key that is not among them. Mirrors the TS `CipherOptions`.
#[derive(Debug, Clone, Default)]
pub struct CipherOptions {
    /// Every key that may be needed to read, by id. Each must be 32 bytes for AES-256-GCM.
    pub keys: HashMap<String, Vec<u8>>,
    /// Which of them new values are written with. Defaults to the only key, when there is one.
    pub key_id: Option<String>,
    pub on_missing_key: Option<MissingKeyPolicy>,
}

fn is_key_id(id: &str) -> bool {
    !id.is_empty()
        && id
            .bytes()
            .all(|b| b.is_ascii_alphanumeric() || b == b'.' || b == b'_' || b == b'-')
}

pub fn is_envelope(value: &Value) -> bool {
    matches!(value, Value::String(s) if s.starts_with(&format!("${ENVELOPE_PREFIX}$")))
}

/// The key id of a value shaped like a `v1` envelope this build could open — every part present,
/// the key id legal, the IV exactly `IV_BYTES` long and a body long enough to hold a tag.
///
/// Says nothing about the value being a genuine ciphertext; only [`FieldCipher::decrypt`] can say
/// that, and only while holding the key. This is the cheap half of [`assert_carried_seals`] and is
/// never on its own a reason to leave a value unsealed.
fn envelope_shape(text: &str) -> Option<&str> {
    let parts: Vec<&str> = text.strip_prefix('$')?.split('$').collect();
    if parts.len() != 5 || parts[0] != ENVELOPE_PREFIX || parts[1] != ENVELOPE_VERSION || !is_key_id(parts[2]) {
        return None;
    }
    let iv = URL_SAFE_NO_PAD.decode(parts[3]).ok()?;
    let body = URL_SAFE_NO_PAD.decode(parts[4]).ok()?;
    if iv.len() != IV_BYTES || body.len() < TAG_BYTES {
        return None;
    }
    Some(parts[2])
}

/// The key id an envelope was sealed under — `None` for anything that is not an envelope of a
/// version this build reads. Read straight off the value rather than by decrypting it, which is
/// what lets a maintenance pass tell an already-current record from one still on a retired key
/// without holding either.
pub fn envelope_key_id(value: &Value) -> Option<&str> {
    let text = value.as_str()?;
    if !is_envelope(value) {
        return None;
    }
    // NOTE: the envelope opens with "$", so drop it before splitting or part 0 comes back empty.
    let parts: Vec<&str> = text.get(1..)?.split('$').collect();
    if parts.len() != 5 || parts[0] != ENVELOPE_PREFIX || parts[1] != ENVELOPE_VERSION {
        return None;
    }
    Some(parts[2])
}

/// The names of the fields a schema marks `cypher`, sorted.
pub fn cypher_fields_of(schema: &TableSchema) -> Vec<String> {
    let mut fields: Vec<String> = schema
        .fields
        .iter()
        .filter(|(_, spec)| spec.cypher)
        .map(|(name, _)| name.clone())
        .collect();
    fields.sort();
    fields
}

fn key_from_slice(material: &[u8]) -> Key<Aes256Gcm> {
    Key::<Aes256Gcm>::try_from(material).expect("key material is checked to be KEY_BYTES long")
}

fn aad_of(table: &str, key: &str, field: &str) -> Vec<u8> {
    let mut aad = Vec::with_capacity(table.len() + key.len() + field.len() + 2);
    aad.extend_from_slice(table.as_bytes());
    aad.push(AAD_SEPARATOR);
    aad.extend_from_slice(key.as_bytes());
    aad.push(AAD_SEPARATOR);
    aad.extend_from_slice(field.as_bytes());
    aad
}

/// Encrypts and decrypts the fields a schema marks `cypher`, so their values never reach the disk
/// in the clear.
///
/// The additional authenticated data binds each value to its table, its record and its field name,
/// which is what stops a stored value from being moved somewhere it did not belong. Nothing that
/// compaction rewrites takes part in it, so compacting a log needs no key at all.
#[derive(Debug, Clone)]
pub struct FieldCipher {
    keys: HashMap<String, Vec<u8>>,
    write_key_id: String,
    on_missing_key: MissingKeyPolicy,
}

impl FieldCipher {
    pub fn new(options: CipherOptions) -> Result<Self, HaysonCipherError> {
        let mut keys = HashMap::with_capacity(options.keys.len());
        for (id, material) in options.keys {
            if !is_key_id(&id) {
                return Err(HaysonCipherError::new(
                    "",
                    "",
                    format!("key id \"{id}\" may only hold letters, digits, \".\", \"_\" and \"-\""),
                ));
            }
            if material.len() != KEY_BYTES {
                return Err(HaysonCipherError::new(
                    "",
                    "",
                    format!("key \"{id}\" must be {KEY_BYTES} bytes, not {}", material.len()),
                ));
            }
            keys.insert(id, material);
        }
        if keys.is_empty() {
            return Err(HaysonCipherError::new("", "", "needs at least one key"));
        }
        if let Some(key_id) = &options.key_id {
            if !keys.contains_key(key_id) {
                return Err(HaysonCipherError::new(
                    "",
                    "",
                    format!("keyId \"{key_id}\" is not among the keys given"),
                ));
            }
        }
        if options.key_id.is_none() && keys.len() > 1 {
            return Err(HaysonCipherError::new(
                "",
                "",
                "several keys were given, so \"keyId\" has to say which one writes",
            ));
        }
        let write_key_id = match options.key_id {
            Some(id) => id,
            None => keys.keys().next().expect("checked non-empty above").clone(),
        };
        Ok(FieldCipher {
            keys,
            write_key_id,
            on_missing_key: options.on_missing_key.unwrap_or_default(),
        })
    }

    pub fn write_key_id(&self) -> &str {
        &self.write_key_id
    }

    /// What a read of a value sealed under a key this cipher does not hold does — the policy a
    /// maintenance pass has to honour as well, so that it never turns a missing key into lost data.
    pub fn on_missing_key(&self) -> MissingKeyPolicy {
        self.on_missing_key
    }

    pub fn knows(&self, key_id: &str) -> bool {
        self.keys.contains_key(key_id)
    }

    pub fn encrypt(&self, table: &str, key: &str, field: &str, value: &Value) -> String {
        let material = self
            .keys
            .get(&self.write_key_id)
            .expect("write_key_id is always among the keys");
        let cipher = Aes256Gcm::new(&key_from_slice(material));

        let mut iv = [0u8; IV_BYTES];
        rand::rng().fill_bytes(&mut iv);
        let nonce = Nonce::from(iv);

        let plaintext = serde_json::to_vec(value).expect("a validated field value always serializes to JSON");
        let aad = aad_of(table, key, field);
        let body = cipher
            .encrypt(
                &nonce,
                Payload {
                    msg: &plaintext,
                    aad: &aad,
                },
            )
            .expect("AES-256-GCM encryption with a valid 32-byte key must not fail");

        format!(
            "${ENVELOPE_PREFIX}${ENVELOPE_VERSION}${}${}${}",
            self.write_key_id,
            URL_SAFE_NO_PAD.encode(iv),
            URL_SAFE_NO_PAD.encode(body),
        )
    }

    /// `Ok(None)` only when the key is missing and the policy is `omit`.
    pub fn decrypt(
        &self,
        table: &str,
        key: &str,
        field: &str,
        envelope: &str,
    ) -> Result<Option<Value>, HaysonCipherError> {
        // NOTE: the envelope opens with "$", so drop it before splitting or part 0 comes back empty.
        let parts: Vec<&str> = envelope.get(1..).unwrap_or("").split('$').collect();
        if parts.len() != 5 || parts[0] != ENVELOPE_PREFIX {
            return Err(HaysonCipherError::new(
                table,
                field,
                "holds a value that is not a cypher envelope",
            ));
        }
        let (version, key_id, iv_raw, body_raw) = (parts[1], parts[2], parts[3], parts[4]);
        if version != ENVELOPE_VERSION {
            return Err(HaysonCipherError::new(
                table,
                field,
                format!("was written in envelope \"{version}\", which this build cannot read"),
            ));
        }

        let Some(material) = self.keys.get(key_id) else {
            return match self.on_missing_key {
                MissingKeyPolicy::Omit => Ok(None),
                MissingKeyPolicy::Raw => Ok(Some(Value::String(envelope.to_string()))),
                MissingKeyPolicy::Throw => Err(HaysonCipherError::new(
                    table,
                    field,
                    format!("was written with key \"{key_id}\", which was not given"),
                )
                .with_key_id(key_id)),
            };
        };

        let iv = URL_SAFE_NO_PAD.decode(iv_raw).map_err(|_| {
            HaysonCipherError::new(table, field, "holds a truncated cypher envelope").with_key_id(key_id)
        })?;
        let body = URL_SAFE_NO_PAD.decode(body_raw).map_err(|_| {
            HaysonCipherError::new(table, field, "holds a truncated cypher envelope").with_key_id(key_id)
        })?;
        if iv.len() != IV_BYTES || body.len() < TAG_BYTES {
            return Err(HaysonCipherError::new(table, field, "holds a truncated cypher envelope").with_key_id(key_id));
        }

        let cipher = Aes256Gcm::new(&key_from_slice(material));
        let iv_arr: [u8; IV_BYTES] = iv.as_slice().try_into().expect("checked length above");
        let nonce = Nonce::from(iv_arr);
        let aad = aad_of(table, key, field);
        let plain = cipher.decrypt(&nonce, Payload { msg: &body, aad: &aad }).map_err(|_| {
            HaysonCipherError::new(
                table,
                field,
                "failed its authentication tag — the value, the record it sits on or the field name changed under it",
            )
            .with_key_id(key_id)
        })?;

        let value = serde_json::from_slice(&plain).map_err(|_| {
            HaysonCipherError::new(
                table,
                field,
                "holds a cypher envelope whose plaintext is not valid JSON",
            )
            .with_key_id(key_id)
        })?;
        Ok(Some(value))
    }
}

/// Refuses everything `carried` names that the engine cannot recognise as an envelope of its own —
/// the check that has to pass before [`seal_record`] may store a value as it stands.
///
/// Two steps, both needed. The shape has to be a `v1` envelope this build could open, which rules
/// out a plaintext that merely starts with `$cypher$`. On top of that, when the keyring holds the
/// key the envelope names, the value also has to authenticate against this very table, record and
/// field — a caller holding the key cannot smuggle a plaintext past this by calling it sealed, and
/// an envelope copied into the wrong record or field is refused now rather than found unreadable
/// later.
///
/// A key that is not on hand leaves nothing to verify against, so the claim is taken on the
/// caller's word: that is the restore-without-the-key case the mechanism exists for. It is why the
/// entry point carrying seals must never be wired to untrusted input.
pub fn assert_carried_seals(
    schema: &TableSchema,
    key: &str,
    record: &HaysonRecord,
    cipher: Option<&FieldCipher>,
    carried: &[String],
) -> Result<(), HaysonCipherError> {
    for field in carried {
        let Some(value) = record.get(field) else { continue };
        if value.is_null() {
            continue;
        }
        let shaped = value
            .as_str()
            .and_then(|envelope| Some((envelope, envelope_shape(envelope)?)));
        let Some((envelope, key_id)) = shaped else {
            return Err(HaysonCipherError::new(
                &schema.table,
                field.clone(),
                "was handed over as already sealed, but it is not a cypher envelope",
            ));
        };
        let Some(cipher) = cipher.filter(|cipher| cipher.knows(key_id)) else {
            continue;
        };
        cipher.decrypt(&schema.table, key, field, envelope).map_err(|_| {
            HaysonCipherError::new(
                &schema.table,
                field.clone(),
                "was handed over as already sealed, but it does not open for this record and field",
            )
            .with_key_id(key_id)
        })?;
    }
    Ok(())
}

/// Replaces the plaintext of every `cypher` field with its envelope, leaving `null` as it is.
///
/// A value is sealed whatever it looks like: a plaintext shaped exactly like an envelope is
/// ciphertext on disk like any other, because a declared `cypher` field is a promise about the log,
/// not about the caller's good intentions. The one exception is a field `carried` names, which
/// [`assert_carried_seals`] has already vouched for and which is stored as it stands — the explicit
/// replacement for the shape sniffing this used to do.
pub fn seal_record(
    schema: &TableSchema,
    key: &str,
    record: &HaysonRecord,
    cipher: Option<&FieldCipher>,
    fields: &[String],
    carried: &[String],
) -> Result<HaysonRecord, HaysonCipherError> {
    if fields.is_empty() {
        return Ok(record.clone());
    }
    assert_carried_seals(schema, key, record, cipher, carried)?;
    let mut sealed = record.clone();
    for field in fields {
        let Some(value) = sealed.get(field) else { continue };
        if value.is_null() || carried.iter().any(|carried| carried == field) {
            continue;
        }
        let Some(cipher) = cipher else {
            return Err(HaysonCipherError::new(
                &schema.table,
                field.clone(),
                "cannot be written without a key",
            ));
        };
        let envelope = cipher.encrypt(&schema.table, key, field, value);
        sealed.insert(field.clone(), Value::String(envelope));
    }
    Ok(sealed)
}

/// Replaces the envelope of every `cypher` field with its plaintext.
pub fn open_record(
    schema: &TableSchema,
    key: &str,
    record: &HaysonRecord,
    cipher: Option<&FieldCipher>,
    fields: &[String],
) -> Result<HaysonRecord, HaysonCipherError> {
    if fields.is_empty() {
        return Ok(record.clone());
    }
    let mut opened = record.clone();
    for field in fields {
        let Some(value) = opened.get(field) else { continue };
        if value.is_null() || !is_envelope(value) {
            continue;
        }
        let Some(cipher) = cipher else {
            return Err(HaysonCipherError::new(
                &schema.table,
                field.clone(),
                "cannot be read without a key",
            ));
        };
        let envelope = value.as_str().expect("is_envelope guarantees a string").to_string();
        match cipher.decrypt(&schema.table, key, field, &envelope)? {
            Some(plain) => {
                opened.insert(field.clone(), plain);
            }
            None => {
                opened.remove(field);
            }
        }
    }
    Ok(opened)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::schema::parse_schema;
    use serde_json::json;

    fn key(byte: u8) -> Vec<u8> {
        vec![byte; KEY_BYTES]
    }

    fn secrets_schema() -> TableSchema {
        parse_schema(&json!({
            "schemaVersion": 1,
            "table": "secrets",
            "revision": 1,
            "primaryKey": "id",
            "fields": {
                "id": { "type": "string" },
                "label": { "type": "string", "index": "exact" },
                "token": { "type": "string", "cypher": true },
                "pin": { "type": "int", "cypher": true },
            },
        }))
        .unwrap()
    }

    fn cipher_with(keys: &[(&str, u8)], key_id: Option<&str>) -> FieldCipher {
        FieldCipher::new(CipherOptions {
            keys: keys.iter().map(|(id, byte)| (id.to_string(), key(*byte))).collect(),
            key_id: key_id.map(str::to_string),
            on_missing_key: None,
        })
        .unwrap()
    }

    #[test]
    fn round_trips_a_value_with_the_correct_key() {
        let cipher = cipher_with(&[("k1", 1)], None);
        let envelope = cipher.encrypt("secrets", "s1", "token", &json!("hunter2"));
        assert!(envelope.starts_with("$cypher$v1$k1$"));
        let plain = cipher.decrypt("secrets", "s1", "token", &envelope).unwrap();
        assert_eq!(plain, Some(json!("hunter2")));
    }

    #[test]
    fn two_equal_values_get_two_different_envelopes() {
        let cipher = cipher_with(&[("k1", 1)], None);
        let a = cipher.encrypt("secrets", "s1", "token", &json!("same"));
        let b = cipher.encrypt("secrets", "s2", "token", &json!("same"));
        assert_ne!(a, b);
    }

    #[test]
    fn decryption_fails_with_the_wrong_key() {
        let writer = cipher_with(&[("k1", 1)], None);
        let envelope = writer.encrypt("secrets", "s1", "token", &json!("hunter2"));

        let reader = cipher_with(&[("k1", 9)], None);
        let error = reader.decrypt("secrets", "s1", "token", &envelope).unwrap_err();
        assert!(error.reason.contains("authentication tag"));
    }

    #[test]
    fn decryption_fails_when_the_ciphertext_is_tampered_with() {
        let cipher = cipher_with(&[("k1", 1)], None);
        let mut envelope = cipher.encrypt("secrets", "s1", "token", &json!("hunter2"));
        envelope.push('A');
        let error = cipher.decrypt("secrets", "s1", "token", &envelope).unwrap_err();
        assert!(error.reason.contains("authentication tag") || error.reason.contains("truncated"));
    }

    #[test]
    fn moving_a_value_to_another_field_fails_authentication() {
        let cipher = cipher_with(&[("k1", 1)], None);
        let envelope = cipher.encrypt("secrets", "s1", "token", &json!("hunter2"));
        let error = cipher.decrypt("secrets", "s1", "pin", &envelope).unwrap_err();
        assert!(error.reason.contains("authentication tag"));
    }

    #[test]
    fn moving_a_value_to_another_record_fails_authentication() {
        let cipher = cipher_with(&[("k1", 1)], None);
        let envelope = cipher.encrypt("secrets", "s1", "token", &json!("hunter2"));
        let error = cipher.decrypt("secrets", "s2", "token", &envelope).unwrap_err();
        assert!(error.reason.contains("authentication tag"));
    }

    #[test]
    fn moving_a_value_to_another_table_fails_authentication() {
        let cipher = cipher_with(&[("k1", 1)], None);
        let envelope = cipher.encrypt("secrets", "s1", "token", &json!("hunter2"));
        let error = cipher.decrypt("other", "s1", "token", &envelope).unwrap_err();
        assert!(error.reason.contains("authentication tag"));
    }

    #[test]
    fn missing_key_policy_throw_is_the_default() {
        let cipher = FieldCipher::new(CipherOptions {
            keys: HashMap::from([("k1".to_string(), key(1))]),
            key_id: None,
            on_missing_key: None,
        })
        .unwrap();
        let envelope = cipher.encrypt("secrets", "s1", "token", &json!("hunter2"));
        let other = cipher_with(&[("other", 2)], None);
        let error = other.decrypt("secrets", "s1", "token", &envelope).unwrap_err();
        assert!(error.reason.contains("was not given"));
        assert_eq!(error.key_id.as_deref(), Some("k1"));
    }

    #[test]
    fn missing_key_policy_omit_drops_the_field() {
        let cipher = cipher_with(&[("k1", 1)], None);
        let envelope = cipher.encrypt("secrets", "s1", "token", &json!("hunter2"));

        let reader = FieldCipher::new(CipherOptions {
            keys: HashMap::from([("other".to_string(), key(2))]),
            key_id: None,
            on_missing_key: Some(MissingKeyPolicy::Omit),
        })
        .unwrap();
        assert_eq!(reader.decrypt("secrets", "s1", "token", &envelope).unwrap(), None);
    }

    #[test]
    fn missing_key_policy_raw_returns_the_envelope_unchanged() {
        let cipher = cipher_with(&[("k1", 1)], None);
        let envelope = cipher.encrypt("secrets", "s1", "token", &json!("hunter2"));

        let reader = FieldCipher::new(CipherOptions {
            keys: HashMap::from([("other".to_string(), key(2))]),
            key_id: None,
            on_missing_key: Some(MissingKeyPolicy::Raw),
        })
        .unwrap();
        assert_eq!(
            reader.decrypt("secrets", "s1", "token", &envelope).unwrap(),
            Some(Value::String(envelope))
        );
    }

    #[test]
    fn rejects_a_key_that_is_not_32_bytes() {
        let error = FieldCipher::new(CipherOptions {
            keys: HashMap::from([("k".to_string(), vec![0u8; 16])]),
            key_id: None,
            on_missing_key: None,
        })
        .unwrap_err();
        assert!(error.reason.contains("must be 32 bytes"));
    }

    #[test]
    fn rejects_an_unknown_key_id() {
        let error = FieldCipher::new(CipherOptions {
            keys: HashMap::from([("a".to_string(), key(1)), ("b".to_string(), key(2))]),
            key_id: Some("c".to_string()),
            on_missing_key: None,
        })
        .unwrap_err();
        assert!(error.reason.contains("is not among the keys given"));
    }

    #[test]
    fn insists_on_a_key_id_when_several_keys_are_given() {
        let error = FieldCipher::new(CipherOptions {
            keys: HashMap::from([("a".to_string(), key(1)), ("b".to_string(), key(2))]),
            key_id: None,
            on_missing_key: None,
        })
        .unwrap_err();
        assert!(error.reason.contains("keyId"));
    }

    #[test]
    fn seal_record_leaves_a_null_value_alone() {
        let schema = secrets_schema();
        let cipher = cipher_with(&[("k1", 1)], None);
        let fields = cypher_fields_of(&schema);
        let record = HaysonRecord::from([("id".to_string(), json!("s1")), ("token".to_string(), Value::Null)]);
        let sealed = seal_record(&schema, "s1", &record, Some(&cipher), &fields, &[]).unwrap();
        assert_eq!(sealed.get("token"), Some(&Value::Null));
    }

    #[test]
    fn seal_record_seals_a_plaintext_that_only_looks_like_an_envelope() {
        let schema = secrets_schema();
        let cipher = cipher_with(&[("k1", 1)], None);
        let fields = cypher_fields_of(&schema);
        let masquerade = "$cypher$v1$k1$not$real";
        let record = HaysonRecord::from([
            ("id".to_string(), json!("s1")),
            ("token".to_string(), json!(masquerade)),
        ]);

        let sealed = seal_record(&schema, "s1", &record, Some(&cipher), &fields, &[]).unwrap();

        let stored = sealed.get("token").unwrap().as_str().unwrap();
        assert_ne!(stored, masquerade, "the value reached the log in the clear");
        let opened = open_record(&schema, "s1", &sealed, Some(&cipher), &fields).unwrap();
        assert_eq!(opened.get("token"), Some(&json!(masquerade)));
    }

    #[test]
    fn seal_record_seals_a_genuine_envelope_again_when_it_is_not_carried() {
        let schema = secrets_schema();
        let cipher = cipher_with(&[("k1", 1)], None);
        let fields = cypher_fields_of(&schema);
        let envelope = cipher.encrypt("secrets", "s1", "token", &json!("hunter2"));
        let record = HaysonRecord::from([
            ("id".to_string(), json!("s1")),
            ("token".to_string(), json!(envelope.clone())),
        ]);

        let sealed = seal_record(&schema, "s1", &record, Some(&cipher), &fields, &[]).unwrap();

        assert_ne!(sealed.get("token").unwrap().as_str().unwrap(), envelope);
    }

    #[test]
    fn seal_record_carries_a_verified_envelope_byte_for_byte() {
        let schema = secrets_schema();
        let cipher = cipher_with(&[("k1", 1)], None);
        let fields = cypher_fields_of(&schema);
        let envelope = cipher.encrypt("secrets", "s1", "token", &json!("hunter2"));
        let record = HaysonRecord::from([
            ("id".to_string(), json!("s1")),
            ("token".to_string(), json!(envelope.clone())),
        ]);

        let carried = vec!["token".to_string()];
        let sealed = seal_record(&schema, "s1", &record, Some(&cipher), &fields, &carried).unwrap();

        assert_eq!(sealed.get("token").unwrap().as_str().unwrap(), envelope);
        let opened = open_record(&schema, "s1", &sealed, Some(&cipher), &fields).unwrap();
        assert_eq!(opened.get("token"), Some(&json!("hunter2")));
    }

    #[test]
    fn a_carried_value_that_is_not_an_envelope_is_refused() {
        let schema = secrets_schema();
        let cipher = cipher_with(&[("k1", 1)], None);
        let fields = cypher_fields_of(&schema);
        let record = HaysonRecord::from([
            ("id".to_string(), json!("s1")),
            ("token".to_string(), json!("$cypher$v1$k1$not$real")),
        ]);

        let error = seal_record(&schema, "s1", &record, Some(&cipher), &fields, &["token".to_string()]).unwrap_err();

        assert!(error.reason.contains("is not a cypher envelope"), "{}", error.reason);
    }

    #[test]
    fn a_carried_envelope_sealed_for_another_record_is_refused() {
        let schema = secrets_schema();
        let cipher = cipher_with(&[("k1", 1)], None);
        let fields = cypher_fields_of(&schema);
        let stolen = cipher.encrypt("secrets", "s2", "token", &json!("yours"));
        let record = HaysonRecord::from([("id".to_string(), json!("s1")), ("token".to_string(), json!(stolen))]);

        let error = seal_record(&schema, "s1", &record, Some(&cipher), &fields, &["token".to_string()]).unwrap_err();

        assert!(
            error.reason.contains("does not open for this record and field"),
            "{}",
            error.reason
        );
        assert_eq!(error.key_id.as_deref(), Some("k1"));
    }

    #[test]
    fn a_carried_envelope_under_a_key_that_is_not_on_hand_is_taken_on_trust() {
        let schema = secrets_schema();
        let writer = cipher_with(&[("k1", 1)], None);
        let fields = cypher_fields_of(&schema);
        let envelope = writer.encrypt("secrets", "s1", "token", &json!("hunter2"));
        let record = HaysonRecord::from([
            ("id".to_string(), json!("s1")),
            ("token".to_string(), json!(envelope.clone())),
        ]);

        let stranger = cipher_with(&[("other", 2)], None);
        let sealed = seal_record(&schema, "s1", &record, Some(&stranger), &fields, &["token".to_string()]).unwrap();

        assert_eq!(sealed.get("token").unwrap().as_str().unwrap(), envelope);
    }

    #[test]
    fn seal_record_without_a_cipher_refuses_to_write_a_cypher_field() {
        let schema = secrets_schema();
        let fields = cypher_fields_of(&schema);
        let record = HaysonRecord::from([("id".to_string(), json!("s1")), ("token".to_string(), json!("secret"))]);
        let error = seal_record(&schema, "s1", &record, None, &fields, &[]).unwrap_err();
        assert!(error.reason.contains("cannot be written without a key"));
    }

    #[test]
    fn seal_record_without_a_cipher_still_refuses_a_carried_value_that_is_not_an_envelope() {
        let schema = secrets_schema();
        let fields = cypher_fields_of(&schema);
        let record = HaysonRecord::from([("id".to_string(), json!("s1")), ("token".to_string(), json!("secret"))]);
        let error = seal_record(&schema, "s1", &record, None, &fields, &["token".to_string()]).unwrap_err();
        assert!(error.reason.contains("is not a cypher envelope"), "{}", error.reason);
    }

    #[test]
    fn seal_then_open_round_trips_every_cypher_field() {
        let schema = secrets_schema();
        let cipher = cipher_with(&[("k1", 1)], None);
        let fields = cypher_fields_of(&schema);
        let record = HaysonRecord::from([
            ("id".to_string(), json!("s1")),
            ("token".to_string(), json!("hunter2")),
            ("pin".to_string(), json!(4321)),
        ]);
        let sealed = seal_record(&schema, "s1", &record, Some(&cipher), &fields, &[]).unwrap();
        assert!(is_envelope(sealed.get("token").unwrap()));
        assert!(is_envelope(sealed.get("pin").unwrap()));

        let opened = open_record(&schema, "s1", &sealed, Some(&cipher), &fields).unwrap();
        assert_eq!(opened.get("token"), Some(&json!("hunter2")));
        assert_eq!(opened.get("pin"), Some(&json!(4321)));
    }

    #[test]
    fn open_record_with_omit_policy_drops_the_field() {
        let schema = secrets_schema();
        let writer = cipher_with(&[("k1", 1)], None);
        let fields = cypher_fields_of(&schema);
        let record = HaysonRecord::from([("id".to_string(), json!("s1")), ("token".to_string(), json!("hunter2"))]);
        let sealed = seal_record(&schema, "s1", &record, Some(&writer), &fields, &[]).unwrap();

        let reader = FieldCipher::new(CipherOptions {
            keys: HashMap::from([("other".to_string(), key(2))]),
            key_id: None,
            on_missing_key: Some(MissingKeyPolicy::Omit),
        })
        .unwrap();
        let opened = open_record(&schema, "s1", &sealed, Some(&reader), &fields).unwrap();
        assert!(!opened.contains_key("token"));
    }
}