cachekit-rs 0.13.1

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
//! Master key input rows from the shared protocol vectors, driven through
//! every public hex and raw-bytes key entry point, and the
//! `keyring.configuration` rows, driven through every hex keyring loader.
//!
//! Vectors: `tests/vectors/encryption.json`, vendored verbatim from
//! cachekit-io/protocol test-vectors/encryption.json 1.5.0 at `main@b4ae567a`
//! (<https://github.com/cachekit-io/protocol/pull/180> and
//! <https://github.com/cachekit-io/protocol/pull/181>)
//! (sha256 `1a8a3735408675bf9660ce1372f77723a9ffda8084010fa52eb756a330961589`).
//! Do not edit the JSON here; regenerate upstream and re-vendor.
//!
//! Every reject must be a `Config` error from the key validator, not merely
//! an `Err`: `CacheKit::secure` would also fail on the Redis connect a
//! wrongly accepted key reaches. `OTHER_KEY_HEX` fills the slot a row does not,
//! so the repeat-key check cannot fire in the decoder's place. The accepting
//! controls show no entry point passes by refusing everything.
//!
//! The accept rows' decrypts through the `secure` preset and the rotation read
//! live in `src/intents.rs` (`secure_tests`): they need the crate-internal
//! preset route, as default CI has no Redis.
//!
//! Run with:
//!   cargo test --test master_key_input_tests --features redis,encryption

#![cfg(feature = "encryption")]

mod common;

use cachekit::config::CachekitConfigBuilder;
use cachekit::{CacheKit, CachekitConfig, CachekitError, EncryptionLayer};
use common::EnvGuard;
use serde_json::Value as Json;
use serial_test::serial;

const VECTORS_JSON: &str = include_str!("vectors/encryption.json");

/// sha256 of the vendored file, pinned so a local edit cannot drift from the
/// protocol copy unnoticed.
const VECTORS_SHA256: &str = "1a8a3735408675bf9660ce1372f77723a9ffda8084010fa52eb756a330961589"; // pragma: allowlist secret

/// A valid 32-byte key that no row decodes to (`default_tenant_interop`'s), for
/// the slot a row does not fill, so a previous-key row is never refused as a
/// repeat of the current key.
const OTHER_KEY_HEX: &str = "6161616161616161616161616161616161616161616161616161616161616161"; // pragma: allowlist secret

const TENANT: &str = "default";

#[test]
fn vendored_fixture_matches_the_pinned_sha256() {
    use sha2::{Digest, Sha256};
    assert_eq!(
        hex::encode(Sha256::digest(VECTORS_JSON.as_bytes())),
        VECTORS_SHA256,
        "tests/vectors/encryption.json differs from the pinned protocol copy: \
         re-vendor it from protocol and update VECTORS_SHA256"
    );
}

fn block() -> Json {
    let all: Json =
        serde_json::from_str(VECTORS_JSON).expect("vendored vector file must be valid JSON");
    all["master_key_input"].clone()
}

/// `(name, field)` of every row in `group`, the count asserted exactly so a
/// silently skipped row fails loudly.
fn rows(group: &str, field: &str, count: usize) -> Vec<(String, String)> {
    let rows: Vec<(String, String)> = block()[group]
        .as_array()
        .unwrap_or_else(|| panic!("{group} must be an array"))
        .iter()
        .map(|row| {
            let get = |k: &str| {
                row[k]
                    .as_str()
                    .unwrap_or_else(|| panic!("{group} row lacks {k}"))
                    .to_owned()
            };
            (get("name"), get(field))
        })
        .collect();
    assert_eq!(rows.len(), count, "{group} row count");
    rows
}

fn accept_rows() -> Vec<(String, String)> {
    rows("accept_vectors", "master_key_hex", 2)
}

fn reject_rows() -> Vec<(String, String)> {
    rows("reject_vectors", "master_key_hex", 11)
}

fn raw_reject_rows() -> Vec<(String, Vec<u8>)> {
    rows("raw_reject_vectors", "raw_key_hex", 5)
        .into_iter()
        .map(|(name, h)| (name, hex::decode(h).expect("raw_key_hex is hex")))
        .collect()
}

#[track_caller]
fn assert_config_err<T>(result: Result<T, CachekitError>, names: &str, row: &str, entry: &str) {
    match result {
        Err(CachekitError::Config(msg)) if msg.contains(names) => {}
        Err(e) => panic!("{row} via {entry}: want a Config error naming {names:?}, got {e:?}"),
        Ok(_) => panic!("{row} via {entry}: accepted a key protocol requires refused"),
    }
}

// ── Hex entry points ─────────────────────────────────────────────────────────

#[test]
fn builder_encryption_rejects_every_hex_reject_row() {
    for (row, key) in accept_rows() {
        assert!(
            CacheKit::builder().encryption(&key, TENANT).is_ok(),
            "{row} refused"
        );
    }
    for (row, key) in reject_rows() {
        assert_config_err(
            CacheKit::builder().encryption(&key, TENANT),
            "master key",
            &row,
            "CacheKitBuilder::encryption",
        );
    }
}

#[test]
fn builder_encryption_with_previous_rejects_every_hex_reject_row() {
    for (row, accept) in accept_rows() {
        assert!(
            CacheKit::builder()
                .encryption_with_previous(&accept, &[OTHER_KEY_HEX], TENANT)
                .is_ok(),
            "{row} refused as the current key"
        );
        assert!(
            CacheKit::builder()
                .encryption_with_previous(OTHER_KEY_HEX, &[&accept], TENANT)
                .is_ok(),
            "{row} refused as a previous key"
        );
    }
    for (row, key) in reject_rows() {
        assert_config_err(
            CacheKit::builder().encryption_with_previous(&key, &[OTHER_KEY_HEX], TENANT),
            "master key",
            &row,
            "CacheKitBuilder::encryption_with_previous (current)",
        );
        assert_config_err(
            CacheKit::builder().encryption_with_previous(OTHER_KEY_HEX, &[&key], TENANT),
            "previous master key 0",
            &row,
            "CacheKitBuilder::encryption_with_previous (previous)",
        );
    }
}

#[test]
fn config_builder_rejects_every_hex_reject_row() {
    for (row, accept) in accept_rows() {
        assert!(
            CachekitConfigBuilder::new()
                .master_key(&accept)
                .and_then(|b| b.previous_master_keys(&[OTHER_KEY_HEX]))
                .is_ok(),
            "{row} refused as the current key"
        );
        assert!(
            CachekitConfigBuilder::new()
                .master_key(OTHER_KEY_HEX)
                .and_then(|b| b.previous_master_keys(&[&accept]))
                .is_ok(),
            "{row} refused as a previous key"
        );
    }
    for (row, key) in reject_rows() {
        assert_config_err(
            CachekitConfigBuilder::new().master_key(&key),
            "master_key",
            &row,
            "CachekitConfigBuilder::master_key",
        );
        assert_config_err(
            CachekitConfigBuilder::new()
                .master_key(OTHER_KEY_HEX)
                .and_then(|b| b.previous_master_keys(&[&key])),
            "previous_master_keys",
            &row,
            "CachekitConfigBuilder::previous_master_keys",
        );
    }
}

/// Every env reader — `CachekitConfig::from_env`, the client constructor
/// `CacheKit::from_env` built on it, and the builder's
/// `.encryption_from_env()` — under the given key variables. A valid API key
/// is set so the client constructor can only fail on a key.
fn env_entry_points(
    master: &str,
    previous: Option<&str>,
) -> Vec<(&'static str, Result<(), CachekitError>)> {
    let _env = EnvGuard::set(&[
        ("CACHEKIT_MASTER_KEY", Some(master)),
        ("CACHEKIT_PREVIOUS_MASTER_KEYS", previous),
        ("CACHEKIT_API_KEY", Some("ck_test_key")),
        ("CACHEKIT_API_URL", None),
    ]);
    vec![
        (
            "CachekitConfig::from_env",
            CachekitConfig::from_env().map(drop),
        ),
        #[cfg(feature = "cachekitio")]
        ("CacheKit::from_env", CacheKit::from_env().map(drop)),
        (
            "CacheKitBuilder::encryption_from_env",
            CacheKit::builder().encryption_from_env().map(drop),
        ),
    ]
}

#[test]
#[serial]
fn env_readers_reject_every_hex_reject_row() {
    for (row, accept) in accept_rows() {
        for (entry, result) in env_entry_points(&accept, Some(OTHER_KEY_HEX))
            .into_iter()
            .chain(env_entry_points(OTHER_KEY_HEX, Some(&accept)))
        {
            assert!(result.is_ok(), "{entry} refused {row}'s key: {result:?}");
        }
    }
    for (row, key) in reject_rows() {
        for (entry, result) in env_entry_points(&key, None) {
            assert_config_err(result, "CACHEKIT_MASTER_KEY", &row, entry);
        }
        for (entry, result) in env_entry_points(OTHER_KEY_HEX, Some(&key)) {
            assert_config_err(
                result,
                "CACHEKIT_PREVIOUS_MASTER_KEYS",
                &row,
                &format!("{entry} (previous keys)"),
            );
        }
    }
}

// ── Keyring configuration ────────────────────────────────────────────────────

/// One `keyring.configuration` row: its name, current key, decrypt-only keys
/// and whether a conforming SDK accepts it at load.
struct KeyringRow {
    name: String,
    current: String,
    decrypt_only: Vec<String>,
    accept: bool,
}

fn keyring_rows() -> Vec<KeyringRow> {
    let all: Json =
        serde_json::from_str(VECTORS_JSON).expect("vendored vector file must be valid JSON");
    let rows: Vec<KeyringRow> = all["keyring"]["configuration"]["vectors"]
        .as_array()
        .expect("keyring.configuration.vectors must be an array")
        .iter()
        .map(|row| {
            let name = row["name"].as_str().expect("name").to_owned();
            let text = |v: &Json| {
                v.as_str()
                    .unwrap_or_else(|| panic!("{name}: hex"))
                    .to_owned()
            };
            KeyringRow {
                current: text(&row["current_master_key_hex"]),
                decrypt_only: row["decrypt_only_master_keys_hex"]
                    .as_array()
                    .unwrap_or_else(|| panic!("{name}: decrypt_only_master_keys_hex"))
                    .iter()
                    .map(text)
                    .collect(),
                accept: match row["verdict"].as_str() {
                    Some("accept") => true,
                    Some("reject") => false,
                    other => panic!("{name}: verdict {other:?}"),
                },
                name,
            }
        })
        .collect();
    assert_eq!(rows.len(), 4, "keyring.configuration row count");
    rows
}

/// Each row loads, or is refused with a `Config` error, as its verdict says,
/// through the hex builders and through `CACHEKIT_PREVIOUS_MASTER_KEYS`
/// (comma-separated) on every env reader.
#[test]
#[serial]
fn keyring_configuration_rows_load_as_their_verdict_says() {
    for row in keyring_rows() {
        let decrypt_only: Vec<&str> = row.decrypt_only.iter().map(String::as_str).collect();
        let mut loads = vec![
            (
                "CacheKitBuilder::encryption_with_previous".to_owned(),
                CacheKit::builder()
                    .encryption_with_previous(&row.current, &decrypt_only, TENANT)
                    .map(drop),
            ),
            (
                "CachekitConfigBuilder::previous_master_keys".to_owned(),
                CachekitConfigBuilder::new()
                    .master_key(&row.current)
                    .and_then(|b| b.previous_master_keys(&decrypt_only))
                    .map(drop),
            ),
        ];
        loads.extend(
            env_entry_points(&row.current, Some(&decrypt_only.join(",")))
                .into_iter()
                .map(|(entry, result)| {
                    (format!("{entry} (CACHEKIT_PREVIOUS_MASTER_KEYS)"), result)
                }),
        );
        for (entry, result) in loads {
            match (row.accept, result) {
                (true, Ok(())) | (false, Err(CachekitError::Config(_))) => {}
                (true, Err(e)) => panic!("{} via {entry}: refused an accept row: {e:?}", row.name),
                (false, other) => panic!(
                    "{} via {entry}: want a Config error at load, got {other:?}",
                    row.name
                ),
            }
        }
    }
}

/// Port 1 refuses at once, so a wrongly accepted key ends in a connect error,
/// which `assert_config_err` reports, rather than a hang.
#[cfg(feature = "redis")]
const UNREACHABLE_REDIS: &str = "redis://127.0.0.1:1";

#[cfg(feature = "redis")]
#[tokio::test]
async fn secure_rejects_every_hex_reject_row() {
    for (row, key) in reject_rows() {
        assert_config_err(
            CacheKit::secure(UNREACHABLE_REDIS, &key).await,
            "master_key_hex",
            &row,
            "CacheKit::secure",
        );
    }
}

#[cfg(feature = "redis")]
#[tokio::test]
#[serial]
async fn secure_from_env_rejects_every_hex_reject_row() {
    for (row, key) in reject_rows() {
        let current = {
            let _env = EnvGuard::set(&[
                ("CACHEKIT_MASTER_KEY", Some(&key)),
                ("CACHEKIT_PREVIOUS_MASTER_KEYS", None),
            ]);
            CacheKit::secure_from_env(UNREACHABLE_REDIS).await
        };
        assert_config_err(
            current,
            "CACHEKIT_MASTER_KEY",
            &row,
            "CacheKit::secure_from_env",
        );
        let previous = {
            let _env = EnvGuard::set(&[
                ("CACHEKIT_MASTER_KEY", Some(OTHER_KEY_HEX)),
                ("CACHEKIT_PREVIOUS_MASTER_KEYS", Some(&key)),
            ]);
            CacheKit::secure_from_env(UNREACHABLE_REDIS).await
        };
        assert_config_err(
            previous,
            "CACHEKIT_PREVIOUS_MASTER_KEYS",
            &row,
            "CacheKit::secure_from_env (previous keys)",
        );
    }
}

// ── Raw-bytes entry points ───────────────────────────────────────────────────

const RAW_LEN_ERR: &str = "exactly 32 bytes";

/// Every raw-bytes entry point, with `key` in each slot it can fill and the
/// valid `OTHER_KEY_HEX` bytes in the other.
fn raw_entry_points(key: &[u8]) -> [(&'static str, Result<(), CachekitError>); 6] {
    let other = hex::decode(OTHER_KEY_HEX).expect("hex");
    [
        (
            "CacheKitBuilder::encryption_from_bytes",
            CacheKit::builder()
                .encryption_from_bytes(key, TENANT)
                .map(drop),
        ),
        (
            "CacheKitBuilder::encryption_from_bytes_with_previous (current)",
            CacheKit::builder()
                .encryption_from_bytes_with_previous(key, &[&other], TENANT)
                .map(drop),
        ),
        (
            "CacheKitBuilder::encryption_from_bytes_with_previous (previous)",
            CacheKit::builder()
                .encryption_from_bytes_with_previous(&other, &[key], TENANT)
                .map(drop),
        ),
        (
            "EncryptionLayer::new",
            EncryptionLayer::new(key, TENANT).map(drop),
        ),
        (
            "EncryptionLayer::with_previous_keys (current)",
            EncryptionLayer::with_previous_keys(key, &[&other], TENANT).map(drop),
        ),
        (
            "EncryptionLayer::with_previous_keys (previous)",
            EncryptionLayer::with_previous_keys(&other, &[key], TENANT).map(drop),
        ),
    ]
}

#[test]
fn raw_entry_points_accept_the_accept_rows_bytes() {
    for (row, key) in accept_rows() {
        let accept = hex::decode(key).expect("accept row is hex");
        for (entry, result) in raw_entry_points(&accept) {
            assert!(result.is_ok(), "{row} refused via {entry}: {result:?}");
        }
    }
}

#[test]
fn raw_entry_points_reject_every_raw_reject_row() {
    for (row, key) in raw_reject_rows() {
        for (entry, result) in raw_entry_points(&key) {
            assert_config_err(result, RAW_LEN_ERR, &row, entry);
        }
    }
}