Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
107 changes: 53 additions & 54 deletions src/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
import secrets
import time
import tomllib
from collections.abc import Mapping
from collections.abc import Iterator, Mapping
from contextlib import asynccontextmanager, contextmanager
from functools import lru_cache
from pathlib import Path
Expand All @@ -44,10 +44,8 @@
# aliased anyway because tests still assert against them as app attributes (override
# mirrors those copies); every other knob lost its alias when the last monkeypatch site
# that needed one moved to override.
RATE_READ = config.RATE_READ # requests/min/IP
RATE_WRITE = config.RATE_WRITE
RATE_ROOMS_PER_DAY = config.RATE_ROOMS_PER_DAY
CLIENT_IP_HEADER = config.CLIENT_IP_HEADER
RATE_READ, RATE_WRITE = config.RATE_READ, config.RATE_WRITE # requests/min/IP
RATE_ROOMS_PER_DAY, CLIENT_IP_HEADER = config.RATE_ROOMS_PER_DAY, config.CLIENT_IP_HEADER

# Sized from what the wire actually carries, not from what a parser tolerates. A real
# agent request through Cloudflare — Host, UA, Accept, CF-Connecting-IP, CF-Ray,
Expand Down Expand Up @@ -308,10 +306,7 @@ def text(
reached it not to index the thing robots.txt had just advertised. A service whose whole
premise is being discoverable was hiding its own manual. Documents pass index=True.
"""
headers = {
"Cache-Control": "no-store",
"X-Content-Type-Options": "nosniff",
}
headers = {"Cache-Control": "no-store", "X-Content-Type-Options": "nosniff"}
if not index:
headers["X-Robots-Tag"] = "noindex"
if extra_headers:
Expand Down Expand Up @@ -1531,7 +1526,7 @@ def _condition(source: Mapping[str, object]) -> tuple[str | None, bool]:
return expect, absent


def _note_write_gate(ns: str, key: str, value: str, signer: str | None) -> Response | None:
def _note_write_gate(ns: str, key: str, value: str, signer: str | None) -> Response | bool | None:
"""Two reserved namespaces carry room ownership, and only those two take signed writes.

Not a general signed-kv system: a note is world-writable by design and stays that way,
Expand Down Expand Up @@ -1600,7 +1595,7 @@ def _note_write_gate(ns: str, key: str, value: str, signer: str | None) -> Respo
"take over a conversation already in progress.",
403,
)
return None
return current is None
owner = store.note_get(config.ROOT, store.OWNERS_NS, key)
if owner is None:
return text(
Expand All @@ -1626,16 +1621,21 @@ def _note_write_gate(ns: str, key: str, value: str, signer: str | None) -> Respo
return None


def _set_note(ns: str, key: str, val: str, exp: str | None, no: bool, first: object = None) -> dict:
cas = no or (first is True and exp is None)
return store.note_set(config.ROOT, ns, key, val, expect=exp, expect_absent=cas)


def note_write(request: Request) -> Response:
left, retry = take(request, "write", RATE_WRITE)
if retry:
return limit.limited("write", RATE_WRITE, retry, text=text, max_wait=MAX_WAIT)
p = request.path_params
value = store.clean_text(p["value"], store.MAX_VALUE_CHARS)
denied = _note_write_gate(p["ns"], p["key"], value, None)
if denied:
if isinstance(denied, Response):
return denied
meta = store.note_set(config.ROOT, p["ns"], p["key"], value, *_condition(request.query_params))
meta = _set_note(p["ns"], p["key"], value, *_condition(request.query_params), denied)
return respond(
request,
meta,
Expand All @@ -1644,32 +1644,28 @@ def note_write(request: Request) -> Response:
)


def _burn_nonce(room: str, nonce: str) -> Response | None:
"""Spend a nonce for a room's signed ownership writes, or refuse the replay.

A message replay stops mattering when the message leaves the ring; a note has no ring,
so a captured signed URL would work forever — including the one that re-adds a key the
owner has since removed. The counter is claimed with a compare-and-set on the note that
holds it, so two concurrent writers cannot both spend the same value; the loser gets
the ordinary 409. A burnt nonce is not refunded if the write behind it then fails —
counters only move forward, and re-signing costs one line of shell.
@contextmanager
def _signed_note_gate(room: str, nonce: str) -> Iterator[Response | None]:
"""Hold a serialization lock on the room's replay counter across the note mutation.

The counter check, the protected-note CAS, and the nonce commit must share an atomic
boundary. A check-then-commit gap allows concurrent updates using the same nonce to
both pass and both mutate state; burning the nonce before the mutation commits a
side effect for a first-claim rejected by CAS. A distinct `.gate` lock serializes
competing signed updates for this room without recursively colliding with the inner
`note_set` lock on the nonce note itself.
"""
current = store.note_get(config.ROOT, store.NONCE_NS, room)
if current is not None and not (current.isdigit() and int(nonce) > int(current)):
return text(
f"403 nonce {nonce} was already used for /r/{room} (last {current}). A signed "
"ownership URL is single-use — count up and sign again.",
403,
)
store.note_set(
config.ROOT,
store.NONCE_NS,
room,
nonce,
expect=current,
expect_absent=current is None,
)
return None
with store._locked(store.note_path(config.ROOT, store.NONCE_NS, room).with_suffix(".gate")):
current = store.note_get(config.ROOT, store.NONCE_NS, room)
if current is not None and not (current.isdigit() and int(nonce) > int(current)):
yield text(
f"403 nonce {nonce} was already used for /r/{room} (last {current}). A signed "
"ownership URL is single-use — count up and sign again.",
403,
)
return
yield None
store.note_set(config.ROOT, store.NONCE_NS, room, nonce)


def note_write_signed(request: Request) -> Response:
Expand All @@ -1683,13 +1679,13 @@ def note_write_signed(request: Request) -> Response:
signer = _signer(p["did"], p["sig"], nonce, f"{ns}|{key}|{nonce}|{value}")
if isinstance(signer, Response):
return signer
denied = _note_write_gate(ns, key, value, signer)
if denied:
return denied
denied = _burn_nonce(key, nonce)
if denied:
return denied
meta = store.note_set(config.ROOT, ns, key, value, *_condition(request.query_params))
first = _note_write_gate(ns, key, value, signer)
if isinstance(first, Response):
return first
with _signed_note_gate(key, nonce) as denied:
if denied:
return denied
meta = _set_note(ns, key, value, *_condition(request.query_params), first)
return respond(
request,
meta,
Expand Down Expand Up @@ -1725,18 +1721,21 @@ async def note_post(request: Request) -> Response:
# note, the nonce burn is a compare-and-swap on disk, and note_set walks the notes tree
# to enforce the global cap. None of that may run on the loop from an `async def`.
def write() -> Response:
denied = _note_write_gate(ns, key, value, signer)
if denied:
return denied
if signer is not None:
burned = _burn_nonce(key, nonce)
if burned:
return burned
meta = store.note_set(config.ROOT, ns, key, value, *condition)
first = _note_write_gate(ns, key, value, signer)
if isinstance(first, Response):
return first
if signer is None:
meta = _set_note(ns, key, value, *condition, first)
else:
with _signed_note_gate(key, nonce) as denied:
if denied:
return denied
meta = _set_note(ns, key, value, *condition, first)
return respond(
request,
meta,
f"ok {meta['ns']}/{meta['key']} {meta['bytes']}B {meta['ts']}",
f"ok {meta['ns']}/{meta['key']} {meta['bytes']}B {meta['ts']}"
+ (f" signed by {didkey.abbreviate(signer)}" if signer else ""),
budget_note("write", left, RATE_WRITE),
)

Expand Down
4 changes: 2 additions & 2 deletions src/didkey.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,13 +77,13 @@ class SignatureError(ValueError):


def _b58decode(raw: str) -> bytes:
n = 0
n, pad = 0, len(raw) - len(raw.lstrip("1"))
for ch in raw:
digit = _B58_INDEX.get(ch)
if digit is None:
raise DidError(f"bad did:key: {ch!r} is not base58btc")
n = n * 58 + digit
return n.to_bytes((n.bit_length() + 7) // 8, "big") if n else b""
return b"\x00" * pad + (n.to_bytes((n.bit_length() + 7) // 8, "big") if n else b"")


def public_key(did: str) -> bytes:
Expand Down
56 changes: 56 additions & 0 deletions tests/http/test_rooms.py
Original file line number Diff line number Diff line change
Expand Up @@ -1094,6 +1094,62 @@ def create():
assert store.note_get(tmp_path, store.OWNERS_NS, "d-first") is None


def test_two_first_claims_racing_ownership_note_enforces_cas(client, tmp_path, monkeypatch):
"""TOCTOU race in room ownership claim (#173).
A first-time claim on an unowned d- room without ?if_absent=1 must enforce
create-if-absent CAS under the lock, so a concurrent racer that created the
owner note in the gap is refused with 409 and cannot be overwritten.
"""
import store

owner, owner_sign = _keypair(seed=1)
other, _ = _keypair(seed=2)
owner_note = store.note_path(tmp_path, store.OWNERS_NS, "d-race-owner")

def create_other_owner():
owner_note.parent.mkdir(parents=True, exist_ok=True)
owner_note.write_text(other, encoding="utf-8")

raced = _race_before_lock(monkeypatch, store, owner_note, create_other_owner)
lost = _claim(client, "d-race-owner", owner, owner_sign)

assert raced, "the race never happened — this test proved nothing"
assert lost.status_code == 409
assert store.note_get(tmp_path, store.OWNERS_NS, "d-race-owner") == other
# A losing claimer's rejected mutation must not commit or advance the room's durable nonce counter
assert store.note_get(tmp_path, store.NONCE_NS, "d-race-owner") is None


def test_concurrent_signed_update_with_same_nonce_cannot_mutate_note(client, tmp_path):
"""Replay race and atomic serialization on signed control notes (#173, reported by @yukkie3276).
Under the serialization lock (.gate), a signed room-control write must complete its
mutation and nonce commit without self-deadlocking. Concurrent signed updates with the
same nonce cannot both mutate state: the second caller observing the already-updated
nonce is refused with 403 and its note write never executes.
"""
import store

owner, owner_sign = _keypair(seed=1)
claim_res = _claim(client, "d-replay-race", owner, owner_sign)
assert claim_res.status_code == 200
assert store.note_get(tmp_path, store.OWNERS_NS, "d-replay-race") == owner
assert store.note_get(tmp_path, store.NONCE_NS, "d-replay-race") == "1"

guest1, _ = _keypair(seed=2)
guest2, _ = _keypair(seed=3)

res1 = _set_signed(client, store.ALLOW_NS, "d-replay-race", owner, owner_sign, guest1, nonce=2)
assert res1.status_code == 200
assert store.note_get(tmp_path, store.ALLOW_NS, "d-replay-race") == guest1
assert store.note_get(tmp_path, store.NONCE_NS, "d-replay-race") == "2"

res2 = _set_signed(client, store.ALLOW_NS, "d-replay-race", owner, owner_sign, guest2, nonce=2)
assert res2.status_code == 403
assert "already used" in res2.text
assert store.note_get(tmp_path, store.ALLOW_NS, "d-replay-race") == guest1
assert store.note_get(tmp_path, store.NONCE_NS, "d-replay-race") == "2"


def test_note_capacity_walk_is_cached_and_a_note_write_invalidates_it(client, monkeypatch):
"""The note gauge under /rooms changes only when a note is written or reaped, so it
lives behind its own generation-stamped cache: reused across /rooms requests, dropped
Expand Down
17 changes: 17 additions & 0 deletions tests/unit/test_didkey.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,3 +98,20 @@ def test_the_signed_lane_refuses_an_aliased_signature_over_http(client):
assert client.get("/r/alias?format=json").json()["messages"] == []

assert _client._say_signed(client, "alias", did, sign, "hi").status_code == 200


def test_b58decode_preserves_leading_zero_bytes():
"""Base58btc decodes each leading '1' character to a 0x00 byte (RFC 5869 / multibase).
Truncating leading zero bytes violates the base58 specification (#155)."""
import didkey

assert didkey._b58decode("") == b""
assert didkey._b58decode("1") == b"\x00"
assert didkey._b58decode("11") == b"\x00\x00"
assert didkey._b58decode("111") == b"\x00\x00\x00"
assert didkey._b58decode("12") == b"\x00\x01"
assert didkey._b58decode("2") == b"\x01"
with pytest.raises(didkey.DidError):
didkey._b58decode("0") # '0' is not in base58btc
with pytest.raises(didkey.DidError):
didkey._b58decode("I") # 'I' is not in base58btc