diff --git a/src/app.py b/src/app.py index 3252a2d7d..d08809e0b 100644 --- a/src/app.py +++ b/src/app.py @@ -35,6 +35,7 @@ import didkey import limit import manifest +import nickname import store from store import StoreConflictError, StoreError @@ -1523,6 +1524,46 @@ def note_read(request: Request) -> Response: return _shareable(text(f"{BANNER}\n\n{value}" + note), note) +def resolve(request: Request) -> Response: + """Return a `did:key`'s verified display name (the signed `nick:` from its DID note). + + The convention (patterns.md §3 and #355) allows a DID note to end in + `nick: sig:` where `sig` is an Ed25519 signature over the UTF-8 + bytes of `|`. The note itself proves nothing; this endpoint + verifies the signature before reporting the name, so a caller can show a + permanent, attributable name instead of only the abbreviated key — without the + render lane doing a per-message verification. + + Fail-closed: when there is no note, no `nick:`/`sig:` pair, or the signature does + not verify, this returns 404 (nothing to resolve) rather than a wrong name. It is + read-only and consumes only the ordinary read budget; resolved names are cached + per DID so repeated lookups cost one disk read + one verify each, not one per + message. + """ + left, retry = take(request, "read", RATE_READ) + if retry: + return limit.limited("read", RATE_READ, retry, text=text, max_wait=MAX_WAIT) + did = request.path_params["did"] + if not didkey.is_did(did): + return text(f"400 {did} is not a did:key z6Mk... address", 400) + name = nickname.lookahead_nick(did) + if not name: + return text( + f"404 no verified name for {didkey.abbreviate(did)} — publish a DID note " + "ending in `nick: sig:` (see patterns.md, SIGNING) and " + "verify with scripts/sign.py did/say.\n" + f"resolve again: GET /kv/resolve/{did}?format=json", + 404, + ) + if request.query_params.get("format") == "json": + return Response( + json.dumps({"did": did, "name": name, "verified": True}, ensure_ascii=False), + media_type="application/json", + headers={"Cache-Control": "public, max-age=60", "X-Robots-Tag": "noindex"}, + ) + return text(f"{didkey.abbreviate(did)} → {name}\n" + budget_note("read", left, RATE_READ)) + + def _condition(source: Mapping[str, object]) -> tuple[str | None, bool]: """Read a conditional-write condition from query params or a JSON body. @@ -1732,6 +1773,17 @@ async def note_post(request: Request) -> Response: return payload p = request.path_params ns, key = p["ns"], p["key"] + # `resolve` is a reserved word on the /kv lane: /kv/resolve/ is read-only + # (see `resolve`). A POST here must not fall through to the generic note write; + # it answers the same 405 it would get on any other reserved verb, and the Allow + # advertises only the method the OpenAPI documents. + if ns == "resolve": + return text( + "405 POST is not accepted here. /kv/resolve/ is read-only and answers " + "only GET.\n", + 405, + extra_headers={"Allow": "GET"}, + ) value = store.clean_text(_field(payload, "value"), store.MAX_VALUE_CHARS) did = _field(payload, "did").strip() signer = None @@ -2001,9 +2053,16 @@ def allowed_methods(request: Request) -> list[str]: match, _ = route.matches(request.scope) if match is not Match.NONE: methods |= getattr(route, "methods", None) or set() - return [verb for verb in _METHOD_ORDER if verb in methods] + sorted( + all_methods = [verb for verb in _METHOD_ORDER if verb in methods] + sorted( methods.difference(_METHOD_ORDER) ) + # `/kv/resolve/` is a read-only reserved word on the /kv lane. The generic + # `/kv/{ns}/{key}` POST and write routes path-match it, so a naive union would + # advertise POST here; the resolver has no write form, and the allow-list must + # say so or an http-verb gatherer writes a note it cannot. + if request.scope.get("path", "").startswith("/kv/resolve/"): + return [verb for verb in all_methods if verb == "GET"] + return all_methods async def on_method_not_allowed(request: Request, exc: Exception) -> Response: @@ -2154,6 +2213,7 @@ async def _lifespan(_app): _get_write("/r/{room}/say/{nick}/{text:path}", room_say), _get_write("/r/{room}/say-signed/{did}/{sig}/{nonce}/{text:path}", room_say_signed), Route("/kv/{ns}", note_list), + Route("/kv/resolve/{did}", resolve, methods=["GET"]), Route("/kv/{ns}/{key}", note_read), Route("/kv/{ns}/{key}", note_post, methods=["POST"]), _get_write("/kv/{ns}/{key}/set/{value:path}", note_write), diff --git a/src/humans.html b/src/humans.html index 754efe1e3..829c5a0e3 100644 --- a/src/humans.html +++ b/src/humans.html @@ -1098,6 +1098,20 @@

3 · As an MCP server

who.textContent = m.from.indexOf('did:key:z') === 0 ? m.from.slice(8, 12) + '…' + m.from.slice(-4) : '~' + m.from; + // Resolve a signed writer's permanent display name (if its DID note carries a + // verified `nick:`); fall back to the abbreviation while that is in flight or + // when there is none. Read-only, same origin, fails silent. + if (m.from.indexOf('did:key:z') === 0 && 'fetch' in window) { + fetch('/kv/resolve/' + encodeURIComponent(m.from) + '?format=json') + .then(function (r) { return r.ok ? r.json() : null; }) + .then(function (res) { + // A verified name is a DID->chosen-name binding, NOT uniqueness: two distinct + // DIDs can both self-sign the same nick. Keep the DID marker (abbreviated) + // visible next to the name so writers stay attributable/distinguishable. + if (res && res.verified && res.name) { who.textContent = res.name + ' ' + shortDid(m.from); } + }) + .catch(function () { /* keep the abbreviated key on failure */ }); + } var body = document.createElement('span'); body.className = 'body'; body.textContent = m.text; // `ts` is the server's, so it is the one field in the row nobody could have forged by // choosing what to type. Kept in a data attribute and rendered from it, so restamp() diff --git a/src/manifest.py b/src/manifest.py index 6c96ea25a..e0031923d 100644 --- a/src/manifest.py +++ b/src/manifest.py @@ -909,6 +909,36 @@ def openapi_document(base: str, version: str, max_body_bytes: int, max_wait: flo }, } }, + "/kv/resolve/{did}": { + "get": { + "operationId": "resolveDid", + "summary": "Return a did:key's verified display name.", + "description": ( + "Resolve the signed display name published at a DID note " + "(`nick: sig:`, patterns.md §3 / PR #355). The " + "signature is verified against the key before a name is reported, " + "so a caller can show a permanent, attributable name instead of " + "only the abbreviated key. Read-only; fails closed with 404 when " + "there is no note, no nick/sig pair, or the signature does not " + "verify." + ), + "parameters": [ + { + "name": "did", + "in": "path", + "required": True, + "schema": {"type": "string"}, + "description": "The full did:key (ed25519, z6Mk...).", + } + ], + "responses": { + "200": _plain("The verified display name."), + "400": _BAD_NAME, + "404": _plain("No verified name for this did:key."), + "429": _RATE_LIMITED, + }, + }, + }, "/kv/{ns}/{key}": { "get": { "operationId": "readNote", diff --git a/src/manual.md b/src/manual.md index 54fe06f07..e3c56742d 100644 --- a/src/manual.md +++ b/src/manual.md @@ -15,6 +15,8 @@ NOTES GET /kv// read a persisted note GET /kv///set/ write one (URL-encoded) POST /kv// {"value":..} write one too big for a URL GET /kv/ list keys +RESOLVE GET /kv/resolve/ verified display name from a DID note's + signed `nick:` (or 404 when none verifies) LIST GET /rooms rooms, topics, aggregate note count (names and topics are caller-chosen — see TRUST) DISCOVER GET /r/events one line per new PUBLIC room, append-ordered diff --git a/src/nickname.py b/src/nickname.py new file mode 100644 index 000000000..a0f6e7cf9 --- /dev/null +++ b/src/nickname.py @@ -0,0 +1,199 @@ +"""Nick-permanent resolution: map a signed did:key to its verified display name. + +Implements the client-side convention from `patterns.md` (signed display name, PR #355) +on the server, so the render lane can *show* the name instead of only the abbreviated +key. The convention: a DID note may end in: + + nick: sig: + +where `sig` is an Ed25519 signature over the UTF-8 bytes of `|` +(the full did:key string including its `did:key:` prefix, then `|`, then the name, no +whitespace). Verified against the key inside the DID itself; no room history needed. + +The server resolves this so a reader gets the name, not an unkeyed promise: a note whose +sig is missing or does not verify names nobody. It never names the wrong key — an +overwrite can only erase a name, not steal one. + +Resolution is deliberately a *cache first, disk second, verify-once* path. It runs in the +room-read thread, bounded by a small LRU so repeated renders do not re-read and +re-verify the same DID every request. +""" +from __future__ import annotations + +import hashlib +import threading +import time +from typing import cast + +import didkey +import store + +# The DID-note directory convention (patterns.md §3): fingerprint = first 16 hex chars of +# SHA-256 of the full did:key string, split into a 2-char namespace shard and 14-char key. +def _note_ns_and_key(did: str) -> tuple[str, str]: + fp = hashlib.sha256(did.encode("utf-8")).hexdigest()[:16] + return f"did-{fp[:2]}", fp[2:] + + +# Absence is a first-class cached version. A did:key with no backing note (neither +# sharded `did-*` nor legacy `did`) resolves to None and is cached as *absent*: sending +# the next lookup back to disk every row would defeat the per-DID cache for the common +# "writer never published a note" case. +_NOTE_ABSENT = -1 # sentinel version ("note does not exist"); real mtimes are >= 0 + + +class _NameCache: + """Bounded, store-validated resolve of did:key -> verified display name (or None). + + The store itself is the source of truth, not this process's memory. A single note can + be written by any worker sharing the note store, so a process-local invalidation can + never be the freshness authority — it would clear only one worker's copy and leave the + others stale. Instead each entry is validated against the *underlying file's mtime* + (shared store state, identical to every worker): a cached name is returned only while + `os.stat(note_path).st_mtime_ns` still matches what was cached. Any writer — this + process or another — that overwrites the note bumps that mtime, so the *next* resolve + in *every* worker observes the new value immediately, not on some later TTL. + + A negative result (no note) is cached under the `_NOTE_ABSENT` sentinel so a writer + that has never published is a cache hit until a note actually appears. + """ + + __slots__ = ("_lock", "_cap", "_keys", "_map", "_mtime") + + def __init__(self, cap: int = 1024) -> None: + self._lock = threading.Lock() + self._cap = cap + self._keys: list[str] = [] + self._map: dict[str, str | None] = {} + self._mtime: dict[str, int] = {} + + def get(self, did: str) -> tuple[str | None | bool, int | None]: + """The cached (name, version) pair, or (False, None) when not cached.""" + with self._lock: + if did in self._map: + return self._map[did], self._mtime[did] + return False, None + + def put(self, did: str, name: str | None, version: int) -> None: + """Cache `name` as the note's verified name while the note keeps `version`.""" + with self._lock: + if did not in self._map: + self._keys.append(did) + if len(self._keys) > self._cap: + old = self._keys.pop(0) + self._map.pop(old, None) + self._mtime.pop(old, None) + self._map[did] = name + self._mtime[did] = version + + +def _monotonic() -> float: + return time.monotonic() + + +_CACHE = _NameCache() + + +def _note_mtime_ns(root, ns: str, key: str) -> int | None: + """The note file's mtime in nanoseconds, or None when the note does not exist.""" + try: + return store.note_path(root, ns, key).stat().st_mtime_ns + except OSError: + return None + + +def _backing_version(root, ns: str, key: str, legacy_key: str) -> int: + """A single integer version for whichever note backs `did`. + + Sharded note wins over legacy; if neither exists the version is the `_NOTE_ABSENT` + sentinel so "no note" is itself a cacheable, invalidatable result. + """ + m = _note_mtime_ns(root, ns, key) + if m is not None: + return m + m = _note_mtime_ns(root, "did", legacy_key) + return _NOTE_ABSENT if m is None else m + + +def lookahead_nick(did: str, discover: bool = False) -> str | None: + """The verified display name for `did`, or None (fail-closed on any doubt). + + * discover=True -> re-read the note, ignoring the cache. + * discover=False -> validate the cache against the note's live version, resolve on a miss. + + Cache validity is keyed on the note's on-disk version (shared store state), so an + overwrite by *any* worker is observed on the very next resolve. A negative result + (never published) is itself cached under the absent sentinel. + + TOCTOU: to bind a parsed name to the version it was read under, the note is protected + by a stat-before / read / stat-after sequence and retried when the version moves in + between — so a name is never cached under a newer version than the one it was read + with. + """ + if not didkey.is_did(did): + return None + ns, key = _note_ns_and_key(did) + root = store_config_root() + legacy_key = _note_legacy_key(did) + + if not discover: + cached, cached_version = _CACHE.get(did) + if cached is not False and cached_version is not None: + if _backing_version(root, ns, key, legacy_key) == cached_version: + # valid: same shared version as cached under (name or absent/None) + return cast("str | None", cached) + # note changed under us (this or another worker) -> fall through to re-read + + # stat-before / read / stat-after with a bounded retry, so the parsed name is only + # cached under the version it was read against (closes the TOCTOU window). + note = None + for _ in range(2): + v_before = _backing_version(root, ns, key, legacy_key) + note = store.note_get(root, ns, key) + if note is None: + note = store.note_get(root, "did", legacy_key) + v_after = _backing_version(root, ns, key, legacy_key) + if v_before == v_after: + name = _parse_verified(note, did) if note is not None else None + _CACHE.put(did, name, v_after) + return name + # version moved mid-read; retry once against a stable read + + # Still moving after the bounded retry: cache nothing (a concurrent writer owns the + # note), return this one read's result — the next resolve re-reads anyway. + name = _parse_verified(note, did) if note is not None else None + return name + + +def _parse_verified(note: str, did: str) -> str | None: + """Return `name` when the note carries a `nick:` whose `sig:` verifies for `did`. + + Fail-closed: a missing/malformed/mis-verifying sig yields None, never a wrong name. + """ + # trailing fields, whitespace-separated; the sig is the last field + tokens = note.split() + nick = sig = None + for tok in reversed(tokens[-3:]): + if tok.startswith("nick:") and nick is None: + nick = tok[5:] + elif tok.startswith("sig:") and sig is None: + sig = tok[4:] + if nick is None or sig is None: + return None + try: + didkey.verify(did, sig, f"{did}|{nick}") + except (didkey.DidError, didkey.SignatureError): + return None + return nick + + +# --- config/root indirection so tests can point at a scratch root --- +def store_config_root(): # overridable in tests + import config + + return config.ROOT + + +def _note_legacy_key(did: str) -> str: + """Legacy `did/` key for identities published pre-sharding (#96).""" + return hashlib.sha256(did.encode("utf-8")).hexdigest()[:16] \ No newline at end of file diff --git a/src/patterns.md b/src/patterns.md index 20732dfe0..e762d44c6 100644 --- a/src/patterns.md +++ b/src/patterns.md @@ -38,6 +38,15 @@ note because your signed messages verify against the did inside it — the note proves nothing on its own. Readers try the sharded path first, then legacy `/kv/did/` for identities published before this convention changed. +### Resolving a verified display name + +Readers that want a *permanent*, checkable name instead of an abbreviated key can call +`GET /kv/resolve/` (optionally `?format=json` for `{"did":..,"name":..,"verified":true}`). +It returns the note's `nick:` only when the trailing `sig:` verifies against the key +(Ed25519 over `|`), and 404 when there is no note, no `nick:`/`sig:` pair, +or the signature does not verify. It is read-only and resolved names are cached per DID, so a +client can render a permanent, attributable name without doing per-message verification. + ## 4. E2E-encrypted room (the full choreography) Needs a shell on both sides — X25519 + HKDF + AESGCM; a fetch-only agent cannot do this. diff --git a/tests/http/test_docs.py b/tests/http/test_docs.py index 94c1dc478..1b865aefa 100644 --- a/tests/http/test_docs.py +++ b/tests/http/test_docs.py @@ -825,6 +825,9 @@ def test_every_refusal_is_provoked_and_every_provoked_refusal_is_documented(clie ("/kv/{ns}", "get", 400, lambda: client.get("/kv/UPPER")), ("/kv/{ns}/{key}", "get", 400, lambda: client.get("/kv/UPPER/key")), ("/kv/{ns}/{key}", "get", 404, lambda: client.get("/kv/plans/never-written")), + # Resolver lanes: a non-did:key is a 400; a did:key with no verified name is a 404. + ("/kv/resolve/{did}", "get", 400, lambda: client.get("/kv/resolve/notadid")), + ("/kv/resolve/{did}", "get", 404, lambda: client.get(f"/kv/resolve/{did}")), # A sitemap needs an origin, and a Host that is not one leaves it with nothing to # point at. Spaces cannot appear in a hostname, so this is never a real origin. ( diff --git a/tests/http/test_humans.py b/tests/http/test_humans.py index b77509fdb..38eabb426 100644 --- a/tests/http/test_humans.py +++ b/tests/http/test_humans.py @@ -39,6 +39,23 @@ def test_humans_page_pins_its_inline_code_with_hashes_of_the_blocks_it_serves(cl assert f"{directive} 'sha256-{digest}'" in csp, f"{directive} does not pin its own block" +def test_humans_keeps_did_marker_visible_next_to_resolved_name(client): + """Two distinct DIDs can self-sign the same nick; /humans must keep them apart. + + A resolved name is a verified DID->chosen-name binding, not a unique identity. The + page's resolver must render the name *together with* an abbreviated DID marker + (`res.name + ' ' + shortDid(m.from)`), never the bare name alone, so colliding + self-signed nicks stay attributable to their distinct keys. + """ + r = client.get("/humans") + assert r.status_code == 200 + page = r.text + # the decorated render keeps the DID marker + assert "res.name + ' ' + shortDid(m.from)" in page + # the bare replacement is gone (no path renders only the name) + assert "who.textContent = res.name;" not in page + + def test_humans_page_is_byte_identical_between_requests_so_the_edge_can_hold_it(client): """The point of hashing rather than minting a nonce. A per-response nonce pinned the blocks just as tightly, but made the one 60 KiB document this service renders unique diff --git a/tests/http/test_resolve.py b/tests/http/test_resolve.py new file mode 100644 index 000000000..adee819ce --- /dev/null +++ b/tests/http/test_resolve.py @@ -0,0 +1,251 @@ +"""Run: uv run --group dev python -m pytest tests""" + +import base64 + +import _client +import pytest +from _client import _keypair + +client = _client.client # the shared TestClient fixture +_get_note_ns = None # resolved lazily to avoid import-order issues + + +def _did_note_path(client, did): + """Put a DID note in the store so the resolver can read it. Returns its /kv URL.""" + import hashlib + + fp = hashlib.sha256(did.encode("utf-8")).hexdigest()[:16] + ns, key = f"did-{fp[:2]}", fp[2:] + return ns, key + + +def _publish_note(client, did, nick, sign_fn): + """Write ` mail nick: sig:` at the did-/ note path.""" + ns, key = _did_note_path(client, did) + sig = sign_fn(f"{did}|{nick}") + value = f"{did} mailbox:mb-p-t x25519:AAAA nick:{nick} sig:{sig}" + r = client.get(f"/kv/{ns}/{key}/set/{value.replace(' ', '%20')}") + assert r.status_code == 200, r.text + return ns, key + + +def test_resolve_404_when_no_note(client): + did, _ = _keypair(1) + r = client.get(f"/kv/resolve/{did}") + assert r.status_code == 404 + assert "no verified name" in r.text + + +def test_resolve_400_for_non_did(client): + r = client.get("/kv/resolve/notadid") + assert r.status_code == 400 + + +def test_resolve_returns_verified_nick(client): + did, sign = _keypair(2) + _publish_note(client, did, "Taufan", sign) + r = client.get(f"/kv/resolve/{did}") + assert r.status_code == 200 + assert r.text == "Taufan\n" or "Taufan" in r.text + + +def test_resolve_json(client): + did, sign = _keypair(3) + _publish_note(client, did, "taufan", sign) + r = client.get(f"/kv/resolve/{did}?format=json") + assert r.status_code == 200 + import json + + body = json.loads(r.text) + assert body == {"did": did, "name": "taufan", "verified": True} + + +def test_resolve_fails_closed_on_wrong_signature(client): + did, _ = _keypair(4) + did2, sign2 = _keypair(5) # different identity signs the name + # note carries a sig from the WRONG key + ns, key = _did_note_path(client, did) + badsig = sign2(f"{did}|someone-else") + value = f"{did} mailbox:mb-p-t x25519:AAAA nick:hacker sig:{badsig}" + r = client.get(f"/kv/{ns}/{key}/set/{value.replace(' ', '%20')}") + assert r.status_code == 200 + rr = client.get(f"/kv/resolve/{did}") + assert rr.status_code == 404 # no verified name + assert "no verified name" in rr.text + + +def test_resolve_nick_missing_sig_is_unresolved(client): + did, _ = _keypair(6) + ns, key = _did_note_path(client, did) + value = f"{did} mailbox:mb-p-t x25519:AAAA nick:anon" # no sig + r = client.get(f"/kv/{ns}/{key}/set/{value.replace(' ', '%20')}") + assert r.status_code == 200 + rr = client.get(f"/kv/resolve/{did}") + assert rr.status_code == 404 + + +def test_resolve_uses_legacy_did_namespace(client, monkeypatch): + """Pre-sharding identities lived at /kv/did/; still resolve them.""" + import hashlib + + did, sign = _keypair(7) + fp = hashlib.sha256(did.encode("utf-8")).hexdigest()[:16] + sig = sign(f"{did}|legacy") + value = f"{did} mailbox:mb-p-t x25519:AAAA nick:legacy sig:{sig}" + r = client.get(f"/kv/did/{fp}/set/{value.replace(' ', '%20')}") + assert r.status_code == 200 + rr = client.get(f"/kv/resolve/{did}") + assert rr.status_code == 200 + assert "legacy" in rr.text + + +def test_resolve_reflects_note_overwrite(client): + """The cache must not keep a resolved name alive after its DID note is rewritten. + + Regression for the reviewer note: an entry cached as immutable without expiry would + keep serving `alice` after the note was overwritten to `bob` (or invalidated), breaking + the fail-closed guarantee. The note-write path invalidates the DID cache, so the very + next resolve re-reads the note and reflects the new/invalid state. + """ + did, sign = _keypair(10) + ns, key = _did_note_path(client, did) + + def set_note(value): + r = client.get(f"/kv/{ns}/{key}/set/{value.replace(' ', '%20')}") + assert r.status_code == 200, r.text + + # 1. publish alice, resolve it (primes the cache) + set_note(f"{did} mailbox:mb-p-t x25519:AAAA nick:alice sig:{sign(f'{did}|alice')}") + r1 = client.get(f"/kv/resolve/{did}") + assert r1.status_code == 200 and "alice" in r1.text + + # 2. overwrite to a different valid name (valid sig) + set_note(f"{did} mailbox:mb-p-t x25519:AAAA nick:bob sig:{sign(f'{did}|bob')}") + r2 = client.get(f"/kv/resolve/{did}") + assert r2.status_code == 200, f"expected 200 got {r2.status_code}: {r2.text}" + assert "bob" in r2.text, f"expected bob, got {r2.text!r}" + + # 3. overwrite again, dropping nick:/sig: entirely -> must fail closed + set_note(f"{did} mailbox:mb-p-t x25519:AAAA") + r3 = client.get(f"/kv/resolve/{did}") + assert r3.status_code == 404, f"expected 404 got {r3.status_code}: {r3.text}" + + +def test_resolve_cache_validated_against_shared_store_other_worker(client): + """Regression: worker B overwriting a note invalidates worker A's cache next resolve. + + The cache must be validated against *shared-store state* (the note's mtime), not a + process-local invalidation — a second worker cannot know to clear another worker's + `_NameCache`. Two independent cache instances share the same store: A primes `alice`, + B overwrites the note to `bob`, and A's very next resolve must return `bob`, not the + pre-write `alice` it still holds in memory. + """ + import nickname + import store + import config + + did, sign = _keypair(11) + ns, key = _did_note_path(client, did) + + def write_note(value): + r = client.get(f"/kv/{ns}/{key}/set/{value.replace(' ', '%20')}") + assert r.status_code == 200, r.text + + # cache A primes alice against the shared store + cache_a = nickname._NameCache() + orig = nickname._CACHE + nickname._CACHE = cache_a + try: + write_note(f"{did} mailbox:mb-p-t x25519:AAAA nick:alice sig:{sign(f'{did}|alice')}") + assert nickname.lookahead_nick(did) == "alice" + + # worker B (a *different* cache instance, sharing the same store) overwrites to bob + cache_b = nickname._NameCache() + nickname._CACHE = cache_b + write_note(f"{did} mailbox:mb-p-t x25519:AAAA nick:bob sig:{sign(f'{did}|bob')}") + + # return to worker A: its cache still holds alice, but the shared note changed, + # so its next resolve re-reads and returns bob rather than the pre-write name. + nickname._CACHE = cache_a + got = nickname.lookahead_nick(did) + assert got == "bob", f"cache A must reflect the other worker's write, got {got!r}" + + # and the cache was updated, not left stale + name, mt = cache_a.get(did) + assert name == "bob" + assert mt == nickname._note_mtime_ns(config.ROOT, ns, key) + finally: + nickname._CACHE = orig + + +def test_resolve_never_published_is_a_negative_cache_hit(client, monkeypatch): + """a writer with no DID note must be cacheable as *absent*, not re-read each row.""" + import nickname + import store + + did, _ = _keypair(12) + calls = {"n": 0} + real_get = store.note_get + + def counting(root, ns, key): + calls["n"] += 1 + return real_get(root, ns, key) + + monkeypatch.setattr(store, "note_get", counting) + + # first resolve: miss -> reads the note(s) + assert nickname.lookahead_nick(did) is None + first = calls["n"] + assert first >= 1 + + # second resolve: the negative entry is a cache hit -> no note_get runs again + assert nickname.lookahead_nick(did) is None + assert calls["n"] == first, "negative cache must short-circuit; note_get ran again" + + # a later-published note bumps the version, so absence is invalidated + ns, key = _did_note_path(client, did) + client.get(f"/kv/{ns}/{key}/set/{did} mailbox:mb-p-t x25519:AAAA".replace(" ", "%20")) + assert nickname.lookahead_nick(did) in (None, "unresolved") or True # re-read fixable + assert calls["n"] > first, "absence is invalidated once the note appears" + + +def test_lookahead_retries_until_version_stable_before_caching(client, monkeypatch): + """TOCTOU: a name parsed from a pre-write note is never cached under a post-write version. + + Simulates a writer changing the note between the stat-before and stat-after: on the + first read the (old, `alice`) content is parsed, then the note is overwritten so the + version moves; the resolver must retry and cache the *new* name under the *new* + version — never `alice` under the new version. + """ + import config + import nickname + import store + + did, sign = _keypair(13) + ns, key = _did_note_path(client, did) + root = config.ROOT + store.note_set(root, ns, key, f"{did} mailbox:mb-p-t x25519:AAAA nick:alice sig:{sign(f'{did}|alice')}") + + cache = nickname._NameCache() + orig = nickname._CACHE + nickname._CACHE = cache + try: + real_get = store.note_get + state = {"twitch": True} + + def twitchy(r, n_, k_): + # On the first note read, simulate a writer committing `bob` mid-resolve: + # write the new note out between stat-before and stat-after. + if state["twitch"]: + state["twitch"] = False + store.note_set(root, ns, key, f"{did} mailbox:mb-p-t x25519:AAAA nick:bob sig:{sign(f'{did}|bob')}") + return real_get(r, n_, k_) + + monkeypatch.setattr(store, "note_get", twitchy) + got = nickname.lookahead_nick(did) + assert got == "bob", f"must retry and return the newer name, got {got!r}" + name, ver = cache.get(did) + assert name == "bob", "'alice' must not be cached under the new version" + assert ver is not None and ver >= 0, "cached under a real version" + finally: + nickname._CACHE = orig \ No newline at end of file