diff --git a/backend/main.py b/backend/main.py index 1439d0a2..0c9f03a4 100644 --- a/backend/main.py +++ b/backend/main.py @@ -10049,6 +10049,13 @@ def compose_wormhole_dm( } +def _intercept_gate_key_frame(peer_id: str, plain_text: str) -> tuple[str, dict | None]: + """Pull gate-key control frames out of DM text so secrets never reach the UI.""" + from services.mesh.mesh_gate_invites import intercept_dm_plaintext + + return intercept_dm_plaintext(str(peer_id or "").strip(), plain_text) + + def decrypt_wormhole_dm_envelope( *, peer_id: str, @@ -10102,6 +10109,7 @@ def decrypt_wormhole_dm_envelope( ) alias_applied = bool(alias_result.get("ok")) mark_contact_alias_reply_observed(str(peer_id or "").strip()) + plain_text, gate_key_event = _intercept_gate_key_frame(peer_id, plain_text) response = { "ok": True, "peer_id": str(peer_id or "").strip(), @@ -10112,6 +10120,8 @@ def decrypt_wormhole_dm_envelope( } if alias_update: response["alias_update_applied"] = alias_applied + if gate_key_event: + response["gate_key_event"] = gate_key_event return response from services.wormhole_supervisor import get_transport_tier @@ -10140,6 +10150,7 @@ def decrypt_wormhole_dm_envelope( ) alias_applied = bool(alias_result.get("ok")) mark_contact_alias_reply_observed(str(peer_id or "").strip()) + plain_text, gate_key_event = _intercept_gate_key_frame(peer_id, plain_text) response = { "ok": True, "peer_id": str(peer_id or "").strip(), @@ -10150,6 +10161,8 @@ def decrypt_wormhole_dm_envelope( } if alias_update: response["alias_update_applied"] = alias_applied + if gate_key_event: + response["gate_key_event"] = gate_key_event return response diff --git a/backend/routers/wormhole.py b/backend/routers/wormhole.py index 94f6ee5a..d8b10fe3 100644 --- a/backend/routers/wormhole.py +++ b/backend/routers/wormhole.py @@ -419,6 +419,22 @@ class WormholeGateKeyGrantRequest(BaseModel): recipient_scope: str = "member" +class WormholeGateInviteRequest(BaseModel): + gate_id: str + peer_id: str + note: str = "" + + +class WormholeGateInviteDecisionRequest(BaseModel): + invite_id: str + + +class WormholeGateKeyRekeyRequest(BaseModel): + gate_id: str + exclude_peer_ids: list[str] = [] + reason: str = "manual" + + class WormholeGateComposeRequest(BaseModel): gate_id: str plaintext: str @@ -923,6 +939,64 @@ async def api_wormhole_gate_key_grant(request: Request, body: WormholeGateKeyGra ) +@router.post("/api/wormhole/gate/invite", dependencies=[Depends(require_local_operator)]) +@limiter.limit("20/minute") +async def api_wormhole_gate_invite(request: Request, body: WormholeGateInviteRequest): + from services.mesh.mesh_gate_invites import send_gate_invite + + return await asyncio.to_thread( + send_gate_invite, + str(body.gate_id or ""), + str(body.peer_id or ""), + note=str(body.note or ""), + ) + + +@router.get("/api/wormhole/gate/invites", dependencies=[Depends(require_local_operator)]) +@limiter.limit("60/minute") +async def api_wormhole_gate_invites(request: Request): + from services.mesh.mesh_gate_invites import list_pending_gate_invites + + return list_pending_gate_invites() + + +@router.post("/api/wormhole/gate/invite/accept", dependencies=[Depends(require_local_operator)]) +@limiter.limit("20/minute") +async def api_wormhole_gate_invite_accept(request: Request, body: WormholeGateInviteDecisionRequest): + from services.mesh.mesh_gate_invites import accept_gate_invite + + return await asyncio.to_thread(accept_gate_invite, str(body.invite_id or "")) + + +@router.post("/api/wormhole/gate/invite/decline", dependencies=[Depends(require_local_operator)]) +@limiter.limit("20/minute") +async def api_wormhole_gate_invite_decline(request: Request, body: WormholeGateInviteDecisionRequest): + from services.mesh.mesh_gate_invites import decline_gate_invite + + return decline_gate_invite(str(body.invite_id or "")) + + +@router.post("/api/wormhole/gate/key/rekey", dependencies=[Depends(require_local_operator)]) +@limiter.limit("10/minute") +async def api_wormhole_gate_key_rekey(request: Request, body: WormholeGateKeyRekeyRequest): + from services.mesh.mesh_gate_invites import rotate_gate_key + + return await asyncio.to_thread( + rotate_gate_key, + str(body.gate_id or ""), + exclude_peer_ids=list(body.exclude_peer_ids or []), + reason=str(body.reason or "manual"), + ) + + +@router.get("/api/wormhole/gate/{gate_id}/key/sharing", dependencies=[Depends(require_local_operator)]) +@limiter.limit("60/minute") +async def api_wormhole_gate_key_sharing(request: Request, gate_id: str): + from services.mesh.mesh_gate_invites import gate_key_status + + return gate_key_status(gate_id) + + def _backend_gate_plaintext_guard( *, gate_id: str, diff --git a/backend/services/mesh/mesh_gate_invites.py b/backend/services/mesh/mesh_gate_invites.py new file mode 100644 index 00000000..2bd4a75f --- /dev/null +++ b/backend/services/mesh/mesh_gate_invites.py @@ -0,0 +1,487 @@ +"""Cross-node gate key distribution over the Dead Drop DM lane. + +Gate history is readable on another node only through the durable gate +envelope, which is keyed from the per-gate ``gate_secret``. Each node +generates that secret locally, so without distribution two operators in the +same gate cannot read each other. This module moves the secret between +members inside an end-to-end encrypted DM: + +- ``invite``: a member hands the current secret to one contact. The + recipient's operator must accept it explicitly. +- ``rekey``: a member rotates the secret and sends the new one to every + contact it previously granted. Recipients apply it automatically only when + it comes from their upstream (the peer they accepted the current key + from); anything else waits for manual acceptance. A node that applies a + rekey forwards it to its own grantees, minus the sender and any excluded + peers, so the whole grant tree converges. + +The secret is carried as a control frame inside the DM plaintext and is +stripped on decrypt, so it never reaches the browser or the visible mailbox. +""" + +from __future__ import annotations + +import hashlib +import json +import logging +import secrets +import threading +import time +from typing import Any, Callable + +from services.mesh.mesh_local_custody import ( + read_sensitive_domain_json, + write_sensitive_domain_json, +) +from services.mesh.mesh_privacy_logging import privacy_log_label + +logger = logging.getLogger(__name__) + +GATE_KEY_FRAME_KIND = "sb_gate_key_v1" +PENDING_DOMAIN = "gate_invites" +PENDING_FILENAME = "pending_gate_invites.json" +PENDING_CUSTODY_SCOPE = "gate_invite_pending_store" +PENDING_TTL_S = 14 * 24 * 3600 +MAX_PENDING = 64 +MAX_EXCLUDE = 64 + +# Contacts in these trust states never send or receive gate keys. +BLOCKED_TRUST_LEVELS = {"mismatch", "continuity_broken"} + +_LOCK = threading.RLock() + +# Overridable in tests; production sends through the operator DM lane. +_send_dm_impl: Callable[[str, str], dict[str, Any]] | None = None + + +def _send_dm(peer_id: str, plaintext: str) -> dict[str, Any]: + if _send_dm_impl is not None: + return _send_dm_impl(peer_id, plaintext) + from services.openclaw_infonet import send_dm + + return send_dm(peer_id, plaintext) + + +def _gate_manager(): + from services.mesh.mesh_reputation import gate_manager + + return gate_manager + + +def secret_fingerprint(secret: str) -> str: + """Short non-reversible id so peers can compare keys without revealing them.""" + return hashlib.sha256(f"sb-gate-secret-id|{secret}".encode("utf-8")).hexdigest()[:16] + + +def _local_epoch(gate_id: str) -> int: + try: + from services.mesh import mesh_gate_mls + + return int(mesh_gate_mls._sync_binding(gate_id).epoch or 0) + except Exception: + return 0 + + +def _contact_check(peer_id: str) -> dict[str, Any]: + from services.mesh.mesh_wormhole_contacts import get_wormhole_dm_contact + + contact = get_wormhole_dm_contact(peer_id) + if contact is None: + return {"ok": False, "detail": "recipient is not a DM contact; connect with them first"} + trust_level = str(contact.get("trust_level", "") or "unpinned").strip().lower() + if bool(contact.get("blocked")) or trust_level in BLOCKED_TRUST_LEVELS: + return {"ok": False, "detail": f"contact trust state does not allow gate keys: {trust_level}"} + return {"ok": True, "trust_level": trust_level} + + +def _trust_level(peer_id: str) -> str: + try: + from services.mesh.mesh_wormhole_contacts import get_contact_trust_level + + return get_contact_trust_level(peer_id) + except Exception: + return "unpinned" + + +def _build_frame( + *, + op: str, + gate_id: str, + display_name: str, + secret: str, + version: int, + note: str = "", + exclude: list[str] | None = None, +) -> str: + frame = { + "kind": GATE_KEY_FRAME_KIND, + "op": op, + "gate_id": gate_id, + "gate_name": str(display_name or gate_id)[:64], + "secret": secret, + "secret_id": secret_fingerprint(secret), + "version": int(version or 0), + "issued_at": int(time.time()), + "frame_id": secrets.token_hex(8), + "note": str(note or "")[:240], + "exclude": [str(p) for p in (exclude or [])][:MAX_EXCLUDE], + } + return json.dumps(frame, sort_keys=True, separators=(",", ":")) + + +def parse_gate_key_frame(plaintext: str) -> dict[str, Any] | None: + raw = str(plaintext or "") + if not raw.startswith("{") or GATE_KEY_FRAME_KIND not in raw: + return None + try: + frame = json.loads(raw) + except Exception: + return None + if not isinstance(frame, dict) or frame.get("kind") != GATE_KEY_FRAME_KIND: + return None + if frame.get("op") not in {"invite", "rekey"}: + return None + gate_id = str(frame.get("gate_id", "") or "").strip().lower() + secret = str(frame.get("secret", "") or "").strip() + if not gate_id or len(gate_id) > 64 or not secret or len(secret) > 128: + return None + if secret_fingerprint(secret) != str(frame.get("secret_id", "") or ""): + return None + frame["gate_id"] = gate_id + frame["secret"] = secret + exclude = frame.get("exclude") + frame["exclude"] = [str(p) for p in exclude][:MAX_EXCLUDE] if isinstance(exclude, list) else [] + return frame + + +# --- pending store -------------------------------------------------------- + + +def _read_pending() -> dict[str, dict[str, Any]]: + raw = read_sensitive_domain_json( + PENDING_DOMAIN, + PENDING_FILENAME, + lambda: {}, + custody_scope=PENDING_CUSTODY_SCOPE, + ) + if not isinstance(raw, dict): + return {} + now = time.time() + return { + str(k): dict(v) + for k, v in raw.items() + if isinstance(v, dict) and now - float(v.get("received_at", 0) or 0) < PENDING_TTL_S + } + + +def _write_pending(pending: dict[str, dict[str, Any]]) -> None: + if len(pending) > MAX_PENDING: + newest = sorted(pending.items(), key=lambda kv: float(kv[1].get("received_at", 0) or 0))[-MAX_PENDING:] + pending = dict(newest) + write_sensitive_domain_json( + PENDING_DOMAIN, + PENDING_FILENAME, + pending, + custody_scope=PENDING_CUSTODY_SCOPE, + ) + + +def _public_view(invite_id: str, entry: dict[str, Any]) -> dict[str, Any]: + return { + "invite_id": invite_id, + "op": entry.get("op", "invite"), + "gate_id": entry.get("gate_id", ""), + "gate_name": entry.get("gate_name", ""), + "from_peer_id": entry.get("from_peer_id", ""), + "from_trust_level": _trust_level(str(entry.get("from_peer_id", "") or "")), + "secret_id": entry.get("secret_id", ""), + "version": int(entry.get("version", 0) or 0), + "note": entry.get("note", ""), + "received_at": int(entry.get("received_at", 0) or 0), + } + + +def list_pending_gate_invites() -> dict[str, Any]: + with _LOCK: + pending = _read_pending() + invites = [_public_view(k, v) for k, v in pending.items()] + invites.sort(key=lambda item: -item["received_at"]) + return {"ok": True, "invites": invites} + + +# --- sending -------------------------------------------------------------- + + +def send_gate_invite(gate_id: str, peer_id: str, *, note: str = "") -> dict[str, Any]: + gate_key = str(gate_id or "").strip().lower() + peer = str(peer_id or "").strip() + if not gate_key or not peer: + return {"ok": False, "detail": "gate_id and peer_id required"} + manager = _gate_manager() + gate = manager.get_gate(gate_key) + if not gate: + return {"ok": False, "detail": "Gate not found"} + if manager.get_envelope_policy(gate_key) == "envelope_disabled": + return {"ok": False, "detail": "gate has envelopes disabled; members on other nodes could not read it"} + contact = _contact_check(peer) + if not contact.get("ok"): + return contact + secret = manager.ensure_gate_secret(gate_key) + if not secret: + return {"ok": False, "detail": "gate secret unavailable"} + version = int(manager.get_gate_key_meta(gate_key).get("gate_secret_version", 0) or 0) + plaintext = _build_frame( + op="invite", + gate_id=gate_key, + display_name=str(gate.get("display_name", "") or gate_key), + secret=secret, + version=version, + note=note, + ) + sent = _send_dm(peer, plaintext) + if not isinstance(sent, dict) or not sent.get("ok"): + detail = sent.get("detail") if isinstance(sent, dict) else "dm send failed" + return {"ok": False, "detail": str(detail or "dm send failed")} + manager.record_key_grant(gate_key, peer, secret_id=secret_fingerprint(secret), op="invite") + logger.info( + "Gate invite sent for %s to %s", + privacy_log_label(gate_key, label="gate"), + privacy_log_label(peer, label="peer"), + ) + return { + "ok": True, + "gate_id": gate_key, + "peer_id": peer, + "secret_id": secret_fingerprint(secret), + "recipient_trust_level": contact.get("trust_level", ""), + } + + +def _distribute_rekey( + gate_id: str, + *, + skip_peer_ids: set[str], + exclude: list[str], +) -> dict[str, Any]: + manager = _gate_manager() + gate = manager.get_gate(gate_id) or {} + secret = manager.get_gate_secret(gate_id) + meta = manager.get_gate_key_meta(gate_id) + version = int(meta.get("gate_secret_version", 0) or 0) + plaintext = _build_frame( + op="rekey", + gate_id=gate_id, + display_name=str(gate.get("display_name", "") or gate_id), + secret=secret, + version=version, + exclude=exclude, + ) + delivered: list[str] = [] + failed: list[dict[str, str]] = [] + for peer in sorted(meta.get("key_grants", {})): + if peer in skip_peer_ids: + continue + if not _contact_check(peer).get("ok"): + failed.append({"peer_id": peer, "detail": "contact unavailable"}) + continue + sent = _send_dm(peer, plaintext) + if isinstance(sent, dict) and sent.get("ok"): + manager.record_key_grant(gate_id, peer, secret_id=secret_fingerprint(secret), op="rekey") + delivered.append(peer) + else: + failed.append({"peer_id": peer, "detail": str((sent or {}).get("detail") or "dm send failed")}) + return {"delivered": delivered, "failed": failed} + + +def rotate_gate_key(gate_id: str, *, exclude_peer_ids: list[str] | None = None, reason: str = "manual") -> dict[str, Any]: + """Generate a new gate secret and send it to every grantee not excluded.""" + gate_key = str(gate_id or "").strip().lower() + manager = _gate_manager() + if not manager.get_gate(gate_key): + return {"ok": False, "detail": "Gate not found"} + exclude = sorted({str(p).strip() for p in (exclude_peer_ids or []) if str(p).strip()})[:MAX_EXCLUDE] + with manager._gate_lock: + manager._rotate_gate_secret_for_member_removal_locked( + gate_key, + reason=f"rekey:{reason}", + previous_valid_through_epoch=_local_epoch(gate_key), + ) + manager.drop_key_grants(gate_key, exclude) + result = _distribute_rekey(gate_key, skip_peer_ids=set(exclude), exclude=exclude) + return { + "ok": True, + "gate_id": gate_key, + "secret_id": secret_fingerprint(manager.get_gate_secret(gate_key)), + "excluded": exclude, + **result, + } + + +def redistribute_after_local_rotation(gate_id: str) -> dict[str, Any]: + """Send the already-rotated local secret to grantees (ban/kick path).""" + gate_key = str(gate_id or "").strip().lower() + if not _gate_manager().get_gate_key_meta(gate_key).get("key_grants"): + return {"delivered": [], "failed": []} + return _distribute_rekey(gate_key, skip_peer_ids=set(), exclude=[]) + + +# --- receiving ------------------------------------------------------------ + + +def _apply(entry: dict[str, Any], *, from_peer_id: str) -> dict[str, Any]: + manager = _gate_manager() + gate_key = str(entry.get("gate_id", "") or "") + if not manager.get_gate(gate_key): + return {"ok": False, "detail": "gate is not known on this node"} + adopted = manager.adopt_gate_secret( + gate_key, + str(entry.get("secret", "") or ""), + version=int(entry.get("version", 0) or 0), + upstream_peer_id=from_peer_id, + previous_valid_through_epoch=_local_epoch(gate_key), + ) + if not adopted.get("ok"): + return adopted + forwarded: dict[str, Any] = {"delivered": [], "failed": []} + if adopted.get("changed") and entry.get("op") == "rekey": + exclude = list(entry.get("exclude") or []) + manager.drop_key_grants(gate_key, exclude) + forwarded = _distribute_rekey( + gate_key, + skip_peer_ids={from_peer_id, *exclude}, + exclude=exclude, + ) + return { + "ok": True, + "gate_id": gate_key, + "changed": bool(adopted.get("changed")), + "secret_id": entry.get("secret_id", ""), + "forwarded": forwarded, + } + + +def receive_gate_key_frame(from_peer_id: str, frame: dict[str, Any]) -> dict[str, Any]: + """Handle a decrypted gate-key frame. Returns a summary without the secret.""" + sender = str(from_peer_id or "").strip() + gate_key = frame["gate_id"] + summary = { + "op": frame["op"], + "gate_id": gate_key, + "gate_name": str(frame.get("gate_name", "") or gate_key), + "secret_id": frame["secret_id"], + "from_peer_id": sender, + } + manager = _gate_manager() + if not sender or not _contact_check(sender).get("ok"): + summary["status"] = "rejected_untrusted_sender" + return summary + if manager.get_gate_secret(gate_key) == frame["secret"]: + summary["status"] = "already_current" + return summary + meta = manager.get_gate_key_meta(gate_key) + from_upstream = bool(meta) and meta.get("key_upstream") == sender + if frame["op"] == "rekey" and from_upstream: + applied = _apply(frame, from_peer_id=sender) + summary["status"] = "applied" if applied.get("ok") else "apply_failed" + return summary + entry = { + "op": frame["op"], + "gate_id": gate_key, + "gate_name": summary["gate_name"], + "secret": frame["secret"], + "secret_id": frame["secret_id"], + "version": int(frame.get("version", 0) or 0), + "note": str(frame.get("note", "") or ""), + "exclude": list(frame.get("exclude") or []), + "from_peer_id": sender, + "received_at": time.time(), + } + invite_id = secrets.token_hex(8) + with _LOCK: + pending = _read_pending() + # One pending entry per (gate, sender): a newer frame supersedes. + for key, existing in list(pending.items()): + if existing.get("gate_id") == gate_key and existing.get("from_peer_id") == sender: + pending.pop(key, None) + pending[invite_id] = entry + _write_pending(pending) + summary["status"] = "pending" + summary["invite_id"] = invite_id + return summary + + +def intercept_dm_plaintext(peer_id: str, plaintext: str) -> tuple[str, dict[str, Any] | None]: + """Strip a gate-key frame out of decrypted DM text. + + Returns the text to show the user and, when a frame was present, a + secret-free summary of what happened to it. + """ + frame = parse_gate_key_frame(plaintext) + if frame is None: + return plaintext, None + try: + summary = receive_gate_key_frame(peer_id, frame) + except Exception: + logger.exception("gate key frame handling failed") + summary = {"op": frame["op"], "gate_id": frame["gate_id"], "status": "error"} + name = summary.get("gate_name") or frame["gate_id"] + status = summary.get("status", "") + if status == "pending": + label = "invited you to" if frame["op"] == "invite" else "sent a new key for" + text = f"[Gate key] This contact {label} '{name}'. Open Gate invites in Messages or the gate's key panel to accept." + elif status == "applied": + text = f"[Gate key] Key for '{name}' was rotated by your upstream member and applied." + elif status == "already_current": + text = f"[Gate key] You already hold the current key for '{name}'." + else: + text = f"[Gate key] A key for '{name}' was received but not accepted ({status or 'error'})." + return text, summary + + +def accept_gate_invite(invite_id: str) -> dict[str, Any]: + with _LOCK: + pending = _read_pending() + entry = pending.get(str(invite_id or "")) + if entry is None: + return {"ok": False, "detail": "invite not found or expired"} + sender = str(entry.get("from_peer_id", "") or "") + check = _contact_check(sender) + if not check.get("ok"): + return check + result = _apply(entry, from_peer_id=sender) + if result.get("ok"): + # The sender holds this key already; record them so our own + # rotations reach them too. + _gate_manager().record_key_grant( + entry["gate_id"], sender, secret_id=str(entry.get("secret_id", "")), op="upstream" + ) + pending.pop(str(invite_id), None) + _write_pending(pending) + return result + + +def decline_gate_invite(invite_id: str) -> dict[str, Any]: + with _LOCK: + pending = _read_pending() + if pending.pop(str(invite_id or ""), None) is None: + return {"ok": False, "detail": "invite not found or expired"} + _write_pending(pending) + return {"ok": True, "invite_id": str(invite_id)} + + +def gate_key_status(gate_id: str) -> dict[str, Any]: + gate_key = str(gate_id or "").strip().lower() + manager = _gate_manager() + if not manager.get_gate(gate_key): + return {"ok": False, "detail": "Gate not found"} + secret = manager.get_gate_secret(gate_key) + meta = manager.get_gate_key_meta(gate_key) + return { + "ok": True, + "gate_id": gate_key, + "secret_id": secret_fingerprint(secret) if secret else "", + "version": int(meta.get("gate_secret_version", 0) or 0), + "upstream_peer_id": meta.get("key_upstream", ""), + "shared": bool(meta.get("key_upstream") or meta.get("key_grants")), + "grantees": sorted(meta.get("key_grants", {})), + } diff --git a/backend/services/mesh/mesh_reputation.py b/backend/services/mesh/mesh_reputation.py index 6a8e3ad2..eefa6986 100644 --- a/backend/services/mesh/mesh_reputation.py +++ b/backend/services/mesh/mesh_reputation.py @@ -1324,9 +1324,93 @@ class GateManager: } gate["gate_secret_archive"] = _normalized_gate_secret_archive(archive) gate["gate_secret"] = _generate_gate_secret() + gate["gate_secret_version"] = int(gate.get("gate_secret_version", 0) or 0) + 1 self._save() return dict(gate["gate_secret_archive"]) + def get_gate_key_meta(self, gate_id: str) -> dict[str, Any]: + """Return non-secret key-distribution metadata for a gate.""" + gate = self.gates.get(str(gate_id or "").strip().lower()) + if not gate: + return {} + return { + "gate_secret_version": int(gate.get("gate_secret_version", 0) or 0), + "key_upstream": str(gate.get("key_upstream", "") or ""), + "key_grants": { + str(peer): dict(grant or {}) + for peer, grant in dict(gate.get("key_grants") or {}).items() + }, + } + + def record_key_grant(self, gate_id: str, peer_id: str, *, secret_id: str, op: str) -> None: + gate_key = str(gate_id or "").strip().lower() + peer_key = str(peer_id or "").strip() + with self._gate_lock: + gate = self.gates.get(gate_key) + if not gate or not peer_key: + return + grants = dict(gate.get("key_grants") or {}) + grants[peer_key] = {"secret_id": str(secret_id or ""), "granted_at": time.time(), "op": str(op or "")} + gate["key_grants"] = grants + self._save() + + def drop_key_grants(self, gate_id: str, peer_ids: list[str]) -> None: + gate_key = str(gate_id or "").strip().lower() + with self._gate_lock: + gate = self.gates.get(gate_key) + if not gate: + return + grants = dict(gate.get("key_grants") or {}) + for peer in peer_ids: + grants.pop(str(peer or "").strip(), None) + gate["key_grants"] = grants + self._save() + + def adopt_gate_secret( + self, + gate_id: str, + secret: str, + *, + version: int, + upstream_peer_id: str, + previous_valid_through_epoch: int = 0, + ) -> dict[str, Any]: + """Replace the local gate secret with one received from another member. + + The prior secret moves into the single-slot archive so history this + node already holds stays readable, bounded by the same epoch ceiling + the ban/kick rotation uses. + """ + gate_key = str(gate_id or "").strip().lower() + new_secret = str(secret or "").strip() + if not new_secret: + return {"ok": False, "detail": "gate secret required"} + with self._gate_lock: + gate = self.gates.get(gate_key) + if not gate: + return {"ok": False, "detail": "Gate not found"} + current_secret = str(gate.get("gate_secret", "") or "") + if current_secret == new_secret: + gate["gate_secret_version"] = max(int(gate.get("gate_secret_version", 0) or 0), int(version or 0)) + gate["key_upstream"] = str(upstream_peer_id or "") + self._save() + return {"ok": True, "gate_id": gate_key, "changed": False} + if current_secret: + gate["gate_secret_archive"] = _normalized_gate_secret_archive( + { + "previous_secret": current_secret, + "previous_valid_through_event_id": "", + "previous_valid_through_epoch": max(0, int(previous_valid_through_epoch or 0)), + "rotated_at": time.time(), + "reason": "adopted_invite", + } + ) + gate["gate_secret"] = new_secret + gate["gate_secret_version"] = max(0, int(version or 0)) + gate["key_upstream"] = str(upstream_peer_id or "") + self._save() + return {"ok": True, "gate_id": gate_key, "changed": True} + def remove_member(self, gate_id: str, member_id: str, *, kind: str = "leave") -> dict[str, Any]: """Single authority for gate-member removal and ban/kick secret rotation.""" gate_key = str(gate_id or "").strip().lower() @@ -1374,6 +1458,18 @@ class GateManager: previous_valid_through_epoch=int(removed.get("previous_epoch", 0) or 0), ) rotated = True + # Other nodes hold the old secret; hand the new one to every + # grantee or the gate splits after a kick. + try: + from services.mesh.mesh_gate_invites import redistribute_after_local_rotation + + redistribute_after_local_rotation(gate_key) + except Exception: + logger.exception( + "gate key redistribution failed after %s for %s", + removal_kind, + privacy_log_label(gate_key, label="gate"), + ) else: logger.info( "Gate secret rotation disabled; observed %s for %s member %s without rotating", diff --git a/backend/tests/mesh/test_gate_invites.py b/backend/tests/mesh/test_gate_invites.py new file mode 100644 index 00000000..10b34cf8 --- /dev/null +++ b/backend/tests/mesh/test_gate_invites.py @@ -0,0 +1,250 @@ +"""Cross-node gate key distribution over the DM lane.""" + +import base64 +import copy +import json +import os + +import pytest + + +@pytest.fixture() +def env(monkeypatch): + from cryptography.hazmat.primitives.ciphers.aead import AESGCM # noqa: F401 + + from services.mesh import mesh_gate_invites, mesh_reputation, mesh_wormhole_contacts + + manager = mesh_reputation.gate_manager + original_gates = copy.deepcopy(manager.gates) + monkeypatch.setattr(manager, "_save", lambda: None) + manager.gates["lab"] = { + "display_name": "Lab", + "gate_secret": "local-secret", + "gate_secret_archive": {}, + "envelope_policy": "envelope_always", + "rules": {"min_overall_rep": 0, "min_gate_rep": {}}, + } + + contacts: dict[str, dict] = { + "!alice": {"trust_level": "sas_verified"}, + "!bob": {"trust_level": "tofu_pinned"}, + "!carol": {"trust_level": "invite_pinned"}, + "!mallory": {"trust_level": "mismatch"}, + } + monkeypatch.setattr( + mesh_wormhole_contacts, + "get_wormhole_dm_contact", + lambda peer: dict(contacts[peer]) if peer in contacts else None, + ) + monkeypatch.setattr( + mesh_wormhole_contacts, + "get_contact_trust_level", + lambda peer: contacts.get(peer, {}).get("trust_level", "unpinned"), + ) + + pending: dict = {} + monkeypatch.setattr(mesh_gate_invites, "_read_pending", lambda: copy.deepcopy(pending)) + + def _write(value): + pending.clear() + pending.update(copy.deepcopy(value)) + + monkeypatch.setattr(mesh_gate_invites, "_write_pending", _write) + monkeypatch.setattr(mesh_gate_invites, "_local_epoch", lambda _gate: 3) + + sent: list[tuple[str, str]] = [] + + def _fake_send(peer, plaintext): + sent.append((peer, plaintext)) + return {"ok": True} + + monkeypatch.setattr(mesh_gate_invites, "_send_dm_impl", _fake_send) + yield {"mod": mesh_gate_invites, "manager": manager, "sent": sent, "pending": pending, "contacts": contacts} + manager.gates = original_gates + + +def _frame(mod, *, op="invite", secret="shared-secret", gate="lab", version=1, exclude=None): + return mod._build_frame( + op=op, gate_id=gate, display_name="Lab", secret=secret, version=version, exclude=exclude + ) + + +def test_frame_roundtrip_and_tamper_rejection(env): + mod = env["mod"] + raw = _frame(mod) + parsed = mod.parse_gate_key_frame(raw) + assert parsed["secret"] == "shared-secret" + assert parsed["secret_id"] == mod.secret_fingerprint("shared-secret") + + tampered = json.loads(raw) + tampered["secret"] = "other" + assert mod.parse_gate_key_frame(json.dumps(tampered)) is None + assert mod.parse_gate_key_frame("hello there") is None + assert mod.parse_gate_key_frame('{"kind":"something_else"}') is None + + +def test_invite_requires_existing_trusted_contact(env): + mod = env["mod"] + assert mod.send_gate_invite("lab", "!stranger")["ok"] is False + assert mod.send_gate_invite("lab", "!mallory")["ok"] is False + assert env["sent"] == [] + + +def test_invite_refuses_envelope_disabled_gate(env): + env["manager"].gates["lab"]["envelope_policy"] = "envelope_disabled" + assert env["mod"].send_gate_invite("lab", "!alice")["ok"] is False + + +def test_invite_sends_current_secret_and_records_grant(env): + mod, manager = env["mod"], env["manager"] + result = mod.send_gate_invite("lab", "!alice", note="welcome") + assert result["ok"] is True + peer, plaintext = env["sent"][0] + assert peer == "!alice" + frame = mod.parse_gate_key_frame(plaintext) + assert frame["op"] == "invite" and frame["secret"] == "local-secret" + assert "!alice" in manager.get_gate_key_meta("lab")["key_grants"] + # The status surface never exposes the secret itself. + status = mod.gate_key_status("lab") + assert "local-secret" not in json.dumps(status) + assert status["grantees"] == ["!alice"] + + +def test_received_invite_is_hidden_pending_then_accepted(env): + mod, manager = env["mod"], env["manager"] + text, summary = mod.intercept_dm_plaintext("!alice", _frame(mod, version=4)) + assert "shared-secret" not in text + assert summary["status"] == "pending" + assert "shared-secret" not in json.dumps(mod.list_pending_gate_invites()) + # Not applied until the operator accepts. + assert manager.get_gate_secret("lab") == "local-secret" + + accepted = mod.accept_gate_invite(summary["invite_id"]) + assert accepted["ok"] is True and accepted["changed"] is True + assert manager.get_gate_secret("lab") == "shared-secret" + meta = manager.get_gate_key_meta("lab") + assert meta["key_upstream"] == "!alice" + assert meta["gate_secret_version"] == 4 + archive = manager.get_gate_secret_archive("lab") + assert archive["previous_secret"] == "local-secret" + assert archive["previous_valid_through_epoch"] == 3 + assert mod.list_pending_gate_invites()["invites"] == [] + + +def test_decline_discards_invite(env): + mod, manager = env["mod"], env["manager"] + _text, summary = mod.intercept_dm_plaintext("!alice", _frame(mod)) + assert mod.decline_gate_invite(summary["invite_id"])["ok"] is True + assert manager.get_gate_secret("lab") == "local-secret" + assert mod.accept_gate_invite(summary["invite_id"])["ok"] is False + + +def test_frames_from_untrusted_senders_are_rejected(env): + mod, manager = env["mod"], env["manager"] + for sender in ("!stranger", "!mallory"): + _text, summary = mod.intercept_dm_plaintext(sender, _frame(mod)) + assert summary["status"] == "rejected_untrusted_sender" + assert env["pending"] == {} + assert manager.get_gate_secret("lab") == "local-secret" + + +def test_rekey_from_upstream_applies_and_forwards_with_exclusions(env): + mod, manager = env["mod"], env["manager"] + _text, summary = mod.intercept_dm_plaintext("!alice", _frame(mod)) + mod.accept_gate_invite(summary["invite_id"]) + manager.record_key_grant("lab", "!bob", secret_id="x", op="invite") + manager.record_key_grant("lab", "!carol", secret_id="x", op="invite") + env["sent"].clear() + + rekey = _frame(mod, op="rekey", secret="rotated-secret", version=2, exclude=["!carol"]) + _text, summary = mod.intercept_dm_plaintext("!alice", rekey) + assert summary["status"] == "applied" + assert manager.get_gate_secret("lab") == "rotated-secret" + # Forwarded to bob only: not back to alice, not to excluded carol. + assert [peer for peer, _ in env["sent"]] == ["!bob"] + assert mod.parse_gate_key_frame(env["sent"][0][1])["secret"] == "rotated-secret" + assert "!carol" not in manager.get_gate_key_meta("lab")["key_grants"] + + # Replaying the same rekey is a no-op and does not loop. + env["sent"].clear() + _text, summary = mod.intercept_dm_plaintext("!alice", rekey) + assert summary["status"] == "already_current" + assert env["sent"] == [] + + +def test_rekey_from_non_upstream_waits_for_operator(env): + mod, manager = env["mod"], env["manager"] + _text, summary = mod.intercept_dm_plaintext("!bob", _frame(mod, op="rekey", secret="sneaky")) + assert summary["status"] == "pending" + assert manager.get_gate_secret("lab") == "local-secret" + + +def test_rotate_sends_new_secret_to_grantees_except_excluded(env): + mod, manager = env["mod"], env["manager"] + manager.record_key_grant("lab", "!alice", secret_id="x", op="invite") + manager.record_key_grant("lab", "!bob", secret_id="x", op="invite") + result = mod.rotate_gate_key("lab", exclude_peer_ids=["!bob"]) + assert result["ok"] is True + assert result["delivered"] == ["!alice"] + new_secret = manager.get_gate_secret("lab") + assert new_secret != "local-secret" + frame = mod.parse_gate_key_frame(env["sent"][0][1]) + assert frame["op"] == "rekey" and frame["secret"] == new_secret and frame["exclude"] == ["!bob"] + assert set(manager.get_gate_key_meta("lab")["key_grants"]) == {"!alice"} + assert manager.get_gate_secret_archive("lab")["previous_secret"] == "local-secret" + + +def test_adopted_secret_decrypts_envelopes_from_other_node(env, monkeypatch): + """The point of the feature: a peer's envelope becomes readable here.""" + from cryptography.hazmat.primitives.ciphers.aead import AESGCM + + from services.mesh import mesh_gate_mls + + mod = env["mod"] + message_nonce = "msg-nonce-1" + key = mesh_gate_mls._gate_envelope_key_scoped("lab", "shared-secret", message_nonce=message_nonce) + iv = os.urandom(12) + ct = AESGCM(key).encrypt(iv, b"hello from node A", f"gate_envelope|lab|{message_nonce}".encode()) + token = base64.b64encode(iv + ct).decode("ascii") + + assert mesh_gate_mls._gate_envelope_decrypt("lab", token, message_nonce=message_nonce) is None + _text, summary = mod.intercept_dm_plaintext("!alice", _frame(mod)) + mod.accept_gate_invite(summary["invite_id"]) + assert mesh_gate_mls._gate_envelope_decrypt("lab", token, message_nonce=message_nonce) == "hello from node A" + + +def test_kick_rotation_redistributes_to_grantees(env, monkeypatch): + from services.config import get_settings + from services.mesh import mesh_gate_mls + + mod, manager = env["mod"], env["manager"] + monkeypatch.setenv("MESH_GATE_BAN_KICK_ROTATION_ENABLE", "true") + get_settings.cache_clear() + monkeypatch.setattr( + mesh_gate_mls, + "remove_gate_member", + lambda *_a, **_k: {"ok": True, "previous_epoch": 2, "epoch": 3, "previous_valid_through_event_id": ""}, + ) + manager.record_key_grant("lab", "!alice", secret_id="x", op="invite") + result = manager.remove_member("lab", "persona-1", kind="kick") + assert result["gate_secret_rotated"] is True + assert [peer for peer, _ in env["sent"]] == ["!alice"] + assert mod.parse_gate_key_frame(env["sent"][0][1])["secret"] == manager.get_gate_secret("lab") + get_settings.cache_clear() + + +def test_dm_decrypt_strips_gate_key_frame_before_returning(env, monkeypatch): + import main + + mod = env["mod"] + frame = _frame(mod) + monkeypatch.setattr(main, "_resolve_dm_aliases", lambda **_k: ("local", "remote")) + monkeypatch.setattr(main, "has_mls_dm_session", lambda *_a: {"ok": True, "exists": True}) + monkeypatch.setattr(main, "decrypt_mls_dm", lambda *_a: {"ok": True, "plaintext": frame}) + monkeypatch.setattr(main, "mark_contact_alias_reply_observed", lambda *_a: None) + + result = main.decrypt_wormhole_dm_envelope(peer_id="!alice", ciphertext="ct", payload_format="mls1") + assert result["ok"] is True + assert "shared-secret" not in json.dumps(result) + assert result["gate_key_event"]["status"] == "pending" + assert result["plaintext"].startswith("[Gate key]") diff --git a/backend/tests/mesh/test_gate_secret_rotation_guard.py b/backend/tests/mesh/test_gate_secret_rotation_guard.py index b917e49b..d00e0a9d 100644 --- a/backend/tests/mesh/test_gate_secret_rotation_guard.py +++ b/backend/tests/mesh/test_gate_secret_rotation_guard.py @@ -11,6 +11,8 @@ BACKEND_DIR = Path(__file__).resolve().parents[2] ALLOWED_GATE_SECRET_WRITERS = { "ensure_gate_secret", "_rotate_gate_secret_for_member_removal_locked", + # Cross-node key distribution: installs a secret received from a member. + "adopt_gate_secret", } diff --git a/frontend/src/components/InfonetTerminal/GateKeySharingPanel.tsx b/frontend/src/components/InfonetTerminal/GateKeySharingPanel.tsx new file mode 100644 index 00000000..55889ca5 --- /dev/null +++ b/frontend/src/components/InfonetTerminal/GateKeySharingPanel.tsx @@ -0,0 +1,217 @@ +'use client'; + +import React, { useCallback, useEffect, useMemo, useState } from 'react'; +import { KeyRound } from 'lucide-react'; +import { getContacts } from '@/mesh/meshIdentity'; +import { + acceptWormholeGateInvite, + declineWormholeGateInvite, + fetchWormholeGateInvites, + fetchWormholeGateKeySharing, + rekeyWormholeGate, + sendWormholeGateInvite, + type WormholeGateInvite, + type WormholeGateKeySharing, +} from '@/mesh/wormholeIdentityClient'; + +const TRUST_LABELS: Record = { + sas_verified: 'SAS verified', + invite_pinned: 'invite pinned', + tofu_pinned: 'unverified (TOFU)', + unpinned: 'unknown', +}; + +function contactLabel(peerId: string, alias?: string): string { + return alias ? `${alias} (${peerId.slice(0, 10)})` : peerId; +} + +interface GateKeySharingPanelProps { + /** Limit to one gate; omit to show pending invites for every gate. */ + gateId?: string; + /** Called after a key is accepted so the room can reload. */ + onKeyChanged?: () => void; +} + +export default function GateKeySharingPanel({ gateId, onKeyChanged }: GateKeySharingPanelProps) { + const [open, setOpen] = useState(false); + const [sharing, setSharing] = useState(null); + const [invites, setInvites] = useState([]); + const [peerId, setPeerId] = useState(''); + const [note, setNote] = useState(''); + const [busy, setBusy] = useState(false); + const [notice, setNotice] = useState(''); + + const contacts = useMemo(() => { + if (!open) return []; + return Object.entries(getContacts()) + .filter(([, contact]) => !contact.blocked) + .map(([id, contact]) => ({ id, alias: contact.alias })); + }, [open]); + + const visibleInvites = useMemo( + () => (gateId ? invites.filter((invite) => invite.gate_id === gateId) : invites), + [gateId, invites], + ); + + const refresh = useCallback(async () => { + try { + setInvites(await fetchWormholeGateInvites()); + if (gateId) setSharing(await fetchWormholeGateKeySharing(gateId)); + } catch (error) { + setNotice(error instanceof Error ? error.message : 'Key sharing unavailable'); + } + }, [gateId]); + + useEffect(() => { + void refresh(); + }, [refresh]); + + const run = async (action: () => Promise) => { + setBusy(true); + setNotice(''); + try { + setNotice(await action()); + await refresh(); + } catch (error) { + setNotice(error instanceof Error ? error.message : 'Request failed'); + } finally { + setBusy(false); + } + }; + + const sendInvite = () => + run(async () => { + const result = await sendWormholeGateInvite(gateId || '', peerId, note); + setNote(''); + const trust = TRUST_LABELS[result.recipient_trust_level || ''] || result.recipient_trust_level; + return `Key sent over encrypted DM (${trust}). They must accept it on their node.`; + }); + + const rekey = () => + run(async () => { + const result = await rekeyWormholeGate(gateId || ''); + const failed = result.failed?.length ? `, ${result.failed.length} unreachable` : ''; + return `New key sent to ${result.delivered?.length || 0} member(s)${failed}.`; + }); + + const accept = (invite: WormholeGateInvite) => + run(async () => { + await acceptWormholeGateInvite(invite.invite_id); + onKeyChanged?.(); + return `Key for ${invite.gate_name} installed. Members on other nodes are now readable.`; + }); + + const decline = (invite: WormholeGateInvite) => + run(async () => { + await declineWormholeGateInvite(invite.invite_id); + return 'Invite declined.'; + }); + + const pendingBadge = visibleInvites.length ? ` • ${visibleInvites.length} PENDING` : ''; + + return ( +
+ + {open ? ( +
+ {visibleInvites.map((invite) => ( +
+
+ {invite.op === 'rekey' ? 'New key' : 'Invite'} for {invite.gate_name} from{' '} + {invite.from_peer_id} +
+
+ Sender trust: {TRUST_LABELS[invite.from_trust_level] || invite.from_trust_level} • key{' '} + {invite.secret_id.slice(0, 8)} + {invite.note ? ` • “${invite.note}”` : ''} +
+ {invite.from_trust_level !== 'sas_verified' ? ( +
+ Compare safety codes with this contact before accepting if you need to be sure who sent it. +
+ ) : null} +
+ + +
+
+ ))} + {!visibleInvites.length && !gateId ?
No pending gate invites.
: null} + {gateId ? ( + <> +
+ Members on other nodes can only read this room if they hold the same key. Send it to a DM + contact; it travels inside an end-to-end encrypted DM and is never shown on screen. +
+
+ + setNote(e.target.value)} + maxLength={240} + placeholder="Optional note" + className="bg-[#0a0a0a] border border-gray-800 text-white px-2 py-1 flex-1 min-w-[8rem]" + /> + +
+ {sharing?.grantees?.length ? ( +
+ Shared with {sharing.grantees.length} contact(s). + +
+ ) : null} + + ) : null} + {notice ?
{notice}
: null} +
+ ) : null} +
+ ); +} diff --git a/frontend/src/components/InfonetTerminal/GateView.tsx b/frontend/src/components/InfonetTerminal/GateView.tsx index 3dc648ca..38634cc0 100644 --- a/frontend/src/components/InfonetTerminal/GateView.tsx +++ b/frontend/src/components/InfonetTerminal/GateView.tsx @@ -33,6 +33,7 @@ import { } from '@/mesh/wormholeIdentityClient'; import { gateEnvelopeDisplayText, gateEnvelopeState, isEncryptedGateEnvelope } from '@/mesh/gateEnvelope'; import { validateEventPayload } from '@/mesh/meshSchema'; +import GateKeySharingPanel from './GateKeySharingPanel'; const GATE_INTROS: Record = { infonet: @@ -974,6 +975,8 @@ export default function GateView({ + void refreshGate({ force: true })} /> +
diff --git a/frontend/src/components/InfonetTerminal/MessagesView.tsx b/frontend/src/components/InfonetTerminal/MessagesView.tsx index a0034008..3e010322 100644 --- a/frontend/src/components/InfonetTerminal/MessagesView.tsx +++ b/frontend/src/components/InfonetTerminal/MessagesView.tsx @@ -123,6 +123,7 @@ import { rootWitnessBadgeLabel, rootWitnessContinuityLabel, } from '@/mesh/contactTrustSummary'; +import GateKeySharingPanel from './GateKeySharingPanel'; type ViewTab = 'mailbox' | 'compose' | 'requests' | 'contacts' | 'restricted'; type MailFolder = 'inbox' | 'sent' | 'junk' | 'spam' | 'trash'; @@ -2915,6 +2916,8 @@ export default function MessagesView({ onBack, onOpenDeadDrop }: MessagesViewPro })}
+ +
{activeTab === 'mailbox' && (
diff --git a/frontend/src/mesh/wormholeIdentityClient.ts b/frontend/src/mesh/wormholeIdentityClient.ts index 590765c6..f2dbb0ab 100644 --- a/frontend/src/mesh/wormholeIdentityClient.ts +++ b/frontend/src/mesh/wormholeIdentityClient.ts @@ -2198,3 +2198,93 @@ export async function signRawMeshMessage( protocolVersion: PROTOCOL_VERSION, }; } + +export interface WormholeGateKeySharing { + ok: boolean; + gate_id: string; + secret_id: string; + version: number; + upstream_peer_id: string; + shared: boolean; + grantees: string[]; + detail?: string; +} + +export interface WormholeGateInvite { + invite_id: string; + op: 'invite' | 'rekey'; + gate_id: string; + gate_name: string; + from_peer_id: string; + from_trust_level: string; + secret_id: string; + version: number; + note: string; + received_at: number; +} + +const gateInviteRequestOptions = { + requireAdminSession: false, + capabilityIntent: 'wormhole_gate_key', + sessionProfileHint: 'gate_operator', + enforceProfileHint: true, +} as const; + +function postGateInviteJson(path: string, body: Record): Promise { + return controlPlaneJson(path, { + ...gateInviteRequestOptions, + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(body), + }); +} + +export function fetchWormholeGateKeySharing(gateId: string): Promise { + return controlPlaneJson( + `/api/wormhole/gate/${encodeURIComponent(gateId)}/key/sharing`, + gateInviteRequestOptions, + ); +} + +export async function fetchWormholeGateInvites(): Promise { + const result = await controlPlaneJson<{ ok: boolean; invites?: WormholeGateInvite[] }>( + '/api/wormhole/gate/invites', + gateInviteRequestOptions, + ); + return Array.isArray(result.invites) ? result.invites : []; +} + +export function sendWormholeGateInvite( + gateId: string, + peerId: string, + note = '', +): Promise<{ ok: boolean; secret_id?: string; recipient_trust_level?: string; detail?: string }> { + return postGateInviteJson('/api/wormhole/gate/invite', { gate_id: gateId, peer_id: peerId, note }); +} + +export async function acceptWormholeGateInvite( + inviteId: string, +): Promise<{ ok: boolean; gate_id?: string; detail?: string }> { + const result = await postGateInviteJson<{ ok: boolean; gate_id?: string; detail?: string }>( + '/api/wormhole/gate/invite/accept', + { invite_id: inviteId }, + ); + if (result.gate_id) { + gateKeyStatusCache.delete(normalizeGateId(result.gate_id)); + } + return result; +} + +export function declineWormholeGateInvite(inviteId: string): Promise<{ ok: boolean }> { + return postGateInviteJson('/api/wormhole/gate/invite/decline', { invite_id: inviteId }); +} + +export function rekeyWormholeGate( + gateId: string, + excludePeerIds: string[] = [], +): Promise<{ ok: boolean; delivered?: string[]; failed?: { peer_id: string; detail: string }[] }> { + return postGateInviteJson('/api/wormhole/gate/key/rekey', { + gate_id: gateId, + exclude_peer_ids: excludePeerIds, + }); +}