diff --git a/meshterm/core/connection.py b/meshterm/core/connection.py index 13a9c0c..22a7dbc 100644 --- a/meshterm/core/connection.py +++ b/meshterm/core/connection.py @@ -34,6 +34,7 @@ from .models import ( NeighbourInfo, Observation, TraceResult, + advert_time, utcnow, ) @@ -1429,7 +1430,7 @@ class MeshCoreDevice(Device): name=info.get("adv_name", name), public_key=info.get("public_key", ""), key_prefix=info.get("public_key", "")[:12], - last_seen=_advert_time(info.get("last_advert")), + last_seen=advert_time(info.get("last_advert")), node_type=_as_int(info.get("type", info.get("adv_type"))), lat=lat, lon=lon, @@ -2899,27 +2900,6 @@ def _as_int(value: object) -> Optional[int]: return None -def _advert_time(last_advert: object) -> Optional[datetime]: - """Convert a contact's ``last_advert`` Unix timestamp to a UTC datetime. - - The firmware reports the seconds-since-epoch of a contact's most recent advert; a - zero/absent/garbage value means "never heard", which maps to ``None``. - - Args: - last_advert: The raw ``last_advert`` field from a contact payload. - - Returns: - A timezone-aware UTC :class:`datetime`, or ``None`` when unknown. - """ - try: - seconds = int(last_advert) # type: ignore[arg-type] - except (TypeError, ValueError): - return None - if seconds <= 0: - return None - return datetime.fromtimestamp(seconds, tz=timezone.utc) - - def _contact_route(info: dict) -> Optional[tuple[str, ...]]: """Extract a contact's device-learned outbound route as per-hop hex hashes. diff --git a/meshterm/core/contact_store.py b/meshterm/core/contact_store.py index fc13848..cd50ec4 100644 --- a/meshterm/core/contact_store.py +++ b/meshterm/core/contact_store.py @@ -29,11 +29,10 @@ from __future__ import annotations import json from dataclasses import dataclass -from datetime import datetime, timezone from pathlib import Path from typing import Optional -from .models import Contact +from .models import Contact, advert_time def _norm(pubkey: str) -> str: @@ -102,12 +101,11 @@ class RememberedContact: The learned route is dropped (``route_hops=None``): a remembered contact floods until the device relearns a path from received traffic, exactly as a freshly-heard one does. + The stored epoch re-enters through :func:`~meshterm.core.models.advert_time`, so a + future-stamped advert remembered before its sender's clock was corrected reads as + unknown rather than resurfacing as "heard in the future". """ - last_seen = ( - datetime.fromtimestamp(self.last_advert, tz=timezone.utc) - if self.last_advert - else None - ) + last_seen = advert_time(self.last_advert) return Contact( name=self.name, public_key=self.public_key, diff --git a/meshterm/core/models.py b/meshterm/core/models.py index ddc1bf8..8e04709 100644 --- a/meshterm/core/models.py +++ b/meshterm/core/models.py @@ -9,7 +9,7 @@ from __future__ import annotations import statistics from collections import Counter from dataclasses import dataclass, field -from datetime import datetime, timezone +from datetime import datetime, timedelta, timezone from typing import Optional #: Label used for our own (local) device when framing a trace path's endpoints. @@ -70,6 +70,45 @@ def utcnow() -> datetime: return datetime.now(timezone.utc) +#: How far into the future an advert timestamp may sit (seconds) before it is refused as a +#: lie. An advert's timestamp is stamped by the *sender's* clock, and a mesh node with no +#: time source can be minutes — or months — off; a couple of minutes of skew is ordinary and +#: harmless (the age clamps to "now" until real time catches up), but anything beyond it +#: would pin the contact at the top of every heard-sorted list, reading "now" for as long as +#: the bogus timestamp stays ahead of the wall clock. +ADVERT_FUTURE_SKEW_S = 300 + + +def advert_time(last_advert: object) -> Optional[datetime]: + """Convert an advert's Unix timestamp into a *plausible* UTC datetime, or ``None``. + + THE converter for every ``last_advert`` epoch entering the app — the device's live + contact table and the cross-session contact store both pass through here — so the + plausibility rule lives in one place. The value is written by the advertising node's + own clock, which makes it hearsay: a zero/absent/garbage value means "never heard", + and a timestamp more than :data:`ADVERT_FUTURE_SKEW_S` ahead of our clock is a mis-set + sender clock and is refused the same way. Callers with their own reception evidence + (recorded observations) fill the resulting ``None`` from that instead — an honest + "when *we* heard it" beats a fictional "heard in the future". + + Args: + last_advert: The raw ``last_advert`` field from a contact payload or stored entry. + + Returns: + A timezone-aware UTC :class:`datetime`, or ``None`` when unknown or implausible. + """ + try: + seconds = int(last_advert) # type: ignore[arg-type] + except (TypeError, ValueError): + return None + if seconds <= 0: + return None + when = datetime.fromtimestamp(seconds, tz=timezone.utc) + if when > utcnow() + timedelta(seconds=ADVERT_FUTURE_SKEW_S): + return None + return when + + @dataclass(slots=True) class Contact: """A node known to the connected companion device. diff --git a/meshterm/services/device_state.py b/meshterm/services/device_state.py index 16d2dcd..90ecec6 100644 --- a/meshterm/services/device_state.py +++ b/meshterm/services/device_state.py @@ -39,6 +39,7 @@ from __future__ import annotations import asyncio import time +from dataclasses import replace from typing import TYPE_CHECKING, Optional if TYPE_CHECKING: @@ -130,7 +131,8 @@ class DeviceState: ): return self._contacts device = await self._ctx.device() - self._contacts = await self._remember_and_merge(await device.get_contacts()) + merged = await self._remember_and_merge(await device.get_contacts()) + self._contacts = self._fill_heard(merged) self._contacts_at = time.monotonic() return self._contacts @@ -158,6 +160,38 @@ class DeviceState: store.remember_all(pubkey, fetched) return merge_contacts(store, pubkey, fetched) + def _fill_heard(self, contacts: list["Contact"]) -> list["Contact"]: + """Fill each contact's missing last-heard time from our own recorded receptions. + + A contact arrives with no ``last_seen`` when the firmware never caught an advert — + or when it reported one stamped implausibly far in the future by the *sender's* + clock, which :func:`~meshterm.core.models.advert_time` refuses rather than letting + the contact read "heard now" forever. Either way our observation history may still + hold first-hand evidence (stamped by *our* clock at reception), so it fills the gap + here — once, at the one point every screen fetches contacts through — and the heard + lanes, sorts, and the purge ladder all see the same honest value. A contact we have + truly never heard stays ``None`` and reads ``never``. Best-effort: a history read + failure just returns the list unfilled, never blocking the fetch. + """ + if all(c.last_seen is not None for c in contacts): + return contacts + try: + heard = { + n.node: n.last_seen for n in self._ctx.repo.heard_nodes() if n.node + } + except Exception as exc: # noqa: BLE001 - never block a contacts read on history + self._ctx.log.debug("devstate: last-heard fill skipped: %s", exc) + return contacts + filled: list["Contact"] = [] + for contact in contacts: + if contact.last_seen is None: + ident = (contact.public_key or contact.key_prefix or "").lower() + when = heard.get(ident.removeprefix("0x")[:12]) + if when is not None: + contact = replace(contact, last_seen=when) + filled.append(contact) + return filled + async def _refresh_contacts_quietly(self) -> None: """Background contacts refresh: update the cache, swallow a failure (keep the old list).""" try: diff --git a/tests/test_contact_store.py b/tests/test_contact_store.py index dc6e06e..1e67700 100644 --- a/tests/test_contact_store.py +++ b/tests/test_contact_store.py @@ -22,7 +22,13 @@ from meshterm.core.admin_store import AdminStore from meshterm.core.config import Settings from meshterm.core.contact_store import ContactStore, RememberedContact, merge_contacts from meshterm.core.device_store import DeviceStore -from meshterm.core.models import NODE_TYPE_CHAT, NODE_TYPE_REPEATER, Contact, is_direct_messageable +from meshterm.core.models import ( + NODE_TYPE_CHAT, + NODE_TYPE_REPEATER, + Contact, + is_direct_messageable, + utcnow, +) from meshterm.persistence.repository import Repository PUB_A = "aa" * 32 @@ -152,6 +158,17 @@ def test_remembered_contact_round_trip() -> None: assert rebuilt.route_hops is None # a remembered contact floods until a path is relearned +def test_remembered_future_advert_rebuilds_as_never_heard() -> None: + """A future-stamped epoch remembered before this guard existed rebuilds as unknown. + + The stored epoch re-enters through ``models.advert_time``, so a poisoned value written + by an old session can't resurface a contact as "heard in the future" on a bridge. + """ + future = int(utcnow().timestamp()) + 7 * 86400 + entry = RememberedContact(public_key="cc" * 32, name="Bogus-Clock", last_advert=future) + assert entry.to_contact().last_seen is None + + # --- merge ------------------------------------------------------------------- diff --git a/tests/test_device_state.py b/tests/test_device_state.py index 01e3953..ee2b979 100644 --- a/tests/test_device_state.py +++ b/tests/test_device_state.py @@ -11,8 +11,10 @@ from __future__ import annotations import asyncio import time +from datetime import datetime, timezone from types import SimpleNamespace +from meshterm.core.models import Contact from meshterm.services.device_state import DeviceState, _CONTACTS_TTL_S @@ -25,10 +27,13 @@ class FakeDevice: self.mode_calls = 0 self.channel_calls = 0 self.capacity_calls = 0 + self.contact_rows: "list[Contact] | None" = None # fixed table, when a test needs one async def get_contacts(self) -> list: self.contacts_calls += 1 - return [f"contact-{self.contacts_calls}"] # a fresh identity per fetch, to spot refreshes + if self.contact_rows is not None: + return list(self.contact_rows) + return [Contact(name=f"contact-{self.contacts_calls}")] # fresh identity per fetch, to spot refreshes async def get_self_info(self) -> dict: self.self_info_calls += 1 @@ -51,8 +56,8 @@ class FakeDevice: return 8 -def _devstate(device: FakeDevice) -> DeviceState: - """A DeviceState over a fake ctx exposing just device() and a silent logger.""" +def _devstate(device: FakeDevice, heard: tuple = ()) -> DeviceState: + """A DeviceState over a fake ctx: device(), a silent logger, and a heard-node history.""" async def device_getter(): return device @@ -60,6 +65,7 @@ def _devstate(device: FakeDevice) -> DeviceState: ctx = SimpleNamespace( device=device_getter, log=SimpleNamespace(debug=lambda *a, **k: None), + repo=SimpleNamespace(heard_nodes=lambda: list(heard)), ) return DeviceState(ctx) # type: ignore[arg-type] @@ -112,7 +118,34 @@ def test_contacts_refresh_in_background_past_ttl() -> None: # Let the scheduled background refresh run. await asyncio.gather(*list(ds._tasks)) assert dev.contacts_calls == 2 # refreshed behind the read - assert (await ds.contacts())[0] == "contact-2" # now serving the fresh list + assert (await ds.contacts())[0].name == "contact-2" # now serving the fresh list + + asyncio.run(run()) + + +def test_missing_heard_times_fill_from_recorded_receptions() -> None: + """A contact with no plausible advert time gets the time *we* last heard it, if any. + + The device's ``last_advert`` is stamped by the sender's clock and refused upstream when + implausible (see ``models.advert_time``), so a contact can arrive with no heard time + even though our own observation history holds first-hand receptions. The cache fills + that gap once, at the fetch — and never overrides a plausible device-reported time. + """ + dev = FakeDevice() + device_says = datetime(2026, 7, 28, 9, 0, tzinfo=timezone.utc) + we_heard = datetime(2026, 7, 29, 12, 0, tzinfo=timezone.utc) + dev.contact_rows = [ + Contact(name="Bogus-Clock", public_key="aa" * 32, key_prefix="aa" * 6), + Contact(name="Honest", public_key="bb" * 32, key_prefix="bb" * 6, last_seen=device_says), + Contact(name="Quiet", public_key="cc" * 32, key_prefix="cc" * 6), + ] + ds = _devstate(dev, heard=(SimpleNamespace(node="aa" * 6, last_seen=we_heard),)) + + async def run() -> None: + by_name = {c.name: c for c in await ds.contacts()} + assert by_name["Bogus-Clock"].last_seen == we_heard # filled from our own history + assert by_name["Honest"].last_seen == device_says # a plausible device time stands + assert by_name["Quiet"].last_seen is None # truly never heard stays never asyncio.run(run()) diff --git a/tests/test_skeleton.py b/tests/test_skeleton.py index f7be198..68dbfc9 100644 --- a/tests/test_skeleton.py +++ b/tests/test_skeleton.py @@ -22,6 +22,26 @@ def test_clamp_tx_power() -> None: assert clamp_tx_power(14) == 14 +def test_advert_time_refuses_a_future_sender_clock() -> None: + """An advert stamp is hearsay from the sender's clock: plausible converts, future doesn't. + + A node with a mis-set clock advertises timestamps from the future; taken at face value + the contact would read "heard now" and top every heard-sorted list until the wall clock + caught up. Ordinary skew (under the tolerance) stays: its age clamps to "now" briefly + and self-heals. The classic never-heard shapes (zero/absent/garbage) still map to None. + """ + from meshterm.core.models import ADVERT_FUTURE_SKEW_S, advert_time, utcnow + + past = int(utcnow().timestamp()) - 3600 + when = advert_time(past) + assert when is not None and int(when.timestamp()) == past + assert advert_time(int(utcnow().timestamp()) + 60) is not None # ordinary skew + assert advert_time(int(utcnow().timestamp()) + ADVERT_FUTURE_SKEW_S + 60) is None + assert advert_time(0) is None + assert advert_time(None) is None + assert advert_time("garbage") is None + + def test_trace_stats_aggregation() -> None: """Robust stats reflect successes and bottleneck SNR.""" from meshterm.core.models import Hop @@ -589,6 +609,34 @@ def _mc_with(contacts: dict, path_hash_mode: int = 2): return _MC() +async def test_contact_with_future_advert_stamp_reads_as_never_heard() -> None: + """A contact whose advert was stamped by a wrong (future) clock arrives with no heard time. + + The firmware stores the advert's embedded timestamp verbatim and only ever advances it + (its replay filter), so a bogus future stamp sticks until real time passes it — the + conversion refuses it here rather than showing the contact as "heard in the future". + """ + from meshterm.core.connection import MeshCoreDevice + from meshterm.core.models import utcnow + + now = int(utcnow().timestamp()) + mc = _mc_with( + { + "Bogus-Clock": { + "adv_name": "Bogus-Clock", + "public_key": "aa" * 32, + "last_advert": now + 7 * 86400, + }, + "Honest": {"adv_name": "Honest", "public_key": "bb" * 32, "last_advert": now - 300}, + } + ) + device = MeshCoreDevice(port="COM-test") + device._mc = mc + by_name = {c.name: c for c in await device.get_contacts()} + assert by_name["Bogus-Clock"].last_seen is None # refused, not "heard in the future" + assert by_name["Honest"].last_seen is not None + + async def test_three_byte_route_appends_destination_hash() -> None: """A learned multi-hop route walks the repeaters, the target, then back (#1).