cachekit-rs 0.12.0

Caching for Rust (beta). Supports cachekit.io SaaS, Redis, Memcached, local File, and Cloudflare Workers.
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
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
//! Integration tests for the zero-knowledge encryption layer.
//!
//! Run with:
//!   cargo test --test encryption_tests --features cachekitio,encryption,l1

mod common;

use std::time::Duration;

use serde::{Deserialize, Serialize};

use crate::common::MockBackend;
use cachekit::client::SharedBackend;
use cachekit::{CacheKit, CachekitError};

// ── Test fixtures ─────────────────────────────────────────────────────────────

/// 32-byte master key for tests. NOT for production use.
const TEST_MASTER_KEY: &[u8] = b"test_master_key_32_bytes_long!!!";

/// Hex-encoded version of the test master key.
fn test_master_key_hex() -> String {
    hex::encode(TEST_MASTER_KEY)
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
struct Secret {
    api_key: String,
    user_id: u64,
}

fn make_encrypted_client(backend: SharedBackend) -> CacheKit {
    CacheKit::builder()
        .backend(backend)
        .default_ttl(Duration::from_secs(60))
        .no_l1()
        .encryption_from_bytes(TEST_MASTER_KEY, "test-tenant")
        .expect("encryption setup")
        .build()
        .expect("client builds")
}

fn make_encrypted_client_with_l1(backend: SharedBackend) -> CacheKit {
    CacheKit::builder()
        .backend(backend)
        .default_ttl(Duration::from_secs(60))
        .l1_capacity(100)
        .encryption_from_bytes(TEST_MASTER_KEY, "test-tenant")
        .expect("encryption setup")
        .build()
        .expect("client builds")
}

// ── Tests ─────────────────────────────────────────────────────────────────────

#[tokio::test]
async fn secure_set_and_get() {
    let backend = MockBackend::shared();
    let client = make_encrypted_client(backend);

    let secret = Secret {
        api_key: "sk-live-abc123".to_owned(), // pragma: allowlist secret
        user_id: 42,
    };

    let secure = client
        .secure_cache()
        .expect("secure_cache() should work with encryption configured");
    secure.set("secret:42", &secret).await.expect("secure set");

    let retrieved: Secret = secure
        .get("secret:42")
        .await
        .expect("secure get")
        .expect("value should exist");

    assert_eq!(retrieved, secret);
}

#[tokio::test]
async fn secure_data_is_encrypted_in_backend() {
    let (shared, backend) = MockBackend::new_with_handle();
    let client = make_encrypted_client(shared);

    let secret = Secret {
        api_key: "sk-live-SUPERSECRET".to_owned(), // pragma: allowlist secret
        user_id: 999,
    };

    let secure = client.secure_cache().unwrap();
    secure.set("secret:999", &secret).await.unwrap();

    // Read raw bytes from the backend
    let raw_bytes = backend
        .store
        .lock()
        .await
        .get("secret:999")
        .cloned()
        .expect("key should exist in backend");

    // The stored bytes must NOT contain the plaintext API key
    let raw_str = String::from_utf8_lossy(&raw_bytes);
    assert!(
        !raw_str.contains("SUPERSECRET"),
        "backend must store ciphertext, not plaintext; got: {raw_str}"
    );

    // Ciphertext must include the 12-byte nonce prefix + at least 16-byte auth tag
    assert!(
        raw_bytes.len() >= 28,
        "ciphertext too short: {} bytes (expected nonce + tag overhead)",
        raw_bytes.len()
    );
}

#[tokio::test]
async fn secure_without_master_key_fails() {
    let client = CacheKit::builder()
        .backend(MockBackend::shared())
        .no_l1()
        .build()
        .expect("client builds without encryption");

    let result = client.secure_cache();
    assert!(
        result.is_err(),
        "secure_cache() without encryption should fail"
    );

    let err = result.unwrap_err();
    assert!(
        matches!(err, CachekitError::Config(_)),
        "expected Config error, got: {err:?}"
    );
    let msg = err.to_string();
    assert!(
        msg.contains("CacheKit::secure(url, master_key_hex)")
            && msg.contains("CacheKit::secure_from_env(url)")
            && msg.contains("CACHEKIT_MASTER_KEY"),
        "error should name both secure preset forms and CACHEKIT_MASTER_KEY: {msg}"
    );
}

#[tokio::test]
async fn secure_get_missing_returns_none() {
    let client = make_encrypted_client(MockBackend::shared());
    let secure = client.secure_cache().unwrap();

    let result: Option<String> = secure.get("nonexistent").await.expect("get should succeed");
    assert!(result.is_none());
}

#[tokio::test]
async fn secure_delete() {
    let client = make_encrypted_client(MockBackend::shared());
    let secure = client.secure_cache().unwrap();

    secure.set("to-delete", &"temporary").await.unwrap();
    assert!(secure.exists("to-delete").await.unwrap());

    let deleted = secure.delete("to-delete").await.unwrap();
    assert!(deleted);

    let gone: Option<String> = secure.get("to-delete").await.unwrap();
    assert!(gone.is_none());
}

#[tokio::test]
async fn secure_wrong_key_fails_decryption() {
    let (shared, backend) = MockBackend::new_with_handle();
    let client = make_encrypted_client(shared);

    let secure = client.secure_cache().unwrap();
    secure.set("key-a", &"secret data").await.unwrap();

    // Manually swap the value to a different key in the backend
    let stored = backend.store.lock().await.get("key-a").cloned().unwrap();
    backend
        .store
        .lock()
        .await
        .insert("key-b".to_owned(), stored);

    // Decrypting with a different cache key should fail (AAD mismatch)
    let result: Result<Option<String>, _> = secure.get("key-b").await;
    assert!(
        result.is_err(),
        "decryption with wrong cache key AAD must fail"
    );
}

#[tokio::test]
async fn secure_different_tenants_cant_decrypt() {
    let (shared_a, _backend) = MockBackend::new_with_handle();
    let shared_b = shared_a.clone();

    let client_a = CacheKit::builder()
        .backend(shared_a)
        .no_l1()
        .encryption_from_bytes(TEST_MASTER_KEY, "tenant-a")
        .unwrap()
        .build()
        .unwrap();

    let client_b = CacheKit::builder()
        .backend(shared_b)
        .no_l1()
        .encryption_from_bytes(TEST_MASTER_KEY, "tenant-b")
        .unwrap()
        .build()
        .unwrap();

    client_a
        .secure_cache()
        .unwrap()
        .set("shared-key", &"tenant-a-secret")
        .await
        .unwrap();

    // Tenant B should fail to decrypt tenant A's data
    let result: Result<Option<String>, _> =
        client_b.secure_cache().unwrap().get("shared-key").await;
    assert!(
        result.is_err(),
        "cross-tenant decryption must fail (different derived keys)"
    );
}

#[tokio::test]
async fn secure_hex_builder() {
    let client = CacheKit::builder()
        .backend(MockBackend::shared())
        .no_l1()
        .encryption(&test_master_key_hex(), "hex-tenant")
        .expect("hex encryption setup")
        .build()
        .unwrap();

    let secure = client.secure_cache().unwrap();
    secure.set("hex-test", &42u64).await.unwrap();

    let val: u64 = secure.get("hex-test").await.unwrap().unwrap();
    assert_eq!(val, 42);
}

#[test]
fn hex_builder_error_does_not_quote_the_key() {
    // hex's own error Display names the offending character — key material
    // in an error string (CWE-532).
    let key = format!("{}Q9", "a1".repeat(31));
    let err = CacheKit::builder()
        .backend(MockBackend::shared())
        .encryption(&key, "hex-tenant")
        .err()
        .expect("non-hex key must be rejected");
    assert!(matches!(err, CachekitError::Config(_)), "got {err:?}");
    assert!(
        !err.to_string().contains('Q'),
        "error quotes key material: {err}"
    );
}

#[tokio::test]
async fn secure_with_l1_roundtrip() {
    let (shared, backend) = MockBackend::new_with_handle();
    let client = make_encrypted_client_with_l1(shared);

    let secure = client.secure_cache().unwrap();
    secure.set("l1-test", &"encrypted in L1").await.unwrap();

    // First get populates L1 (already done by set write-through)
    let val: String = secure.get("l1-test").await.unwrap().unwrap();
    assert_eq!(val, "encrypted in L1");

    // Remove from backend to prove L1 is serving ciphertext
    backend.store.lock().await.remove("l1-test");

    // Should still get the value from L1 (decrypted from ciphertext)
    let val2: String = secure.get("l1-test").await.unwrap().unwrap();
    assert_eq!(val2, "encrypted in L1");
}

#[tokio::test]
async fn secure_l1_stores_ciphertext_not_plaintext() {
    let (shared, backend) = MockBackend::new_with_handle();
    let client = make_encrypted_client_with_l1(shared);

    let secure = client.secure_cache().unwrap();
    secure.set("l1-cipher", &"PLAINTEXT_VALUE").await.unwrap();

    // The backend should have ciphertext, not the msgpack encoding of "PLAINTEXT_VALUE".
    let store = backend.store.lock().await;
    let (_key, raw_bytes) = store.iter().next().expect("backend should have one entry");
    let plaintext_msgpack = rmp_serde::to_vec_named(&"PLAINTEXT_VALUE").unwrap();
    assert_ne!(
        raw_bytes, &plaintext_msgpack,
        "backend should store ciphertext, not plaintext msgpack"
    );
    // Ciphertext has AAD prefix (0x03 version byte) and is longer than plaintext
    assert!(
        raw_bytes.len() > plaintext_msgpack.len(),
        "ciphertext should be larger than plaintext due to AAD + GCM tag"
    );
}

/// Write a real ciphertext for `key` through an L1-less client, then flip its
/// last byte in the backend so it fails AES-GCM authentication. Returns the
/// planted bytes.
async fn plant_tampered(shared: SharedBackend, backend: &MockBackend, key: &str) -> Vec<u8> {
    let writer = make_encrypted_client(shared);
    writer
        .secure_cache()
        .unwrap()
        .set(key, &"authentic")
        .await
        .unwrap();
    let mut store = backend.store.lock().await;
    let bytes = store.get_mut(key).expect("writer stored the entry");
    *bytes.last_mut().unwrap() ^= 0x01;
    bytes.clone()
}

#[tokio::test]
async fn secure_get_evicts_l1_after_decrypt_failure() {
    let (shared, backend) = MockBackend::new_with_handle();
    let client = make_encrypted_client_with_l1(shared.clone());
    let secure = client.secure_cache().unwrap();
    let planted = plant_tampered(shared, &backend, "poisoned").await;

    let err = secure.get::<String>("poisoned").await.unwrap_err();
    assert!(matches!(err, CachekitError::Encryption(_)), "got: {err:?}");
    // The failed read must not remove or rewrite the backend entry.
    assert_eq!(backend.store.lock().await.get("poisoned"), Some(&planted));

    // Remove the entry behind the client's back: a surviving L1 copy would
    // keep failing; an evicted one yields a miss.
    backend.store.lock().await.remove("poisoned");
    assert_eq!(secure.get::<String>("poisoned").await.unwrap(), None);
}

#[tokio::test]
async fn secure_interop_get_swr_evicts_l1_after_decrypt_failure() {
    let (shared, backend) = MockBackend::new_with_handle();
    let client = make_encrypted_client_with_l1(shared.clone());
    let secure = client.secure_cache().unwrap();
    let planted = plant_tampered(shared, &backend, "poisoned-swr").await;

    let err = secure
        .interop_get_swr::<String>("poisoned-swr")
        .await
        .unwrap_err();
    assert!(matches!(err, CachekitError::Encryption(_)), "got: {err:?}");
    assert_eq!(
        backend.store.lock().await.get("poisoned-swr"),
        Some(&planted)
    );

    backend.store.lock().await.remove("poisoned-swr");
    assert!(matches!(
        secure.interop_get_swr::<String>("poisoned-swr").await,
        Ok(cachekit::SwrRead::Miss)
    ));
}

#[tokio::test]
async fn secure_with_namespace() {
    let (shared, backend) = MockBackend::new_with_handle();
    let client = CacheKit::builder()
        .backend(shared)
        .namespace("ns")
        .no_l1()
        .encryption_from_bytes(TEST_MASTER_KEY, "test-tenant")
        .unwrap()
        .build()
        .unwrap();

    let secure = client.secure_cache().unwrap();
    secure.set("namespaced", &"value").await.unwrap();

    // Backend should have the namespaced key
    let keys: Vec<String> = backend.store.lock().await.keys().cloned().collect();
    assert!(
        keys.contains(&"ns:namespaced".to_owned()),
        "expected namespaced key, got: {keys:?}"
    );

    // Round-trip should work
    let val: String = secure.get("namespaced").await.unwrap().unwrap();
    assert_eq!(val, "value");
}

/// The AAD binds the key the client passes to its backend, namespace
/// included: same master key and tenant, but ciphertext copied from `app1:k1`
/// to `app2:k1` must not decrypt.
#[tokio::test]
async fn secure_namespace_is_bound_in_aad() {
    let (shared, backend) = MockBackend::new_with_handle();
    let client_in = |ns: &str| {
        CacheKit::builder()
            .backend(shared.clone())
            .namespace(ns)
            .no_l1()
            .encryption_from_bytes(TEST_MASTER_KEY, "one-tenant")
            .unwrap()
            .build()
            .unwrap()
    };
    let (app1, app2) = (client_in("app1"), client_in("app2"));

    app1.secure_cache()
        .unwrap()
        .set("k1", &"v-from-app1")
        .await
        .unwrap();
    let stored = backend.store.lock().await["app1:k1"].clone();

    // The ciphertext authenticates under the namespaced key, not the bare one.
    let layer = cachekit::EncryptionLayer::new(TEST_MASTER_KEY, "one-tenant").unwrap();
    assert!(layer.decrypt(&stored, "app1:k1").is_ok());
    assert!(layer.decrypt(&stored, "k1").is_err());

    backend
        .store
        .lock()
        .await
        .insert("app2:k1".to_owned(), stored);
    let err = app2
        .secure_cache()
        .unwrap()
        .get::<String>("k1")
        .await
        .expect_err("ciphertext moved across namespaces must fail authentication");
    assert!(
        matches!(err, CachekitError::Encryption(_)),
        "expected Encryption, got: {err:?}"
    );
}

#[tokio::test]
async fn secure_set_rejects_payload_whose_ciphertext_exceeds_limit() {
    // The get paths size-check the STORED ciphertext (plaintext + 28 bytes of
    // nonce + tag). If set only checked the plaintext, a value within 28 bytes
    // of the limit would write successfully and then fail every read with
    // PayloadTooLarge. set must therefore check the ciphertext length.
    let client = CacheKit::builder()
        .backend(MockBackend::shared())
        .no_l1()
        .max_payload_bytes(64)
        .encryption_from_bytes(TEST_MASTER_KEY, "test-tenant")
        .expect("encryption setup")
        .build()
        .expect("client builds");
    let secure = client.secure_cache().expect("secure handle");

    // 50 serialized bytes: under the 64-byte limit as plaintext, over it as
    // ciphertext (50 + 28 = 78). Must fail at write time, not become
    // unreadable after a successful write.
    let value = "x".repeat(48); // msgpack str8: 2 header bytes + 48
    let err = secure
        .set("boundary:key", &value)
        .await
        .expect_err("ciphertext over limit must fail at set time");
    assert!(
        matches!(err, CachekitError::PayloadTooLarge { .. }),
        "expected PayloadTooLarge, got: {err:?}"
    );

    // Well under the limit still round-trips.
    secure.set("small:key", &"ok").await.expect("small set");
    let got: Option<String> = secure.get("small:key").await.expect("small get");
    assert_eq!(got.as_deref(), Some("ok"));
}

// ── Key rotation (keyring) ────────────────────────────────────────────────────

/// End-to-end rotation round-trip:
/// value written under k1 → k2 promoted with k1 decrypt-only → read succeeds
/// without re-encryption → k1 dropped → read fails as an error.
#[tokio::test]
async fn rotation_round_trip_without_reencryption() {
    const K1: &[u8] = &[0x11; 32];
    const K2: &[u8] = &[0x22; 32];

    let (backend, store) = common::MockBackend::new_with_handle();

    // Phase 1: pre-rotation client writes under k1.
    let writer = CacheKit::builder()
        .backend(backend.clone())
        .default_ttl(Duration::from_secs(60))
        .no_l1()
        .encryption_from_bytes(K1, "test-tenant")
        .expect("encryption setup")
        .build()
        .expect("client builds");
    let secret = Secret {
        api_key: "sk-live-rotate-me".to_owned(), // pragma: allowlist secret
        user_id: 7,
    };
    writer
        .secure_cache()
        .expect("secure_cache()")
        .set("secret:7", &secret)
        .await
        .expect("secure set under k1");

    let ciphertext_before = store.store.lock().await.get("secret:7").cloned().unwrap();

    // Phase 2: k2 promoted to current, k1 retained decrypt-only.
    let rotated = CacheKit::builder()
        .backend(backend.clone())
        .default_ttl(Duration::from_secs(60))
        .no_l1()
        .encryption_from_bytes_with_previous(K2, &[K1], "test-tenant")
        .expect("keyring setup")
        .build()
        .expect("client builds");
    let read_back: Secret = rotated
        .secure_cache()
        .expect("secure_cache()")
        .get("secret:7")
        .await
        .expect("secure get after rotation")
        .expect("value should exist");
    assert_eq!(read_back, secret);

    // The read must not have re-encrypted: stored bytes are untouched.
    let ciphertext_after = store.store.lock().await.get("secret:7").cloned().unwrap();
    assert_eq!(
        ciphertext_before, ciphertext_after,
        "read-through rotation must not rewrite the entry"
    );

    // Phase 3: k1 dropped — hard cut-over, the k1-era entry is unreadable.
    let cut_over = CacheKit::builder()
        .backend(backend)
        .default_ttl(Duration::from_secs(60))
        .no_l1()
        .encryption_from_bytes_with_previous(K2, &[], "test-tenant")
        .expect("keyring setup")
        .build()
        .expect("client builds");
    let result: Result<Option<Secret>, _> = cut_over
        .secure_cache()
        .expect("secure_cache()")
        .get("secret:7")
        .await;
    assert!(
        matches!(result, Err(CachekitError::Encryption(_))),
        "dropped-key read must surface as an encryption error, got {result:?}"
    );
}

/// Rotation drain signal: the builder wires the counters into the
/// user-held secure handle, so a read served by the retiring key is visible
/// there. Index-0 silence is owned and tested at the layer (`encryption.rs`).
#[tokio::test]
async fn rotation_drain_signal_is_visible_on_secure_cache() {
    const K1: &[u8] = &[0x11; 32];
    const K2: &[u8] = &[0x22; 32];

    let backend = common::MockBackend::shared();

    let writer = CacheKit::builder()
        .backend(backend.clone())
        .default_ttl(Duration::from_secs(60))
        .no_l1()
        .encryption_from_bytes(K1, "test-tenant")
        .expect("encryption setup")
        .build()
        .expect("client builds");
    writer
        .secure_cache()
        .expect("secure_cache()")
        .set("drain:old", &"written under k1")
        .await
        .expect("secure set under k1");

    let rotated = CacheKit::builder()
        .backend(backend)
        .default_ttl(Duration::from_secs(60))
        .no_l1()
        .encryption_from_bytes_with_previous(K2, &[K1], "test-tenant")
        .expect("keyring setup")
        .build()
        .expect("client builds");
    let secure = rotated.secure_cache().expect("secure_cache()");
    assert_eq!(secure.previous_key_hits(), vec![0], "nothing read yet");

    // The k1-era entry is served by previous[0]: the grace window is still live.
    let _: Option<String> = secure.get("drain:old").await.expect("secure get");
    assert_eq!(
        secure.previous_key_hits(),
        vec![1],
        "previous-key hit is counted"
    );
}

/// The hex rotation path: an entry written under a 48-byte key for a
/// non-default tenant stays readable after a fresh 32-byte key is promoted,
/// with the 48-byte key listed as previous. The raw-bytes path cannot do this
/// (its keys are exactly 32 bytes), nor can the env path (tenant "default").
#[tokio::test]
async fn hex_rotation_reads_a_48_byte_key_entry_for_a_custom_tenant() {
    const TENANT: &str = "tenant-a";
    let old_hex = "11".repeat(48);
    let new_hex = "22".repeat(32);
    let backend = MockBackend::shared();
    let client = |configure: &dyn Fn(
        cachekit::CacheKitBuilder,
    ) -> Result<cachekit::CacheKitBuilder, CachekitError>| {
        let builder = CacheKit::builder()
            .backend(backend.clone())
            .default_ttl(Duration::from_secs(60))
            .no_l1();
        configure(builder)
            .expect("encryption setup")
            .build()
            .expect("client builds")
    };
    let secret = plain_secret();

    let writer = client(&|b| b.encryption(&old_hex, TENANT));
    writer.set("rotate:old", &secret).await.unwrap();

    let rotated = client(&|b| b.encryption_with_previous(&new_hex, &[&old_hex], TENANT));
    assert_eq!(
        rotated.get::<Secret>("rotate:old").await.unwrap(),
        Some(secret.clone()),
        "the 48-byte-key entry must stay readable after rotation"
    );
    assert_eq!(
        rotated.secure_cache().unwrap().previous_key_hits(),
        vec![1],
        "the read was served by the previous key"
    );

    // Writes use the new key alone: a client holding only it reads them,
    // and a client holding only the old key does not.
    rotated.set("rotate:new", &secret).await.unwrap();
    let new_only = client(&|b| b.encryption(&new_hex, TENANT));
    assert_eq!(
        new_only.get::<Secret>("rotate:new").await.unwrap(),
        Some(secret.clone()),
        "a write after rotation must decrypt under the new key alone"
    );
    let old_only = client(&|b| b.encryption(&old_hex, TENANT));
    let result = old_only.get::<Secret>("rotate:new").await;
    assert!(
        matches!(result, Err(CachekitError::Encryption(_))),
        "a write after rotation must not be under the old key, got {result:?}"
    );
}

#[track_caller]
fn assert_builder_config_err_naming(
    result: Result<cachekit::CacheKitBuilder, CachekitError>,
    names: &str,
    what: &str,
) {
    match result {
        Err(CachekitError::Config(msg)) => {
            assert!(
                msg.contains(names),
                "{what}: Config error must name {names:?}, got: {msg}"
            )
        }
        Err(e) => panic!("{what}: expected Config error, got {e:?}"),
        Ok(_) => panic!("{what}: expected Config error, got Ok"),
    }
}

/// `encryption_with_previous` keeps the keyring rules of the hex env path,
/// each a Config error at construction.
#[test]
fn encryption_with_previous_enforces_the_keyring_rules() {
    let current = "22".repeat(32);
    let (k1, k2, k3, k4) = (
        "11".repeat(32),
        "33".repeat(32),
        "44".repeat(48),
        "55".repeat(32),
    );
    let ok = |prev: &[&str], tenant: &str| {
        CacheKit::builder().encryption_with_previous(&current, prev, tenant)
    };

    assert!(
        ok(&[&k1, &k2, &k3], "t").is_ok(),
        "3 previous keys are allowed"
    );
    assert!(ok(&[], "t").is_ok(), "no previous keys is allowed");
    assert!(
        ok(&[&k1], &"t".repeat(255)).is_ok(),
        "a 255-byte tenant is allowed"
    );

    assert_builder_config_err_naming(ok(&[&k1, &k2, &k3, &k4], "t"), "keyring", "4 previous keys");
    assert_builder_config_err_naming(
        ok(&[&k1, &current], "t"),
        "keyring",
        "current key among previous",
    );
    assert_builder_config_err_naming(ok(&[&k1], ""), "tenant_id", "empty tenant");
    assert_builder_config_err_naming(ok(&[&k1], &"t".repeat(256)), "tenant_id", "256-byte tenant");

    for (bad, why) in [
        ("11".repeat(31), "31-byte previous key"),
        ("zz".repeat(32), "non-hex previous key"),
        ("1".repeat(65), "odd-length previous key"),
        (String::new(), "empty previous key"),
    ] {
        assert_builder_config_err_naming(ok(&[&k1, &bad], "t"), "previous master key 1", why);
    }
    for (bad, why) in [
        ("11".repeat(31), "31-byte current key"),
        ("zz".repeat(32), "non-hex current key"),
    ] {
        assert_builder_config_err_naming(
            CacheKit::builder().encryption_with_previous(&bad, &[&k1], "t"),
            "master key",
            why,
        );
    }
}

// ── Plain methods on an encrypted client ──────────────────────────────────────
//
// protocol spec/intent-presets.md § Encryption Activation, rule 1: an explicit
// encryption option encrypts every operation on the client, not only the
// `secure_cache()` handle.

type Configure = fn(cachekit::CacheKitBuilder) -> Result<cachekit::CacheKitBuilder, CachekitError>;

/// Every builder encryption spelling, each with the same key and tenant, so
/// one independently built layer decrypts whatever any of them stores.
const SPELLINGS: [(&str, Configure); 4] = [
    ("encryption", |b| {
        b.encryption(&test_master_key_hex(), "test-tenant")
    }),
    ("encryption_from_bytes", |b| {
        b.encryption_from_bytes(TEST_MASTER_KEY, "test-tenant")
    }),
    ("encryption_from_bytes_with_previous", |b| {
        b.encryption_from_bytes_with_previous(TEST_MASTER_KEY, &[&[0x11; 32]], "test-tenant")
    }),
    ("encryption_with_previous", |b| {
        b.encryption_with_previous(&test_master_key_hex(), &[&"11".repeat(32)], "test-tenant")
    }),
];

fn plain_client(configure: Configure, backend: SharedBackend, l1: bool) -> CacheKit {
    let builder = CacheKit::builder()
        .backend(backend)
        .default_ttl(Duration::from_secs(60));
    let builder = if l1 {
        builder.l1_capacity(100)
    } else {
        builder.no_l1()
    };
    configure(builder)
        .expect("encryption setup")
        .build()
        .expect("client builds")
}

fn plain_secret() -> Secret {
    Secret {
        api_key: "sk-live-PLAINPATH".to_owned(), // pragma: allowlist secret
        user_id: 7,
    }
}

/// The bytes the backend holds for `key` are the AES-GCM ciphertext of
/// `value`'s MessagePack: never the MessagePack itself, and decryptable by a
/// layer built apart from the client.
async fn assert_backend_holds_ciphertext_of<T: Serialize>(
    backend: &MockBackend,
    key: &str,
    value: &T,
    how: &str,
) {
    let stored = backend
        .store
        .lock()
        .await
        .get(key)
        .cloned()
        .unwrap_or_else(|| panic!("{how}: {key} never reached the backend"));
    let plaintext = cachekit::serializer::serialize(value).unwrap();
    assert_ne!(stored, plaintext, "{how}: {key} stored as plaintext");
    let decrypted = cachekit::EncryptionLayer::new(TEST_MASTER_KEY, "test-tenant")
        .unwrap()
        .decrypt(&stored, key)
        .unwrap_or_else(|e| panic!("{how}: {key} is not ciphertext under the key: {e}"));
    assert_eq!(decrypted, plaintext, "{how}: {key}");
}

#[tokio::test]
async fn plain_set_and_set_with_ttl_store_ciphertext() {
    let secret = plain_secret();
    for (how, configure) in SPELLINGS {
        let (shared, backend) = MockBackend::new_with_handle();
        let client = plain_client(configure, shared, false);
        client.set("plain:set", &secret).await.unwrap();
        client
            .set_with_ttl("plain:ttl", &secret, Duration::from_secs(30))
            .await
            .unwrap();
        assert_backend_holds_ciphertext_of(&backend, "plain:set", &secret, how).await;
        assert_backend_holds_ciphertext_of(&backend, "plain:ttl", &secret, how).await;
    }
}

#[tokio::test]
async fn plain_reads_decrypt_what_plain_writes_store() {
    let secret = plain_secret();
    for (how, configure) in SPELLINGS {
        let client = plain_client(configure, MockBackend::shared(), false);
        client.set("plain:rt", &secret).await.unwrap();
        assert_eq!(
            client.get::<Secret>("plain:rt").await.unwrap(),
            Some(secret.clone()),
            "{how}: get"
        );
        assert_eq!(
            client.interop_get::<Secret>("plain:rt").await.unwrap(),
            Some(secret.clone()),
            "{how}: interop_get"
        );
        assert_eq!(
            client.interop_get_swr::<Secret>("plain:rt").await.unwrap(),
            cachekit::SwrRead::Fresh(secret.clone()),
            "{how}: interop_get_swr"
        );

        // One format: the secure_cache() handle and the plain methods read
        // each other's entries.
        let secure = client.secure_cache().unwrap();
        assert_eq!(
            secure.get::<Secret>("plain:rt").await.unwrap(),
            Some(secret.clone()),
            "{how}: handle reads a plain write"
        );
        secure.set("secure:rt", &secret).await.unwrap();
        assert_eq!(
            client.get::<Secret>("secure:rt").await.unwrap(),
            Some(secret.clone()),
            "{how}: plain get reads a handle write"
        );
    }
}

/// L1 is not visible from here, so read it through the handle, which always
/// decrypts: with the backend entry gone, an L1 hit that decrypts proves L1
/// holds ciphertext (the crate-internal `secure_tests` compare the bytes).
#[tokio::test]
async fn plain_writes_keep_ciphertext_in_l1() {
    let secret = plain_secret();
    for (how, configure) in SPELLINGS {
        let (shared, backend) = MockBackend::new_with_handle();
        let client = plain_client(configure, shared, true);
        client.set("plain:l1", &secret).await.unwrap();
        backend.store.lock().await.clear();

        let secure = client.secure_cache().unwrap();
        assert_eq!(
            secure.get::<Secret>("plain:l1").await.unwrap(),
            Some(secret.clone()),
            "{how}"
        );
        assert_eq!(client.stats().l1_hits, 1, "{how}: served from L1");
    }
}

/// An entry written in the clear (by an unencrypted client, or by plain
/// `set` on an encrypted client before plain writes encrypted) fails closed
/// on an encrypted client's plain reads, until it is overwritten or expires.
#[tokio::test]
async fn plain_reads_reject_a_plaintext_entry() {
    let (shared, _backend) = MockBackend::new_with_handle();
    CacheKit::builder()
        .backend(shared.clone())
        .no_l1()
        .build()
        .unwrap()
        .set("legacy", &"in the clear")
        .await
        .unwrap();

    let client = make_encrypted_client(shared);
    let err = client.get::<String>("legacy").await.unwrap_err();
    assert!(matches!(err, CachekitError::Encryption(_)), "got: {err:?}");
    let err = client.interop_get::<String>("legacy").await.unwrap_err();
    assert!(matches!(err, CachekitError::Encryption(_)), "got: {err:?}");
    let err = client
        .interop_get_swr::<String>("legacy")
        .await
        .unwrap_err();
    assert!(matches!(err, CachekitError::Encryption(_)), "got: {err:?}");

    client.set("legacy", &"sealed").await.unwrap();
    assert_eq!(
        client.get::<String>("legacy").await.unwrap().as_deref(),
        Some("sealed")
    );
}

/// A decode failure after a successful decrypt names only the target type:
/// serde's own message quotes the decrypted value (CWE-532) — here
/// `invalid type: string "sk-live-…", expected struct Secret`. The error stays
/// `Serialization`, which `#[cachekit]` reads as a miss.
#[tokio::test]
async fn decode_error_after_decrypt_does_not_quote_the_value() {
    let client = make_encrypted_client(MockBackend::shared());
    client.set("typed", &"sk-live-REDACTME").await.unwrap(); // pragma: allowlist secret
    let secure = client.secure_cache().unwrap();
    for (how, result) in [
        ("get", client.get::<Secret>("typed").await.map(drop)),
        (
            "interop_get",
            client.interop_get::<Secret>("typed").await.map(drop),
        ),
        (
            "interop_get_swr",
            client.interop_get_swr::<Secret>("typed").await.map(drop),
        ),
        ("handle get", secure.get::<Secret>("typed").await.map(drop)),
    ] {
        match result {
            Err(CachekitError::Serialization(msg)) => {
                assert!(!msg.contains("REDACTME"), "{how} quotes the value: {msg}");
                assert!(
                    msg.contains("Secret"),
                    "{how} must name the target type: {msg}"
                );
            }
            other => panic!("{how}: expected a Serialization error, got {other:?}"),
        }
    }
}

/// After a decrypt the reader's container is exactly one MessagePack document
/// (spec/encryption.md): a plaintext sealed under the reader's own AAD with one
/// trailing byte is a parse mismatch, never the value before it. Only the
/// variant is asserted, because `redact_decode` rewrites the message.
#[tokio::test]
async fn secure_get_rejects_a_decrypted_plaintext_with_trailing_bytes() {
    let (backend, handle) = MockBackend::new_with_handle();
    let client = make_encrypted_client(backend);
    let mut plaintext = cachekit::serializer::serialize(&7u8).unwrap();
    plaintext.push(0x00);
    let sealed = cachekit::EncryptionLayer::new(TEST_MASTER_KEY, "test-tenant")
        .unwrap()
        .encrypt(&plaintext, "trailing")
        .unwrap();
    handle
        .store
        .lock()
        .await
        .insert("trailing".to_owned(), sealed);

    let secure = client.secure_cache().unwrap();
    let err = secure.get::<u8>("trailing").await.unwrap_err();
    assert!(
        matches!(err, CachekitError::Serialization(_)),
        "got: {err:?}"
    );
}

// ── Master-key length (spec/intent-presets.md § Master Key Input) ─────────────

#[track_caller]
fn assert_builder_config_err(result: Result<cachekit::CacheKitBuilder, CachekitError>, what: &str) {
    assert_builder_config_err_naming(result, "", what);
}

/// Rule 4: a raw-bytes entry point takes exactly 32 bytes.
#[test]
fn encryption_from_bytes_requires_exactly_32_bytes() {
    for len in [31, 33] {
        assert_builder_config_err(
            CacheKit::builder().encryption_from_bytes(&vec![7u8; len], "t"),
            &format!("{len}-byte key"),
        );
    }
    assert!(CacheKit::builder()
        .encryption_from_bytes(&[7u8; 32], "t")
        .is_ok());
}

/// The ASCII bytes of a 64-char hex string pass a `>= 32` check and derive a
/// silently different key — they must be rejected, not accepted.
#[test]
fn encryption_from_bytes_rejects_ascii_hex() {
    let hex = "ab".repeat(32);
    assert_builder_config_err(
        CacheKit::builder().encryption_from_bytes(hex.as_bytes(), "t"),
        "ASCII hex as raw bytes",
    );
}

#[test]
fn encryption_from_bytes_with_previous_requires_exactly_32_bytes() {
    const K1: &[u8] = &[0x11; 32];
    const K2: &[u8] = &[0x22; 32];
    for len in [31, 33] {
        let bad = vec![7u8; len];
        assert_builder_config_err(
            CacheKit::builder().encryption_from_bytes_with_previous(&bad, &[K1], "t"),
            &format!("{len}-byte current key"),
        );
        assert_builder_config_err(
            CacheKit::builder().encryption_from_bytes_with_previous(K2, &[&bad], "t"),
            &format!("{len}-byte previous key"),
        );
    }
    assert!(CacheKit::builder()
        .encryption_from_bytes_with_previous(K2, &[K1], "t")
        .is_ok());
}

/// Rule 3: the hex path accepts any key decoding to >= 32 bytes.
#[test]
fn encryption_hex_accepts_32_and_48_byte_keys() {
    for bytes in [32, 48] {
        assert!(
            CacheKit::builder()
                .encryption(&"ab".repeat(bytes), "t")
                .is_ok(),
            "{bytes}-byte hex key must be accepted"
        );
    }
}

// ── Env-sourced keys (protocol intent-presets.md § Encryption Activation) ────

/// The `from_env()` environment with the given key variables.
#[cfg(feature = "cachekitio")]
fn key_env(master: Option<&str>, previous: Option<&str>) -> common::EnvGuard {
    common::EnvGuard::set(&[
        ("CACHEKIT_API_KEY", Some("test-key")),
        ("CACHEKIT_API_URL", None),
        ("CACHEKIT_MASTER_KEY", master),
        ("CACHEKIT_PREVIOUS_MASTER_KEYS", previous),
    ])
}

#[cfg(feature = "cachekitio")]
#[test]
#[serial_test::serial]
fn encryption_from_env_accepts_32_and_48_byte_hex_keys() {
    for bytes in [32, 48] {
        let (current, previous) = ("22".repeat(bytes), "11".repeat(bytes));
        let _env = key_env(Some(&current), Some(&previous));
        let builder = CacheKit::from_env()
            .and_then(|b| b.encryption_from_env())
            .unwrap_or_else(|e| panic!("{bytes}-byte hex keys must be accepted: {e}"));
        assert!(builder.build().unwrap().secure_cache().is_ok());
    }
}

/// Write `"plain value"` under `k` through `builder` on a fresh store and
/// return the bytes the backend holds.
#[cfg(feature = "cachekitio")]
fn stored_bytes(builder: cachekit::CacheKitBuilder) -> Option<Vec<u8>> {
    let (backend, handle) = MockBackend::new_with_handle();
    let cache = builder
        .backend(backend)
        .no_l1()
        .build()
        .expect("client builds");
    assert!(
        cache.secure_cache().is_err(),
        "no encryption layer expected"
    );
    common::runtime()
        .block_on(cache.set("k", &"plain value"))
        .expect("set");
    let stored = handle.store.try_lock().unwrap().get("k").cloned();
    stored
}

/// Rule 2: a set `CACHEKIT_MASTER_KEY` is a key source, never a switch —
/// with the opt-out stated, the backend holds the value's plain MessagePack
/// bytes.
#[cfg(feature = "cachekitio")]
#[test]
#[serial_test::serial]
fn from_env_with_a_master_key_and_no_encryption_stores_plaintext() {
    let (current, previous) = ("22".repeat(32), "11".repeat(32));
    let _env = key_env(Some(&current), Some(&previous));
    let builder = CacheKit::from_env().expect("a valid key must not stop from_env");
    assert_eq!(
        stored_bytes(builder.no_encryption()),
        Some(cachekit::serializer::serialize(&"plain value").unwrap()),
        "from_env() must not encrypt because CACHEKIT_MASTER_KEY is set"
    );
}

/// The transitional gate: a `from_env()` builder that saw the key and
/// states no intent refuses to build, naming both spellings, so a deployment
/// that relied on the old activation cannot silently start writing
/// plaintext. Without the key there is nothing to state.
#[cfg(feature = "cachekitio")]
#[test]
#[serial_test::serial]
fn from_env_with_a_master_key_and_no_stated_intent_does_not_build() {
    let current = "22".repeat(32);
    let _env = key_env(Some(&current), None);
    match CacheKit::from_env().and_then(|b| b.build()) {
        Err(CachekitError::Config(msg)) => assert!(
            msg.contains(".encryption_from_env()") && msg.contains(".no_encryption()"),
            "the error must name both spellings: {msg}"
        ),
        Err(e) => panic!("expected a Config error, got {e:?}"),
        Ok(_) => panic!("from_env() with a key built without a stated intent"),
    }

    let _no_key = key_env(None, None);
    assert_eq!(
        stored_bytes(CacheKit::from_env().expect("from_env")),
        Some(cachekit::serializer::serialize(&"plain value").unwrap()),
    );
}

/// An opt-out never quietly undoes an encryption call, in either order.
#[test]
fn no_encryption_with_an_encryption_call_is_a_config_error() {
    let key = test_master_key_hex();
    for builder in [
        CacheKit::builder()
            .encryption(&key, "t")
            .unwrap()
            .no_encryption(),
        CacheKit::builder()
            .no_encryption()
            .encryption(&key, "t")
            .unwrap(),
    ] {
        let result = builder.backend(MockBackend::shared()).build();
        assert!(
            matches!(&result, Err(CachekitError::Config(msg)) if msg.contains(".no_encryption()")),
            "expected a Config error naming .no_encryption(), got {:?}",
            result.err()
        );
    }
}

/// A set, non-UTF-8 key is reported as such, never as unset.
#[cfg(unix)]
#[test]
#[serial_test::serial]
fn encryption_from_env_rejects_a_non_utf8_key_naming_it() {
    use std::os::unix::ffi::OsStrExt;

    let _env = common::EnvGuard::set(&[
        ("CACHEKIT_MASTER_KEY", None),
        ("CACHEKIT_PREVIOUS_MASTER_KEYS", None),
    ]);
    std::env::set_var(
        "CACHEKIT_MASTER_KEY",
        std::ffi::OsStr::from_bytes(&[0xff; 32]),
    );
    match CacheKit::builder().encryption_from_env() {
        Err(CachekitError::Config(msg)) => assert!(msg.contains("not valid UTF-8"), "{msg}"),
        Err(e) => panic!("expected a Config error, got {e:?}"),
        Ok(_) => panic!("a non-UTF-8 key was accepted"),
    }
}

/// `.encryption_from_env()` encrypts under `CACHEKIT_MASTER_KEY` for tenant
/// `"default"` and decrypts with `CACHEKIT_PREVIOUS_MASTER_KEYS` — checked
/// against clients given the same keys explicitly.
#[cfg(feature = "cachekitio")]
#[test]
#[serial_test::serial]
fn encryption_from_env_uses_the_env_keys() {
    let (current, previous) = ("22".repeat(32), "11".repeat(32));
    let _env = key_env(Some(&current), Some(&previous));
    let (backend, handle) = MockBackend::new_with_handle();
    let explicit = |hex: &str| {
        CacheKit::builder()
            .backend(backend.clone())
            .no_l1()
            .encryption(hex, "default")
            .and_then(|b| b.build())
            .expect("explicit client builds")
    };
    let cache = CacheKit::from_env()
        .and_then(|b| b.encryption_from_env())
        .expect("env keys are valid")
        .backend(backend.clone())
        .no_l1()
        .build()
        .expect("client builds");
    let rt = common::runtime();

    rt.block_on(cache.set("k", &"secret")).expect("set");
    let stored = handle.store.try_lock().unwrap().get("k").cloned().unwrap();
    assert_ne!(stored, cachekit::serializer::serialize(&"secret").unwrap());
    let read: Option<String> = rt.block_on(explicit(&current).get("k")).expect("get");
    assert_eq!(
        read.as_deref(),
        Some("secret"),
        "written under the current key"
    );

    rt.block_on(explicit(&previous).set("old", &"rotated"))
        .expect("set");
    let read: Option<String> = rt.block_on(cache.get("old")).expect("get");
    assert_eq!(read.as_deref(), Some("rotated"), "previous key decrypts");
}

/// Asked to encrypt with no key anywhere, the builder errors — never a
/// plaintext client.
#[cfg(feature = "cachekitio")]
#[test]
#[serial_test::serial]
fn encryption_from_env_without_a_key_is_a_config_error() {
    for (master, says) in [(None, "unset"), (Some(""), "empty")] {
        let _env = key_env(master, None);
        for (entry, result) in [
            ("builder", CacheKit::builder().encryption_from_env()),
            (
                "from_env",
                CacheKit::from_env().and_then(|b| b.encryption_from_env()),
            ),
        ] {
            match result {
                Err(CachekitError::Config(msg)) => assert!(
                    msg.contains("CACHEKIT_MASTER_KEY") && msg.contains(says),
                    "{entry} {master:?}: {msg}"
                ),
                Err(e) => panic!("{entry} {master:?}: expected a Config error, got {e:?}"),
                Ok(_) => panic!("{entry} {master:?}: encryption accepted with no key"),
            }
        }
    }
}