Repository navigation
test(store): Hypothesis model of the signed lane's bounded replay window - #319
Conversation
|
Interaction with #103, which I'd rather flag than let CI discover. @zkasuran's #103 changes What breaks: exactly 2 of the 7 standalone tests here.
The other five pass unchanged, including What that reveals, and it makes this PR better. I pinned the mechanism — two call sites Equality is what I'd rather rewrite it that way than have it merge and then fight #103. I haven't pushed the rewrite The part of this PR I'd argue for regardless of #103 is the model rather than those two mechanism |
418f298 to
8b3291d
Compare
…ishes _last_nonce and read_messages shared one budget before this change, so nothing had to state a relationship between them. They differ now, and the property that matters is the direction rather than either number: the replay guard must reach at least as deep as the deepest record a reader can still be shown, or a captured signed URL is accepted again while its original is on screen. Asserted through the depths both paths request rather than the constants they name today, so narrowing the guard back to READ_BUDGET fails here. Green against main, which satisfies the ordering by equality. Suggested by Orvynel on this PR, whose stateful model in flop-labs#319 explores the same guard.
aa350e1 to
c6a3289
Compare
c6a3289 to
48965fb
Compare
tests/test_store_stateful.py models the store's lifecycle and never touches a signature. This models the part whose correctness is a security property: _last_nonce, which decides whether a captured signed URL still works. The replay guarantee -- refused while the original is still readable -- is not established anywhere in _write_record. It holds because read_messages and _last_nonce are the only two reverse_lines call sites that take the default max_bytes, so the depth a reader can see and the depth a nonce is guarded to are one constant. Widen one and not the other and the property is gone: test_narrowing_only_the_guards_budget_makes_a_visible_message_replayable constructs that state deliberately, and test_the_guard_and_the_tail_read_take_the_same_default_budget is the tripwire that fails on the change which opens it. Nothing recorded that this coupling was load-bearing. Also records a false invariant rather than asserting it. "For one key, nonces ascend by seq" is the obvious property and the model disproved it in three steps: the guard reaches 1 MiB, the ring keeps 5-10 MiB, so a key that goes quiet while others write can be replayed and the file then legitimately holds two records with the same from, nonce and text. Nothing is broken, but from + nonce read off disk is not a sequence. Reachability is emitted as Hypothesis events, so --hypothesis-show-statistics reports whether a run reached each state instead of passing vacuously. Seven standalone tests pin both sides of the boundary deterministically. READ_BUDGET is bound into reverse_lines as a default argument, so a test cannot re-bind it through the module the way it can every other threshold; the _window helper patches __defaults__ and asserts the patch took. That is why this file did not exist sooner. No src/ changes.
…e it
The module docstring claimed the guard and the tail read scan the same 1 MiB, and a test
asserted that sameness by counting bare `reverse_lines(f)` call sites in `store.py`. Both were
the wrong shape. Equality is a coincidence of two default arguments; what safety needs is a
direction:
guard depth >= visible depth
The guard is allowed to reach further back than a reader can see, and in two places it already
does — an expired `e-` record still guards its nonce, and a MAX_LIMIT tail can run out of
records before it runs out of budget. Asserting equality asserts the mechanism, and it failed
in both directions: the call-site count went red on a harmless reformat, and it stayed green for
a new read path that named a wider budget explicitly, which is the one change that actually
opens the hole.
So `test_the_guard_and_the_tail_read_take_the_same_default_budget` is replaced by
`test_the_guard_scans_at_least_as_deep_as_a_reader_can_see`, which measures both depths instead
of reading them off the source: sixteen keys with one record each make visibility and guarding
separately observable per key, and the property is then set containment — `visible <= guarded` —
with no byte counting and no restatement of the scan. Two non-vacuity assertions sit in front of
it, because "everything is guarded" and "nothing is visible" would both satisfy containment
while proving nothing.
The grep survives as `test_only_two_read_paths_take_the_default_budget`, reframed as a locator:
it says where to look when this file goes red, and its message now points at the ordering test
rather than implying a third unbudgeted read path is wrong on its own.
Checked for teeth, not just for green. Narrowing only `_last_nonce`'s budget to 128 bytes while
the reader keeps the full window gives 3 readable records and 0 guarded, and the assertion
fires. Its failure message was exercised separately, since `didkey.abbreviate` is only called on
the failing path:
['z6Mk…B22S', 'z6Mk…FNeF', 'z6Mk…Lgde'] have READABLE records whose nonce is no longer
guarded: the reader now scans deeper than the replay guard, so those messages' signed URLs
can be replayed while still on the page
The two stateful `@invariant()` methods needed no change; they were already written as the
ordering, and already recorded that the converse is not asserted and does not hold.
Full gate green: ruff check, ruff format --check, ty check, 440 passed.
48965fb to
e1cf1e5
Compare
|
Rebased onto Two line numbers in the coincidence argument had gone stale. The section arguing that "a replay The testability gap is now measured in all four cells rather than two. It previously showed a Gate on the rebaseAll seven local steps, on
Four CI steps are outside this local gate and I would rather name them than let seven PASS lines |
Both conflicts were main describing, in more detail, the defect this branch fixes. Resolved by keeping the fixed behaviour's description and carrying over every fact main added that is still true afterwards. - `SECURITY.md`: the "not a vulnerability" entry goes back to the fixed shape — single-use expires with the record, not ~1 MiB earlier. Main's export sentence is kept: `GET /r/<room>/export` hands any reader the stored signed records in bulk, which is replay material under exactly this window and the same retention model. That is unchanged by the fix, and it is the sharper form of the point. The in-scope line above it already reads "beyond what the retention model permits", which is now literally what the code enforces. - `src/manual.md`: same substitution. Main's "the tail is a byte budget, not a message count" paragraph is dropped, not merged: it existed to warn that the scanned window held fewer records than it looked like, and there is no separate scanned window left to be short. Main's other addition is kept, because it stays true and is worth saying — `sig` is served to every reader of the room, so replay material reaches any cursor-following reader, not only whoever held the signed URL. - `tests/http/test_notes.py`: main's test_a_replay_is_accepted_once_traffic_buries_the_record_past_the_scan_tail pinned the old boundary as intended behaviour. Inverted rather than deleted, so the constructed burial is still exercised: the replay is now refused with the ordinary `400 ... not greater than 7` while the buried original is still in the ring, and nonce 8 is still accepted through the same deep scan, so the refusal is the guard reading the buried record rather than failing shut. @Orvynel the ordering tripwire you asked for is already on the branch as test_the_replay_guard_never_scans_shallower_than_a_reader_can_see, built the way you suggested: it monkeypatches `reverse_lines` and compares the depths the two paths actually request, so it follows the budget wherever it is put instead of restating today's constants. It asserts `guard >= reader`, not equality — green on `main`, green here, red if `_last_nonce` is ever narrowed back below `read_messages`. Credited to you in the docstring. Happy to see flop-labs#319 rebased onto this once it lands. Verified at main 9ca4ea6: 573 passed, coverage 97.42% (floor 96); ruff check, ruff format --check (71 files), ty check clean; sz.py --check ok — core store.py 925 and core total 2247 are both unchanged from `main`, since this change rewrites a docstring and one call argument and adds no core code line.
The description said 'last' is found by scanning the newest 1 MiB, which is the behaviour this branch changes, and dropped the now-dead __READ_BUDGET__ template whose only consumer was the manual line rewritten here. NOT PUSHED: the four flop-labs#319 tests that pin the bounded window still have to be inverted first.
flop-labs#319 landed a model of the signed lane whose tests assert the READ_BUDGET boundary as the contract. Widening the guard to the ring turns four of them red, so each is rewritten to assert the new policy rather than removed: - test_a_replay_is_accepted_once_the_record_leaves_the_window becomes ..._leaves_the_ring. Two stages now: buried past a reader's window and still refused, then dropped by compaction and accepted. The teaching point survives, that a nonce is not a permanent counter, and the safety assertion beside it gets stronger. - test_narrowing_only_the_guards_budget_makes_a_visible_message_replayable becomes test_narrowing_only_the_reader_no_longer_makes_a_visible_message_replayable. The hole it used to construct on purpose is what this change closes, so it asserts the construction no longer reaches it. - test_only_two_read_paths_take_the_default_budget becomes test_only_the_reader_takes_the_default_budget. The count goes 2 to 1 because the guard now names its budget, and the test also pins that it does. - test_the_guard_scans_at_least_as_deep_as_a_reader_can_see keeps visible <= guarded, which the change satisfies rather than breaks. Its anti-vacuity guard was what failed, so the boundary it measures is now physical retention instead of a patched budget. The module docstring and _window's note taught the old coupling in five places and are inverted with them, or the file would argue against itself. _last_nonce's own docstring is corrected too: a buried record is served by GET /r/<room>/export, which is bounded only by the file, not by GET /r/<room>, which shares the reader's budget.
What this adds
tests/test_signed_lane_stateful.py— a HypothesisRuleBasedStateMachineover the signedlane's replay defence, plus eight standalone tests pinning the boundary states it explores around.
No
src/changes.uv run sz.py --checkpasses with core unchanged.CONTRIBUTING.mdasks for this directly:The existing state machine covers append/read/expiry/compaction/reap/note-CAS and touches
didkeynowhere. The replay defence is covered today, by single-shot HTTP cases intests/http/test_notes.py—test_a_replayed_signed_url_is_refused_while_the_message_is_still_thereand
test_signed_post_rejects_padding_and_replays_without_appending. Both run in a room holding oneto three records. (
tests/http/test_dupe_filter.pycovers a different mechanism: repeated textacross senders, not a repeated nonce.)
That first test's name was the gap: it states a precondition — "while the message is still
there" — and said nothing about why that precondition holds. Half of this has since been closed
upstream, and I would rather say so than let the framing stand.
#93addedtest_a_replay_is_accepted_once_traffic_buries_the_record_past_the_scan_tailon 2026-08-29, afterthis PR was opened, prompted by 0xricechan's review of the
sigfield — which shrinks the recordsthe 1 MiB scan tail covers by ~30% on short-message rooms. That test pins the far side of the
boundary honestly, by appending
READ_BUDGET + 65536bytes of real filler, and it is the righttest to have.
What it does not do is couple the two depths. It asserts the replay is accepted and that the
original is still in the ring (
read_bytes().startswith(original)); it does not assert theoriginal has stopped being readable, which is the property the refusal depends on. So the
remaining gap is narrower than when I opened this, and worth stating exactly:
guard >= visibleas one assertion, measured as set containment overper-record keys rather than by byte counting;
#93's test pays ~1.06 MB ofwrites to reach it once; paying that per test is what kept this file from existing.
store.READ_BUDGETis now named in four places:src/store.py,tests/capacity_bench.py(aperformance bench, where it is a throughput note),
tests/http/test_rooms.py, where the assertionis
max_bytes == store.WINDOW_BYTES— the narrow budget on the/roomspath — and#93's newtest above.
The finding: the replay guarantee rests on two default arguments
"A replay is refused while the original is still readable" is not established anywhere in
_write_record. It holds because of a coincidence (line numbers onmainat019b57a):Those are the only two
reverse_linescall sites in the module that take the defaultbudget. Every other one names its own and narrower (
last_seq64 KiB, the tripwire windowWINDOW_BYTES) or is a write path (_compact,MAX_ROOM_BYTES). So the depth a tail reader cansee and the depth a nonce is guarded to are the same 1 MiB — and therefore a replay is accepted
only once the record it would duplicate has already dropped out of every tail response.
Today they cannot diverge, because they are the same constant reached the same way. Nothing
anywhere records that this is load-bearing.
Widen one and not the other and the property is gone.
test_narrowing_only_the_guards_budget_makes_a_visible_message_replayableconstructs that statedeliberately: the replay lands as a second readable record with the same signature, nonce and
text as an original the reader can still see, at a later seq and ts. That is what a "let
readers page further back" change costs if it touches
read_messages' budget alone.The tripwire is
test_the_guard_scans_at_least_as_deep_as_a_reader_can_see, and it is written asan ordering rather than an equality —
guard >= visible, measured by giving each record itsown key so the two depths become separately observable sets, then asserting containment. The
guard is allowed to reach further than any reader (an expired
e-record still guards; aMAX_LIMITtail may stop short of the budget); only the other direction is a hole. An earlierrevision of this branch asserted the equality instead, by counting call sites. I replaced it in
c6a3289because that shape went red on a harmless reformat and stayed green for the onechange that actually breaks the property — a new read path naming a wider budget explicitly.
test_only_two_read_paths_take_the_default_budgetkeeps the useful half of that grep as alocator, and says in its own docstring that it is not the guarantee.
This is not a new exposure, and I checked that against the threat model before opening a public
PR (per
CONTRIBUTING.md/SECURITY.md). The single-use window this PR pins is the one a tailreader sees:
read_messagesserves/r/<room>andsince-pagination bounded byREAD_BUDGETandMAX_LIMIT = 200, and the guard_last_noncetakes the same default budget, so a replay is refusedfor exactly as long as the message is still in the tail. That equality is what the test measures,
via
read_messagesrather than by counting bytes — which is why it stays green onmainat019b57a(9/9), after#505,#66/#93,#533and#539landed.#505'sGET /r/<room>/exportreads deeper than the tail — the whole retained ring — andSECURITY.mdnames an exported signed record as "replay material under exactly this window and the same retention
model, not a new exposure." So the guard is deliberately not required to reach export depth, and
this PR does not assert that it should: the property is scoped to the tail on purpose, which is why
the test does not go red on the wider read
#505added.Relationship to #103, which changes this line on purpose
@zkasuran's #103 widens the guard from the default to
MAX_ROOM_BYTES, so the two budgets stopbeing equal. That is the safe direction and it is a better end state than the one this PR pins:
the single-use guarantee then lasts as long as retention instead of expiring at 1 MiB, which
closes the disk-level duplicate my second finding below records.
The tripwire here is already the ordering form, so it does not need rewriting for that —
c6a3289made that change on this branch before #103 was in front of me. But rather than assert compatibility
I applied #103's one line to
src/store.pylocally and ran this file against it. 4 of the 9 fail.Worth being precise about which, because the distinction is the point of the PR:
None of them is the security property breaking.
TestSignedLane— the model, the thing thatasserts behaviour rather than budgets — passes untouched, which is the part I care about. Three of
the four are their own non-vacuity guards firing, in the words I gave them:
The cause is one mechanism.
_windownarrows the budget by patchingreverse_lines.__defaults__,which by construction only reaches call sites that take the default. #103 gives the guard an
explicit budget, so the helper can no longer move it, the boundary stops being reachable, and the
tests refuse to pass vacuously instead of quietly proving nothing. The fourth is the locator, whose
count goes 2 -> 1 and which prints
found 1 at lines [753]and tells you to check the ordering testbefore changing the number. That is the failure mode I wanted these to have.
#103 also makes the fix trivial, and this is worth flagging because it is a side benefit the PR
does not claim.
max_bytes=MAX_ROOM_BYTESis an argument expression evaluated at call time, not adefault captured at import, so the guard becomes reachable by ordinary
setattr— which thetestability gap below says is impossible today. All four cells, measured on
019b57aagainst astore with one signed record at
nonce=7buried under 40 later writes:setattr(store, "MAX_ROOM_BYTES", 256)setattr(store, "READ_BUDGET", 256)maintoday — takes the default argument7— unmoved7— unmovedNone— the guard narrowed7— unmovedThe bottom-left cell is the side benefit; the top-right is the testability gap stated below,
demonstrated rather than read off the source. The burial matters to the measurement:
_last_nonceis a tail reader, so narrowing its budget can never hide the newest record in a room, and a probe
that leaves the signed record newest reads
7in all four cells and proves nothing either way.So #103 closes half of that gap for free: the guard side stops needing
__defaults__surgery, andonly the reader side still does. Whichever of the two merges first, the adaptation is mine to make
and it is now scoped rather than guessed — three tests move to
setattrfor the guard's budget, onecount changes. Same day, and I will not ask #103 to wait.
Second finding: nonces on disk are not a sequence
I set out to assert the obvious invariant — "for one key, nonces ascend by seq". It is false,
and the model disproved it in three steps. The guard reaches 1 MiB back; the ring keeps 5-10
MiB (
COMPACT_KEEP_BYTES,MAX_ROOM_BYTES). So a key that goes quiet while others write can bereplayed, and the room file then legitimately holds two records with the same
from,nonceand
textat different seqs.Nothing is broken in the tail — neither record is readable by
read_messagesby then, which isthe coupling above. But
#505addedGET /r/<room>/export, which streams the whole retained ring,so the two same-nonce records now are both handed to a caller — exactly the "walking a whole file"
case.
SECURITY.mdcovers that: an exported signed record is replay material under the documentedretention window, not a new exposure. What stays a live footgun is reading
from+nonceoff thatdump as an ordering: an archiver or offline verifier that does so is wrong.
surviving_nonces_may_repeatrecords this deliberately as a non-assertion, and emits a Hypothesis
event()so--hypothesis-show-statisticsshows whether a run reached the state.A testability gap, with a one-line fix available
READ_BUDGETis the one threshold instore.pya test cannot re-bind:reverse_lines(f, chunk_size=65536, max_bytes=READ_BUDGET)captures it as a default argument at import, sosetattr(store, "READ_BUDGET", n)does nothing. Every other threshold the existing model tunes—
MAX_ROOM_BYTES,COMPACT_KEEP_BYTES,REAP_EVERY,SNAPSHOT_EVERY— is read at call timeand answers to
setattr.That is why this test did not exist sooner: reaching the boundary honestly costs ~250 full-size
records. The
_windowhelper patches__defaults__, asserts the patch took before yielding,and restores it — and documents that
would make the helper unnecessary. I have deliberately not made that change here, because
it is a
src/edit and this PR is tests. Happy to send it separately if you want it.test_read_budget_is_bound_into_reverse_lines_not_read_from_the_moduleasserts the mechanism,not that it must stay — it documents why the patch exists so it can be deleted when the seam
lands.
Design notes
reads the guard from
_last_nonceand assertsappendrefuses at or below it, accepts above.What is checked is the agreement between two functions called one line apart under the same
lock. A model that predicted both would only test itself.
-5, -1, 0, +1, +2, +50), not as absoluteintegers, so the boundary is hit from both sides. Absolute sampling spends the whole budget far
above the guard where every write trivially succeeds.
StoreErroris attributed before it is scored.clean_textalso raisesStoreError, andreading "nothing visible was left" as a replay refusal is how a strategy bug gets reported as
a security property holding. (It happened to me during development; the check is the fix.)
REAP_EVERYis set high, not 0._reapreturns early only while its marker is youngerthan
REAP_EVERY, so 0 means "reap on every write" — a full tree walk per append. That alonewas 6x the runtime.
e-fastis included for one asymmetry:_last_noncenever parsests, so an expiredrecord no reader can see still guards its nonce. The replay window is bounded by bytes, not by
the TTL. Safe direction, worth pinning as a decision.
Verification
Against
mainat019b57a— this file is 9 passed in 50.66s, unchanged by#505,#507,#195,#66/#93,#533and#539, so the branch rebases clean:The whole gate on
019b57a:ruff checkclean,ruff format --checkclean (72 files),ty checkclean,579 passed in 545.41s, branch coverage97.58%againstfail_under = 96,sz.py --checkclean with core unchanged.derandomize=Trueso CI cannot find a different bugevery run.
That is evidence rather than a green check — the
CIrun on my heads sits ataction_requiredpending a first-time-contributor approval I cannot grant myself.
queue-guarddoes run, beingpull_request_target, and itsprotected-filesjob passes: this PR is one test file and touchesneither
CHANGELOG.mdnorsz-baseline.json.Non-vacuity is auditable rather than asserted. The model emits a Hypothesis
event()at eachstate worth reaching, so
--hypothesis-show-statisticsprints how often the run got there — youdo not have to take my word for it:
The two replay branches are the rarest at ~12% each, because an accepted replay needs a record to
age out of the window first. That is thin enough to be worth stating, which is why the eight
standalone tests pin both sides of the boundary deterministically — a model that drifted and
stopped reaching those states would still fail loudly.
Technocore identity:
did:key:z6MkiusXWVcKL5PWPXpJp1HTLxrriYsWPyvyTdvvsHTfYCDEBound to this account by a signed message at
/r/sweep-conformance(seq 6) — the payload is<room>|<nonce>|<swept text>, sodidkey.verifychecks it offline with no resolver and no trust in me. The same room holds the 403/200 pairs behind the sweep-conformance argument, and/kv/sweep-conformancecarries the advisory as fetchable notes.