1use std::fmt;
4use std::io::{self, Read};
5use std::path::Path;
6
7use aws_lc_rs::aead::{AES_256_GCM, Aad, LessSafeKey, Nonce, UnboundKey};
8use aws_lc_rs::digest::{SHA256, digest};
9use aws_lc_rs::hkdf::{HKDF_SHA256, KeyType, Salt};
10use uuid::Uuid;
11use zeroize::Zeroizing;
12
13use crate::ids::{KeyId, TenantId, VersionId};
14
15mod column;
16mod locked;
17
18pub use column::{
19 ColumnContext, ColumnKeys, REGISTRY, SEALED_COLUMN_OVERHEAD, mac, open_column, seal_column,
20};
21use locked::LockedPage;
22
23const KEY_LEN: usize = 32;
25
26const FORMAT: u8 = 1;
29const NONCE_LEN: usize = 12;
30const TAG_LEN: usize = 16;
31
32const LABEL: &[u8] = b"vcon-server/v1";
34
35const CATALOG_LABEL: &[u8] = b"vcon-server/v1 catalog";
37
38pub struct Key {
43 page: LockedPage,
44}
45
46impl fmt::Debug for Key {
47 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
48 f.debug_struct("Key")
49 .field("id", &format_args!("{}", self.id()))
50 .finish_non_exhaustive()
51 }
52}
53
54impl Key {
55 pub fn generate() -> Result<Key, KeyError> {
67 let mut page = LockedPage::new().map_err(KeyError::Memory)?;
68 aws_lc_rs::rand::fill(&mut page.bytes_mut()[..KEY_LEN])
71 .expect("AWS-LC aborts instead of failing");
72 Ok(Key { page })
73 }
74
75 pub fn load_master(path: &Path) -> Result<Key, KeyError> {
87 Key::load_master_named(path, "master_key")
88 }
89
90 pub fn load_master_named(path: &Path, key: &str) -> Result<Key, KeyError> {
97 let mut page = LockedPage::new().map_err(KeyError::Memory)?;
98 let mut file = crate::secret_file::check_open(path).map_err(|problem| match problem {
99 crate::secret_file::Problem::Io(e) => KeyError::Read(e),
100 crate::secret_file::Problem::Refused(refusal) => {
101 KeyError::Refused(crate::secret_file::describe(key, path, refusal))
102 }
103 })?;
104 let buf = page.bytes_mut();
105 file.read_exact(&mut buf[..KEY_LEN])
106 .map_err(|e| match e.kind() {
107 io::ErrorKind::UnexpectedEof => KeyError::WrongSize,
108 _ => KeyError::Read(e),
109 })?;
110 if file
111 .read(&mut buf[KEY_LEN..=KEY_LEN])
112 .map_err(KeyError::Read)?
113 != 0
114 {
115 return Err(KeyError::WrongSize);
116 }
117 Ok(Key { page })
118 }
119
120 #[must_use]
126 pub fn id(&self) -> KeyId {
127 let hash = digest(&SHA256, self.bytes());
128 KeyId(hash.as_ref()[..8].try_into().expect("SHA-256 is 32 bytes"))
129 }
130
131 fn bytes(&self) -> &[u8] {
132 &self.page.bytes()[..KEY_LEN]
133 }
134
135 pub(crate) fn sqlcipher_raw(&self) -> Zeroizing<String> {
139 const HEX: &[u8; 16] = b"0123456789abcdef";
140 let mut literal = Zeroizing::new(String::with_capacity(3 + 2 * KEY_LEN));
141 literal.push_str("x'");
142 for byte in self.bytes() {
143 literal.push(char::from(HEX[usize::from(byte >> 4)]));
144 literal.push(char::from(HEX[usize::from(byte & 0x0f)]));
145 }
146 literal.push('\'');
147 literal
148 }
149}
150
151#[derive(Debug)]
153pub enum KeyError {
154 Memory(io::Error),
156 Read(io::Error),
158 Refused(String),
161 WrongSize,
163 Damaged,
166}
167
168impl fmt::Display for KeyError {
170 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
171 f.write_str(match self {
172 KeyError::Refused(why) => why,
173 KeyError::Memory(_) => "the key's memory could not be locked or kept out of core dumps",
174 KeyError::Read(_) => "the master key file could not be read",
175 KeyError::WrongSize => "the master key file does not hold exactly 32 bytes",
176 KeyError::Damaged => "a wrapped key did not open",
177 })
178 }
179}
180
181impl std::error::Error for KeyError {
182 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
183 match self {
184 KeyError::Memory(e) | KeyError::Read(e) => Some(e),
185 KeyError::Refused(_) | KeyError::WrongSize | KeyError::Damaged => None,
186 }
187 }
188}
189
190pub fn lock_all_memory() -> io::Result<()> {
201 if unsafe { libc::mlockall(libc::MCL_CURRENT | libc::MCL_FUTURE) } != 0 {
203 return Err(io::Error::last_os_error());
204 }
205 Ok(())
206}
207
208pub fn disable_core_dumps() -> io::Result<()> {
219 let none = libc::rlimit {
220 rlim_cur: 0,
221 rlim_max: 0,
222 };
223 if unsafe { libc::setrlimit(libc::RLIMIT_CORE, &none) } != 0 {
225 return Err(io::Error::last_os_error());
226 }
227 if unsafe { libc::prctl(libc::PR_SET_DUMPABLE, 0) } != 0 {
229 return Err(io::Error::last_os_error());
230 }
231 Ok(())
232}
233
234#[derive(Debug, Clone, Copy, PartialEq, Eq)]
238pub enum Context {
239 Tenant {
241 tenant: TenantId,
243 },
244 Version {
247 tenant: TenantId,
249 uuid: Uuid,
251 version: VersionId,
253 },
254}
255
256impl Context {
257 fn associated_data(&self, format: u8) -> Vec<u8> {
261 let mut ad = LABEL.to_vec();
262 ad.push(format);
263 match self {
264 Context::Tenant { tenant } => {
265 ad.push(1);
266 ad.extend(tenant.0);
267 }
268 Context::Version {
269 tenant,
270 uuid,
271 version,
272 } => {
273 ad.push(2);
274 ad.extend(tenant.0);
275 ad.extend(uuid.as_bytes());
276 ad.extend(version.0);
277 }
278 }
279 ad
280 }
281}
282
283#[derive(Debug, PartialEq, Eq)]
286pub struct OpenError;
287
288impl fmt::Display for OpenError {
289 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
290 f.write_str("the blob did not open under this key and context")
291 }
292}
293
294impl std::error::Error for OpenError {}
295
296pub(crate) const SEALED_OVERHEAD: usize = 1 + NONCE_LEN + TAG_LEN;
299
300#[must_use]
309pub fn seal(data_key: &Key, ctx: &Context, plaintext: &[u8]) -> Vec<u8> {
310 let nonce: [u8; NONCE_LEN] = aws_lc_rs::rand::generate(&aws_lc_rs::rand::SystemRandom::new())
313 .expect("AWS-LC aborts instead of failing")
314 .expose();
315 seal_with_nonce(data_key.bytes(), nonce, ctx, plaintext)
316}
317
318pub fn open(data_key: &Key, ctx: &Context, blob: &[u8]) -> Result<Vec<u8>, OpenError> {
326 let mut text = vec![0; blob.len().saturating_sub(1 + NONCE_LEN)];
327 let len = open_into(data_key.bytes(), ctx, blob, &mut text)?;
328 text.truncate(len);
329 Ok(text)
330}
331
332#[must_use]
335pub fn wrap(wrapping: &Key, ctx: &Context, key: &Key) -> Vec<u8> {
336 seal(wrapping, ctx, key.bytes())
337}
338
339pub fn unwrap(wrapping: &Key, ctx: &Context, wrapped: &[u8]) -> Result<Key, KeyError> {
350 let mut page = LockedPage::new().map_err(KeyError::Memory)?;
351 match open_into(wrapping.bytes(), ctx, wrapped, page.bytes_mut()) {
352 Ok(KEY_LEN) => Ok(Key { page }),
353 _ => Err(KeyError::Damaged),
354 }
355}
356
357pub fn rewrap(old: &Key, new: &Key, ctx: &Context, wrapped: &[u8]) -> Result<Vec<u8>, KeyError> {
365 let key = unwrap(old, ctx, wrapped)?;
366 Ok(wrap(new, ctx, &key))
367}
368
369#[derive(Debug, Clone, Copy, PartialEq, Eq)]
371pub enum WrapLimit {
372 Allow,
374 Warn,
376 Refuse,
378}
379
380#[must_use]
385pub fn wrap_limit(wraps: u64) -> WrapLimit {
386 const REFUSE_AT: u64 = 1 << 32;
387 const WARN_AT: u64 = 1 << 31;
388 if wraps >= REFUSE_AT {
389 WrapLimit::Refuse
390 } else if wraps >= WARN_AT {
391 WrapLimit::Warn
392 } else {
393 WrapLimit::Allow
394 }
395}
396
397fn open_into(key: &[u8], ctx: &Context, blob: &[u8], out: &mut [u8]) -> Result<usize, OpenError> {
400 let (&format, rest) = blob.split_first().ok_or(OpenError)?;
401 let (nonce, sealed) = rest.split_first_chunk::<NONCE_LEN>().ok_or(OpenError)?;
402 let text = out.get_mut(..sealed.len()).ok_or(OpenError)?;
403 text.copy_from_slice(sealed);
404 gcm_open(key, *nonce, &ctx.associated_data(format), text)
405}
406
407pub fn catalog_key(parent: &Key) -> Result<Key, KeyError> {
417 let mut page = LockedPage::new().map_err(KeyError::Memory)?;
418 hkdf_sha256(
419 &[],
420 parent.bytes(),
421 CATALOG_LABEL,
422 &mut page.bytes_mut()[..KEY_LEN],
423 );
424 Ok(Key { page })
425}
426
427fn hkdf_sha256(salt: &[u8], ikm: &[u8], info: &[u8], out: &mut [u8]) {
429 struct Len(usize);
430 impl KeyType for Len {
431 fn len(&self) -> usize {
432 self.0
433 }
434 }
435 Salt::new(HKDF_SHA256, salt)
438 .extract(ikm)
439 .expand(&[info], Len(out.len()))
440 .and_then(|okm| okm.fill(out))
441 .expect("within HKDF's output limit");
442}
443
444fn seal_with_nonce(key: &[u8], nonce: [u8; NONCE_LEN], ctx: &Context, plaintext: &[u8]) -> Vec<u8> {
445 let mut blob = Vec::with_capacity(1 + NONCE_LEN + plaintext.len() + TAG_LEN);
446 blob.push(FORMAT);
447 blob.extend(nonce);
448 blob.extend(plaintext);
449 let ad = ctx.associated_data(FORMAT);
450 let tag = gcm_seal(key, nonce, &ad, &mut blob[1 + NONCE_LEN..]);
451 blob.extend(tag);
452 blob
453}
454
455fn aead_key(key: &[u8]) -> LessSafeKey {
456 LessSafeKey::new(UnboundKey::new(&AES_256_GCM, key).expect("every key is 32 bytes"))
457}
458
459fn gcm_seal(key: &[u8], nonce: [u8; NONCE_LEN], ad: &[u8], in_out: &mut [u8]) -> [u8; TAG_LEN] {
461 let tag = aead_key(key)
465 .seal_in_place_separate_tag(Nonce::assume_unique_for_key(nonce), Aad::from(ad), in_out)
466 .expect("within GCM's limits");
467 tag.as_ref().try_into().expect("a 16-byte tag")
468}
469
470fn gcm_open(
473 key: &[u8],
474 nonce: [u8; NONCE_LEN],
475 ad: &[u8],
476 in_out: &mut [u8],
477) -> Result<usize, OpenError> {
478 aead_key(key)
479 .open_in_place(Nonce::assume_unique_for_key(nonce), Aad::from(ad), in_out)
480 .map(|plaintext| plaintext.len())
481 .map_err(|_| OpenError)
482}
483
484#[cfg(test)]
485mod tests {
486 use super::*;
487
488 #[test]
489 fn every_byte_of_a_key_is_random() {
490 let keys: Vec<Key> = (0..8).map(|_| Key::generate().expect("key")).collect();
491 for i in 0..KEY_LEN {
492 let first = keys[0].bytes()[i];
493 assert!(
494 keys.iter().any(|k| k.bytes()[i] != first),
495 "byte {i} is {first} in all eight keys"
496 );
497 }
498 }
499
500 fn hex(text: &str) -> Vec<u8> {
501 (0..text.len())
502 .step_by(2)
503 .map(|i| u8::from_str_radix(&text[i..i + 2], 16).expect("hex"))
504 .collect()
505 }
506
507 #[test]
511 fn aes_256_gcm_matches_the_published_vector() {
512 let key = hex("feffe9928665731c6d6a8f9467308308feffe9928665731c6d6a8f9467308308");
513 let nonce: [u8; 12] = hex("cafebabefacedbaddecaf888")
514 .try_into()
515 .expect("12 bytes");
516 let ad = hex("feedfacedeadbeeffeedfacedeadbeefabaddad2");
517 let mut text = hex(concat!(
518 "d9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a72",
519 "1c3c0c95956809532fcf0e2449a6b525b16aedf5aa0de657ba637b39"
520 ));
521 let tag = gcm_seal(&key, nonce, &ad, &mut text);
522 assert_eq!(
523 text,
524 hex(concat!(
525 "522dc1f099567d07f47f37a32a84427d643a8cdcbfe5c0c97598a2bd2555d1aa",
526 "8cb08e48590dbb3da7b08b1056828838c5f61e6393ba7a0abcc9f662"
527 )),
528 "the ciphertext is Test Case 16's"
529 );
530 assert_eq!(
531 tag.to_vec(),
532 hex("76fc6ece0f4e1768cddf8853bb2d551b"),
533 "the tag is Test Case 16's"
534 );
535 }
536
537 const TENANT: TenantId = TenantId([0x11; 16]);
538 const VERSION: VersionId = VersionId([0x22; 16]);
539 const UUID: Uuid = Uuid::from_bytes([0x33; 16]);
540
541 fn version_ctx() -> Context {
542 Context::Version {
543 tenant: TENANT,
544 uuid: UUID,
545 version: VERSION,
546 }
547 }
548
549 #[test]
553 fn a_blob_is_the_format_byte_nonce_ciphertext_and_tag() {
554 let key = [0x44; 32];
555 let nonce = [0x55; 12];
556 let mut ad = b"vcon-server/v1".to_vec();
557 ad.extend([1, 2]);
558 ad.extend([0x11; 16]);
559 ad.extend([0x33; 16]);
560 ad.extend([0x22; 16]);
561 let mut ciphertext = b"body".to_vec();
562 let tag = gcm_seal(&key, nonce, &ad, &mut ciphertext);
563 let mut expected = vec![1];
564 expected.extend(nonce);
565 expected.extend(ciphertext);
566 expected.extend(tag);
567 assert_eq!(
568 seal_with_nonce(&key, nonce, &version_ctx(), b"body"),
569 expected,
570 "format byte, nonce, ciphertext, tag, under a version's associated data"
571 );
572
573 let mut tenant_ad = b"vcon-server/v1".to_vec();
574 tenant_ad.extend([1, 1]);
575 tenant_ad.extend([0x11; 16]);
576 let mut ciphertext = b"key".to_vec();
577 let tag = gcm_seal(&key, nonce, &tenant_ad, &mut ciphertext);
578 let mut expected = vec![1];
579 expected.extend(nonce);
580 expected.extend(ciphertext);
581 expected.extend(tag);
582 let tenant = Context::Tenant { tenant: TENANT };
583 assert_eq!(
584 seal_with_nonce(&key, nonce, &tenant, b"key"),
585 expected,
586 "a tenant blob: the same layout under the tenant's associated data"
587 );
588 }
589
590 #[test]
591 fn a_sealed_blob_is_its_body_and_the_stated_overhead() {
592 let key = Key::generate().expect("key");
593 let ctx = Context::Tenant {
594 tenant: crate::ids::TenantId([7; 16]),
595 };
596 for len in [0, 1, 1000] {
597 assert_eq!(
598 seal(&key, &ctx, &vec![0x5a; len]).len(),
599 len + SEALED_OVERHEAD,
600 "a body of {len} bytes"
601 );
602 }
603 }
604
605 #[test]
606 fn a_sealed_body_opens_with_the_same_key_and_context() {
607 let key = Key::generate().expect("key");
608 for body in [&b""[..], b"x", &[0xa5; 100_000]] {
609 let blob = seal(&key, &version_ctx(), body);
610 assert_eq!(
611 blob.len(),
612 1 + 12 + body.len() + 16,
613 "a format byte, a 12-byte nonce, the ciphertext as long as the body, a 16-byte tag"
614 );
615 assert_eq!(
616 open(&key, &version_ctx(), &blob).as_deref(),
617 Ok(body),
618 "the same key and context open what they sealed"
619 );
620 }
621 }
622
623 #[test]
627 fn every_byte_of_a_nonce_is_random() {
628 let key = Key::generate().expect("key");
629 let nonces: Vec<[u8; 12]> = (0..1000)
630 .map(|_| {
631 let blob = seal(&key, &version_ctx(), b"same");
632 blob[1..13].try_into().expect("12 bytes")
633 })
634 .collect();
635 let distinct: std::collections::HashSet<_> = nonces.iter().collect();
636 assert_eq!(distinct.len(), nonces.len(), "a nonce repeated");
637 for i in 0..12 {
638 assert!(
639 nonces.iter().any(|n| n[i] != nonces[0][i]),
640 "byte {i} of the nonce never changes"
641 );
642 }
643 }
644
645 #[test]
646 fn changing_any_byte_of_a_blob_fails() {
647 let key = Key::generate().expect("key");
648 let blob = seal(&key, &version_ctx(), b"a body");
649 assert_eq!(
650 open(&key, &version_ctx(), &blob).as_deref(),
651 Ok(&b"a body"[..]),
652 "unchanged"
653 );
654 for i in 0..blob.len() {
655 let mut bad = blob.clone();
656 bad[i] ^= 0x01;
657 assert_eq!(open(&key, &version_ctx(), &bad), Err(OpenError), "byte {i}");
658 }
659 for len in 0..blob.len() {
660 assert_eq!(
661 open(&key, &version_ctx(), &blob[..len]),
662 Err(OpenError),
663 "first {len} bytes"
664 );
665 }
666 let mut longer = blob.clone();
667 longer.push(0);
668 assert_eq!(
669 open(&key, &version_ctx(), &longer),
670 Err(OpenError),
671 "one byte more"
672 );
673 }
674
675 #[test]
676 fn another_context_or_key_fails() {
677 let key = Key::generate().expect("key");
678 let blob = seal(&key, &version_ctx(), b"a body");
679 assert_eq!(
680 open(&key, &version_ctx(), &blob).as_deref(),
681 Ok(&b"a body"[..]),
682 "unchanged"
683 );
684 let others = [
685 Context::Version {
686 tenant: TenantId([0x12; 16]),
687 uuid: UUID,
688 version: VERSION,
689 },
690 Context::Version {
691 tenant: TENANT,
692 uuid: Uuid::from_bytes([0x34; 16]),
693 version: VERSION,
694 },
695 Context::Version {
696 tenant: TENANT,
697 uuid: UUID,
698 version: VersionId([0x23; 16]),
699 },
700 Context::Tenant { tenant: TENANT },
701 ];
702 for other in others {
703 assert_eq!(open(&key, &other, &blob), Err(OpenError), "{other:?}");
704 }
705 let other_key = Key::generate().expect("key");
706 assert_eq!(
707 open(&other_key, &version_ctx(), &blob),
708 Err(OpenError),
709 "the tag fails under any other key"
710 );
711 }
712
713 const TENANT_CTX: Context = Context::Tenant { tenant: TENANT };
714
715 #[test]
716 fn a_wrapped_key_unwraps_to_the_same_key() {
717 let wrapping = Key::generate().expect("key");
718 let key = Key::generate().expect("key");
719 for ctx in [TENANT_CTX, version_ctx()] {
720 let wrapped = wrap(&wrapping, &ctx, &key);
721 assert_eq!(
722 wrapped.len(),
723 1 + 12 + KEY_LEN + 16,
724 "a wrapped key is a sealed blob of the key's 32 bytes"
725 );
726 let unwrapped = unwrap(&wrapping, &ctx, &wrapped).expect("unwraps");
727 assert_eq!(
728 unwrapped.bytes(),
729 key.bytes(),
730 "unwrap gives back the key wrapped"
731 );
732 }
733 }
734
735 #[test]
736 fn changing_any_byte_of_a_wrapped_key_fails() {
737 let wrapping = Key::generate().expect("key");
738 let key = Key::generate().expect("key");
739 let wrapped = wrap(&wrapping, &TENANT_CTX, &key);
740 assert!(
741 unwrap(&wrapping, &TENANT_CTX, &wrapped).is_ok(),
742 "unchanged"
743 );
744 for i in 0..wrapped.len() {
745 let mut bad = wrapped.clone();
746 bad[i] ^= 0x01;
747 assert!(unwrap(&wrapping, &TENANT_CTX, &bad).is_err(), "byte {i}");
748 }
749 for len in 0..wrapped.len() {
750 assert!(
751 unwrap(&wrapping, &TENANT_CTX, &wrapped[..len]).is_err(),
752 "first {len} bytes"
753 );
754 }
755 }
756
757 #[test]
758 fn another_context_or_wrapping_key_fails() {
759 let wrapping = Key::generate().expect("key");
760 let key = Key::generate().expect("key");
761 let wrapped = wrap(&wrapping, &TENANT_CTX, &key);
762 assert!(
763 unwrap(&wrapping, &TENANT_CTX, &wrapped).is_ok(),
764 "unchanged"
765 );
766 let other_tenant = Context::Tenant {
767 tenant: TenantId([0x12; 16]),
768 };
769 assert!(
770 unwrap(&wrapping, &other_tenant, &wrapped).is_err(),
771 "other tenant"
772 );
773 assert!(
774 unwrap(&wrapping, &version_ctx(), &wrapped).is_err(),
775 "other kind"
776 );
777 let other = Key::generate().expect("key");
778 assert!(
779 unwrap(&other, &TENANT_CTX, &wrapped).is_err(),
780 "other wrapping key"
781 );
782 }
783
784 #[test]
785 fn only_a_32_byte_key_unwraps() {
786 let wrapping = Key::generate().expect("key");
787 for len in [0, 31, 33, 64] {
788 let sealed = seal(&wrapping, &TENANT_CTX, &vec![7; len]);
789 assert!(
790 unwrap(&wrapping, &TENANT_CTX, &sealed).is_err(),
791 "{len} bytes"
792 );
793 }
794 let sealed = seal(&wrapping, &TENANT_CTX, &[7; KEY_LEN]);
795 let key = unwrap(&wrapping, &TENANT_CTX, &sealed).expect("32 bytes unwrap");
796 assert_eq!(key.bytes(), [7; KEY_LEN], "the key is the 32 bytes sealed");
797 }
798
799 fn key_of(bytes: [u8; KEY_LEN]) -> Key {
801 let mut page = LockedPage::new().expect("page");
802 page.bytes_mut()[..KEY_LEN].copy_from_slice(&bytes);
803 Key { page }
804 }
805
806 #[test]
808 fn hkdf_sha256_matches_rfc_5869() {
809 let cases = [
810 (
811 "000102030405060708090a0b0c",
812 "0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b",
813 "f0f1f2f3f4f5f6f7f8f9",
814 concat!(
815 "3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf",
816 "34007208d5b887185865"
817 ),
818 ),
819 (
820 concat!(
821 "606162636465666768696a6b6c6d6e6f707172737475767778797a7b7c7d7e7f",
822 "808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9f",
823 "a0a1a2a3a4a5a6a7a8a9aaabacadaeaf"
824 ),
825 concat!(
826 "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f",
827 "202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f",
828 "404142434445464748494a4b4c4d4e4f"
829 ),
830 concat!(
831 "b0b1b2b3b4b5b6b7b8b9babbbcbdbebfc0c1c2c3c4c5c6c7c8c9cacbcccdcecf",
832 "d0d1d2d3d4d5d6d7d8d9dadbdcdddedfe0e1e2e3e4e5e6e7e8e9eaebecedeeef",
833 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff"
834 ),
835 concat!(
836 "b11e398dc80327a1c8e7f78c596a49344f012eda2d4efad8a050cc4c19afa97c",
837 "59045a99cac7827271cb41c65e590e09da3275600c2f09b8367793a9aca3db71",
838 "cc30c58179ec3e87c14c01d5c1f3434f1d87"
839 ),
840 ),
841 (
842 "",
843 "0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b",
844 "",
845 concat!(
846 "8da4e775a563c18f715f802a063c5a31b8a11f5c5ee1879ec3454e5f3c738d2d",
847 "9d201395faa4b61a96c8"
848 ),
849 ),
850 ];
851 for (n, (salt, ikm, info, okm)) in cases.into_iter().enumerate() {
852 let expected = hex(okm);
853 let mut out = vec![0; expected.len()];
854 hkdf_sha256(&hex(salt), &hex(ikm), &hex(info), &mut out);
855 assert_eq!(out, expected, "test case {}", n + 1);
856 }
857 }
858
859 #[test]
863 fn a_catalog_key_is_hkdf_of_its_parent_with_the_catalog_label() {
864 let catalog = catalog_key(&key_of([0x44; KEY_LEN])).expect("derives");
865 assert_eq!(
866 catalog.bytes(),
867 hex("c0df4ea4f63e64687ca93c494fff4ca00b3ae13112766d8ea24cca35c6b1031b"),
868 "the value Python's HKDF gives for this parent and label"
869 );
870 }
871
872 #[test]
873 fn distinct_parents_or_labels_give_distinct_keys() {
874 let parent = Key::generate().expect("key");
875 let again = catalog_key(&parent).expect("derives");
876 assert_eq!(
877 catalog_key(&parent).expect("derives").bytes(),
878 again.bytes(),
879 "derivation is deterministic: the same parent gives the same catalog key"
880 );
881 let other = catalog_key(&Key::generate().expect("key")).expect("derives");
882 assert_ne!(
883 other.bytes(),
884 again.bytes(),
885 "another parent gives another catalog key"
886 );
887 let mut a = [0; KEY_LEN];
888 let mut b = [0; KEY_LEN];
889 hkdf_sha256(&[], parent.bytes(), b"label a", &mut a);
890 hkdf_sha256(&[], parent.bytes(), b"label b", &mut b);
891 assert_ne!(a, b, "another label gives another key from the same parent");
892 }
893
894 #[test]
895 fn a_rewrapped_key_opens_under_the_new_key_only() {
896 let old = Key::generate().expect("key");
897 let new = Key::generate().expect("key");
898 let key = Key::generate().expect("key");
899 let wrapped = wrap(&old, &version_ctx(), &key);
900 let rewrapped = rewrap(&old, &new, &version_ctx(), &wrapped).expect("rewraps");
901 let opened = unwrap(&new, &version_ctx(), &rewrapped).expect("opens under new");
902 assert_eq!(
903 opened.bytes(),
904 key.bytes(),
905 "rewrapping keeps the wrapped key itself"
906 );
907 assert!(unwrap(&old, &version_ctx(), &rewrapped).is_err(), "old key");
908 assert!(
909 unwrap(&new, &TENANT_CTX, &rewrapped).is_err(),
910 "context kept"
911 );
912 }
913
914 #[test]
915 fn rewrapping_needs_the_right_old_key_and_context() {
916 let old = Key::generate().expect("key");
917 let new = Key::generate().expect("key");
918 let wrapped = wrap(&old, &TENANT_CTX, &Key::generate().expect("key"));
919 assert!(
920 matches!(
921 rewrap(&new, &new, &TENANT_CTX, &wrapped),
922 Err(KeyError::Damaged)
923 ),
924 "the key was not wrapped under new, so new cannot unwrap it to rewrap"
925 );
926 assert!(
927 matches!(
928 rewrap(&old, &new, &version_ctx(), &wrapped),
929 Err(KeyError::Damaged)
930 ),
931 "the key was wrapped for the tenant context, not a version's"
932 );
933 }
934
935 #[test]
936 fn wrapping_warns_from_2_to_the_31_and_stops_at_2_to_the_32() {
937 let cases = [
938 (0, WrapLimit::Allow),
939 ((1 << 31) - 1, WrapLimit::Allow),
940 (1 << 31, WrapLimit::Warn),
941 ((1 << 32) - 1, WrapLimit::Warn),
942 (1 << 32, WrapLimit::Refuse),
943 (u64::MAX, WrapLimit::Refuse),
944 ];
945 for (wraps, expected) in cases {
946 assert_eq!(wrap_limit(wraps), expected, "{wraps} wraps");
947 }
948 }
949
950 #[test]
951 fn the_sqlcipher_literal_spells_the_key_in_hex() {
952 let mut bytes = [0; KEY_LEN];
953 bytes[0] = 0x0a;
954 bytes[31] = 0xff;
955 let literal = key_of(bytes).sqlcipher_raw();
956 let expected = format!("x'0a{}ff'", "00".repeat(30));
957 assert_eq!(
958 *literal, expected,
959 "SQLCipher's raw key literal is x'' around two lower-case hex digits per byte"
960 );
961 assert_eq!(literal.capacity(), literal.len(), "built at its final size");
962 }
963
964 #[test]
967 fn a_keys_debug_shows_its_id_and_none_of_its_bytes() {
968 let bytes: [u8; KEY_LEN] = std::array::from_fn(|i| 0xa0 ^ (5 * i as u8));
969 let key = key_of(bytes);
970 let shown = format!("{key:?}");
971 assert!(
972 shown.contains(&key.id().to_string()),
973 "the id tells keys apart in a log: {shown}"
974 );
975 for run in bytes.windows(4) {
976 let lower: String = run.iter().map(|b| format!("{b:02x}")).collect();
977 let upper = lower.to_uppercase();
978 let decimal = run.iter().map(u8::to_string).collect::<Vec<_>>().join(", ");
979 for rendering in [lower, upper, decimal] {
980 assert!(
981 !shown.contains(&rendering),
982 "no run of the key's bytes may be printed, found {rendering:?} in {shown}"
983 );
984 }
985 }
986 }
987
988 #[test]
989 fn keys_can_be_shared_between_threads() {
990 fn shared<T: Send + Sync>() {}
991 shared::<Key>();
992 }
993}