revault_lockbox_api 0.0.4

reVault lockbox API to create and manage lockboxes
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
mod common;

use common::{
    add_file, add_file_from_path, add_file_from_reader, add_file_with_permissions, add_symlink, p,
    password, public_api_unique_dir as unique_dir, signing_key, variable,
};
use revault_lockbox_api::{
    ContactKeyPair, ContactPublicKey, ContactWrappedKey, ExtractPolicy, ListOptions, Lockbox,
    LockboxId, LockboxKeySlotAlgorithm, LockboxKeySlotProtection, LockboxOpen, LockboxProtection,
    RecoveryReportOptions, RecoveryScanner, SecretString, SecretVec, VariableValueRef,
    WorkloadProfile,
};
use std::io::Cursor;

const KEY: &[u8] = b"public api suite key";

#[test]
fn public_api_files_listing_variables_symlink_and_rename_flow() {
    let root = unique_dir("files");
    let lockbox_path = root.join("files.lbox");
    let _ = std::fs::remove_dir_all(&root);
    std::fs::create_dir_all(&root).unwrap();

    let mut lb = Lockbox::create_file(
        &lockbox_path,
        LockboxProtection::ContentKey(SecretVec::try_from_slice(KEY).unwrap()),
        &signing_key(),
    )
    .unwrap();
    add_file_with_permissions(
        &mut lb,
        &p("/app/config.json"),
        br#"{"mode":"test"}"#,
        0o640,
        false,
    )
    .unwrap();
    add_file_from_reader(
        &mut lb,
        &p("/app/logs/today.txt"),
        Cursor::new(b"hello from a reader"),
        false,
    )
    .unwrap();
    add_symlink(
        &mut lb,
        &p("/app/latest.log"),
        &p("/app/logs/today.txt"),
        false,
    )
    .unwrap();
    lb.set_variable(&variable("DATABASE_URL"), "postgres://localhost/app")
        .unwrap();
    lb.set_variable(&variable("API_TOKEN"), "secret-token")
        .unwrap();
    lb.create_dir(&p("/srv"), false).unwrap();
    lb.rename(&p("/app"), &p("/srv/app")).unwrap();
    lb.commit().unwrap();

    let reopened = Lockbox::open(
        &lockbox_path,
        LockboxOpen::ContentKey(SecretVec::try_from_slice(KEY).unwrap()),
    )
    .unwrap();
    assert_eq!(
        reopened.get_file(&p("/srv/app/config.json")).unwrap(),
        br#"{"mode":"test"}"#
    );
    assert_eq!(
        reopened
            .read_file_range(&p("/srv/app/logs/today.txt"), 6, 4)
            .unwrap(),
        b"from"
    );
    assert_eq!(
        reopened.permissions(&p("/srv/app/config.json")),
        Some(0o640)
    );
    assert!(reopened.is_symlink(&p("/srv/app/latest.log")));
    assert_eq!(
        reopened
            .get_symlink_target(&p("/srv/app/latest.log"))
            .unwrap(),
        "/app/logs/today.txt"
    );

    let entries = reopened
        .list(ListOptions {
            path: p("/srv"),
            glob: Some("**/*.txt".to_string()),
            recursive: true,
            include_files: true,
            include_symlinks: false,
            include_directories: true,
            limit: None,
        })
        .unwrap()
        .collect::<Result<Vec<_>, _>>()
        .unwrap();
    assert_eq!(entries.len(), 1);
    assert_eq!(entries[0].path, "/srv/app/logs/today.txt");

    let mut variables = std::collections::BTreeMap::new();
    reopened
        .visit_variables(|name, value| {
            let VariableValueRef::Normal(value) = value else {
                panic!("fixture stores normal variable values");
            };
            variables.insert(
                name.to_string(),
                (
                    value.to_string(),
                    revault_lockbox_api::VariableSensitivity::Normal,
                ),
            );
            Ok(())
        })
        .unwrap();
    assert_eq!(
        variables
            .get("/DATABASE_URL")
            .map(|(value, sensitivity)| (value.as_str(), *sensitivity)),
        Some((
            "postgres://localhost/app",
            revault_lockbox_api::VariableSensitivity::Normal
        ))
    );
    assert_eq!(
        variables
            .get("/API_TOKEN")
            .map(|(value, sensitivity)| (value.as_str(), *sensitivity)),
        Some((
            "secret-token",
            revault_lockbox_api::VariableSensitivity::Normal
        ))
    );
    assert!(reopened
        .list(ListOptions::new(&p("/srv")))
        .unwrap()
        .all(|entry| {
            let entry = entry.unwrap();
            !entry.path.contains("DATABASE_URL") && !entry.path.contains("API_TOKEN")
        }));

    let all_entries = reopened
        .list(ListOptions {
            path: p("/srv"),
            glob: None,
            recursive: true,
            include_files: true,
            include_symlinks: true,
            include_directories: true,
            limit: None,
        })
        .unwrap()
        .collect::<Result<Vec<_>, _>>()
        .unwrap();
    assert!(all_entries
        .iter()
        .any(|entry| { entry.path == "/srv/app/config.json" && entry.permissions == 0o640 }));
    assert!(all_entries
        .iter()
        .any(|entry| { entry.path == "/srv/app/latest.log" }));

    let mut streamed = Vec::new();
    reopened
        .extract_file_to_writer(&p("/srv/app/config.json"), &mut streamed)
        .unwrap();
    assert_eq!(streamed, br#"{"mode":"test"}"#);

    let _ = std::fs::remove_dir_all(root);
}

#[test]
fn public_api_password_and_contact_key_management_flow() {
    let root = unique_dir("keys");
    let lockbox_path = root.join("shared.lbox");
    let _ = std::fs::remove_dir_all(&root);
    std::fs::create_dir_all(&root).unwrap();

    let contact = ContactKeyPair::generate().unwrap();
    let old_password = password("old-password");
    let new_password = password("new-password");
    let signing_key = signing_key();
    let mut lb = Lockbox::create_file(
        &lockbox_path,
        LockboxProtection::Password(&old_password),
        &signing_key,
    )
    .unwrap();
    let password_slot = lb.list_key_slots()[0].id;
    let contact_slot = lb.add_contact(&contact.public_key()).unwrap();
    let slots = lb.list_key_slots();
    assert!(slots.iter().any(|slot| {
        slot.id == password_slot
            && slot.protection == LockboxKeySlotProtection::Password
            && slot.algorithm == LockboxKeySlotAlgorithm::Argon2idChaCha20Poly1305
    }));
    assert!(slots.iter().any(|slot| {
        slot.id == contact_slot
            && slot.protection == LockboxKeySlotProtection::Contact
            && slot.algorithm == LockboxKeySlotAlgorithm::X25519MlKem768ChaCha20Poly1305
    }));

    lb.add_file(&p("/secret.txt"), b"shared", false).unwrap();
    lb.commit().unwrap();
    drop(lb);

    assert_eq!(
        Lockbox::open(&lockbox_path, LockboxOpen::Password(&old_password))
            .unwrap()
            .get_file(&p("/secret.txt"))
            .unwrap(),
        b"shared"
    );
    assert_eq!(
        Lockbox::open(&lockbox_path, LockboxOpen::ContactKeyPair(contact))
            .unwrap()
            .get_file(&p("/secret.txt"))
            .unwrap(),
        b"shared"
    );

    let mut reopened = Lockbox::open_for_write(
        &lockbox_path,
        LockboxOpen::Password(&old_password),
        &signing_key,
    )
    .unwrap();
    let new_slot = reopened
        .replace_password(&old_password, &new_password)
        .unwrap();
    reopened.commit().unwrap();

    let slots = reopened.list_key_slots();
    assert!(slots
        .iter()
        .any(|slot| slot.id == new_slot && slot.protection == LockboxKeySlotProtection::Password));
    assert!(slots.iter().all(|slot| slot.id != password_slot));
    assert!(Lockbox::open(&lockbox_path, LockboxOpen::Password(&new_password)).is_ok());

    let _ = std::fs::remove_dir_all(root);
}

#[test]
fn public_api_recovery_scanner_reports_and_salvages_intact_files() {
    let root = unique_dir("recovery");
    let lockbox_path = root.join("recovery.lbox");
    let _ = std::fs::remove_dir_all(&root);
    std::fs::create_dir_all(&root).unwrap();

    let mut lb = Lockbox::create_file(
        &lockbox_path,
        LockboxProtection::ContentKey(SecretVec::try_from_slice(KEY).unwrap()),
        &signing_key(),
    )
    .unwrap();
    add_file(&mut lb, &p("/docs/a.txt"), b"alpha", false).unwrap();
    add_file(&mut lb, &p("/docs/b.txt"), b"bravo", false).unwrap();
    add_file(&mut lb, &p("/photos/c.jpg"), b"image", false).unwrap();
    lb.commit().unwrap();

    let mut damaged = std::fs::read(&lockbox_path).unwrap();
    damaged[0] ^= 0xff;

    let report = RecoveryScanner::scan_bytes(damaged.clone(), KEY);
    assert_eq!(report.intact_file_count, 3);
    assert!(report
        .render(&RecoveryReportOptions::default())
        .contains("Intact files"));

    let salvaged = RecoveryScanner::salvage_bytes(damaged, KEY, &signing_key()).unwrap();
    assert_eq!(salvaged.get_file(&p("/docs/a.txt")).unwrap(), b"alpha");
    assert_eq!(salvaged.get_file(&p("/docs/b.txt")).unwrap(), b"bravo");
    assert_eq!(salvaged.get_file(&p("/photos/c.jpg")).unwrap(), b"image");

    let _ = std::fs::remove_dir_all(root);
}

#[test]
fn public_api_secret_lockbox_id_and_hybrid_wrappers_flow() {
    let mut secret = SecretString::new();
    assert!(secret.is_empty());
    secret.try_push_byte(b'a').unwrap();
    secret.try_push_byte(b'b').unwrap();
    secret.try_push_utf8_char('c').unwrap();
    assert_eq!(secret.with_str(|text| text.to_owned()).unwrap(), "abc");
    secret
        .with_bytes(|bytes| assert_eq!(bytes, b"abc"))
        .unwrap();
    assert_eq!(secret.try_pop_byte().unwrap(), Some(b'c'));
    secret.zeroize().unwrap();
    assert!(secret.is_empty());
    assert!(format!("{secret:?}").contains("redacted"));

    let secret_vec = SecretVec::try_from_vec(vec![1, 2, 3]).unwrap();
    secret_vec
        .with_bytes(|bytes| assert_eq!(bytes, &[1, 2, 3]))
        .unwrap();
    assert!(format!("{secret_vec:?}").contains("redacted"));

    let lockbox_id = LockboxId::from_bytes([
        0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0x4d, 0xef, 0x80, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc,
        0xde,
    ]);
    assert_eq!(lockbox_id.as_bytes()[0], 0x12);
    assert_eq!(
        lockbox_id.to_string(),
        "12345678-9abc-4def-8012-3456789abcde"
    );
    let random_id = LockboxId::new_random().unwrap();
    assert_eq!(random_id.as_bytes()[6] & 0xf0, 0x40);
    assert_eq!(random_id.as_bytes()[8] & 0xc0, 0x80);

    let keypair = ContactKeyPair::generate().unwrap();
    let from_record =
        ContactKeyPair::from_private_key_record(keypair.private_key_record().unwrap()).unwrap();
    let contact = keypair.public_key();
    let contact = ContactPublicKey::from_bytes(&contact.to_bytes()).unwrap();
    let wrapped = contact.encrypt(b"content-key").unwrap();
    let wrapped = ContactWrappedKey::from_parts(
        wrapped.x25519_ephemeral_public_key().to_vec(),
        wrapped.ciphertext_bytes().to_vec(),
        wrapped.encrypted_key().to_vec(),
    )
    .unwrap();
    assert_eq!(from_record.decrypt(&wrapped).unwrap(), b"content-key");
    assert_eq!(
        from_record
            .encrypt(b"another-key")
            .unwrap()
            .encrypted_key()
            .len(),
        27
    );
}

#[test]
fn public_api_path_inspector_and_file_helpers_flow() {
    let root = unique_dir("helpers");
    let lockbox_path = root.join("helpers.lbox");
    let source_path = root.join("source.txt");
    let extract_path = root.join("extracted.txt");
    let extract_dir = root.join("extract-dir");
    let _ = std::fs::remove_dir_all(&root);
    std::fs::create_dir_all(&root).unwrap();
    std::fs::write(&source_path, b"from disk").unwrap();

    let mut lb = Lockbox::create_file(
        &lockbox_path,
        LockboxProtection::ContentKey(SecretVec::try_from_slice(KEY).unwrap()),
        &signing_key(),
    )
    .unwrap();
    assert_eq!(lb.workload_profile(), WorkloadProfile::Interactive);
    lb.set_workload_profile(WorkloadProfile::ReadMostly);
    assert_eq!(lb.workload_profile(), WorkloadProfile::ReadMostly);

    add_file_from_path(&mut lb, &source_path, &p("/docs/source.txt"), false).unwrap();
    add_file_from_reader(
        &mut lb,
        &p("/docs/reader.txt"),
        Cursor::new(b"from reader"),
        false,
    )
    .unwrap();
    lb.set_variable(&variable("TEMP"), "1").unwrap();
    lb.delete_variable(&variable("TEMP")).unwrap();
    lb.commit().unwrap();

    let entries = lb.list(ListOptions::new(&p("/docs"))).unwrap();
    assert_eq!(entries.count(), 2);
    let mut out = Vec::new();
    lb.extract_file_to_writer(&p("/docs/source.txt"), &mut out)
        .unwrap();
    assert_eq!(out, b"from disk");
    out.clear();
    lb.extract_file_to_writer(&p("/docs/reader.txt"), &mut out)
        .unwrap();
    assert_eq!(out, b"from reader");
    lb.extract_file_to(&p("/docs/source.txt"), &extract_path, false)
        .unwrap();
    assert_eq!(std::fs::read(&extract_path).unwrap(), b"from disk");
    assert!(matches!(
        lb.extract_file_to(&p("/docs/source.txt"), &extract_path, false),
        Err(revault_lockbox_api::Error::AlreadyExists(_))
    ));
    lb.extract_file_to(&p("/docs/reader.txt"), &extract_path, true)
        .unwrap();
    assert_eq!(std::fs::read(&extract_path).unwrap(), b"from reader");
    let missing_extract_path = root.join("missing-extract.txt");
    assert!(matches!(
        lb.extract_file_to(&p("/docs/source.txt"), &missing_extract_path, true),
        Err(revault_lockbox_api::Error::NotFound(_))
    ));
    lb.extract_to_directory(&extract_dir, &ExtractPolicy::default())
        .unwrap();
    assert_eq!(
        std::fs::read(extract_dir.join("docs/source.txt")).unwrap(),
        b"from disk"
    );

    let inspector = lb.inspector();
    assert!(inspector.storage_len().unwrap() > 0);
    assert!(!inspector.inspect_pages().unwrap().is_empty());
    let _ = inspector.cache_stats();
    assert_eq!(
        RecoveryScanner::scan_path(&lockbox_path, KEY).intact_file_count,
        3
    );

    let reopened = Lockbox::open(
        &lockbox_path,
        LockboxOpen::ContentKey(SecretVec::try_from_slice(KEY).unwrap()),
    )
    .unwrap();
    assert_eq!(
        reopened.get_file(&p("/docs/source.txt")).unwrap(),
        b"from disk"
    );

    let _ = std::fs::remove_dir_all(root);
}

#[test]
fn public_api_password_contact_open_file_flow() {
    let root = unique_dir("open");
    let password_path = root.join("password.lbox");
    let contact_path = root.join("contact.lbox");
    let _ = std::fs::remove_dir_all(&root);
    std::fs::create_dir_all(&root).unwrap();

    let password = password("shared-password");
    let mut by_password = Lockbox::create_file(
        &password_path,
        LockboxProtection::Password(&password),
        &signing_key(),
    )
    .unwrap();
    by_password
        .add_file(&p("/secret.txt"), b"password", false)
        .unwrap();
    by_password.commit().unwrap();
    assert_eq!(
        Lockbox::open(&password_path, LockboxOpen::Password(&password))
            .unwrap()
            .get_file(&p("/secret.txt"))
            .unwrap(),
        b"password"
    );

    let contact = ContactKeyPair::generate().unwrap();
    let mut by_contact = Lockbox::create_file(
        &contact_path,
        LockboxProtection::ContactPublicKey {
            name: Some("contact".to_string()),
            contact: contact.public_key(),
        },
        &signing_key(),
    )
    .unwrap();
    by_contact
        .add_file(&p("/secret.txt"), b"contact", false)
        .unwrap();
    by_contact.commit().unwrap();
    assert_eq!(
        Lockbox::open(&contact_path, LockboxOpen::ContactKeyPair(contact))
            .unwrap()
            .get_file(&p("/secret.txt"))
            .unwrap(),
        b"contact"
    );

    let _ = std::fs::remove_dir_all(root);
}

#[test]
fn public_api_password_contact_open_bytes_flow() {
    let password = password("shared-password");
    let mut by_password =
        Lockbox::create_in_memory(LockboxProtection::Password(&password), &signing_key())
            .expect("create password protected in-memory lockbox");
    by_password
        .add_file(&p("/secret.txt"), b"password", false)
        .unwrap();
    by_password.commit().unwrap();
    let password_bytes = by_password.try_to_bytes().unwrap();
    assert_eq!(
        Lockbox::open_bytes(password_bytes, LockboxOpen::Password(&password))
            .unwrap()
            .get_file(&p("/secret.txt"))
            .unwrap(),
        b"password"
    );

    let contact = ContactKeyPair::generate().unwrap();
    let mut by_contact = Lockbox::create_in_memory(
        LockboxProtection::ContactPublicKey {
            name: Some("contact".to_string()),
            contact: contact.public_key(),
        },
        &signing_key(),
    )
    .expect("create contact protected in-memory lockbox");
    by_contact
        .add_file(&p("/secret.txt"), b"contact", false)
        .unwrap();
    by_contact.commit().unwrap();
    let contact_bytes = by_contact.try_to_bytes().unwrap();
    assert_eq!(
        Lockbox::open_bytes(contact_bytes, LockboxOpen::ContactKeyPair(contact))
            .unwrap()
            .get_file(&p("/secret.txt"))
            .unwrap(),
        b"contact"
    );
}

#[test]
fn public_api_plain_open_returns_read_only_and_write_open_requires_signer() {
    let root = unique_dir("commit-requires-signer");
    let lockbox_path = root.join("signed.lbox");
    let _ = std::fs::remove_dir_all(&root);
    std::fs::create_dir_all(&root).unwrap();

    let password = password("shared-password");
    let signing_key = signing_key();
    let mut created = Lockbox::create_file(
        &lockbox_path,
        LockboxProtection::Password(&password),
        &signing_key,
    )
    .unwrap();
    add_file(&mut created, &p("/docs/a.txt"), b"alpha", false).unwrap();
    created.commit().unwrap();

    let opened_without_signer =
        Lockbox::open(&lockbox_path, LockboxOpen::Password(&password)).unwrap();
    assert_read_only_lockbox(&opened_without_signer);
    assert_eq!(
        opened_without_signer.get_file(&p("/docs/a.txt")).unwrap(),
        b"alpha"
    );

    let mut opened_with_signer = Lockbox::open_for_write(
        &lockbox_path,
        LockboxOpen::Password(&password),
        &signing_key,
    )
    .unwrap();
    add_file(&mut opened_with_signer, &p("/docs/b.txt"), b"bravo", false).unwrap();
    opened_with_signer.commit().unwrap();

    let reopened = Lockbox::open(&lockbox_path, LockboxOpen::Password(&password)).unwrap();
    assert_eq!(reopened.get_file(&p("/docs/b.txt")).unwrap(), b"bravo");

    let _ = std::fs::remove_dir_all(root);
}

fn assert_read_only_lockbox(_: &Lockbox<revault_lockbox_api::ReadOnly>) {}