-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathtest_run_redaction.py
More file actions
2232 lines (1914 loc) · 77.1 KB
/
Copy pathtest_run_redaction.py
File metadata and controls
2232 lines (1914 loc) · 77.1 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
"""Tests for the operator-only lifecycle journal redaction procedure."""
from __future__ import annotations
import hashlib
import json
import os
import subprocess
import stat
import sys
import textwrap
import time
from pathlib import Path
import pytest
from brigade import cli, run_checkpoint, run_events, run_journal, run_projector, run_redaction, run_shadow
RUN_ID = "20260730-190000-redact"
SECRET = "secret-value-that-must-not-survive"
REASON_CODE = "credential-exposure"
def _journal_path(run_dir: Path) -> Path:
return run_dir / "events" / "lifecycle.jsonl"
def _append(
journal: Path,
*,
event_type: str,
payload: dict,
key: str,
prior: int,
second: int,
) -> run_journal.RunEvent:
return run_journal.append_event(
journal,
run_id=RUN_ID,
event_type=event_type,
payload=payload,
idempotency_key=key,
expected_previous_sequence=prior,
recorded_at=f"2026-07-30T19:00:{second:02d}.000000Z",
)
def _authority_run(
tmp_path: Path,
*,
first_idempotency_key: str = "created",
) -> tuple[Path, dict, list[run_journal.RunEvent]]:
run_dir = tmp_path / "workspace" / ".brigade" / "runs" / RUN_ID
journal = _journal_path(run_dir)
base = {
"schema": "brigade.run.v1",
"schema_version": 1,
"task": "redaction fixture",
"status": "ok",
"cwd": str(tmp_path / "workspace"),
"lock_workspace": str(tmp_path / "workspace"),
"lifecycle_journal_requested": True,
"run_journal_authority_requested": True,
}
checkpoint_bytes = run_projector.encode_snapshot_bytes(base)
run_checkpoint.publish_checkpoint_file(run_dir, checkpoint_bytes)
events = [
_append(
journal,
event_type="run.created",
payload={"status": "started"},
key=first_idempotency_key,
prior=0,
second=0,
),
_append(
journal,
event_type="run.planning.started",
payload={"detail": SECRET},
key="planning",
prior=1,
second=1,
),
_append(
journal,
event_type=run_checkpoint.CHECKPOINT_EVENT_TYPE,
payload=run_checkpoint._checkpoint_payload(
checkpoint_bytes,
paired_event_type="run.completed",
body_kind="base-stripped",
),
key=run_checkpoint._checkpoint_idempotency_key(
run_checkpoint._checkpoint_payload(
checkpoint_bytes,
paired_event_type="run.completed",
body_kind="base-stripped",
)["sha256"],
paired_event_type="run.completed",
body_kind="base-stripped",
),
prior=2,
second=2,
),
_append(
journal,
event_type="run.completed",
payload={"status": "ok", "detail": "complete"},
key="completed",
prior=3,
second=3,
),
]
projection = run_projector.project_run_snapshot(base, events, journal_present=True)
(run_dir / "run.json").write_bytes(projection.to_bytes())
return run_dir, projection.snapshot, events
def _without_tail_digest(snapshot: dict) -> dict:
return {key: value for key, value in snapshot.items() if key != "journal_last_event_digest"}
def _latest_checkpoint_path(run_dir: Path) -> Path:
report = run_journal.read_journal_bounded(_journal_path(run_dir))
event = run_checkpoint.latest_checkpoint_event(report.events)
assert event is not None
return run_checkpoint.checkpoint_path(run_dir, event.payload["sha256"])
def _append_uncovered_terminal_event(run_dir: Path) -> None:
journal = _journal_path(run_dir)
report = run_journal.read_journal_bounded(journal)
_append(
journal,
event_type="run.completed",
payload={"status": "ok", "detail": "late terminal event"},
key="late-completed",
prior=report.events[-1].sequence,
second=4,
)
events = run_journal.read_journal_bounded(journal).events
snapshot = json.loads((run_dir / "run.json").read_text())
projection = run_projector.project_run_snapshot(snapshot, events, journal_present=True)
(run_dir / "run.json").write_bytes(projection.to_bytes())
def _artifact_snapshot(run_dir: Path) -> dict[str, bytes]:
return {str(path.relative_to(run_dir)): path.read_bytes() for path in sorted(run_dir.rglob("*")) if path.is_file()}
@pytest.mark.parametrize("platform_name", ["nt", "java"])
def test_redaction_refuses_unsupported_platform_before_lock_or_mutation(
tmp_path,
monkeypatch,
platform_name,
):
run_dir, _, _ = _authority_run(tmp_path)
before = _artifact_snapshot(run_dir)
external = tmp_path / "external"
external.mkdir()
original_events = run_dir / "events"
parked_events = run_dir / "events-parked"
monkeypatch.setattr(run_redaction, "_PLATFORM_NAME", platform_name, raising=False)
def raceable_parent_replacement(*args, **kwargs):
original_events.rename(parked_events)
original_events.symlink_to(external, target_is_directory=True)
(external / "escaped").write_text("unsafe fallback reached")
raise AssertionError("platform gate ran after the write-capable lock path")
monkeypatch.setattr(
run_redaction,
"_exclusive_redaction_lock",
raceable_parent_replacement,
)
with pytest.raises(run_redaction.RedactionError, match="unsupported platform"):
run_redaction.redact_journal(
run_dir,
sequence_start=2,
sequence_end=2,
reason=REASON_CODE,
operator_confirmed=True,
)
assert _artifact_snapshot(run_dir) == before
assert original_events.is_dir()
assert not original_events.is_symlink()
assert list(external.iterdir()) == []
assert not (tmp_path / "workspace" / ".brigade" / "run.lock").exists()
@pytest.mark.parametrize("missing_operation", [os.open, os.mkdir, os.rename, os.unlink, os.link])
def test_redaction_refuses_missing_dirfd_operation_before_any_write(
tmp_path,
monkeypatch,
missing_operation,
):
run_dir, _, _ = _authority_run(tmp_path)
before = _artifact_snapshot(run_dir)
supported = set(os.supports_dir_fd)
supported.discard(missing_operation)
monkeypatch.setattr(run_redaction.os, "supports_dir_fd", supported)
monkeypatch.setattr(
run_redaction,
"_exclusive_redaction_lock",
lambda *args, **kwargs: (_ for _ in ()).throw(
AssertionError("unsupported capability reached lock acquisition")
),
)
with pytest.raises(run_redaction.RedactionError, match="unsupported platform"):
run_redaction.redact_journal(
run_dir,
sequence_start=2,
sequence_end=2,
reason=REASON_CODE,
operator_confirmed=True,
)
assert _artifact_snapshot(run_dir) == before
assert not (tmp_path / "workspace" / ".brigade" / "run.lock").exists()
def test_redaction_refuses_missing_fd_listdir_before_any_write(tmp_path, monkeypatch):
run_dir, _, _ = _authority_run(tmp_path)
before = _artifact_snapshot(run_dir)
supported = set(os.supports_fd)
supported.discard(os.listdir)
monkeypatch.setattr(run_redaction.os, "supports_fd", supported)
monkeypatch.setattr(
run_redaction,
"_exclusive_redaction_lock",
lambda *args, **kwargs: (_ for _ in ()).throw(
AssertionError("unsupported capability reached lock acquisition")
),
)
with pytest.raises(run_redaction.RedactionError, match="unsupported platform"):
run_redaction.redact_journal(
run_dir,
sequence_start=2,
sequence_end=2,
reason=REASON_CODE,
operator_confirmed=True,
)
assert _artifact_snapshot(run_dir) == before
@pytest.mark.parametrize(
"missing_capability",
["directory-fsync", "nofollow", "directory-open", "fchmod", "link-nofollow"],
)
def test_redaction_refuses_missing_durability_or_containment_before_any_write(
tmp_path,
monkeypatch,
missing_capability,
):
run_dir, _, _ = _authority_run(tmp_path)
before = _artifact_snapshot(run_dir)
if missing_capability == "directory-fsync":
monkeypatch.setattr(run_redaction.os, "fsync", None)
elif missing_capability == "nofollow":
monkeypatch.setattr(run_journal, "_O_NOFOLLOW", 0)
elif missing_capability == "directory-open":
monkeypatch.setattr(run_journal, "_O_DIRECTORY", 0)
elif missing_capability == "fchmod":
monkeypatch.setattr(run_journal, "_HAS_FCHMOD", False)
else:
supported = set(os.supports_follow_symlinks)
supported.discard(os.link)
monkeypatch.setattr(run_redaction.os, "supports_follow_symlinks", supported)
monkeypatch.setattr(
run_redaction,
"_exclusive_redaction_lock",
lambda *args, **kwargs: (_ for _ in ()).throw(
AssertionError("unsupported durability or containment reached lock acquisition")
),
)
with pytest.raises(run_redaction.RedactionError, match="unsupported platform"):
run_redaction.redact_journal(
run_dir,
sequence_start=2,
sequence_end=2,
reason=REASON_CODE,
operator_confirmed=True,
)
assert _artifact_snapshot(run_dir) == before
def test_redaction_refuses_directory_fsync_probe_before_lock_or_mutation(
tmp_path,
monkeypatch,
):
run_dir, _, _ = _authority_run(tmp_path)
before = _artifact_snapshot(run_dir)
monkeypatch.setattr(
run_redaction.os,
"fsync",
lambda fd: (_ for _ in ()).throw(OSError("directory fsync unsupported")),
)
monkeypatch.setattr(
run_redaction,
"_exclusive_redaction_lock",
lambda *args, **kwargs: (_ for _ in ()).throw(
AssertionError("failed directory fsync probe reached lock acquisition")
),
)
with pytest.raises(run_redaction.RedactionError, match="unsupported platform"):
run_redaction.redact_journal(
run_dir,
sequence_start=2,
sequence_end=2,
reason=REASON_CODE,
operator_confirmed=True,
)
assert _artifact_snapshot(run_dir) == before
assert not (tmp_path / "workspace" / ".brigade" / "run.lock").exists()
def test_unsupported_platform_does_not_break_redaction_cli_help(monkeypatch, capsys):
monkeypatch.setattr(run_redaction, "_PLATFORM_NAME", "nt")
with pytest.raises(SystemExit) as raised:
cli.main(["runs", "redact", "--help"])
assert raised.value.code == 0
help_text = capsys.readouterr().out
assert "usage: brigade runs redact" in help_text
assert "Closed incident reason code" in help_text
def test_cleanup_refuses_unsupported_platform_before_lock_or_mutation(tmp_path, monkeypatch):
run_dir, _, _ = _authority_run(tmp_path)
report = run_redaction.redact_journal(
run_dir,
sequence_start=2,
sequence_end=2,
reason=REASON_CODE,
operator_confirmed=True,
)
before = _artifact_snapshot(run_dir)
monkeypatch.setattr(run_redaction, "_PLATFORM_NAME", "nt", raising=False)
monkeypatch.setattr(
run_redaction,
"_exclusive_redaction_lock",
lambda *args, **kwargs: (_ for _ in ()).throw(AssertionError("unsupported cleanup reached lock acquisition")),
)
with pytest.raises(run_redaction.RedactionError, match="unsupported platform"):
run_redaction.cleanup_redaction_quarantine(
run_dir,
operation_id=report.operation_id,
operator_confirmed=True,
)
assert _artifact_snapshot(run_dir) == before
assert report.quarantine_path.is_file()
assert not (tmp_path / "workspace" / ".brigade" / "run.lock").exists()
@pytest.mark.parametrize(
("failure_point", "exception_type"),
[
("fstat", KeyboardInterrupt),
("identity", SystemExit),
("mode", KeyboardInterrupt),
],
)
def test_open_directory_handle_closes_fd_once_on_baseexception(
tmp_path,
monkeypatch,
failure_point,
exception_type,
):
directory = tmp_path / "directory"
directory.mkdir(mode=0o755)
real_open = run_journal._open_nofollow
real_close = os.close
real_fstat = os.fstat
opened: list[int] = []
closed: list[int] = []
def capture_open(*args, **kwargs):
fd = real_open(*args, **kwargs)
opened.append(fd)
return fd
def track_close(fd):
if opened and fd == opened[0]:
closed.append(fd)
return real_close(fd)
monkeypatch.setattr(run_journal, "_open_nofollow", capture_open)
monkeypatch.setattr(run_redaction.os, "close", track_close)
if failure_point == "fstat":
monkeypatch.setattr(
run_redaction.os,
"fstat",
lambda fd: (_ for _ in ()).throw(exception_type()),
)
elif failure_point == "identity":
class ExplodingIdentity:
def __init__(self, fd):
info = real_fstat(fd)
self.st_mode = info.st_mode
self.st_ino = info.st_ino
@property
def st_dev(self):
raise exception_type()
monkeypatch.setattr(
run_redaction.os,
"fstat",
ExplodingIdentity,
)
else:
monkeypatch.setattr(
run_journal,
"_chmod_fd_or_path",
lambda *args, **kwargs: (_ for _ in ()).throw(exception_type()),
)
with pytest.raises(exception_type):
run_redaction._open_directory_handle(directory, category="test directory")
assert len(opened) == 1
assert closed == opened
with pytest.raises(OSError):
real_fstat(opened[0])
def test_open_directory_handle_preserves_baseexception_when_close_raises(
tmp_path,
monkeypatch,
):
directory = tmp_path / "directory"
directory.mkdir()
real_open = run_journal._open_nofollow
real_close = os.close
opened: list[int] = []
closed: list[int] = []
def capture_open(*args, **kwargs):
fd = real_open(*args, **kwargs)
opened.append(fd)
return fd
def close_then_raise(fd):
closed.append(fd)
real_close(fd)
raise OSError("simulated close failure")
monkeypatch.setattr(run_journal, "_open_nofollow", capture_open)
monkeypatch.setattr(
run_redaction.os,
"fstat",
lambda fd: (_ for _ in ()).throw(KeyboardInterrupt()),
)
monkeypatch.setattr(run_redaction.os, "close", close_then_raise)
with pytest.raises(KeyboardInterrupt):
run_redaction._open_directory_handle(directory, category="test directory")
assert closed == opened
def test_redaction_quarantines_rewrites_rechains_and_reprojects(tmp_path):
run_dir, before_projection, original_events = _authority_run(tmp_path)
report = run_redaction.redact_journal(
run_dir,
sequence_start=2,
sequence_end=2,
reason=REASON_CODE,
operator_confirmed=True,
)
active = _journal_path(run_dir).read_bytes()
record = report.record_path.read_bytes()
assert SECRET.encode() not in active
assert SECRET.encode() not in record
assert b'"reason_code": "credential-exposure"' in record
assert b'"sequence_start": 2' in record
assert b'"sequence_end": 2' in record
assert report.quarantine_path.is_file()
assert SECRET.encode() in report.quarantine_path.read_bytes()
assert stat.S_IMODE(report.quarantine_path.stat().st_mode) == 0o600
assert stat.S_IMODE(report.quarantine_path.parent.stat().st_mode) == 0o700
verified = run_journal.read_journal_bounded(_journal_path(run_dir))
assert verified.chain_errors == []
assert verified.partial_tail is None
assert len(verified.events) == len(original_events) + 1
assert verified.events[1].payload == {"detail": "[REDACTED]"}
assert verified.events[0].event_digest == original_events[0].event_digest
assert verified.events[1].event_digest != original_events[1].event_digest
assert verified.events[2].previous_digest == verified.events[1].event_digest
current = json.loads((run_dir / "run.json").read_text())
after_projection = run_projector.project_run_snapshot(current, verified.events, journal_present=True).snapshot
assert current == after_projection
expected_projection = dict(before_projection)
expected_projection["journal_last_sequence"] = len(verified.events)
assert _without_tail_digest(current) == _without_tail_digest(expected_projection)
assert current["journal_last_event_digest"] == verified.events[-1].event_digest
def test_redaction_preserves_first_anchor_when_second_range_contains_it(tmp_path):
run_dir, _, _ = _authority_run(tmp_path)
first = run_redaction.redact_journal(
run_dir,
sequence_start=2,
sequence_end=2,
reason=REASON_CODE,
operator_confirmed=True,
)
first_anchor = next(
event
for event in run_journal.read_journal_bounded(_journal_path(run_dir)).events
if event.event_type == "run.redaction.recorded" and event.payload["operation_id"] == first.operation_id
)
second_sequence_start = 2
second_sequence_end = first_anchor.sequence
assert second_sequence_start <= first_anchor.sequence <= second_sequence_end
second = run_redaction.redact_journal(
run_dir,
sequence_start=second_sequence_start,
sequence_end=second_sequence_end,
reason=REASON_CODE,
operator_confirmed=True,
)
verified = run_journal.read_journal_bounded(_journal_path(run_dir))
assert verified.chain_errors == []
assert verified.partial_tail is None
anchors = [event for event in verified.events if event.event_type == "run.redaction.recorded"]
assert {anchor.payload["operation_id"] for anchor in anchors} == {first.operation_id, second.operation_id}
assert all(
set(anchor.payload)
== {
"operation_id",
"affected_first_sequence",
"affected_last_sequence",
"reason_class",
"record_sha256",
}
for anchor in anchors
)
record_hashes = {
report.operation_id: hashlib.sha256(report.record_path.read_bytes()).hexdigest() for report in (first, second)
}
assert {anchor.payload["operation_id"]: anchor.payload["record_sha256"] for anchor in anchors} == record_hashes
second_record = json.loads(second.record_path.read_text())
assert second_record["parent_operation_id"] == first.operation_id
def test_redaction_rejects_preserved_structural_only_range_without_mutation(tmp_path):
run_dir, _, events = _authority_run(tmp_path)
checkpoint = next(event for event in events if event.event_type == run_checkpoint.CHECKPOINT_EVENT_TYPE)
before = _artifact_snapshot(run_dir)
with pytest.raises(run_redaction.RedactionError, match="redaction range contains no redactable payloads"):
run_redaction.redact_journal(
run_dir,
sequence_start=checkpoint.sequence,
sequence_end=checkpoint.sequence,
reason=REASON_CODE,
operator_confirmed=True,
)
assert _artifact_snapshot(run_dir) == before
assert not (run_dir / "events" / "redactions").exists()
def test_resume_projection_accepts_only_trailing_redaction_anchor_lag(tmp_path):
run_dir, _, _ = _authority_run(tmp_path)
run_redaction.redact_journal(
run_dir,
sequence_start=2,
sequence_end=2,
reason=REASON_CODE,
operator_confirmed=True,
)
events = run_journal.read_journal_bounded(_journal_path(run_dir)).events
projected_before_anchor = json.loads((run_dir / "run.json").read_text())
projected_before_anchor["journal_last_sequence"] = events[-2].sequence
projected_before_anchor["journal_last_event_digest"] = events[-2].event_digest
(run_dir / "run.json").write_text(json.dumps(projected_before_anchor, indent=2, sort_keys=True) + "\n")
run_redaction._resume_projection_after_rewrite(run_dir, events)
assert (
json.loads((run_dir / "run.json").read_text())
== run_projector.project_run_snapshot(projected_before_anchor, events, journal_present=True).snapshot
)
def test_resume_projection_rejects_non_anchor_sequence_lag(tmp_path):
run_dir, _, _ = _authority_run(tmp_path)
run_redaction.redact_journal(
run_dir,
sequence_start=2,
sequence_end=2,
reason=REASON_CODE,
operator_confirmed=True,
)
events = run_journal.read_journal_bounded(_journal_path(run_dir)).events
stale = json.loads((run_dir / "run.json").read_text())
stale["journal_last_sequence"] = events[-3].sequence
stale["journal_last_event_digest"] = events[-3].event_digest
(run_dir / "run.json").write_text(json.dumps(stale, indent=2, sort_keys=True) + "\n")
with pytest.raises(run_redaction.RedactionError, match="projection sequence lag"):
run_redaction._resume_projection_after_rewrite(run_dir, events)
def test_redaction_retry_appends_missing_anchor_after_verified_record(tmp_path, monkeypatch):
run_dir, _, _ = _authority_run(tmp_path)
real_append = run_redaction._append_redaction_anchor
failed = False
def fail_before_anchor(*args, **kwargs):
nonlocal failed
if not failed:
failed = True
raise run_redaction.RedactionError("simulated anchor append failure")
return real_append(*args, **kwargs)
monkeypatch.setattr(run_redaction, "_append_redaction_anchor", fail_before_anchor)
with pytest.raises(run_redaction.RedactionError, match="anchor append"):
run_redaction.redact_journal(
run_dir, sequence_start=2, sequence_end=2, reason=REASON_CODE, operator_confirmed=True
)
monkeypatch.setattr(run_redaction, "_append_redaction_anchor", real_append)
report = run_redaction.redact_journal(
run_dir, sequence_start=2, sequence_end=2, reason=REASON_CODE, operator_confirmed=True
)
events = run_journal.read_journal_bounded(_journal_path(run_dir)).events
anchors = [event for event in events if event.event_type == "run.redaction.recorded"]
assert [anchor.payload["operation_id"] for anchor in anchors] == [report.operation_id]
assert (
json.loads((run_dir / "run.json").read_text())
== run_projector.project_run_snapshot(
json.loads((run_dir / "run.json").read_text()), events, journal_present=True
).snapshot
)
def test_redaction_retry_reprojects_after_anchor_before_projection_failure(tmp_path, monkeypatch):
run_dir, _, _ = _authority_run(tmp_path)
real_replace_projection = run_redaction._replace_projection
failed = False
def fail_anchor_projection(path, projection):
nonlocal failed
if not failed and projection.snapshot["journal_last_sequence"] == 5:
failed = True
raise run_redaction.RedactionError("simulated anchor projection failure")
return real_replace_projection(path, projection)
monkeypatch.setattr(run_redaction, "_replace_projection", fail_anchor_projection)
with pytest.raises(run_redaction.RedactionError, match="anchor projection"):
run_redaction.redact_journal(
run_dir, sequence_start=2, sequence_end=2, reason=REASON_CODE, operator_confirmed=True
)
monkeypatch.setattr(run_redaction, "_replace_projection", real_replace_projection)
report = run_redaction.redact_journal(
run_dir, sequence_start=2, sequence_end=2, reason=REASON_CODE, operator_confirmed=True
)
events = run_journal.read_journal_bounded(_journal_path(run_dir)).events
anchors = [event for event in events if event.event_type == "run.redaction.recorded"]
assert [anchor.payload["operation_id"] for anchor in anchors] == [report.operation_id]
assert (
json.loads((run_dir / "run.json").read_text())
== run_projector.project_run_snapshot(
json.loads((run_dir / "run.json").read_text()), events, journal_present=True
).snapshot
)
def test_redaction_refuses_anchor_append_after_ownership_loss(tmp_path, monkeypatch):
run_dir, _, _ = _authority_run(tmp_path)
real_assert_owner = run_redaction._assert_active_owner
calls = 0
def lose_owner(workspace, resolved_run_dir):
nonlocal calls
calls += 1
if calls == 2:
raise run_redaction.RedactionError("redaction lost exclusive run lock ownership")
return real_assert_owner(workspace, resolved_run_dir)
monkeypatch.setattr(run_redaction, "_assert_active_owner", lose_owner)
with pytest.raises(run_redaction.RedactionError, match="lost exclusive"):
run_redaction.redact_journal(
run_dir, sequence_start=2, sequence_end=2, reason=REASON_CODE, operator_confirmed=True
)
assert not [
event
for event in run_journal.read_journal_bounded(_journal_path(run_dir)).events
if event.event_type == "run.redaction.recorded"
]
def test_replaced_redaction_record_set_fails_chained_anchor_validation(tmp_path):
run_dir, _, _ = _authority_run(tmp_path)
report = run_redaction.redact_journal(
run_dir,
sequence_start=2,
sequence_end=2,
reason=REASON_CODE,
operator_confirmed=True,
)
record = json.loads(report.record_path.read_text())
replacement = (json.dumps(record, separators=(",", ":")) + "\n").encode()
assert replacement != report.record_path.read_bytes()
report.record_path.write_bytes(replacement)
with pytest.raises(run_redaction.RedactionError, match="anchor"):
run_redaction._post_replace_verify(run_dir, expected_digest=None)
def test_redaction_refuses_live_lock_without_mutation(tmp_path):
run_dir, _, _ = _authority_run(tmp_path)
workspace = tmp_path / "workspace"
lock = workspace / ".brigade" / "run.lock"
lock.mkdir(parents=True)
(lock / "pid").write_text(f"{os.getpid()}\n")
(lock / "owner.json").write_text(
json.dumps(
{
"schema": "brigade.run_lock.v1",
"owner_token": "active-owner",
"pid": os.getpid(),
"run_dir": str(run_dir.resolve()),
"acquired_at": "2026-07-30T19:00:00+00:00",
}
)
)
before = _journal_path(run_dir).read_bytes()
with pytest.raises(run_redaction.RedactionError, match="run lock state is live"):
run_redaction.redact_journal(
run_dir,
sequence_start=2,
sequence_end=2,
reason=REASON_CODE,
operator_confirmed=True,
)
assert _journal_path(run_dir).read_bytes() == before
assert not (run_dir / "events" / "redactions").exists()
@pytest.mark.parametrize("lock_kind", ["malformed", "stale", "foreign"])
def test_redaction_fails_closed_on_ambiguous_lock_state(tmp_path, lock_kind):
run_dir, _, _ = _authority_run(tmp_path)
workspace = tmp_path / "workspace"
lock = workspace / ".brigade" / "run.lock"
if lock_kind == "malformed":
lock.parent.mkdir(parents=True, exist_ok=True)
lock.write_text("not a directory")
else:
lock.mkdir(parents=True)
(lock / "pid").write_text("99999999\n")
owner_run = run_dir if lock_kind == "stale" else tmp_path / "other-run"
(lock / "owner.json").write_text(
json.dumps(
{
"schema": "brigade.run_lock.v1",
"owner_token": "dead-owner",
"pid": 99999999,
"run_dir": str(owner_run.resolve()),
"acquired_at": "2026-07-30T19:00:00+00:00",
}
)
)
before = _journal_path(run_dir).read_bytes()
with pytest.raises(run_redaction.RedactionError, match="run lock state"):
run_redaction.redact_journal(
run_dir,
sequence_start=2,
sequence_end=2,
reason=REASON_CODE,
operator_confirmed=True,
)
assert _journal_path(run_dir).read_bytes() == before
def test_redaction_refuses_malformed_journal_before_quarantine(tmp_path):
run_dir, _, _ = _authority_run(tmp_path)
journal = _journal_path(run_dir)
journal.write_bytes(journal.read_bytes() + b'{"partial":')
before = journal.read_bytes()
with pytest.raises(run_redaction.RedactionError, match="journal"):
run_redaction.redact_journal(
run_dir,
sequence_start=2,
sequence_end=2,
reason=REASON_CODE,
operator_confirmed=True,
)
assert journal.read_bytes() == before
assert not (run_dir / "events" / "redactions").exists()
@pytest.mark.parametrize(
("start", "end"),
[(0, 1), (1, 0), (2, 5), (True, 2), (2, False)],
)
def test_redaction_rejects_invalid_sequence_range_without_mutation(tmp_path, start, end):
run_dir, _, _ = _authority_run(tmp_path)
before = _journal_path(run_dir).read_bytes()
with pytest.raises(run_redaction.RedactionError, match="sequence range"):
run_redaction.redact_journal(
run_dir,
sequence_start=start,
sequence_end=end,
reason=REASON_CODE,
operator_confirmed=True,
)
assert _journal_path(run_dir).read_bytes() == before
def test_redaction_requires_explicit_operator_confirmation(tmp_path):
run_dir, _, _ = _authority_run(tmp_path)
before = _journal_path(run_dir).read_bytes()
with pytest.raises(run_redaction.RedactionError, match="operator confirmation"):
run_redaction.redact_journal(
run_dir,
sequence_start=2,
sequence_end=2,
reason=REASON_CODE,
)
assert _journal_path(run_dir).read_bytes() == before
@pytest.mark.parametrize("reason", ["", " ", "x" * 241, "line one\nline two"])
def test_redaction_rejects_unbounded_or_multiline_reason(tmp_path, reason):
run_dir, _, _ = _authority_run(tmp_path)
before = _journal_path(run_dir).read_bytes()
with pytest.raises(run_redaction.RedactionError, match="reason"):
run_redaction.redact_journal(
run_dir,
sequence_start=2,
sequence_end=2,
reason=reason,
operator_confirmed=True,
)
assert _journal_path(run_dir).read_bytes() == before
@pytest.mark.parametrize("reason", [SECRET, "planning"])
def test_redaction_rejects_reason_that_copies_affected_private_value(tmp_path, reason):
run_dir, _, _ = _authority_run(tmp_path)
before = _journal_path(run_dir).read_bytes()
with pytest.raises(run_redaction.RedactionError, match="reason"):
run_redaction.redact_journal(
run_dir,
sequence_start=2,
sequence_end=2,
reason=reason,
operator_confirmed=True,
)
assert _journal_path(run_dir).read_bytes() == before
def test_redaction_retry_is_idempotent(tmp_path):
run_dir, _, _ = _authority_run(tmp_path)
first = run_redaction.redact_journal(
run_dir,
sequence_start=2,
sequence_end=2,
reason=REASON_CODE,
operator_confirmed=True,
)
active = _journal_path(run_dir).read_bytes()
replay = run_redaction.redact_journal(
run_dir,
sequence_start=2,
sequence_end=2,
reason=REASON_CODE,
operator_confirmed=True,
)
assert replay.operation_id == first.operation_id
assert replay.quarantine_path == first.quarantine_path
assert replay.record_path == first.record_path
assert _journal_path(run_dir).read_bytes() == active
assert len(list((run_dir / "events" / "redactions").glob("*/original.jsonl"))) == 1
def test_redaction_retry_refuses_tampered_quarantine(tmp_path):
run_dir, _, _ = _authority_run(tmp_path)
first = run_redaction.redact_journal(
run_dir,
sequence_start=2,
sequence_end=2,
reason=REASON_CODE,
operator_confirmed=True,
)
first.quarantine_path.write_bytes(b"tampered")
with pytest.raises(run_redaction.RedactionError, match="quarantine verification"):
run_redaction.redact_journal(
run_dir,
sequence_start=2,
sequence_end=2,
reason=REASON_CODE,
operator_confirmed=True,
)
def test_redaction_retry_refuses_symlinked_record(tmp_path):
run_dir, _, _ = _authority_run(tmp_path)
first = run_redaction.redact_journal(
run_dir,
sequence_start=2,
sequence_end=2,
reason=REASON_CODE,
operator_confirmed=True,
)
outside = tmp_path / "outside-record.json"
outside.write_text("{}")
first.record_path.unlink()
first.record_path.symlink_to(outside)
with pytest.raises(run_redaction.RedactionError, match="redaction record"):
run_redaction.redact_journal(
run_dir,
sequence_start=2,
sequence_end=2,
reason=REASON_CODE,
operator_confirmed=True,
)
assert outside.read_text() == "{}"
def test_redaction_replace_failure_retains_original_and_durable_quarantine(tmp_path, monkeypatch):
run_dir, _, _ = _authority_run(tmp_path)
before = _journal_path(run_dir).read_bytes()
def fail_replace(*args, **kwargs):
raise OSError("simulated replace failure")
monkeypatch.setattr(run_redaction, "_replace_relative", fail_replace)
with pytest.raises(run_redaction.RedactionError, match="replace"):
run_redaction.redact_journal(
run_dir,
sequence_start=2,
sequence_end=2,
reason=REASON_CODE,
operator_confirmed=True,
)
assert _journal_path(run_dir).read_bytes() == before
quarantines = list((run_dir / "events" / "redactions").glob("*/original.jsonl"))
assert len(quarantines) == 1
assert quarantines[0].read_bytes() == before
def test_redaction_retry_completes_after_record_crash_window(tmp_path, monkeypatch):
run_dir, _, _ = _authority_run(tmp_path)
real_write_record = run_redaction._write_redaction_record
calls = 0
def fail_once(*args, **kwargs):
nonlocal calls
calls += 1
if calls == 1:
raise OSError("simulated record failure")
return real_write_record(*args, **kwargs)
monkeypatch.setattr(run_redaction, "_write_redaction_record", fail_once)