forked from ChelseaKR/habitable
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_relay.py
More file actions
1726 lines (1500 loc) · 70.9 KB
/
Copy pathtest_relay.py
File metadata and controls
1726 lines (1500 loc) · 70.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
# SPDX-License-Identifier: AGPL-3.0-or-later
# Copyright 2026 Chelsea Kelly-Reif
"""The optional ciphertext-only relay."""
from __future__ import annotations
import base64
import concurrent.futures
import contextlib
import hashlib
import http.client
import io
import json
import os
import socket
import stat
import struct
import threading
import time
import urllib.error
import urllib.request
from collections.abc import Iterator
from pathlib import Path
from types import SimpleNamespace
from typing import cast
import pytest
from habitable import relay
from habitable.relay import (
RelayStore,
RoomAuthError,
RoomFullError,
_route_label,
configure_logging,
make_server,
)
# A stand-in room write-capability token for tests that drive the store/HTTP layer
# directly (the real client derives it from the channel; see habitable.sync).
_TOKEN = "test-room-token"
_TOKEN_HEADER = "X-Habitable-Room-Token"
# Fields every structured access-log line must carry (OBSERVABILITY-STANDARD §3,
# specialized to the relay's metadata-only contract).
_REQUIRED_LOG_FIELDS = {
"ts",
"level",
"msg",
"request_id",
"method",
"path",
"status",
"latency_ms",
}
class TestRelayStore:
def test_non_finite_ttl_environment_falls_back_to_default(
self, monkeypatch: pytest.MonkeyPatch
) -> None:
for raw in ("nan", "inf", "-inf"):
monkeypatch.setenv("HABITABLE_RELAY_TTL_SECONDS", raw)
assert relay._ttl_from_env() == relay._DEFAULT_TTL_SECONDS
monkeypatch.setenv("HABITABLE_RELAY_TTL_SECONDS", "0")
assert relay._ttl_from_env() == 0.0 # explicit expiry disable remains supported
def test_explicit_initial_state_enforces_room_token_and_record_invariants(self) -> None:
normalized = RelayStore(rooms={"empty": []}, tokens={"empty": "token"})
assert normalized.rooms == {}
assert normalized.tokens == {}
invalid_states: list[tuple[dict[str, list[tuple[float, bytes]]], dict[str, str]]] = [
({"bad/room": [(1.0, b"x")]}, {"bad/room": "token"}),
({"room": [(1.0, b"x")]}, {}),
({}, {"orphan": "token"}),
({"room": [(1.0, b"x")]}, {"room": ""}),
({"room": [(1.0, b"x")]}, {"room": "tökën"}),
(
{"room": [(1.0, b"x")]},
{"room": "t" * (relay._MAX_ROOM_TOKEN_CHARS + 1)},
),
({"room": [(float("nan"), b"x")]}, {"room": "token"}),
({"room": [(1e20, b"x")]}, {"room": "token"}),
({"room": [(1.0, b"")]}, {"room": "token"}),
]
for rooms, tokens in invalid_states:
with pytest.raises(ValueError):
RelayStore(rooms=rooms, tokens=tokens)
valid = RelayStore(rooms={"room": [(1.0, b"x")]}, tokens={"room": "token"})
assert set(valid.tokens) == set(valid.rooms) == {"room"}
def test_explicit_state_caps_fail_before_iterating_message_records(
self, monkeypatch: pytest.MonkeyPatch
) -> None:
class ExplodingQueue(list[tuple[float, bytes]]):
def __iter__(self) -> Iterator[tuple[float, bytes]]:
raise AssertionError("message records were iterated before count admission")
queue = ExplodingQueue([(1.0, b"a"), (2.0, b"b")])
monkeypatch.setattr(relay, "_MAX_LIVE_ROOMS", 0)
with pytest.raises(ValueError, match="room/token limit"):
RelayStore(rooms={"room": queue}, tokens={"room": "token"})
monkeypatch.setattr(relay, "_MAX_LIVE_ROOMS", 10)
monkeypatch.setattr(relay, "_MAX_MESSAGES_PER_ROOM", 1)
with pytest.raises(ValueError, match="message limit"):
RelayStore(rooms={"room": queue}, tokens={"room": "token"})
def test_post_fetch_round_trip_and_metrics(self) -> None:
store = RelayStore()
store.post("room", b"ciphertext-1", token=_TOKEN)
store.post("room", b"ciphertext-2", token=_TOKEN)
assert store.fetch("room") == [b"ciphertext-1", b"ciphertext-2"]
metrics = store.metrics()
assert metrics["posted"] == 2 and metrics["rooms"] == 1
assert metrics["bytes_relayed"] == len(b"ciphertext-1") + len(b"ciphertext-2")
def test_direct_post_rejects_mutable_or_wrongly_typed_inputs_without_state(self) -> None:
store = RelayStore()
with pytest.raises(RoomAuthError, match="invalid room"):
store.post(cast(str, 123), b"x", token=_TOKEN)
with pytest.raises(RoomAuthError, match="invalid room token"):
store.post("room", b"x", token=cast(str, b"token"))
with pytest.raises(TypeError, match="immutable bytes"):
store.post("room", cast(bytes, bytearray(b"mutable")), token=_TOKEN)
assert store.rooms == {} and store.tokens == {}
def test_empty_room(self) -> None:
assert RelayStore().fetch("nobody") == []
def test_post_requires_a_token(self) -> None:
store = RelayStore()
with pytest.raises(RoomAuthError):
store.post("room", b"x", token=None)
with pytest.raises(RoomAuthError):
store.post("room", b"x", token="")
def test_first_token_binds_and_mismatch_is_rejected(self) -> None:
"""Trust-on-first-use: the first token claims the room; others are rejected."""
store = RelayStore()
store.post("room", b"one", token=_TOKEN)
store.post("room", b"two", token=_TOKEN) # same token: fine
with pytest.raises(RoomAuthError):
store.post("room", b"evil", token="a-different-token")
# The rejected write did not land.
assert store.fetch("room") == [b"one", b"two"]
@pytest.mark.parametrize("token", ["tökën", "contains space", "plus+", "dot."])
def test_token_grammar_rejects_non_ascii_or_non_base64url_without_crashing(
self, token: str
) -> None:
store = RelayStore()
store.post("room", b"accepted", token=_TOKEN)
with pytest.raises(RoomAuthError, match="invalid room token"):
store.post("room", b"must-not-land", token=token)
assert store.fetch("room") == [b"accepted"]
def test_room_full_raises_instead_of_silent_eviction(
self, monkeypatch: pytest.MonkeyPatch
) -> None:
monkeypatch.setattr(relay, "_MAX_MESSAGES_PER_ROOM", 2)
store = RelayStore()
store.post("room", b"1", token=_TOKEN)
store.post("room", b"2", token=_TOKEN)
with pytest.raises(RoomFullError):
store.post("room", b"3", token=_TOKEN)
# The earlier messages are intact — no silent pop(0) displacement.
assert store.fetch("room") == [b"1", b"2"]
def test_ttl_expires_stale_messages_lazily(self, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(relay, "_MESSAGE_TTL_SECONDS", 10.0)
now = {"t": 1_000.0}
store = RelayStore(clock=lambda: now["t"])
store.post("room", b"fresh", token=_TOKEN)
assert store.fetch("room") == [b"fresh"]
now["t"] += 11.0 # advance past the TTL
assert store.fetch("room") == [] # expired lazily on fetch
# A subsequent post starts a clean queue (expiry also runs on post).
store.post("room", b"new", token=_TOKEN)
assert store.fetch("room") == [b"new"]
def test_ttl_zero_disables_expiry(self, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(relay, "_MESSAGE_TTL_SECONDS", 0.0)
now = {"t": 1_000.0}
store = RelayStore(clock=lambda: now["t"])
store.post("room", b"keep", token=_TOKEN)
now["t"] += 10_000_000.0
assert store.fetch("room") == [b"keep"]
def test_global_room_message_and_byte_caps_reject_without_eviction(
self, monkeypatch: pytest.MonkeyPatch
) -> None:
monkeypatch.setattr(relay, "_MAX_LIVE_ROOMS", 2)
monkeypatch.setattr(relay, "_MAX_LIVE_MESSAGES", 2)
monkeypatch.setattr(relay, "_MAX_LIVE_CIPHERTEXT_BYTES", 4)
monkeypatch.setattr(relay, "_MAX_CIPHERTEXT_BYTES_PER_ROOM", 10)
store = RelayStore()
store.post("one", b"aa", token="token-one")
store.post("two", b"bb", token="token-two")
with pytest.raises(RoomFullError, match="relay full"):
store.post("three", b"c", token="token-three")
with pytest.raises(RoomFullError, match="relay full"):
store.post("one", b"c", token="token-one")
assert store.fetch("one") == [b"aa"]
assert store.fetch("two") == [b"bb"]
assert "three" not in store.rooms and "three" not in store.tokens
metrics = store.metrics()
assert metrics["rooms"] == 2
assert metrics["live_messages"] == 2
assert metrics["live_ciphertext_bytes"] == 4
assert metrics["capacity_rejections"] == 2
def test_per_room_byte_cap_bounds_non_destructive_fetch(
self, monkeypatch: pytest.MonkeyPatch
) -> None:
monkeypatch.setattr(relay, "_MAX_CIPHERTEXT_BYTES_PER_ROOM", 5)
store = RelayStore()
store.post("room", b"abc", token=_TOKEN)
with pytest.raises(RoomFullError, match="room full"):
store.post("room", b"def", token=_TOKEN)
assert store.fetch("room") == [b"abc"]
assert store.fetch("room") == [b"abc"] # GET/fetch never drains the room
assert store.metrics()["live_ciphertext_bytes"] == 3
def test_size_and_capacity_rejections_do_not_bind_or_mutate_tofu_state(
self, monkeypatch: pytest.MonkeyPatch
) -> None:
monkeypatch.setattr(relay, "_MAX_BODY", 2)
empty = RelayStore()
with pytest.raises(RoomFullError, match="message too large"):
empty.post("new-room", b"abc", token="claimant")
assert empty.rooms == {} and empty.tokens == {}
monkeypatch.setattr(relay, "_MAX_BODY", 10)
monkeypatch.setattr(relay, "_MESSAGE_TTL_SECONDS", 1.0)
now = {"t": 1_000.0}
store = RelayStore(clock=lambda: now["t"])
store.post("existing", b"old", token="bound-token")
before_rooms = {room: list(queue) for room, queue in store.rooms.items()}
before_tokens = dict(store.tokens)
now["t"] += 2.0
monkeypatch.setattr(relay, "_MAX_LIVE_CIPHERTEXT_BYTES", 0)
with pytest.raises(RoomFullError, match="relay full"):
store.post("new-room", b"x", token="new-token")
# The bounded global TTL sweep may remove expired state, but the rejected
# candidate must never claim a token or create a room/message.
assert "new-room" not in store.rooms and "new-room" not in store.tokens
assert before_rooms["existing"][0][1] == b"old"
assert before_tokens["existing"] == "bound-token"
assert store.rooms == {} and store.tokens == {}
def test_global_capacity_check_sweeps_expired_unknown_rooms(
self, monkeypatch: pytest.MonkeyPatch
) -> None:
monkeypatch.setattr(relay, "_MAX_LIVE_ROOMS", 1)
monkeypatch.setattr(relay, "_MESSAGE_TTL_SECONDS", 1.0)
now = {"t": 1_000.0}
store = RelayStore(clock=lambda: now["t"])
store.post("forgotten", b"old", token="old-token")
now["t"] += 2.0
# No caller has to know/touch the stale room before capacity is reclaimed.
store.post("new-room", b"new", token="new-token")
assert store.fetch("new-room") == [b"new"]
assert "forgotten" not in store.rooms and "forgotten" not in store.tokens
def test_ttl_churn_bounds_tokens_and_allows_expired_room_rebinding(
self, monkeypatch: pytest.MonkeyPatch
) -> None:
monkeypatch.setattr(relay, "_MAX_LIVE_ROOMS", 2)
monkeypatch.setattr(relay, "_MESSAGE_TTL_SECONDS", 1.0)
now = {"t": 1_000.0}
store = RelayStore(clock=lambda: now["t"])
for index in range(10):
store.post(f"room-{index}", b"x", token=f"token-{index}")
now["t"] += 2.0
assert len(store.rooms) <= 2
assert len(store.tokens) <= 2
# Fetch-triggered expiry removes the final message and its binding, so the
# same now-empty room may be claimed afresh.
last_room = "room-9"
assert store.fetch(last_room) == []
assert last_room not in store.tokens
store.post(last_room, b"new", token="replacement-token")
assert store.tokens[last_room] == "replacement-token"
def test_ttl_disabled_retains_bounded_binding_and_rejects_rebind(
self, monkeypatch: pytest.MonkeyPatch
) -> None:
monkeypatch.setattr(relay, "_MAX_LIVE_ROOMS", 1)
monkeypatch.setattr(relay, "_MESSAGE_TTL_SECONDS", 0.0)
now = {"t": 1_000.0}
store = RelayStore(clock=lambda: now["t"])
store.post("room", b"keep", token="original-token")
now["t"] += 10_000_000.0
with pytest.raises(RoomAuthError, match="mismatch"):
store.post("room", b"wrong", token="replacement-token")
with pytest.raises(RoomFullError, match="relay full"):
store.post("other", b"other", token="other-token")
assert store.tokens == {"room": "original-token"}
assert store.fetch("room") == [b"keep"]
def test_parallel_posts_cannot_overshoot_global_caps(
self, monkeypatch: pytest.MonkeyPatch
) -> None:
workers = 16
monkeypatch.setattr(relay, "_MAX_LIVE_ROOMS", workers)
monkeypatch.setattr(relay, "_MAX_LIVE_MESSAGES", 1)
monkeypatch.setattr(relay, "_MAX_LIVE_CIPHERTEXT_BYTES", 1)
monkeypatch.setattr(relay, "_MAX_CIPHERTEXT_BYTES_PER_ROOM", 1)
store = RelayStore()
barrier = threading.Barrier(workers)
def attempt(index: int) -> bool:
barrier.wait()
try:
store.post(f"room-{index}", b"x", token=f"token-{index}")
except RoomFullError:
return False
return True
with concurrent.futures.ThreadPoolExecutor(max_workers=workers) as executor:
accepted = list(executor.map(attempt, range(workers)))
assert sum(accepted) == 1
assert len(store.rooms) == len(store.tokens) == 1
metrics = store.metrics()
assert metrics["live_messages"] == metrics["live_ciphertext_bytes"] == 1
assert metrics["capacity_rejections"] == workers - 1
def _journal_path(root: Path, room: str) -> Path:
return root / f"{hashlib.sha256(room.encode()).hexdigest()}.jsonl"
def _journal_record(
room: str,
*,
token: str = _TOKEN,
timestamp: float = 1_000.0,
blob: bytes = b"ciphertext",
) -> bytes:
return (RelayStore._journal_line(room, token, timestamp, blob) + "\n").encode()
class TestPersistence:
def test_round_trip_across_a_new_store_instance(self, tmp_path: Path) -> None:
store = RelayStore(persist_dir=tmp_path)
store.post("room", b"cipher-1", token=_TOKEN)
store.post("room", b"cipher-2", token=_TOKEN)
# A fresh instance (simulating a relay restart) reloads undelivered messages.
reborn = RelayStore(persist_dir=tmp_path)
assert reborn.fetch("room") == [b"cipher-1", b"cipher-2"]
# The trust-on-first-use token binding also survives the restart.
with pytest.raises(RoomAuthError):
reborn.post("room", b"x", token="wrong-token")
reborn.post("room", b"cipher-3", token=_TOKEN)
assert reborn.fetch("room") == [b"cipher-1", b"cipher-2", b"cipher-3"]
def test_repeated_restart_prunes_stale_lines_before_line_cap(
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
monkeypatch.setattr(relay, "_MESSAGE_TTL_SECONDS", 1.0)
monkeypatch.setattr(relay, "_MAX_JOURNAL_LINES_PER_ROOM", 2)
now = {"t": 1_000.0}
store = RelayStore(persist_dir=tmp_path, clock=lambda: now["t"])
store.post("room", b"message-0", token=_TOKEN)
for index in range(1, 6):
now["t"] += 2.0
store = RelayStore(persist_dir=tmp_path, clock=lambda: now["t"])
assert store.fetch("room") == []
store.post("room", f"message-{index}".encode(), token=_TOKEN)
assert len(_journal_path(tmp_path, "room").read_bytes().splitlines()) == 1
# The newest non-expired append remains loadable after repeated restarts;
# old lines never get a chance to strand it behind the physical-line cap.
reborn = RelayStore(persist_dir=tmp_path, clock=lambda: now["t"])
assert reborn.fetch("room") == [b"message-5"]
def test_empty_and_blank_only_canonical_journals_are_removed(self, tmp_path: Path) -> None:
empty = tmp_path / ("0" * 64 + ".jsonl")
blank = tmp_path / ("f" * 64 + ".jsonl")
empty.write_bytes(b"")
blank.write_bytes(b"\n\n")
store = RelayStore(persist_dir=tmp_path, clock=lambda: 1_000.0)
assert store.rooms == {} and store.tokens == {}
assert not empty.exists() and not blank.exists()
def test_startup_cleans_only_exact_owned_compaction_crash_temps(self, tmp_path: Path) -> None:
orphan = tmp_path / f".habitable-relay-{'a' * 32}.tmp"
near_match = tmp_path / ".habitable-relay-not-owned.tmp"
orphan.write_bytes(b"room-token-timestamp-ciphertext-remnant")
near_match.write_bytes(b"operator-file")
room = "temp-cleanup-room"
_journal_path(tmp_path, room).write_bytes(_journal_record(room, blob=b"load-me"))
loaded = RelayStore(persist_dir=tmp_path, clock=lambda: 1_000.0)
assert loaded.fetch(room) == [b"load-me"]
assert not orphan.exists()
assert near_match.read_bytes() == b"operator-file"
def test_created_compaction_temp_uses_the_exact_cleanup_grammar(self, tmp_path: Path) -> None:
store = RelayStore(persist_dir=tmp_path, clock=lambda: 1_000.0)
descriptor, temp = store._new_compaction_temp()
os.close(descriptor)
try:
assert relay._COMPACTION_TEMP_RE.fullmatch(temp.name) is not None
if os.name == "posix":
assert stat.S_IMODE(temp.stat().st_mode) == 0o600
finally:
temp.unlink(missing_ok=True)
@pytest.mark.skipif(not hasattr(os, "symlink"), reason="symlinks unavailable")
def test_temp_cleanup_never_follows_an_exact_name_symlink(self, tmp_path: Path) -> None:
target = tmp_path / "outside-target"
target.write_bytes(b"must-survive")
linked = tmp_path / f".habitable-relay-{'e' * 32}.tmp"
linked.symlink_to(target)
room = "temp-symlink-room"
_journal_path(tmp_path, room).write_bytes(_journal_record(room, blob=b"load-me"))
loaded = RelayStore(persist_dir=tmp_path, clock=lambda: 1_000.0)
assert loaded.fetch(room) == [b"load-me"]
assert linked.is_symlink()
assert target.read_bytes() == b"must-survive"
def test_temp_cleanup_has_separate_non_temp_and_owned_temp_allowances(
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
monkeypatch.setattr(relay, "_MAX_COMPACTION_NON_TEMP_SCAN_ENTRIES", 2)
(tmp_path / "unrelated").write_bytes(b"operator-file")
room = "separate-temp-budget-room"
_journal_path(tmp_path, room).write_bytes(_journal_record(room, blob=b"load-me"))
orphan = tmp_path / f".habitable-relay-{'b' * 32}.tmp"
orphan.write_bytes(b"crash-remnant")
loaded = RelayStore(persist_dir=tmp_path, clock=lambda: 1_000.0)
assert loaded.fetch(room) == [b"load-me"]
assert not orphan.exists()
def test_over_allowance_compaction_temps_refuse_journal_admission(
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
monkeypatch.setattr(relay, "_MAX_COMPACTION_TEMP_FILES", 1)
orphans = [tmp_path / f".habitable-relay-{value * 32}.tmp" for value in ("c", "d")]
for orphan in orphans:
orphan.write_bytes(b"bounded-crash-remnant")
room = "over-temp-allowance-room"
_journal_path(tmp_path, room).write_bytes(_journal_record(room, blob=b"do-not-load"))
refused = RelayStore(persist_dir=tmp_path, clock=lambda: 1_000.0)
assert refused.rooms == {} and refused.tokens == {}
assert all(orphan.exists() for orphan in orphans)
# Refusing the whole directory is one refusal, not "one rejected
# record" -- and it must never render as an idle relay (issue #162).
# The room's ciphertext is still on disk, unloaded and uncounted.
assert _journal_path(tmp_path, room).exists()
metrics = refused.metrics()
assert metrics["journal_load_refusals"] == 1
assert metrics["journal_records_rejected"] == 0
assert metrics["journal_files_rejected"] == 0
assert metrics["startup_replay"] == "incomplete"
assert metrics["startup_replay_reason"] == "crash-temp-file-budget"
def test_expired_messages_are_not_resurrected_on_load(
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
monkeypatch.setattr(relay, "_MESSAGE_TTL_SECONDS", 10.0)
now = {"t": 1_000.0}
store = RelayStore(persist_dir=tmp_path, clock=lambda: now["t"])
store.post("room", b"stale", token=_TOKEN)
now["t"] += 11.0 # let it age past the TTL
reborn = RelayStore(persist_dir=tmp_path, clock=lambda: now["t"])
assert reborn.fetch("room") == []
def test_transient_ttl_cleanup_failure_allows_rebind_and_restart(
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
monkeypatch.setattr(relay, "_MESSAGE_TTL_SECONDS", 1.0)
now = {"t": 1_000.0}
room = "cleanup-rebind-room"
path = _journal_path(tmp_path, room)
store = RelayStore(persist_dir=tmp_path, clock=lambda: now["t"])
store.post(room, b"stale", token="token-a")
now["t"] = 1_002.0
def fail_unlink(
_path: Path,
_expected: relay._JournalCandidate | None = None,
) -> None:
raise OSError("transient cleanup failure")
with monkeypatch.context() as cleanup_failure:
cleanup_failure.setattr(
RelayStore,
"_unlink_empty_journal",
staticmethod(fail_unlink),
)
with pytest.raises(OSError, match="transient cleanup failure"):
store.fetch(room)
assert room not in store.rooms and room not in store.tokens
assert len(path.read_bytes().splitlines()) == 1
store.post(room, b"fresh", token="token-b")
assert len(path.read_bytes().splitlines()) == 2
restarted = RelayStore(persist_dir=tmp_path, clock=lambda: now["t"])
assert restarted.fetch(room) == [b"fresh"]
assert restarted.tokens[room] == "token-b"
compacted = path.read_bytes().splitlines()
assert len(compacted) == 1
assert json.loads(compacted[0])["token"] == "token-b"
def test_far_future_record_cannot_pin_token_or_ttl_capacity(
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
monkeypatch.setattr(relay, "_MESSAGE_TTL_SECONDS", 10.0)
now = {"t": 1_000.0}
room = "future-clock-room"
path = _journal_path(tmp_path, room)
path.write_bytes(
_journal_record(
room,
token="attacker-token",
timestamp=1e20,
blob=b"must-not-pin",
)
+ _journal_record(
room,
token="safe-token",
timestamp=now["t"] + relay._MAX_FUTURE_CLOCK_SKEW_SECONDS,
blob=b"bounded-skew",
)
)
loaded = RelayStore(persist_dir=tmp_path, clock=lambda: now["t"])
assert loaded.fetch(room) == [b"bounded-skew"]
assert loaded.tokens[room] == "safe-token"
# One bad *record*, and the counter now says exactly that.
assert loaded.metrics()["journal_records_rejected"] == 1
assert loaded.metrics()["journal_load_refusals"] == 0
assert loaded.metrics()["startup_replay"] == "degraded"
now["t"] += relay._MAX_FUTURE_CLOCK_SKEW_SECONDS + 11
expired = RelayStore(persist_dir=tmp_path, clock=lambda: now["t"])
assert expired.fetch(room) == []
assert room not in expired.tokens
assert path.exists() # mixed invalid/valid source is never destructively rewritten
def test_raw_room_id_never_becomes_a_filename(self, tmp_path: Path) -> None:
room = "room-SECRETNAME-123"
store = RelayStore(persist_dir=tmp_path)
store.post(room, b"SECRET-CIPHERTEXT-PAYLOAD", token=_TOKEN)
names = [p.name for p in tmp_path.iterdir()]
assert names
for name in names:
assert "SECRETNAME" not in name # no raw room id in any filename
expected = f"{hashlib.sha256(room.encode()).hexdigest()}.jsonl"
assert expected in names
def test_startup_streams_and_strictly_validates_journal_records(
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
room = "strict-room"
invalid_base64 = json.dumps(
{"room": room, "token": _TOKEN, "ts": 1_000.0, "blob": "YQ==junk"}
).encode()
non_finite = json.dumps(
{"room": room, "token": _TOKEN, "ts": float("nan"), "blob": "YQ=="}
).encode()
oversized_token = json.dumps(
{
"room": room,
"token": "t" * (relay._MAX_ROOM_TOKEN_CHARS + 1),
"ts": 1_000.0,
"blob": "YQ==",
}
).encode()
non_ascii_token = json.dumps(
{"room": room, "token": "tökën", "ts": 1_000.0, "blob": "YQ=="}
).encode()
invalid_room = "bad/room"
_journal_path(tmp_path, invalid_room).write_bytes(
_journal_record(invalid_room, blob=b"must-not-load")
)
_journal_path(tmp_path, room).write_bytes(
b"\n".join(
[
invalid_base64,
non_finite,
oversized_token,
non_ascii_token,
_journal_record(room, blob=b"accepted").rstrip(b"\n"),
]
)
+ b"\n"
)
def forbid_read_text(*_args: object, **_kwargs: object) -> str:
raise AssertionError("startup must stream bounded binary lines")
monkeypatch.setattr(Path, "read_text", forbid_read_text)
store = RelayStore(persist_dir=tmp_path, clock=lambda: 1_000.0)
assert store.fetch(room) == [b"accepted"]
assert store.metrics()["journal_records_rejected"] == 5
assert store.metrics()["startup_replay"] == "degraded"
def test_startup_rejection_warning_is_aggregate_metadata_only(self, tmp_path: Path) -> None:
secret_name = "SECRET-ROOM-TOKEN-PAYLOAD.jsonl"
(tmp_path / secret_name).write_bytes(b"SECRET-BODY")
buffer = io.StringIO()
configure_logging(buffer)
try:
store = RelayStore(persist_dir=tmp_path, clock=lambda: 1_000.0)
finally:
configure_logging()
record = json.loads(buffer.getvalue())
assert record["msg"] == (
"relay startup replay degraded: some journal records or files were refused"
)
assert record["journal_files_rejected"] == 1
assert record["journal_records_rejected"] == 0
assert record["journal_load_refusals"] == 0
assert record["startup_replay"] == "degraded"
assert record["startup_replay_reason"] == "journal-file-refused"
assert set(record) == {
"ts",
"level",
"msg",
"startup_replay",
"startup_replay_reason",
"journal_records_rejected",
"journal_files_rejected",
"journal_load_refusals",
}
rendered = buffer.getvalue()
assert secret_name not in rendered and "SECRET-BODY" not in rendered
assert store.rooms == {} and store.tokens == {}
def test_conflicting_tokens_in_one_journal_are_rejected_without_binding(
self, tmp_path: Path
) -> None:
room = "conflict-room"
_journal_path(tmp_path, room).write_bytes(
_journal_record(room, token="token-a", blob=b"a")
+ _journal_record(room, token="token-b", blob=b"b")
)
store = RelayStore(persist_dir=tmp_path, clock=lambda: 1_000.0)
assert room not in store.rooms and room not in store.tokens
# A whole journal file refused -- neither a record nor the directory.
assert store.metrics()["journal_files_rejected"] == 1
assert store.metrics()["startup_replay"] == "degraded"
def test_noncanonical_duplicate_journal_cannot_override_tofu_token(
self, tmp_path: Path
) -> None:
room = "canonical-room"
canonical = _journal_path(tmp_path, room)
canonical.write_bytes(_journal_record(room, token="token-a", blob=b"accepted"))
alternate_name = "0" * 64 + ".jsonl"
if alternate_name == canonical.name:
alternate_name = "f" * 64 + ".jsonl"
(tmp_path / alternate_name).write_bytes(
_journal_record(room, token="token-b", blob=b"must-not-load")
)
store = RelayStore(persist_dir=tmp_path, clock=lambda: 1_000.0)
assert store.fetch(room) == [b"accepted"]
assert store.tokens[room] == "token-a"
with pytest.raises(RoomAuthError, match="mismatch"):
store.post(room, b"wrong", token="token-b")
def test_startup_enforces_per_room_and_global_caps(
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
per_room = tmp_path / "per-room"
per_room.mkdir()
room = "over-room-cap"
_journal_path(per_room, room).write_bytes(
_journal_record(room, blob=b"aa") + _journal_record(room, blob=b"bb")
)
monkeypatch.setattr(relay, "_MAX_CIPHERTEXT_BYTES_PER_ROOM", 3)
rejected = RelayStore(persist_dir=per_room, clock=lambda: 1_000.0)
assert rejected.rooms == {} and rejected.tokens == {}
assert rejected.metrics()["capacity_rejections"] == 1
global_dir = tmp_path / "global"
global_dir.mkdir()
for index in range(2):
current = f"global-room-{index}"
_journal_path(global_dir, current).write_bytes(
_journal_record(current, token=f"token-{index}", blob=b"x")
)
monkeypatch.setattr(relay, "_MAX_CIPHERTEXT_BYTES_PER_ROOM", 10)
monkeypatch.setattr(relay, "_MAX_LIVE_ROOMS", 10)
monkeypatch.setattr(relay, "_MAX_LIVE_MESSAGES", 1)
monkeypatch.setattr(relay, "_MAX_LIVE_CIPHERTEXT_BYTES", 1)
bounded = RelayStore(persist_dir=global_dir, clock=lambda: 1_000.0)
assert len(bounded.rooms) == len(bounded.tokens) == 1
assert bounded.metrics()["capacity_rejections"] == 1
def test_oversized_journal_and_line_are_skipped(
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
monkeypatch.setattr(relay, "_MAX_PERSIST_BYTES_PER_ROOM", 80)
oversized_file_room = "oversized-file"
_journal_path(tmp_path, oversized_file_room).write_bytes(b"x" * 81)
monkeypatch.setattr(relay, "_MAX_JOURNAL_LINE_BYTES", 40)
oversized_line_room = "oversized-line"
line_path = _journal_path(tmp_path, oversized_line_room)
line_path.write_bytes(b"{" + b"x" * 40 + b"}\n")
store = RelayStore(persist_dir=tmp_path, clock=lambda: 1_000.0)
assert store.rooms == {} and store.tokens == {}
metrics = store.metrics()
# One over-long line spends the whole startup byte budget by design
# (`_bounded_journal_lines` zeroes it), so the *remaining* journals in
# the directory are never read. That is a directory refusal, not a
# second file rejection, and the difference is the point of issue #162:
# a single hostile line can leave an unknown amount of at-rest
# ciphertext unloaded, and the operator surface must say so rather than
# report a tidy count of two skipped files.
assert metrics["journal_files_rejected"] == 1
assert metrics["journal_load_refusals"] == 1
assert metrics["startup_replay"] == "incomplete"
def test_startup_total_journal_read_budget_is_enforced(
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
room = "startup-budget"
record = _journal_record(room, blob=b"bounded")
_journal_path(tmp_path, room).write_bytes(record)
monkeypatch.setattr(relay, "_MAX_STARTUP_JOURNAL_BYTES", len(record) - 1)
store = RelayStore(persist_dir=tmp_path, clock=lambda: 1_000.0)
assert store.rooms == {} and store.tokens == {}
assert store.metrics()["journal_files_rejected"] == 1
assert store.metrics()["startup_replay"] == "degraded"
def test_startup_per_journal_and_global_line_budgets_are_enforced(
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
room = "line-budget"
_journal_path(tmp_path, room).write_bytes(
b"".join(_journal_record(room, blob=str(index).encode()) for index in range(3))
)
monkeypatch.setattr(relay, "_MAX_JOURNAL_LINES_PER_ROOM", 2)
store = RelayStore(persist_dir=tmp_path, clock=lambda: 1_000.0)
assert store.rooms == {} and store.tokens == {}
assert store.metrics()["journal_files_rejected"] == 1
global_dir = tmp_path / "global-lines"
global_dir.mkdir()
for index in range(2):
current = f"global-line-{index}"
_journal_path(global_dir, current).write_bytes(
_journal_record(current, token=f"token-{index}", blob=b"x")
)
monkeypatch.setattr(relay, "_MAX_JOURNAL_LINES_PER_ROOM", 2)
monkeypatch.setattr(relay, "_MAX_STARTUP_JOURNAL_LINES", 1)
globally_bounded = RelayStore(persist_dir=global_dir, clock=lambda: 1_000.0)
assert len(globally_bounded.rooms) == len(globally_bounded.tokens) == 1
# The second journal was never read at all: an unknown remainder, so
# this is a directory refusal and the replay is incomplete.
assert globally_bounded.metrics()["journal_load_refusals"] == 1
assert globally_bounded.metrics()["startup_replay"] == "incomplete"
assert globally_bounded.metrics()["startup_replay_reason"] == "startup-read-budget"
@pytest.mark.skipif(not hasattr(os, "mkfifo"), reason="FIFO requires POSIX")
def test_startup_skips_symlink_and_fifo_without_following_or_blocking(
self, tmp_path: Path
) -> None:
symlink_room = "symlink-room"
target = tmp_path / "outside-target"
target.write_bytes(_journal_record(symlink_room, blob=b"must-not-follow"))
_journal_path(tmp_path, symlink_room).symlink_to(target)
fifo_room = "fifo-room"
fifo = _journal_path(tmp_path, fifo_room)
os.mkfifo(fifo)
result: dict[str, RelayStore] = {}
def construct() -> None:
result["store"] = RelayStore(persist_dir=tmp_path, clock=lambda: 1_000.0)
thread = threading.Thread(target=construct, daemon=True)
thread.start()
thread.join(timeout=1.0)
blocked = thread.is_alive()
if blocked: # unblock the vulnerable implementation so teardown stays safe
descriptor = os.open(fifo, os.O_RDWR | os.O_NONBLOCK)
os.write(descriptor, b"\n")
os.close(descriptor)
thread.join(timeout=1.0)
assert not blocked, "journal startup blocked while opening a FIFO"
assert result["store"].rooms == {}
assert target.read_bytes() == _journal_record(symlink_room, blob=b"must-not-follow")
def test_compaction_happens_before_journal_exceeds_its_cap(
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
monkeypatch.setattr(relay, "_MESSAGE_TTL_SECONDS", 1.0)
now = {"t": 1_000.0}
sample_size = len(_journal_record("room", blob=b"old"))
monkeypatch.setattr(relay, "_MAX_PERSIST_BYTES_PER_ROOM", sample_size + 5)
store = RelayStore(persist_dir=tmp_path, clock=lambda: now["t"])
store.post("room", b"old", token=_TOKEN)
now["t"] += 2.0
store.post("room", b"new", token=_TOKEN)
path = _journal_path(tmp_path, "room")
assert path.stat().st_size <= relay._MAX_PERSIST_BYTES_PER_ROOM
assert len(path.read_bytes().splitlines()) == 1
reborn = RelayStore(persist_dir=tmp_path, clock=lambda: now["t"])
assert reborn.fetch("room") == [b"new"]
def test_retry_repairs_unterminated_partial_append_before_acknowledgement(
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
store = RelayStore(persist_dir=tmp_path, clock=lambda: 1_000.0)
real_write = os.write
writes = 0
def partial_then_fail(descriptor: int, payload: bytes | memoryview) -> int:
nonlocal writes
writes += 1
if writes == 1:
partial = bytes(payload[: max(1, len(payload) // 2)])
return real_write(descriptor, partial)
raise OSError("simulated interrupted append")
monkeypatch.setattr(os, "write", partial_then_fail)
with pytest.raises(OSError, match="interrupted append"):
store.post("partial-room", b"first-attempt", token=_TOKEN)
path = _journal_path(tmp_path, "partial-room")
assert path.read_bytes() and not path.read_bytes().endswith(b"\n")
monkeypatch.setattr(os, "write", real_write)
store.post("partial-room", b"acknowledged-retry", token=_TOKEN)
assert path.read_bytes().endswith(b"\n")
assert len(path.read_bytes().splitlines()) == 2
restarted = RelayStore(persist_dir=tmp_path, clock=lambda: 1_000.0)
assert restarted.fetch("partial-room") == [
b"first-attempt",
b"acknowledged-retry",
]
def test_persistent_ttl_churn_bounds_journal_files_and_allows_rebind(
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
monkeypatch.setattr(relay, "_MAX_LIVE_ROOMS", 2)
monkeypatch.setattr(relay, "_MESSAGE_TTL_SECONDS", 1.0)
now = {"t": 1_000.0}
store = RelayStore(persist_dir=tmp_path, clock=lambda: now["t"])
for index in range(10):
store.post(f"room-{index}", b"x", token=f"token-{index}")
now["t"] += 2.0
assert len(list(tmp_path.glob("*.jsonl"))) <= 2
assert len(store.tokens) <= 2
assert store.fetch("room-9") == []
assert not _journal_path(tmp_path, "room-9").exists()
assert len(list(tmp_path.glob("*.jsonl"))) <= 1
store.post("room-9", b"new", token="replacement-token")
assert store.tokens["room-9"] == "replacement-token"
assert len(list(tmp_path.glob("*.jsonl"))) <= 2
def test_journal_identity_swap_is_rejected_before_read_or_append(
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
room = "identity-room"
path = _journal_path(tmp_path, room)
original = _journal_record(room, token="token-a", blob=b"original")
replacement = _journal_record(
room,
token="token-b",
blob=b"replacement-with-a-distinct-size",
)
# Regression: Linux can immediately reuse the unlinked inode. Generation
# checks must still notice the changed size/mtime instead of loading or
# appending to the replacement.
assert len(original) != len(replacement)
path.write_bytes(original)
real_open = os.open
swapped = False
def swap_then_open(
candidate: str | os.PathLike[str],
flags: int,
mode: int = 0o600,
) -> int:
nonlocal swapped
if Path(candidate) == path and not swapped:
swapped = True
path.unlink()
path.write_bytes(replacement)
return real_open(candidate, flags, mode)
monkeypatch.setattr(os, "open", swap_then_open)
loaded = RelayStore(persist_dir=tmp_path, clock=lambda: 1_000.0)
assert loaded.rooms == {} and loaded.tokens == {}
assert path.read_bytes() == replacement
monkeypatch.setattr(os, "open", real_open)
writer = RelayStore(persist_dir=tmp_path, clock=lambda: 1_000.0)
path.write_bytes(original)
swapped = False
monkeypatch.setattr(os, "open", swap_then_open)
with pytest.raises(OSError, match="regular file"):
writer.post(room, b"must-not-append", token="token-b")
assert path.read_bytes() == replacement
monkeypatch.setattr(os, "open", real_open)
path.write_bytes(b"")
swapped = False
monkeypatch.setattr(os, "open", swap_then_open)
with pytest.raises(OSError, match="identity changed"):
RelayStore._unlink_empty_journal(path)
assert path.read_bytes() == replacement
def test_generation_snapshot_rejects_reused_inode_metadata(self, tmp_path: Path) -> None:
def snapshot(*, size: int, modified_ns: int, changed_ns: int) -> os.stat_result:
return cast(
os.stat_result,
SimpleNamespace(
st_dev=7,
st_ino=11,
st_size=size,
st_mtime_ns=modified_ns,
st_ctime_ns=changed_ns,
),
)
candidate = relay._JournalCandidate(tmp_path / "journal", 7, 11, 13, 17, 19)
original = snapshot(size=13, modified_ns=17, changed_ns=19)
reused_with_new_size = snapshot(size=14, modified_ns=17, changed_ns=19)
reused_with_new_mtime = snapshot(size=13, modified_ns=18, changed_ns=19)
reused_with_new_ctime = snapshot(size=13, modified_ns=17, changed_ns=20)
assert candidate.matches(original)
assert not candidate.matches(reused_with_new_size)
assert not candidate.matches(reused_with_new_mtime)
assert not candidate.matches(reused_with_new_ctime)
assert not relay._same_journal_generation(original, reused_with_new_size)
assert not relay._same_journal_generation(original, reused_with_new_mtime)
assert not relay._same_journal_generation(original, reused_with_new_ctime)
def test_windows_unlink_fallback_closes_then_rechecks_generation(
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
path = tmp_path / "windows-cleanup.jsonl"
path.write_bytes(b"")
real_lstat = Path.lstat
lstat_calls = 0
def swap_before_final_check(candidate: Path) -> os.stat_result:
nonlocal lstat_calls
if candidate == path:
lstat_calls += 1
if lstat_calls == 3:
candidate.unlink()
candidate.write_bytes(b"replacement-generation")
return real_lstat(candidate)
monkeypatch.setattr(relay, "_CLOSE_BEFORE_UNLINK", True)
monkeypatch.setattr(Path, "lstat", swap_before_final_check)
with pytest.raises(OSError, match="identity changed"):
RelayStore._unlink_empty_journal(path)
assert path.read_bytes() == b"replacement-generation"
@pytest.fixture
def server_url() -> Iterator[str]:
server = make_server("127.0.0.1", 0)
port = server.server_address[1]
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
try:
yield f"http://127.0.0.1:{port}"
finally:
server.shutdown()
server.server_close()
thread.join(timeout=5)