forked from ChelseaKR/habitable
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_token_sidecars.py
More file actions
2513 lines (2120 loc) · 98.6 KB
/
Copy pathtest_token_sidecars.py
File metadata and controls
2513 lines (2120 loc) · 98.6 KB
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
# SPDX-License-Identifier: AGPL-3.0-or-later
# Copyright 2026 Chelsea Kelly-Reif
"""Adversarial coverage for encrypted timestamp-token sidecars and migration."""
from __future__ import annotations
import hashlib
import json
import os
import signal
import stat
import subprocess
import sys
from collections.abc import Callable, Iterable, Iterator
from contextlib import contextmanager
from pathlib import Path
from typing import cast
import pytest
import habitable.vault as vault_module
from habitable.crypto import open_keyfile
from habitable.errors import HabitableError, VaultError
from habitable.tsa import TimestampToken
from habitable.vault import Vault
def _token(label: str) -> TimestampToken:
marker = f"PRIVATE-GEN-TIME-{label}-2041-02-03T04:05:06Z"
return TimestampToken(
kind="dev",
tsa_name=f"PRIVATE-TSA-{label}",
data=json.dumps({"gen_time": marker, "label": label}).encode(),
)
def _deep_json_with_escape_prefix() -> str:
prefix = json.dumps({"x": '"'})[:-1] + ', "d": '
return prefix + "[" * 256 + "null" + "]" * 256 + "}"
def _sidecar_path(vault: Vault, capture_id: str) -> Path:
digest = hashlib.sha256(capture_id.encode()).hexdigest()
return vault.path / "tokens" / f"{digest}.tokens.enc"
def _write_legacy_set(vault: Vault, capture_id: str) -> tuple[TimestampToken, ...]:
primary = _token("primary")
extra_one = _token("extra-one")
extra_two = _token("extra-two")
archive_one = _token("archive-one")
archive_two = _token("archive-two")
directory = vault.path / "tokens"
(directory / f"{capture_id}.json").write_text(json.dumps(primary.to_dict()))
(directory / f"{capture_id}.additional.json").write_text(
json.dumps([extra_one.to_dict(), extra_two.to_dict()])
)
(directory / f"{capture_id}.archive.json").write_text(
json.dumps([archive_one.to_dict(), archive_two.to_dict()])
)
return primary, extra_one, extra_two, archive_one, archive_two
def test_one_encrypted_sidecar_preserves_public_tokens_order_and_path_safety(
make_vault: Callable[..., Vault],
) -> None:
vault = make_vault("consolidated")
capture_id = "../../escaped-sidecar"
primary = _token("primary-distinctive")
additional = [_token("additional-a"), _token("additional-b")]
archives = [_token("archive-a"), _token("archive-b")]
vault.store_token(capture_id, primary)
for token in additional:
vault.add_additional_token(capture_id, token)
for token in archives:
vault.add_archive_token(capture_id, token)
sidecar = _sidecar_path(vault, capture_id)
entries = list((vault.path / "tokens").iterdir())
assert entries == [sidecar]
assert sidecar.is_file()
assert not (vault.path.parent / "escaped-sidecar.json").exists()
assert vault.get_token(capture_id) == primary
assert vault.get_additional_tokens(capture_id) == additional
assert vault.get_archive_tokens(capture_id) == archives
assert vault.latest_token(capture_id) == archives[-1]
assert vault.get_token(capture_id).to_dict() == primary.to_dict() # type: ignore[union-attr]
ciphertext = sidecar.read_bytes()
for private_text in (
capture_id,
primary.tsa_name,
additional[0].tsa_name,
"PRIVATE-GEN-TIME",
"gen_time",
):
assert private_text.encode() not in ciphertext
if os.name == "posix":
assert stat.S_IMODE(sidecar.stat().st_mode) == 0o600
reopened = Vault.open(vault.path, "test-passphrase")
assert reopened.get_token(capture_id) == primary
assert reopened.get_additional_tokens(capture_id) == additional
assert reopened.get_archive_tokens(capture_id) == archives
with pytest.raises(VaultError, match="must not be empty"):
vault.store_token("", primary)
with pytest.raises(VaultError, match="valid UTF-8"):
vault.store_token("\ud800", primary)
def test_legacy_migration_waits_for_unlock_then_removes_all_plaintext(
make_vault: Callable[..., Vault],
) -> None:
vault = make_vault("legacy")
capture_id = "legacy-cap"
primary, extra_one, extra_two, archive_one, archive_two = _write_legacy_set(vault, capture_id)
legacy_paths = sorted((vault.path / "tokens").glob("*.json"))
with pytest.raises(HabitableError):
Vault.open(vault.path, "wrong-passphrase")
assert all(path.exists() for path in legacy_paths)
assert not _sidecar_path(vault, capture_id).exists()
migrated = Vault.open(vault.path, "test-passphrase")
assert not list((vault.path / "tokens").glob("*.json"))
assert migrated.get_token(capture_id) == primary
assert migrated.get_additional_tokens(capture_id) == [extra_one, extra_two]
assert migrated.get_archive_tokens(capture_id) == [archive_one, archive_two]
@pytest.mark.parametrize(
"capture_id",
["tenant.additional", "tenant.archive"],
ids=["additional-suffix", "archive-suffix"],
)
def test_legacy_primary_capture_ids_ending_component_suffix_migrate(
make_vault: Callable[..., Vault], capture_id: str
) -> None:
vault = make_vault(f"legacy-{capture_id}")
primary, extra_one, extra_two, archive_one, archive_two = _write_legacy_set(vault, capture_id)
migrated = Vault.open(vault.path, "test-passphrase")
assert migrated.get_token(capture_id) == primary
assert migrated.get_additional_tokens(capture_id) == [extra_one, extra_two]
assert migrated.get_archive_tokens(capture_id) == [archive_one, archive_two]
assert _sidecar_path(vault, capture_id).is_file()
assert not list((vault.path / "tokens").glob("*.json"))
@pytest.mark.parametrize(
("name", "payload", "message"),
[
("tenant.json", [], "corrupt token record"),
("tenant.additional.json", "not-an-object-or-list", "invalid top-level shape"),
("tenant.archive.json", None, "invalid top-level shape"),
],
ids=["plain-list", "additional-scalar", "archive-null"],
)
def test_legacy_filename_shape_ambiguity_fails_closed(
make_vault: Callable[..., Vault], name: str, payload: object, message: str
) -> None:
vault = make_vault(f"ambiguous-{name}")
legacy = vault.path / "tokens" / name
legacy.write_text(json.dumps(payload))
with pytest.raises(VaultError, match=message):
Vault.open(vault.path, "test-passphrase")
assert legacy.exists()
assert not list((vault.path / "tokens").glob("*.tokens.enc"))
@pytest.mark.parametrize("survivor", ["primary", "additional"])
def test_legacy_shared_suffix_filename_preserves_only_surviving_shape(
make_vault: Callable[..., Vault], survivor: str
) -> None:
vault = make_vault(f"legacy-shared-name-{survivor}")
shared = vault.path / "tokens" / "tenant.additional.json"
suffix_primary = _token("suffix-primary")
shorter_additional = _token("shorter-additional")
first, last = (
(suffix_primary.to_dict(), [shorter_additional.to_dict()])
if survivor == "additional"
else ([shorter_additional.to_dict()], suffix_primary.to_dict())
)
shared.write_text(json.dumps(first))
shared.write_text(json.dumps(last)) # the legacy format reused this exact path
migrated = Vault.open(vault.path, "test-passphrase")
if survivor == "additional":
assert migrated.get_additional_tokens("tenant") == [shorter_additional]
assert migrated.get_token("tenant.additional") is None
else:
assert migrated.get_token("tenant.additional") == suffix_primary
assert migrated.get_additional_tokens("tenant") == []
assert not shared.exists()
def test_legacy_shape_change_between_grouping_and_reread_fails_closed(
make_vault: Callable[..., Vault], monkeypatch: pytest.MonkeyPatch
) -> None:
vault = make_vault("legacy-shape-race")
capture_id = "tenant.additional"
primary_path = vault.path / "tokens" / f"{capture_id}.json"
primary_path.write_text(json.dumps(_token("shape-primary").to_dict()))
real_read = vault_module._read_legacy_token_json_value
classified = False
def mutate_after_classification(
directory: vault_module._TokenDirectory,
name: str,
*,
parse_error: str | None = None,
) -> object:
nonlocal classified
raw = real_read(directory, name, parse_error=parse_error)
if not classified and name == primary_path.name:
classified = True
primary_path.write_text(json.dumps([_token("shape-list").to_dict()]))
return raw
monkeypatch.setattr(vault_module, "_read_legacy_token_json_value", mutate_after_classification)
with pytest.raises(VaultError, match="corrupt token record"):
Vault.open(vault.path, "test-passphrase")
assert primary_path.exists()
assert not _sidecar_path(vault, capture_id).exists()
def test_live_limit_migration_classifies_legacy_directory_once(
make_vault: Callable[..., Vault], monkeypatch: pytest.MonkeyPatch
) -> None:
vault = make_vault("legacy-linear-classification")
expected: dict[str, TimestampToken] = {}
for index in range(4):
capture_id = f"cap-{index}"
token = _token(f"linear-{index}")
expected[capture_id] = token
(vault.path / "tokens" / f"{capture_id}.json").write_text(json.dumps(token.to_dict()))
monkeypatch.setattr(vault_module, "_MAX_TOKEN_DIRECTORY_ENTRIES", len(expected))
real_groups = vault_module._legacy_token_groups
group_calls = 0
def count_groups(
directory: vault_module._TokenDirectory, entries: Iterable[str]
) -> dict[str, dict[str, str]]:
nonlocal group_calls
group_calls += 1
return real_groups(directory, entries)
monkeypatch.setattr(vault_module, "_legacy_token_groups", count_groups)
migrated = Vault.open(vault.path, "test-passphrase")
assert group_calls == 1
assert not list((vault.path / "tokens").glob("*.json"))
assert all(migrated.get_token(capture_id) == token for capture_id, token in expected.items())
def test_migration_failure_before_publish_keeps_plaintext(
make_vault: Callable[..., Vault], monkeypatch: pytest.MonkeyPatch
) -> None:
vault = make_vault("before-publish")
capture_id = "cap-before"
_write_legacy_set(vault, capture_id)
legacy_paths = sorted((vault.path / "tokens").glob("*.json"))
def fail_publish(_directory: vault_module._TokenDirectory, _name: str, _data: bytes) -> None:
raise OSError("injected pre-publish failure")
monkeypatch.setattr(vault_module, "_atomic_replace_private_entry", fail_publish)
with pytest.raises(OSError, match="pre-publish"):
Vault.open(vault.path, "test-passphrase")
assert all(path.exists() for path in legacy_paths)
assert not _sidecar_path(vault, capture_id).exists()
def test_partial_plaintext_cleanup_resumes_from_both_present_state(
make_vault: Callable[..., Vault], monkeypatch: pytest.MonkeyPatch
) -> None:
vault = make_vault("partial-cleanup")
capture_id = "cap-partial"
expected = _write_legacy_set(vault, capture_id)
def delete_one_then_fail(
directory: vault_module._TokenDirectory,
names: tuple[str, ...],
_snapshots: object,
) -> None:
directory.unlink(names[0])
directory.fsync()
raise OSError("injected crash after first plaintext unlink")
monkeypatch.setattr(vault_module, "_remove_migrated_token_entries", delete_one_then_fail)
with pytest.raises(OSError, match="after first plaintext unlink"):
Vault.open(vault.path, "test-passphrase")
sidecar = _sidecar_path(vault, capture_id)
assert sidecar.exists()
assert len(list((vault.path / "tokens").glob("*.json"))) == 2
monkeypatch.undo()
reopened = Vault.open(vault.path, "test-passphrase")
assert reopened.get_token(capture_id) == expected[0]
assert reopened.get_additional_tokens(capture_id) == list(expected[1:3])
assert reopened.get_archive_tokens(capture_id) == list(expected[3:])
assert not list((vault.path / "tokens").glob("*.json"))
def test_both_present_disagreement_fails_closed_without_deleting_plaintext(
make_vault: Callable[..., Vault], monkeypatch: pytest.MonkeyPatch
) -> None:
vault = make_vault("disagree")
capture_id = "cap-disagree"
_write_legacy_set(vault, capture_id)
def fail_cleanup(
_directory: vault_module._TokenDirectory,
_names: tuple[str, ...],
_snapshots: object,
) -> None:
raise OSError("leave both generations")
monkeypatch.setattr(vault_module, "_remove_migrated_token_entries", fail_cleanup)
with pytest.raises(OSError, match="both generations"):
Vault.open(vault.path, "test-passphrase")
monkeypatch.undo()
primary_path = vault.path / "tokens" / f"{capture_id}.json"
primary_path.write_text(json.dumps(_token("different").to_dict()))
with pytest.raises(VaultError, match="disagree"):
Vault.open(vault.path, "test-passphrase")
assert primary_path.exists()
assert _sidecar_path(vault, capture_id).exists()
def test_migration_reread_mismatch_keeps_legacy_plaintext(
make_vault: Callable[..., Vault], monkeypatch: pytest.MonkeyPatch
) -> None:
vault = make_vault("migration-reread-mismatch")
capture_id = "cap-migration-reread"
_write_legacy_set(vault, capture_id)
real_read = Vault._read_token_sidecar_entry
def mismatching_read(
self: Vault,
directory: vault_module._TokenDirectory,
name: str,
*,
expected_capture_id: str | None = None,
) -> vault_module._TokenSidecar:
record = real_read(self, directory, name, expected_capture_id=expected_capture_id)
return vault_module._TokenSidecar(
record.capture_id,
_token("injected-reread-mismatch"),
record.additional,
record.archive,
)
monkeypatch.setattr(Vault, "_read_token_sidecar_entry", mismatching_read)
with pytest.raises(VaultError, match="migration verification"):
Vault.open(vault.path, "test-passphrase")
assert len(list((vault.path / "tokens").glob("*.json"))) == 3
assert _sidecar_path(vault, capture_id).exists()
def test_atomic_sidecar_failure_preserves_previous_ciphertext(
make_vault: Callable[..., Vault], monkeypatch: pytest.MonkeyPatch
) -> None:
vault = make_vault("atomic")
capture_id = "cap-atomic"
original_token = _token("old")
vault.store_token(capture_id, original_token)
sidecar = _sidecar_path(vault, capture_id)
original_ciphertext = sidecar.read_bytes()
real_write = vault_module._write_private_entry_and_fsync
def fail_after_flush(directory: vault_module._TokenDirectory, name: str, data: bytes) -> None:
real_write(directory, name, data)
raise OSError("injected failure after ciphertext flush")
monkeypatch.setattr(vault_module, "_write_private_entry_and_fsync", fail_after_flush)
with pytest.raises(OSError, match="after ciphertext flush"):
vault.store_token(capture_id, _token("new"))
assert sidecar.read_bytes() == original_ciphertext
assert vault.get_token(capture_id) == original_token
assert not list((vault.path / "tokens").glob(".token-atomic-*.tmp"))
def test_private_writer_removes_partial_file_after_short_write(
make_vault: Callable[..., Vault], monkeypatch: pytest.MonkeyPatch
) -> None:
vault = make_vault("short-write")
capture_id = "cap-short-write"
original = _token("old-short-write")
vault.store_token(capture_id, original)
sidecar = _sidecar_path(vault, capture_id)
before = sidecar.read_bytes()
real_write = os.write
calls = 0
def short_then_fail(descriptor: int, data: memoryview[bytes]) -> int:
nonlocal calls
calls += 1
if calls == 1:
partial = max(1, len(data) // 2)
return int(real_write(descriptor, data[:partial]))
raise OSError("injected short-write failure")
monkeypatch.setattr(os, "write", short_then_fail)
with pytest.raises(OSError, match="short-write"):
vault.store_token(capture_id, _token("new-short-write"))
assert sidecar.read_bytes() == before
assert vault.get_token(capture_id) == original
assert not list((vault.path / "tokens").glob(".token-atomic-*.tmp"))
def test_tamper_and_aad_filename_swap_are_rejected(
make_vault: Callable[..., Vault],
) -> None:
vault = make_vault("tamper")
vault.store_token("cap-a", _token("a"))
vault.store_token("cap-b", _token("b"))
sidecar_a = _sidecar_path(vault, "cap-a")
sidecar_b = _sidecar_path(vault, "cap-b")
bytes_a = sidecar_a.read_bytes()
bytes_b = sidecar_b.read_bytes()
sidecar_a.write_bytes(bytes_b)
sidecar_b.write_bytes(bytes_a)
with pytest.raises(VaultError, match="corrupt encrypted"):
vault.get_token("cap-a")
with pytest.raises(VaultError, match="corrupt encrypted"):
vault.get_token("cap-b")
sidecar_a.write_bytes(bytes_a)
damaged = bytearray(bytes_a)
damaged[-1] ^= 0xFF
sidecar_a.write_bytes(damaged)
with pytest.raises(VaultError, match="corrupt encrypted"):
vault.get_token("cap-a")
def test_sidecar_filename_and_expected_capture_bindings_fail_closed(
make_vault: Callable[..., Vault],
) -> None:
vault = make_vault("binding-errors")
with pytest.raises(VaultError, match="invalid encrypted"):
vault._read_token_sidecar_path(vault.path / "tokens" / "not-a-sidecar")
with pytest.raises(VaultError, match="invalid encrypted"):
vault_module._token_sidecar_aad("not-a-sidecar")
token = _token("binding")
path_a = _sidecar_path(vault, "cap-a")
wrong_record = vault_module._TokenSidecar("cap-b", token)
path_a.write_bytes(
vault._dek.encrypt(
vault_module._encode_token_sidecar(wrong_record),
aad=vault_module._token_sidecar_aad(path_a.name),
)
)
with pytest.raises(VaultError, match="does not match its name"):
vault.get_token("cap-a")
vault.store_token("cap-good", token)
good_path = _sidecar_path(vault, "cap-good")
with pytest.raises(VaultError, match="belongs to another"):
vault._read_token_sidecar_path(good_path, expected_capture_id="cap-other")
def test_same_inode_same_size_change_between_stat_and_open_is_rejected(
make_vault: Callable[..., Vault], monkeypatch: pytest.MonkeyPatch
) -> None:
vault = make_vault("ctime-open-race")
capture_id = "cap-ctime-race"
token = _token("ctime-race")
vault.store_token(capture_id, token)
sidecar = _sidecar_path(vault, capture_id)
real_stat = vault_module._TokenDirectory.stat
token_stat_calls = 0
def mutate_after_snapshot(directory: vault_module._TokenDirectory, name: str) -> os.stat_result:
nonlocal token_stat_calls
before = real_stat(directory, name)
if name == sidecar.name:
token_stat_calls += 1
if token_stat_calls == 2:
ciphertext = sidecar.read_bytes()
sidecar.write_bytes(ciphertext)
os.utime(
sidecar,
ns=(before.st_atime_ns, before.st_mtime_ns),
)
return before
monkeypatch.setattr(vault_module._TokenDirectory, "stat", mutate_after_snapshot)
with pytest.raises(VaultError, match="changed while opening"):
vault.get_token(capture_id)
assert token_stat_calls == 2
monkeypatch.undo()
assert vault.get_token(capture_id) == token
def test_encrypted_sidecar_rejects_symlink_fifo_and_oversize(
make_vault: Callable[..., Vault], tmp_path: Path
) -> None:
vault = make_vault("hostile-sidecar")
capture_id = "cap-hostile"
vault.store_token(capture_id, _token("hostile"))
sidecar = _sidecar_path(vault, capture_id)
sidecar.unlink()
target = tmp_path / "outside-ciphertext"
target.write_bytes(b"outside")
sidecar.symlink_to(target)
with pytest.raises(VaultError, match="must be regular"):
vault.get_token(capture_id)
assert target.read_bytes() == b"outside"
sidecar.unlink()
if hasattr(os, "mkfifo"):
os.mkfifo(sidecar)
with pytest.raises(VaultError, match="must be regular"):
vault.get_token(capture_id)
sidecar.unlink()
with sidecar.open("wb") as handle:
handle.truncate(vault_module._MAX_TOKEN_SIDECAR_BYTES + 1)
with pytest.raises(VaultError, match="too large"):
vault.get_token(capture_id)
def test_legacy_inputs_reject_symlink_fifo_bad_base64_and_excess_count(
make_vault: Callable[..., Vault], tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
vault = make_vault("hostile-legacy")
directory = vault.path / "tokens"
outside = tmp_path / "outside-legacy.json"
outside.write_text(json.dumps(_token("outside").to_dict()))
legacy = directory / "linked.json"
legacy.symlink_to(outside)
with pytest.raises(VaultError, match="must be regular"):
Vault.open(vault.path, "test-passphrase")
assert outside.exists()
legacy.unlink()
if hasattr(os, "mkfifo"):
fifo = directory / "fifo.additional.json"
os.mkfifo(fifo)
with pytest.raises(VaultError, match="must be regular"):
Vault.open(vault.path, "test-passphrase")
fifo.unlink()
(directory / "bad.json").write_text(
json.dumps({"kind": "dev", "tsa_name": "bad", "token_b64": "%%%"})
)
with pytest.raises(VaultError, match="corrupt token record"):
Vault.open(vault.path, "test-passphrase")
(directory / "bad.json").unlink()
monkeypatch.setattr(vault_module, "_MAX_TOKENS_PER_LIST", 1)
(directory / "many.additional.json").write_text(
json.dumps([_token("one").to_dict(), _token("two").to_dict()])
)
with pytest.raises(VaultError, match="too many"):
Vault.open(vault.path, "test-passphrase")
def test_real_token_directory_required_and_entry_scan_is_bounded(
make_vault: Callable[..., Vault], tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
vault = make_vault("directory")
directory = vault.path / "tokens"
directory.rmdir()
outside = tmp_path / "outside-token-directory"
outside.mkdir()
directory.symlink_to(outside, target_is_directory=True)
with pytest.raises(VaultError, match="real directory"):
vault.get_token("cap")
assert not list(outside.iterdir())
directory.unlink()
directory.mkdir()
monkeypatch.setattr(vault_module, "_MAX_TOKEN_DIRECTORY_ENTRIES", 3)
for index in range(4):
(directory / f"unrelated-{index}").touch()
with pytest.raises(VaultError, match="too many entries"):
Vault.open(vault.path, "test-passphrase")
def test_missing_token_directory_is_a_controlled_error(
make_vault: Callable[..., Vault],
) -> None:
vault = make_vault("missing-token-directory")
(vault.path / "tokens").rmdir()
with pytest.raises(VaultError, match="unavailable"):
vault.get_token("cap")
def test_directory_swap_race_fails_without_touching_symlink_target(
make_vault: Callable[..., Vault], tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
vault = make_vault("directory-swap-race")
token_directory = vault.path / "tokens"
displaced = vault.path / "tokens-displaced"
outside = tmp_path / "outside-swap-target"
outside.mkdir()
real_exists = vault_module._TokenDirectory.exists
calls = 0
def swap_before_write(directory: vault_module._TokenDirectory, name: str) -> bool:
nonlocal calls
calls += 1
if calls == 2:
token_directory.rename(displaced)
token_directory.symlink_to(outside, target_is_directory=True)
return real_exists(directory, name)
monkeypatch.setattr(vault_module._TokenDirectory, "exists", swap_before_write)
with pytest.raises(VaultError, match="changed during operation"):
vault.store_token("cap-race", _token("race"))
assert calls == 2
assert not list(outside.iterdir())
assert list(displaced.glob("*.tokens.enc"))
def test_unsupported_directory_fd_platform_fails_closed(
make_vault: Callable[..., Vault], tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
vault = make_vault("unsupported-dirfd")
monkeypatch.setattr(vault_module, "_secure_token_directory_operations_supported", lambda: False)
with pytest.raises(VaultError, match="cannot securely anchor"):
vault.get_token("cap")
with pytest.raises(VaultError, match="vaults are unsupported"):
Vault.open(vault.path, "test-passphrase")
unsupported = tmp_path / "unsupported-new-vault"
with pytest.raises(VaultError, match="vaults are unsupported"):
Vault.create(unsupported, "passphrase", case_id="case")
assert not unsupported.exists()
def test_missing_stat_nofollow_capability_rejects_create_and_open(
make_vault: Callable[..., Vault], tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
vault = make_vault("missing-stat-nofollow")
monkeypatch.setattr(
os,
"supports_follow_symlinks",
os.supports_follow_symlinks - {os.stat},
)
assert not vault_module._secure_token_directory_operations_supported()
with pytest.raises(VaultError, match="vaults are unsupported"):
Vault.open(vault.path, "test-passphrase")
destination = tmp_path / "unsupported-stat-nofollow"
with pytest.raises(VaultError, match="vaults are unsupported"):
Vault.create(destination, "passphrase", case_id="case")
assert not destination.exists()
def test_create_rejects_destination_symlink_without_mutating_target(tmp_path: Path) -> None:
outside = tmp_path / "outside-destination"
outside.mkdir()
sentinel = outside / "sentinel"
sentinel.write_bytes(b"untouched")
destination = tmp_path / "vault-link"
destination.symlink_to(outside, target_is_directory=True)
with pytest.raises(VaultError, match="real directory"):
Vault.create(destination, "passphrase", case_id="case")
assert destination.is_symlink()
assert sentinel.read_bytes() == b"untouched"
assert set(outside.iterdir()) == {sentinel}
@pytest.mark.parametrize("child", ["tokens", "originals"])
def test_create_rejects_preexisting_child_symlink_without_writing_state(
tmp_path: Path, child: str
) -> None:
outside = tmp_path / f"outside-{child}"
outside.mkdir()
sentinel = outside / "sentinel"
sentinel.write_bytes(b"untouched")
destination = tmp_path / f"vault-{child}-link"
destination.mkdir()
(destination / child).symlink_to(outside, target_is_directory=True)
with pytest.raises(VaultError, match="must be empty"):
Vault.create(destination, "passphrase", case_id="case")
assert sentinel.read_bytes() == b"untouched"
assert set(outside.iterdir()) == {sentinel}
assert not (destination / "config.toml").exists()
assert not (destination / "keyfile.json").exists()
assert not list(destination.glob("*.enc"))
def test_create_rejects_nonempty_token_directory_before_state_writes(tmp_path: Path) -> None:
destination = tmp_path / "vault-nonempty-tokens"
tokens = destination / "tokens"
tokens.mkdir(parents=True)
sentinel = tokens / "legacy.json"
sentinel.write_bytes(b"do not touch")
with pytest.raises(VaultError, match="must be empty"):
Vault.create(destination, "passphrase", case_id="case")
assert sentinel.read_bytes() == b"do not touch"
assert not (destination / "config.toml").exists()
assert not (destination / "keyfile.json").exists()
assert not list(destination.glob("*.enc"))
def test_create_accepts_precreated_empty_real_destination(tmp_path: Path) -> None:
destination = tmp_path / "empty-vault-root"
destination.mkdir()
vault = Vault.create(destination, "passphrase", case_id="case")
assert vault.path == destination
assert Vault.open(destination, "passphrase").path == destination
def test_new_sidecar_capacity_is_enforced_but_existing_update_is_allowed(
make_vault: Callable[..., Vault], monkeypatch: pytest.MonkeyPatch
) -> None:
vault = make_vault("sidecar-capacity")
monkeypatch.setattr(vault_module, "_MAX_TOKEN_DIRECTORY_ENTRIES", 1)
first = _token("first-at-cap")
updated = _token("updated-at-cap")
vault.store_token("cap-one", first)
with pytest.raises(VaultError, match="live-entry limit"):
vault.store_token("cap-two", _token("over-cap"))
vault.store_token("cap-one", updated)
assert vault.get_token("cap-one") == updated
assert vault.get_token("cap-two") is None
def test_live_entry_limit_still_allows_strictly_bounded_orphan_cleanup(
make_vault: Callable[..., Vault],
) -> None:
vault = make_vault("full-token-directory")
directory = vault.path / "tokens"
token = _token("full-directory")
for index in range(vault_module._MAX_TOKEN_DIRECTORY_ENTRIES):
capture_id = f"cap-{index}"
path = _sidecar_path(vault, capture_id)
record = vault_module._TokenSidecar(capture_id, token)
path.write_bytes(
vault._dek.encrypt(
vault_module._encode_token_sidecar(record),
aad=vault_module._token_sidecar_aad(path.name),
)
)
orphan = directory / f".token-atomic-{'a' * 32}.tmp"
if not hasattr(signal, "SIGKILL"):
pytest.skip("SIGKILL crash injection requires POSIX")
script = (
"import os, signal, sys; "
"open(sys.argv[1], 'wb').write(b'partial ciphertext'); "
"os.kill(os.getpid(), signal.SIGKILL)"
)
killed = subprocess.run([sys.executable, "-c", script, str(orphan)], check=False)
assert killed.returncode == -signal.SIGKILL
assert orphan.exists()
reopened = Vault.open(vault.path, "test-passphrase")
assert reopened.path == vault.path
assert not orphan.exists()
assert len(list(directory.iterdir())) == vault_module._MAX_TOKEN_DIRECTORY_ENTRIES
assert reopened.get_token("cap-4095") == token
def test_full_legacy_directory_allows_one_verified_crash_overlap(
make_vault: Callable[..., Vault], monkeypatch: pytest.MonkeyPatch
) -> None:
vault = make_vault("full-legacy-overlap")
directory = vault.path / "tokens"
capture_id = "cap-full-legacy"
token = _token("full-legacy")
(directory / f"{capture_id}.json").write_text(json.dumps(token.to_dict()))
for index in range(vault_module._MAX_TOKEN_DIRECTORY_ENTRIES - 1):
(directory / f"filler-{index}").touch()
def crash_after_publish(
_directory: vault_module._TokenDirectory,
_names: tuple[str, ...],
_snapshots: object,
) -> None:
raise OSError("injected cap-overlap crash")
monkeypatch.setattr(vault_module, "_remove_migrated_token_entries", crash_after_publish)
with pytest.raises(OSError, match="cap-overlap crash"):
Vault.open(vault.path, "test-passphrase")
assert len(list(directory.iterdir())) == vault_module._MAX_TOKEN_DIRECTORY_ENTRIES + 1
assert _sidecar_path(vault, capture_id).exists()
monkeypatch.undo()
reopened = Vault.open(vault.path, "test-passphrase")
assert len(list(directory.iterdir())) == vault_module._MAX_TOKEN_DIRECTORY_ENTRIES
assert not (directory / f"{capture_id}.json").exists()
assert reopened.get_token(capture_id) == token
def test_temporary_entry_allowance_is_itself_bounded(
make_vault: Callable[..., Vault], monkeypatch: pytest.MonkeyPatch
) -> None:
vault = make_vault("too-many-token-temps")
directory = vault.path / "tokens"
monkeypatch.setattr(vault_module, "_MAX_TOKEN_TEMP_ENTRIES", 1)
for marker in ("a", "b"):
(directory / f".token-atomic-{marker * 32}.tmp").touch()
with pytest.raises(VaultError, match="too many temporary"):
Vault.open(vault.path, "test-passphrase")
def test_directory_scan_stops_at_limit_without_materializing_the_rest(
make_vault: Callable[..., Vault], monkeypatch: pytest.MonkeyPatch
) -> None:
vault = make_vault("streaming-directory-bound")
directory_path = vault.path / "tokens"
for index in range(3):
(directory_path / f"entry-{index}").touch()
consumed = 0
with vault_module._open_token_directory(vault.path) as directory:
real_scandir = os.scandir
@contextmanager
def limited_scandir(
descriptor: int,
) -> Iterator[Iterator[os.DirEntry[str]]]:
nonlocal consumed
with real_scandir(descriptor) as scanned:
def limited_entries() -> Iterator[os.DirEntry[str]]:
nonlocal consumed
for entry in scanned:
consumed += 1
if consumed > 2:
raise AssertionError("scanner consumed beyond fail-closed limit")
yield entry
yield limited_entries()
monkeypatch.setattr(os, "scandir", limited_scandir)
monkeypatch.setattr(vault_module, "_MAX_TOKEN_DIRECTORY_ENTRIES", 1)
with pytest.raises(VaultError, match="too many entries"):
vault_module._bounded_token_directory_entries(directory)
assert consumed == 2
def test_eager_migration_scan_happens_once_not_per_getter(
make_vault: Callable[..., Vault], monkeypatch: pytest.MonkeyPatch
) -> None:
vault = make_vault("scan-once")
for index in range(20):
vault.store_token(f"cap-{index}", _token(f"token-{index}"))
real_scan = vault_module._bounded_token_directory_entries
scan_count = 0
def counted_scan(
directory: vault_module._TokenDirectory,
*,
allow_migration_overlap: bool = False,
) -> list[str]:
nonlocal scan_count
scan_count += 1
return real_scan(directory, allow_migration_overlap=allow_migration_overlap)
monkeypatch.setattr(vault_module, "_bounded_token_directory_entries", counted_scan)
reopened = Vault.open(vault.path, "test-passphrase")
assert scan_count == 1
for _repeat in range(3):
for index in range(20):
assert reopened.get_token(f"cap-{index}") == _token(f"token-{index}")
assert reopened.get_additional_tokens(f"cap-{index}") == []
assert reopened.get_archive_tokens(f"cap-{index}") == []
assert scan_count == 1
def test_dek_rotation_reencrypts_token_sidecars_and_preserves_all_tokens(
make_vault: Callable[..., Vault],
) -> None:
vault = make_vault("rotate")
capture_id = "cap-rotate"
primary = _token("primary")
additional = [_token("extra-one"), _token("extra-two")]
archive = [_token("archive-one"), _token("archive-two")]
vault.store_token(capture_id, primary)
for token in additional:
vault.add_additional_token(capture_id, token)
for token in archive:
vault.add_archive_token(capture_id, token)
sidecar = _sidecar_path(vault, capture_id)
before = sidecar.read_bytes()
vault.rotate_dek("test-passphrase")
assert sidecar.read_bytes() != before
assert not list((vault.path / "tokens").glob("*.new"))
assert vault.get_token(capture_id) == primary
assert vault.get_additional_tokens(capture_id) == additional
assert vault.get_archive_tokens(capture_id) == archive
reopened = Vault.open(vault.path, "test-passphrase")
assert reopened.get_token(capture_id) == primary
assert reopened.get_additional_tokens(capture_id) == additional
assert reopened.get_archive_tokens(capture_id) == archive
def test_dek_rotation_fsync_failure_cleans_staging_and_is_retryable(
make_vault: Callable[..., Vault], monkeypatch: pytest.MonkeyPatch
) -> None:
vault = make_vault("rotate-fsync")
capture_id = "cap-rotate-fsync"
token = _token("rotate-fsync")
vault.store_token(capture_id, token)
sidecar = _sidecar_path(vault, capture_id)
before_sidecar = sidecar.read_bytes()
before_keyfile = (vault.path / "keyfile.json").read_bytes()
def fail_fsync(_descriptor: int) -> None:
raise OSError("injected rotation fsync failure")
monkeypatch.setattr(os, "fsync", fail_fsync)
with pytest.raises(OSError, match="rotation fsync"):
vault.rotate_dek("test-passphrase")
assert sidecar.read_bytes() == before_sidecar
assert (vault.path / "keyfile.json").read_bytes() == before_keyfile
assert not list((vault.path / "tokens").glob("*.new"))
assert vault.get_token(capture_id) == token
monkeypatch.undo()
vault.rotate_dek("test-passphrase")
assert Vault.open(vault.path, "test-passphrase").get_token(capture_id) == token
def test_prepublication_directory_fsync_failure_prevents_all_renames(
make_vault: Callable[..., Vault], monkeypatch: pytest.MonkeyPatch
) -> None:
vault = make_vault("rotate-prepublish-directory-fsync")
capture_id = "cap-prepublish-directory-fsync"
token = _token("prepublish-directory-fsync")
vault.store_token(capture_id, token)
before_case = (vault.path / "case.enc").read_bytes()
real_path_replace = Path.replace
real_token_replace = vault_module._TokenDirectory.replace
path_replace_calls = 0
token_replace_calls = 0
def count_path_replace(source: Path, destination: Path) -> Path:
nonlocal path_replace_calls
path_replace_calls += 1
return real_path_replace(source, destination)
def count_token_replace(
directory: vault_module._TokenDirectory, source: str, destination: str
) -> None:
nonlocal token_replace_calls
token_replace_calls += 1
real_token_replace(directory, source, destination)
def fail_prepublication_fsync(_path: Path) -> bool:
raise OSError("injected prepublication directory fsync failure")
monkeypatch.setattr(Path, "replace", count_path_replace)
monkeypatch.setattr(vault_module._TokenDirectory, "replace", count_token_replace)
monkeypatch.setattr(vault_module, "_fsync_directory", fail_prepublication_fsync)
with pytest.raises(OSError, match="prepublication directory fsync"):
vault.rotate_dek("test-passphrase")
assert path_replace_calls == 0
assert token_replace_calls == 0
assert (vault.path / "case.enc").read_bytes() == before_case
assert not list(vault.path.rglob("*.new"))
assert vault.get_token(capture_id) == token
monkeypatch.undo()
vault.rotate_dek("test-passphrase")
assert Vault.open(vault.path, "test-passphrase").get_token(capture_id) == token
def test_dek_rotation_commits_data_directories_before_keyfile(
make_vault: Callable[..., Vault], monkeypatch: pytest.MonkeyPatch
) -> None:
vault = make_vault("rotate-durability-order")
vault.store_token("cap-durability-order", _token("durability-order"))
events: list[tuple[str, str]] = []
real_path_fsync = vault_module._fsync_directory
real_token_fsync = vault_module._TokenDirectory.fsync
real_path_replace = Path.replace
real_token_replace = vault_module._TokenDirectory.replace