-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_evidence_store.py
More file actions
1578 lines (1360 loc) · 57.9 KB
/
Copy pathtest_evidence_store.py
File metadata and controls
1578 lines (1360 loc) · 57.9 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
"""Content-addressed evidence index, rollback, crash, and concurrency tests."""
import hashlib
import json
import os
import re
import sqlite3
import stat
from concurrent.futures import ThreadPoolExecutor
from dataclasses import replace
from pathlib import Path
from threading import Barrier
from typing import Any, NoReturn
import pytest
from jsonschema import Draft202012Validator
import contextsafe.evidence_store as store_module
from contextsafe.errors import ContextSafeError
from contextsafe.evidence import EvidenceMetadata, EvidenceScope
from contextsafe.evidence_store import (
EvidenceStore,
store_internal_synthetic_evidence,
)
from contextsafe.preflight import PreflightedSource
ROOT = Path(__file__).resolve().parents[1]
class _CloseFailingConnection:
def __init__(
self,
connection: sqlite3.Connection,
*,
fail_statement: str | None = None,
) -> None:
self._connection = connection
self._fail_statement = fail_statement
@property
def in_transaction(self) -> bool:
return self._connection.in_transaction
def execute(
self, statement: str, *args: object, **kwargs: object
) -> sqlite3.Cursor:
if self._fail_statement is not None and self._fail_statement in statement:
raise sqlite3.OperationalError("injected connection operation failure")
return self._connection.execute(statement, *args, **kwargs)
def close(self) -> None:
self._connection.close()
raise sqlite3.OperationalError("injected connection close failure")
def _write_source(path: Path, value: object) -> Path:
path.write_text(json.dumps(value, separators=(",", ":")), encoding="utf-8")
return path
def _store(
source: Path,
workspace: Path,
scope: EvidenceScope,
metadata: EvidenceMetadata,
):
return store_internal_synthetic_evidence(
source,
workspace=workspace,
scope=scope,
metadata=metadata,
)
def _object_path(workspace: Path, raw_sha256: str) -> Path:
return workspace / "evidence" / "raw" / "sha256" / raw_sha256[:2] / raw_sha256
def _tree_snapshot(root: Path) -> dict[str, tuple[int, int, int, int, bytes | None]]:
paths = (root, *root.rglob("*"))
snapshot: dict[str, tuple[int, int, int, int, bytes | None]] = {}
for path in paths:
details = path.lstat()
payload = path.read_bytes() if stat.S_ISREG(details.st_mode) else None
snapshot[str(path.relative_to(root))] = (
details.st_mode,
details.st_size,
details.st_mtime_ns,
details.st_ctime_ns,
payload,
)
return snapshot
def _sqlite_sequence_rows(database: Path) -> tuple[tuple[object, object], ...]:
connection = sqlite3.connect(database)
try:
return tuple(
connection.execute(
"SELECT name, seq FROM sqlite_sequence ORDER BY name"
).fetchall()
)
finally:
connection.close()
def test_store_writes_private_content_address_and_append_only_record(
tmp_path: Path,
evidence_source_json: dict[str, Any],
evidence_scope: EvidenceScope,
evidence_metadata: EvidenceMetadata,
) -> None:
source = _write_source(tmp_path / "source.json", evidence_source_json)
workspace = tmp_path / "workspace"
record = _store(source, workspace, evidence_scope, evidence_metadata)
raw = source.read_bytes()
assert record.raw_sha256 == hashlib.sha256(raw).hexdigest()
assert record.usable_for_execution is False
assert record.authorization_status == "not_verified_internal_test_only"
object_path = _object_path(workspace, record.raw_sha256)
assert object_path.read_bytes() == raw
assert stat.S_IMODE(object_path.stat().st_mode) == 0o600
assert stat.S_IMODE(workspace.stat().st_mode) == 0o700
assert stat.S_IMODE((workspace / "contextsafe.sqlite").stat().st_mode) == 0o600
store = EvidenceStore(workspace)
assert store.get(record.evidence_id) == record
assert store.get("EVD-" + "f" * 64) is None
assert store.list_records() == (record,)
store.verify_integrity()
schema = json.loads(
(ROOT / "schemas" / "contextsafe-evidence-v1.schema.json").read_text(
encoding="utf-8"
)
)
Draft202012Validator.check_schema(schema)
Draft202012Validator(schema).validate(record.to_dict())
def test_identical_import_is_idempotent_and_metadata_change_appends(
tmp_path: Path,
evidence_source_json: dict[str, Any],
evidence_scope: EvidenceScope,
evidence_metadata: EvidenceMetadata,
) -> None:
source = _write_source(tmp_path / "source.json", evidence_source_json)
workspace = tmp_path / "workspace"
first = _store(source, workspace, evidence_scope, evidence_metadata)
second = _store(source, workspace, evidence_scope, evidence_metadata)
assert first == second
assert EvidenceStore(workspace).list_records() == (first,)
later = replace(
evidence_metadata,
captured_at=evidence_metadata.captured_at.replace(second=1),
)
third = _store(source, workspace, evidence_scope, later)
assert third.evidence_id != first.evidence_id
assert third.raw_sha256 == first.raw_sha256
assert EvidenceStore(workspace).list_records() == (first, third)
raw_files = [
path
for path in (workspace / "evidence" / "raw" / "sha256").glob("*/*")
if path.is_file()
]
assert raw_files == [_object_path(workspace, first.raw_sha256)]
def test_sqlite_guards_record_updates_and_deletes(
tmp_path: Path,
evidence_source_json: dict[str, Any],
evidence_scope: EvidenceScope,
evidence_metadata: EvidenceMetadata,
) -> None:
source = _write_source(tmp_path / "source.json", evidence_source_json)
workspace = tmp_path / "workspace"
record = _store(source, workspace, evidence_scope, evidence_metadata)
connection = sqlite3.connect(workspace / "contextsafe.sqlite")
try:
with pytest.raises(sqlite3.IntegrityError):
connection.execute(
"UPDATE evidence_records SET raw_sha256 = ? WHERE evidence_id = ?",
("0" * 64, record.evidence_id),
)
connection.rollback()
with pytest.raises(sqlite3.IntegrityError):
connection.execute(
"DELETE FROM evidence_records WHERE evidence_id = ?",
(record.evidence_id,),
)
finally:
connection.close()
def test_rejection_happens_before_workspace_persistence(
tmp_path: Path,
evidence_source_json: dict[str, Any],
evidence_scope: EvidenceScope,
evidence_metadata: EvidenceMetadata,
) -> None:
evidence_source_json["records"][0]["value_code"] = "person@example.invalid"
source = _write_source(tmp_path / "source.json", evidence_source_json)
workspace = tmp_path / "workspace"
with pytest.raises(ContextSafeError) as raised:
_store(source, workspace, evidence_scope, evidence_metadata)
assert raised.value.code == "direct_identifier_detected"
assert not workspace.exists()
def test_source_must_remain_outside_workspace(
tmp_path: Path,
evidence_source_json: dict[str, Any],
evidence_scope: EvidenceScope,
evidence_metadata: EvidenceMetadata,
) -> None:
workspace = tmp_path / "workspace"
workspace.mkdir(mode=0o700)
source = _write_source(workspace / "source.json", evidence_source_json)
with pytest.raises(ContextSafeError) as raised:
_store(source, workspace, evidence_scope, evidence_metadata)
assert raised.value.code == "source_not_caller_owned"
assert not (workspace / "contextsafe.sqlite").exists()
def test_unsafe_workspace_permissions_fail_before_raw_copy(
tmp_path: Path,
evidence_source_json: dict[str, Any],
evidence_scope: EvidenceScope,
evidence_metadata: EvidenceMetadata,
) -> None:
source = _write_source(tmp_path / "source.json", evidence_source_json)
workspace = tmp_path / "workspace"
workspace.mkdir(mode=0o755)
os.chmod(workspace, 0o755) # noqa: S103 - intentionally unsafe fixture
with pytest.raises(ContextSafeError) as raised:
_store(source, workspace, evidence_scope, evidence_metadata)
assert raised.value.code == "workspace_permission_unsafe"
assert not (workspace / "evidence").exists()
def test_insert_failure_rolls_back_index_object_and_stage(
tmp_path: Path,
evidence_source_json: dict[str, Any],
evidence_scope: EvidenceScope,
evidence_metadata: EvidenceMetadata,
monkeypatch: pytest.MonkeyPatch,
) -> None:
source = _write_source(tmp_path / "source.json", evidence_source_json)
workspace = tmp_path / "workspace"
def fail(_connection: sqlite3.Connection, _record: object) -> None:
raise ContextSafeError("injected_index_failure", "$", "injected safe failure")
monkeypatch.setattr(EvidenceStore, "_append_record", staticmethod(fail))
with pytest.raises(ContextSafeError) as raised:
_store(source, workspace, evidence_scope, evidence_metadata)
assert raised.value.code == "injected_index_failure"
assert EvidenceStore(workspace).list_records() == ()
raw_root = workspace / "evidence" / "raw" / "sha256"
assert not [path for path in raw_root.glob("*/*") if path.is_file()]
assert not list((raw_root / ".staging").iterdir())
def test_primary_index_error_survives_object_cleanup_denial_and_exposes_orphan(
tmp_path: Path,
evidence_source_json: dict[str, Any],
evidence_scope: EvidenceScope,
evidence_metadata: EvidenceMetadata,
monkeypatch: pytest.MonkeyPatch,
) -> None:
source = _write_source(tmp_path / "source.json", evidence_source_json)
workspace = tmp_path / "workspace"
raw_sha256 = hashlib.sha256(source.read_bytes()).hexdigest()
original_unlink = Path.unlink
def deny_object_unlink(path: Path, *args: object, **kwargs: object) -> None:
if path.name == raw_sha256:
raise PermissionError("injected object cleanup denial")
original_unlink(path, *args, **kwargs)
def fail(_connection: sqlite3.Connection, _record: object) -> None:
raise ContextSafeError("injected_index_failure", "$", "injected failure")
monkeypatch.setattr(Path, "unlink", deny_object_unlink)
monkeypatch.setattr(EvidenceStore, "_append_record", staticmethod(fail))
with pytest.raises(ContextSafeError) as raised:
_store(source, workspace, evidence_scope, evidence_metadata)
assert raised.value.code == "injected_index_failure"
assert _object_path(workspace, raw_sha256).read_bytes() == source.read_bytes()
connection = sqlite3.connect(workspace / "contextsafe.sqlite")
try:
assert connection.execute(
"SELECT COUNT(*) FROM evidence_records"
).fetchone() == (0,)
finally:
connection.close()
assert not list((workspace / "evidence" / "raw" / "sha256" / ".staging").iterdir())
def test_object_cleanup_denial_without_primary_is_a_structured_error(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
workspace = tmp_path / "workspace"
object_path = workspace / "orphan"
workspace.mkdir(mode=0o700)
object_path.write_bytes(b"orphan")
os.chmod(object_path, 0o600)
def deny_unlink(_path: Path, *args: object, **kwargs: object) -> None:
raise PermissionError("injected cleanup denial")
monkeypatch.setattr(Path, "unlink", deny_unlink)
with pytest.raises(ContextSafeError) as raised:
EvidenceStore(workspace)._remove_object(object_path)
assert raised.value.code == "evidence_store_io_error"
assert object_path.read_bytes() == b"orphan"
def test_descriptor_close_denial_is_structured_without_primary_and_preserves_primary(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
path = tmp_path / "descriptor"
path.write_bytes(b"")
cleanup_descriptor = os.open(path, os.O_RDONLY)
primary_descriptor = os.open(path, os.O_RDONLY)
original_close = os.close
def deny_test_descriptors(descriptor: int) -> None:
if descriptor in {cleanup_descriptor, primary_descriptor}:
raise OSError("injected descriptor close denial")
original_close(descriptor)
monkeypatch.setattr(os, "close", deny_test_descriptors)
try:
with (
pytest.raises(ContextSafeError) as cleanup_raised,
store_module._closing_descriptor(
cleanup_descriptor,
code="evidence_store_io_error",
message="injected cleanup failed",
),
):
pass
assert cleanup_raised.value.code == "evidence_store_io_error"
with (
pytest.raises(ContextSafeError) as primary_raised,
store_module._closing_descriptor(
primary_descriptor,
code="evidence_store_io_error",
message="injected cleanup failed",
),
):
raise ContextSafeError("injected_primary", "$", "injected primary failure")
assert primary_raised.value.code == "injected_primary"
finally:
original_close(cleanup_descriptor)
original_close(primary_descriptor)
def test_commit_cleanup_without_primary_reports_stage_and_connection_failures(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
workspace = tmp_path / "workspace"
workspace.mkdir(mode=0o700)
stage = workspace / "leaked.part"
stage.write_bytes(b"leaked")
connection = sqlite3.connect(":memory:")
def deny_unlink(_path: Path, *args: object, **kwargs: object) -> None:
raise PermissionError("injected cleanup denial")
monkeypatch.setattr(Path, "unlink", deny_unlink)
with pytest.raises(ContextSafeError) as raised:
EvidenceStore(workspace)._finish_commit_cleanup(connection, stage, None)
assert raised.value.code == "evidence_store_io_error"
assert stage.read_bytes() == b"leaked"
with pytest.raises(sqlite3.ProgrammingError):
connection.execute("SELECT 1")
class FailingConnection:
def close(self) -> None:
raise sqlite3.OperationalError("injected connection close denial")
failing_connection: Any = FailingConnection()
with pytest.raises(ContextSafeError) as raised:
EvidenceStore(workspace)._finish_commit_cleanup(failing_connection, None, None)
assert raised.value.code == "evidence_store_io_error"
def test_object_cleanup_fsync_error_is_structured_unless_primary_exists(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
workspace = tmp_path / "workspace"
workspace.mkdir(mode=0o700)
object_path = workspace / "orphan"
def fail_fsync(_path: Path) -> None:
raise ContextSafeError(
"evidence_store_io_error", "$", "injected directory fsync denial"
)
monkeypatch.setattr(EvidenceStore, "_fsync_directory", staticmethod(fail_fsync))
object_path.write_bytes(b"first")
with pytest.raises(ContextSafeError) as raised:
EvidenceStore(workspace)._remove_object(object_path)
assert raised.value.code == "evidence_store_io_error"
assert not object_path.exists()
object_path.write_bytes(b"second")
primary = ContextSafeError("injected_primary", "$", "injected primary failure")
EvidenceStore(workspace)._remove_object(object_path, primary_error=primary)
assert not object_path.exists()
def test_second_pass_failure_leaves_no_content_or_index_row(
tmp_path: Path,
evidence_source_json: dict[str, Any],
evidence_scope: EvidenceScope,
evidence_metadata: EvidenceMetadata,
monkeypatch: pytest.MonkeyPatch,
) -> None:
source = _write_source(tmp_path / "source.json", evidence_source_json)
workspace = tmp_path / "workspace"
def fail_copy(self: PreflightedSource, _destination_descriptor: int) -> None:
raise ContextSafeError(
"source_mutated", "$", "evidence changed after its boundary check"
)
monkeypatch.setattr(PreflightedSource, "copy_to", fail_copy)
with pytest.raises(ContextSafeError) as raised:
_store(source, workspace, evidence_scope, evidence_metadata)
assert raised.value.code == "source_mutated"
assert EvidenceStore(workspace).list_records() == ()
raw_root = workspace / "evidence" / "raw" / "sha256"
assert not [path for path in raw_root.glob("*/*") if path.is_file()]
assert not list((raw_root / ".staging").iterdir())
def test_primary_copy_error_survives_stage_cleanup_denial_and_exposes_stage_leak(
tmp_path: Path,
evidence_source_json: dict[str, Any],
evidence_scope: EvidenceScope,
evidence_metadata: EvidenceMetadata,
monkeypatch: pytest.MonkeyPatch,
) -> None:
source = _write_source(tmp_path / "source.json", evidence_source_json)
workspace = tmp_path / "workspace"
original_unlink = Path.unlink
def fail_copy(self: PreflightedSource, _destination_descriptor: int) -> None:
raise ContextSafeError(
"source_mutated", "$", "evidence changed after its boundary check"
)
def deny_stage_unlink(path: Path, *args: object, **kwargs: object) -> None:
if path.suffix == ".part":
raise PermissionError("injected staging cleanup denial")
original_unlink(path, *args, **kwargs)
monkeypatch.setattr(PreflightedSource, "copy_to", fail_copy)
monkeypatch.setattr(Path, "unlink", deny_stage_unlink)
with pytest.raises(ContextSafeError) as raised:
_store(source, workspace, evidence_scope, evidence_metadata)
assert raised.value.code == "source_mutated"
raw_root = workspace / "evidence" / "raw" / "sha256"
assert len(list((raw_root / ".staging").iterdir())) == 1
assert not [
path
for path in raw_root.glob("*/*")
if path.is_file() and path.parent != raw_root / ".staging"
]
connection = sqlite3.connect(workspace / "contextsafe.sqlite")
try:
assert connection.execute(
"SELECT COUNT(*) FROM evidence_records"
).fetchone() == (0,)
finally:
connection.close()
def test_next_transaction_recovers_crash_orphans_and_staging(
tmp_path: Path,
evidence_source_json: dict[str, Any],
evidence_scope: EvidenceScope,
evidence_metadata: EvidenceMetadata,
) -> None:
source = _write_source(tmp_path / "source.json", evidence_source_json)
workspace = tmp_path / "workspace"
record = _store(source, workspace, evidence_scope, evidence_metadata)
raw_root = workspace / "evidence" / "raw" / "sha256"
orphan_bytes = b"accepted-before-crash"
orphan_hash = hashlib.sha256(orphan_bytes).hexdigest()
orphan_dir = raw_root / orphan_hash[:2]
orphan_dir.mkdir(mode=0o700)
orphan = orphan_dir / orphan_hash
orphan.write_bytes(orphan_bytes)
os.chmod(orphan, 0o600)
stage = raw_root / ".staging" / "crashed.part"
stage.write_bytes(orphan_bytes)
os.chmod(stage, 0o600)
assert _store(source, workspace, evidence_scope, evidence_metadata) == record
assert not orphan.exists()
assert not stage.exists()
EvidenceStore(workspace).verify_integrity()
def test_concurrent_identical_imports_serialize_to_one_record(
tmp_path: Path,
evidence_source_json: dict[str, Any],
evidence_scope: EvidenceScope,
evidence_metadata: EvidenceMetadata,
) -> None:
source = _write_source(tmp_path / "source.json", evidence_source_json)
workspace = tmp_path / "workspace"
def run(_index: int):
return _store(source, workspace, evidence_scope, evidence_metadata)
with ThreadPoolExecutor(max_workers=6) as executor:
records = tuple(executor.map(run, range(12)))
assert len({record.evidence_id for record in records}) == 1
assert EvidenceStore(workspace).list_records() == (records[0],)
EvidenceStore(workspace).verify_integrity()
def test_corrupt_content_object_fails_integrity_verification(
tmp_path: Path,
evidence_source_json: dict[str, Any],
evidence_scope: EvidenceScope,
evidence_metadata: EvidenceMetadata,
) -> None:
source = _write_source(tmp_path / "source.json", evidence_source_json)
workspace = tmp_path / "workspace"
record = _store(source, workspace, evidence_scope, evidence_metadata)
_object_path(workspace, record.raw_sha256).write_bytes(b"corrupt")
with pytest.raises(ContextSafeError) as raised:
EvidenceStore(workspace).verify_integrity()
assert raised.value.code == "evidence_store_corrupt"
def test_missing_unsafe_and_unsupported_indexes_fail_closed(tmp_path: Path) -> None:
missing = EvidenceStore(tmp_path / "missing")
with pytest.raises(ContextSafeError) as raised:
missing.list_records()
assert raised.value.code == "evidence_index_missing"
workspace = tmp_path / "unsafe"
workspace.mkdir(mode=0o700)
target = tmp_path / "target.sqlite"
target.write_bytes(b"")
(workspace / "contextsafe.sqlite").symlink_to(target)
with pytest.raises(ContextSafeError) as raised:
EvidenceStore(workspace).list_records()
assert raised.value.code == "evidence_store_path_unsafe"
def test_index_version_and_canonical_columns_are_verified_on_next_transaction(
tmp_path: Path,
evidence_source_json: dict[str, Any],
evidence_scope: EvidenceScope,
evidence_metadata: EvidenceMetadata,
) -> None:
source = _write_source(tmp_path / "source.json", evidence_source_json)
workspace = tmp_path / "workspace"
record = _store(source, workspace, evidence_scope, evidence_metadata)
connection = sqlite3.connect(workspace / "contextsafe.sqlite")
try:
connection.execute(
"UPDATE evidence_index_metadata SET schema_version = 'future'"
)
connection.commit()
finally:
connection.close()
with pytest.raises(ContextSafeError) as raised:
EvidenceStore(workspace).list_records()
assert raised.value.code == "unsupported_evidence_index"
connection = sqlite3.connect(workspace / "contextsafe.sqlite")
try:
connection.execute(
"UPDATE evidence_index_metadata SET schema_version = ?",
(store_module.INDEX_SCHEMA_VERSION,),
)
connection.execute("DROP TRIGGER evidence_records_no_update")
connection.execute(
"UPDATE evidence_records SET raw_sha256 = ? WHERE evidence_id = ?",
("f" * 64, record.evidence_id),
)
connection.commit()
finally:
connection.close()
with pytest.raises(ContextSafeError) as raised:
_store(source, workspace, evidence_scope, evidence_metadata)
assert raised.value.code == "evidence_store_corrupt"
@pytest.mark.parametrize(
("damage_sql", "remaining_sql"),
[
(
"DROP TABLE evidence_records",
"SELECT COUNT(*) FROM sqlite_master WHERE name = 'evidence_records'",
),
(
"DELETE FROM evidence_index_metadata",
"SELECT COUNT(*) FROM evidence_index_metadata",
),
(
"DROP TRIGGER evidence_records_no_delete",
"SELECT COUNT(*) FROM sqlite_master "
"WHERE name = 'evidence_records_no_delete'",
),
],
)
def test_existing_index_damage_is_not_repaired_or_allowed_to_delete_objects(
tmp_path: Path,
evidence_source_json: dict[str, Any],
evidence_scope: EvidenceScope,
evidence_metadata: EvidenceMetadata,
damage_sql: str,
remaining_sql: str,
) -> None:
source = _write_source(tmp_path / "source.json", evidence_source_json)
workspace = tmp_path / "workspace"
record = _store(source, workspace, evidence_scope, evidence_metadata)
object_path = _object_path(workspace, record.raw_sha256)
original_bytes = object_path.read_bytes()
database = workspace / "contextsafe.sqlite"
connection = sqlite3.connect(database)
try:
connection.execute(damage_sql)
connection.commit()
finally:
connection.close()
with pytest.raises(ContextSafeError) as raised:
EvidenceStore(workspace).list_records()
assert raised.value.code == "evidence_store_corrupt"
connection = sqlite3.connect(database)
try:
assert connection.execute(remaining_sql).fetchone() == (0,)
finally:
connection.close()
with pytest.raises(ContextSafeError) as raised:
_store(source, workspace, evidence_scope, evidence_metadata)
assert raised.value.code == "evidence_store_corrupt"
assert object_path.read_bytes() == original_bytes
def test_truncated_existing_index_fails_closed_without_reinitialization(
tmp_path: Path,
evidence_source_json: dict[str, Any],
evidence_scope: EvidenceScope,
evidence_metadata: EvidenceMetadata,
) -> None:
source = _write_source(tmp_path / "source.json", evidence_source_json)
workspace = tmp_path / "workspace"
record = _store(source, workspace, evidence_scope, evidence_metadata)
object_path = _object_path(workspace, record.raw_sha256)
original_bytes = object_path.read_bytes()
database = workspace / "contextsafe.sqlite"
database.write_bytes(b"")
with pytest.raises(ContextSafeError) as raised:
EvidenceStore(workspace).verify_integrity()
assert raised.value.code == "evidence_store_corrupt"
assert database.read_bytes() == b""
with pytest.raises(ContextSafeError) as raised:
_store(source, workspace, evidence_scope, evidence_metadata)
assert raised.value.code == "evidence_store_corrupt"
assert database.read_bytes() == b""
assert object_path.read_bytes() == original_bytes
def test_missing_index_with_raw_objects_is_not_recreated(
tmp_path: Path,
evidence_source_json: dict[str, Any],
evidence_scope: EvidenceScope,
evidence_metadata: EvidenceMetadata,
) -> None:
source = _write_source(tmp_path / "source.json", evidence_source_json)
workspace = tmp_path / "workspace"
record = _store(source, workspace, evidence_scope, evidence_metadata)
object_path = _object_path(workspace, record.raw_sha256)
original_bytes = object_path.read_bytes()
database = workspace / "contextsafe.sqlite"
database.unlink()
with pytest.raises(ContextSafeError) as raised:
EvidenceStore(workspace).list_records()
assert raised.value.code == "evidence_index_missing"
with pytest.raises(ContextSafeError) as raised:
_store(source, workspace, evidence_scope, evidence_metadata)
assert raised.value.code == "evidence_index_missing"
assert not database.exists()
assert object_path.read_bytes() == original_bytes
@pytest.mark.parametrize(
"partial_kind",
["raw-object-without-staging", "staged-object", "unexpected-raw-entry"],
)
def test_preexisting_partial_raw_store_fails_without_any_workspace_mutation(
tmp_path: Path,
evidence_source_json: dict[str, Any],
evidence_scope: EvidenceScope,
evidence_metadata: EvidenceMetadata,
partial_kind: str,
) -> None:
source = _write_source(tmp_path / "source.json", evidence_source_json)
workspace = tmp_path / "workspace"
evidence = workspace / "evidence"
raw = evidence / "raw"
for directory in (workspace, evidence, raw):
directory.mkdir(mode=0o700)
if partial_kind == "unexpected-raw-entry":
partial = raw / "unindexed.part"
else:
raw_root = raw / "sha256"
raw_root.mkdir(mode=0o700)
if partial_kind == "raw-object-without-staging":
shard = raw_root / "aa"
shard.mkdir(mode=0o700)
partial = shard / ("a" * 64)
else:
staging = raw_root / ".staging"
staging.mkdir(mode=0o700)
partial = staging / "unindexed.part"
partial.write_bytes(b"unindexed")
os.chmod(partial, 0o600)
before = _tree_snapshot(workspace)
with pytest.raises(ContextSafeError) as raised:
_store(source, workspace, evidence_scope, evidence_metadata)
assert raised.value.code == "evidence_index_missing"
assert _tree_snapshot(workspace) == before
assert not (workspace / "contextsafe.sqlite").exists()
def test_pragma_header_sql_is_a_fixed_integer_assignment() -> None:
"""The two valued header PRAGMAs cannot carry SQL syntax.
SQLite rejects bound parameters in a PRAGMA, so these statements are rendered
from module constants rather than parameterized. Pin the exact text: the store's
format identity must not drift, and the right-hand side must stay an integer
literal so no future edit can route a string into the statement.
"""
assert store_module._SET_APPLICATION_ID_SQL == "PRAGMA application_id = 1129601107"
assert store_module._SET_USER_VERSION_SQL == "PRAGMA user_version = 1"
for statement in (
store_module._SET_APPLICATION_ID_SQL,
store_module._SET_USER_VERSION_SQL,
):
assert re.fullmatch(r"PRAGMA [a-z_]+ = -?\d+", statement), statement
with pytest.raises(sqlite3.OperationalError):
sqlite3.connect(":memory:").execute("PRAGMA user_version = ?", (1,))
@pytest.mark.parametrize(
"pragma",
[
"PRAGMA application_id = 0",
"PRAGMA user_version = 2",
"PRAGMA journal_mode = WAL",
],
)
def test_index_header_drift_fails_closed(
tmp_path: Path,
evidence_source_json: dict[str, Any],
evidence_scope: EvidenceScope,
evidence_metadata: EvidenceMetadata,
pragma: str,
) -> None:
source = _write_source(tmp_path / "source.json", evidence_source_json)
workspace = tmp_path / "workspace"
_store(source, workspace, evidence_scope, evidence_metadata)
connection = sqlite3.connect(workspace / "contextsafe.sqlite")
try:
connection.execute(pragma)
finally:
connection.close()
with pytest.raises(ContextSafeError) as raised:
EvidenceStore(workspace).list_records()
assert raised.value.code == "evidence_store_corrupt"
def test_empty_index_has_no_autoincrement_authority_row(tmp_path: Path) -> None:
workspace = tmp_path / "workspace"
store = EvidenceStore(workspace)
store._ensure_store()
assert store.list_records() == ()
assert _sqlite_sequence_rows(workspace / "contextsafe.sqlite") == ()
@pytest.mark.parametrize(
("damage_sql", "damaged_rows"),
[
(
"DELETE FROM sqlite_sequence WHERE name = 'evidence_records'",
(),
),
(
"UPDATE sqlite_sequence SET seq = 0 WHERE name = 'evidence_records'",
(("evidence_records", 0),),
),
(
"UPDATE sqlite_sequence SET seq = 2 WHERE name = 'evidence_records'",
(("evidence_records", 2),),
),
(
"INSERT INTO sqlite_sequence(name, seq) VALUES ('unexpected', 1)",
(("evidence_records", 1), ("unexpected", 1)),
),
],
)
def test_sqlite_sequence_drift_fails_reads_and_writes_without_repair_or_leaks(
tmp_path: Path,
evidence_source_json: dict[str, Any],
evidence_scope: EvidenceScope,
evidence_metadata: EvidenceMetadata,
damage_sql: str,
damaged_rows: tuple[tuple[object, object], ...],
) -> None:
source = _write_source(tmp_path / "source.json", evidence_source_json)
workspace = tmp_path / "workspace"
first = _store(source, workspace, evidence_scope, evidence_metadata)
database = workspace / "contextsafe.sqlite"
connection = sqlite3.connect(database)
try:
connection.execute(damage_sql)
connection.commit()
finally:
connection.close()
raw_root = workspace / "evidence" / "raw" / "sha256"
objects_before = {
path.relative_to(raw_root) for path in raw_root.glob("*/*") if path.is_file()
}
with pytest.raises(ContextSafeError) as raised:
EvidenceStore(workspace).list_records()
assert raised.value.code == "evidence_store_corrupt"
later = replace(
evidence_metadata,
captured_at=evidence_metadata.captured_at.replace(second=3),
)
with pytest.raises(ContextSafeError) as raised:
_store(source, workspace, evidence_scope, later)
assert raised.value.code == "evidence_store_corrupt"
assert _sqlite_sequence_rows(database) == damaged_rows
connection = sqlite3.connect(database)
try:
assert connection.execute(
"SELECT sequence, evidence_id FROM evidence_records"
).fetchall() == [(1, first.evidence_id)]
finally:
connection.close()
assert {
path.relative_to(raw_root) for path in raw_root.glob("*/*") if path.is_file()
} == objects_before
assert not list((raw_root / ".staging").iterdir())
@pytest.mark.parametrize(
("column", "replacement"),
[
("sequence", 7),
("evidence_id", "EVD-" + "f" * 64),
("raw_sha256", "f" * 64),
("record_json", None),
],
)
def test_integrity_verification_checks_every_index_column(
tmp_path: Path,
evidence_source_json: dict[str, Any],
evidence_scope: EvidenceScope,
evidence_metadata: EvidenceMetadata,
column: str,
replacement: object,
) -> None:
source = _write_source(tmp_path / "source.json", evidence_source_json)
workspace = tmp_path / "workspace"
record = _store(source, workspace, evidence_scope, evidence_metadata)
database = workspace / "contextsafe.sqlite"
connection = sqlite3.connect(database)
try:
trigger_sql = connection.execute(
"SELECT sql FROM sqlite_master "
"WHERE type = 'trigger' AND name = 'evidence_records_no_update'"
).fetchone()
assert trigger_sql is not None and isinstance(trigger_sql[0], str)
connection.execute("DROP TRIGGER evidence_records_no_update")
if column == "record_json":
stored = connection.execute(
"SELECT record_json FROM evidence_records WHERE evidence_id = ?",
(record.evidence_id,),
).fetchone()
assert stored is not None and isinstance(stored[0], str)
replacement = f" {stored[0]}"
update_sql = {
"sequence": "UPDATE evidence_records SET sequence = ? WHERE sequence = 1",
"evidence_id": (
"UPDATE evidence_records SET evidence_id = ? WHERE sequence = 1"
),
"raw_sha256": (
"UPDATE evidence_records SET raw_sha256 = ? WHERE sequence = 1"
),
"record_json": (
"UPDATE evidence_records SET record_json = ? WHERE sequence = 1"
),
}[column]
connection.execute(update_sql, (replacement,))
connection.execute(trigger_sql[0])
connection.commit()
finally:
connection.close()
with pytest.raises(ContextSafeError) as raised:
EvidenceStore(workspace).verify_integrity()
assert raised.value.code == "evidence_store_corrupt"
def test_read_apis_do_not_modify_the_database_or_workspace_shape(
tmp_path: Path,
evidence_source_json: dict[str, Any],
evidence_scope: EvidenceScope,
evidence_metadata: EvidenceMetadata,
) -> None:
source = _write_source(tmp_path / "source.json", evidence_source_json)
workspace = tmp_path / "workspace"
record = _store(source, workspace, evidence_scope, evidence_metadata)
database = workspace / "contextsafe.sqlite"
before = database.stat()
entries_before = {path.relative_to(workspace) for path in workspace.rglob("*")}
store = EvidenceStore(workspace)
assert store.get(record.evidence_id) == record
assert store.list_records() == (record,)
store.verify_integrity()
after = database.stat()
assert (after.st_size, after.st_mtime_ns, after.st_ctime_ns) == (
before.st_size,
before.st_mtime_ns,
before.st_ctime_ns,
)
assert {path.relative_to(workspace) for path in workspace.rglob("*")} == (
entries_before
)
def test_open_primary_error_survives_connection_close_failure(
tmp_path: Path,
evidence_source_json: dict[str, Any],
evidence_scope: EvidenceScope,
evidence_metadata: EvidenceMetadata,
monkeypatch: pytest.MonkeyPatch,
) -> None:
source = _write_source(tmp_path / "source.json", evidence_source_json)
workspace = tmp_path / "workspace"
_store(source, workspace, evidence_scope, evidence_metadata)
original_connect = sqlite3.connect
def close_failing_connect(*args: object, **kwargs: object) -> Any:
return _CloseFailingConnection(
original_connect(*args, **kwargs),
fail_statement="PRAGMA trusted_schema",
)
monkeypatch.setattr(store_module.sqlite3, "connect", close_failing_connect)
with pytest.raises(ContextSafeError) as raised:
EvidenceStore(workspace)._connect(read_only=True)
assert raised.value.code == "evidence_store_io_error"
assert isinstance(raised.value.__cause__, sqlite3.OperationalError)
assert str(raised.value.__cause__) == "injected connection operation failure"
def test_read_primary_error_survives_connection_close_failure(
tmp_path: Path,
evidence_source_json: dict[str, Any],
evidence_scope: EvidenceScope,
evidence_metadata: EvidenceMetadata,