Files
Shadowbroker/backend/tests/mesh/test_dm_first_contact_lookup.py
BigBodyCobainandClaude Opus 5.5 90d3fa370b Make secure mail work between two fresh nodes
Mail between two nodes that had just exchanged contact addresses never
arrived readable. Fixes along the whole path, each covered by a test:

- Status: the web UI's own requests get the full wormhole status, so it
  stops treating a ready node as not ready.
- Invites: the owner node named in an invite is asked first, with an
  onion-sized timeout; an import that could not reach it finishes in the
  background and replaces the keyless contact it left behind.
- Aliases: no one-sided mailbox alias is made up on compose; both sides
  address mail by node id until an alias is agreed.
- Signing: each mailbox request is signed once, keeping polls under the
  sign rate limit.
- MLS: the welcome is sent with the mail until the peer answers, and the
  receiver joins as the identity whose key package the sender used, with
  that identity's DH key.
- Sender seal: a seal addressed to the node's DM identity opens even when
  the browser names the node's transport identity.
- Gate rooms: the chat controller restarted the live stream and the room
  long-poll on every status refresh, about 60 requests a second, which
  exhausted local ports; it now reacts only to access changes, and the
  stream waits a minute between tries when there is no admin session.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 05:17:48 -07:00

163 lines
7.0 KiB
Python

"""First contact between two fresh nodes finds the invite owner's keys.
A signed DM invite names the node that holds its owner's keys
(lookup_peer_url). That hint used to be lost three ways: the import never
passed it to the lookup, the contact store dropped the field when it saved,
and the lookup read the contact store's keys rather than its records. So
every first contact searched hundreds of mostly dead peers and gave up.
"""
import time
from unittest.mock import patch
import pytest
from services.mesh import mesh_wormhole_contacts as contacts_mod
from services.mesh import mesh_wormhole_identity as identity_mod
from services.mesh import mesh_wormhole_prekey as prekey_mod
OWNER = "http://owner-node.example:8000"
@pytest.fixture(autouse=True)
def _forget_answered_peers():
prekey_mod._ANSWERED_LOOKUP_PEERS.clear()
yield
prekey_mod._ANSWERED_LOOKUP_PEERS.clear()
def test_contact_store_keeps_the_lookup_hint():
contact = contacts_mod._normalize_contact({"invitePinnedLookupPeerUrl": OWNER + "/"})
assert contact["invitePinnedLookupPeerUrl"] == OWNER
assert contacts_mod._normalize_contact({})["invitePinnedLookupPeerUrl"] == ""
def test_saved_hint_is_found_for_the_invite_token():
store = {
"!sb_owner": {"invitePinnedPrekeyLookupHandle": "tok", "invitePinnedLookupPeerUrl": OWNER},
"!sb_other": {"invitePinnedPrekeyLookupHandle": "other", "invitePinnedLookupPeerUrl": "http://x:1"},
}
with patch.object(contacts_mod, "list_wormhole_dm_contacts", return_value=store):
assert prekey_mod._preferred_invite_lookup_peer_urls("tok") == [OWNER]
@pytest.mark.parametrize(
("raw", "expected"),
[
(OWNER, OWNER),
(OWNER + "/", OWNER),
("http://abc.onion:8000", "http://abc.onion:8000"),
("http://owner-node.example:8000/api/evil", ""),
("file:///etc/passwd", ""),
("", ""),
],
)
def test_invite_hint_is_a_bare_http_origin(raw, expected):
assert identity_mod._invite_lookup_peer_url_hint({"lookup_peer_url": raw}) == expected
def test_onion_request_without_tor_is_refused_not_sent_directly():
def _no_tor(_url):
raise RuntimeError("onion peer requests require Arti to be enabled")
with (
patch("main._infonet_peer_requests_proxies", side_effect=_no_tor),
patch("requests.get") as direct_get,
):
with pytest.raises(OSError):
prekey_mod._peer_http_request("GET", "http://abc.onion:8000/api/mesh/dm/prekey-bundle?lookup_token=t")
direct_get.assert_not_called()
def test_owner_node_is_asked_first_with_the_onion_timeout():
calls = []
def _lookup(peer_url, encoded, *, timeout=None):
calls.append((peer_url, timeout))
if peer_url == OWNER:
return {"ok": True, "agent_id": "!sb_owner"}
return {"ok": False, "detail": prekey_mod._PEER_LOOKUP_UNAVAILABLE}
with (
patch.object(prekey_mod, "_preferred_invite_lookup_peer_urls", return_value=[OWNER]),
patch.object(prekey_mod, "_prioritized_invite_lookup_peer_urls", return_value=[OWNER, "http://dead:1"]),
patch.object(prekey_mod, "_try_public_prekey_lookup_peer", side_effect=_lookup),
):
result = prekey_mod._fetch_dm_prekey_bundle_from_public_lookup("tok")
assert result["ok"] is True
assert calls == [(OWNER, prekey_mod._hinted_lookup_timeout(OWNER))]
def test_parallel_search_returns_at_its_deadline():
def _slow(peer_url, encoded, *, timeout=None):
time.sleep(3)
return {"ok": False, "detail": prekey_mod._PEER_LOOKUP_UNAVAILABLE}
with (
patch.object(prekey_mod, "_preferred_invite_lookup_peer_urls", return_value=[]),
patch.object(prekey_mod, "_prioritized_invite_lookup_peer_urls", return_value=[f"http://dead{i}:1" for i in range(4)]),
patch.object(prekey_mod, "_try_public_prekey_lookup_peer", side_effect=_slow),
patch.object(prekey_mod, "_INVITE_LOOKUP_MAX_ELAPSED_S", 0.5),
):
started = time.monotonic()
result = prekey_mod._fetch_dm_prekey_bundle_from_public_lookup("tok")
elapsed = time.monotonic() - started
assert result["ok"] is False
assert elapsed < 2.5
def test_shared_alias_of_a_verified_contact_counts_as_verified():
# Shared mail is addressed to the mailbox alias both sides agreed on, and
# the send route checks trust for that alias. Looked up by id alone, a
# contact pinned from a signed invite read as unpinned and every send to
# it was refused.
store = {
"!sb_owner": {
"sharedAlias": "dmx_shared",
"trust_level": "invite_pinned",
"trustSummary": {"state": "invite_pinned", "verifiedFirstContact": True},
}
}
with patch.object(contacts_mod, "_read_contacts", return_value=store):
assert contacts_mod.verified_first_contact_requirement("dmx_shared")["ok"] is True
assert contacts_mod.verified_first_contact_requirement("!sb_owner")["ok"] is True
assert contacts_mod.verified_first_contact_requirement("dmx_unknown")["ok"] is False
def test_release_finds_the_owner_node_for_mail_sent_to_the_shared_alias():
# Private release pushes the sealed mail to the recipient's own node
# (the invite's lookup_peer_url). Mail is addressed to the shared alias,
# so the contact must be found by alias or the push skips that node.
from services.mesh import mesh_dm_connect_delivery as delivery
store = {"!sb_owner": {"sharedAlias": "dmx_shared", "invitePinnedLookupPeerUrl": OWNER}}
with patch.object(contacts_mod, "_read_contacts", return_value=store):
assert contacts_mod.get_wormhole_dm_contact("dmx_shared")["invitePinnedLookupPeerUrl"] == OWNER
enriched = delivery.enrich_connect_release_payload({"recipient_id": "dmx_shared"})
assert enriched["relay_push_peer_urls"][0] == OWNER
def test_second_lookup_of_a_short_address_asks_the_peer_that_answered():
# A contact request looks the same short address up twice. The first
# search finds the owner among many peers; the second must go straight
# back there instead of searching for another minute.
calls = []
def _lookup(peer_url, encoded, *, timeout=None):
calls.append(peer_url)
if peer_url == OWNER:
return {"ok": True, "agent_id": "!sb_owner"}
return {"ok": False, "detail": prekey_mod._PEER_LOOKUP_UNAVAILABLE}
pool = ["http://dead1:1", "http://dead2:1", OWNER]
with (
patch.object(contacts_mod, "list_wormhole_dm_contacts", return_value={}),
patch.object(prekey_mod, "_prioritized_invite_lookup_peer_urls", side_effect=lambda preferred=None: list(dict.fromkeys([*(preferred or []), *pool]))),
patch.object(prekey_mod, "_try_public_prekey_lookup_peer", side_effect=_lookup),
):
assert prekey_mod._fetch_dm_prekey_bundle_from_public_lookup("short-addr")["ok"] is True
calls.clear()
assert prekey_mod._fetch_dm_prekey_bundle_from_public_lookup("short-addr")["ok"] is True
assert calls == [OWNER]
assert "short-addr" not in str(prekey_mod._ANSWERED_LOOKUP_PEERS)