""" MeshBay Hub — MHP (Mesh Bay Hub Protocol) federation endpoints. Federation allows multiple hubs to exchange public group directories and propagate revocations. Each hub explicitly chooses its peers (no automatic discovery). MHP endpoints: GET /mhp/info — hub identity and capabilities POST /mhp/directory — receive a Mesh Directory from a peer hub POST /mhp/revoke — receive a revocation from a peer hub GET /mhp/directory — export our public Mesh Directory POST /mhp/peers — admin: register a trusted peer hub GET /mhp/peers — admin: list registered peers Peer authentication: each request carries a JWT signed by the sending hub's Ed25519 key. Receiving hub verifies with the sender's cached public key (registered when adding the peer). Protocol version: MHP 0.1 """ import logging import time import uuid import jwt from fastapi import APIRouter, Depends, HTTPException, Header from pydantic import BaseModel from sqlalchemy import select from sqlalchemy.ext.asyncio import AsyncSession from meshbay_common import MHP_VERSION from meshbay_hub import __version__, hub_settings from meshbay_hub.api.deps import require_admin from meshbay_hub.auth import _hub_id, _hub_sk_pem, hub_public_key_pem from meshbay_hub.db.engine import get_db from meshbay_hub.db.models import FederatedGroup, Group, HubPeer, User log = logging.getLogger(__name__) router = APIRouter(prefix="/mhp", tags=["federation"]) def _issue_mhp_token(target_hub_id: str) -> str: """Issue a short-lived JWT for authenticating to a peer hub.""" now = int(time.time()) return jwt.encode({ "iss": _hub_id, "sub": _hub_id, "aud": target_hub_id, "jti": str(uuid.uuid4()), "iat": now, "exp": now + 300, "mhp": MHP_VERSION, }, _hub_sk_pem, algorithm="EdDSA") async def _verify_mhp_token( token: str, db: AsyncSession, expected_aud: str | None = None, ) -> dict: """Verify a JWT from a peer hub using DB-stored public key.""" unverified = jwt.decode(token, options={"verify_signature": False}) sender_id = unverified.get("iss") peer = await db.get(HubPeer, sender_id) if not peer: raise PermissionError(f"Unknown hub: {sender_id!r}. Register as peer first.") options = {} if expected_aud: options["audience"] = expected_aud decoded = jwt.decode( token, peer.pk_hub_pem.encode(), algorithms=["EdDSA"], options=options, ) return decoded # ── Hub identity ────────────────────────────────────────────────────────────── @router.get("/info") async def mhp_info(): """Return this hub's identity for peer registration.""" return { "hub_id": _hub_id, "mhp_version": MHP_VERSION, "hub_version": __version__, "pk_hub_pem": hub_public_key_pem().decode(), } # ── Directory exchange ──────────────────────────────────────────────────────── @router.get("/directory") async def export_directory( db: AsyncSession = Depends(get_db), authorization: str = Header(...), ): try: await _verify_mhp_token(authorization.removeprefix("Bearer "), db) except Exception as e: raise HTTPException(status_code=401, detail=str(e)) # A hub with public groups switched off advertises nothing to its peers — # the local directory is empty (groups.list_public_groups), and the exported # one has to match or peers keep showing groups this hub no longer serves. if not await hub_settings.public_groups_allowed(db): groups = [] else: result = await db.execute( select(Group).where(Group.visibility == "public", Group.status == "active")) groups = result.scalars().all() return { "hub_id": _hub_id, "mhp_version": MHP_VERSION, "groups": [ { "id": g.id, "name": g.name, "join_policy": g.join_policy, "created_at": g.created_at.isoformat(), "hub_id": _hub_id, } for g in groups ], } class DirectoryPayload(BaseModel): hub_id: str groups: list[dict] @router.post("/directory", status_code=202) async def receive_directory( body: DirectoryPayload, authorization: str = Header(...), db: AsyncSession = Depends(get_db), ): try: await _verify_mhp_token(authorization.removeprefix("Bearer "), db) except Exception as e: raise HTTPException(status_code=401, detail=str(e)) from datetime import datetime, timezone now = datetime.now(timezone.utc) count = 0 for g in body.groups: existing = await db.get(FederatedGroup, g["id"]) if existing: existing.name = g.get("name", existing.name) existing.join_policy = g.get("join_policy", existing.join_policy) existing.updated_at = now else: db.add(FederatedGroup( id=g["id"], name=g.get("name", ""), source_hub=body.hub_id, join_policy=g.get("join_policy", "invite"), )) count += 1 await db.commit() log.info("Persisted %d groups from hub %s", count, body.hub_id[:16]) return {"accepted": count, "from_hub": body.hub_id} # ── Revocation propagation ──────────────────────────────────────────────────── class RevocationPayload(BaseModel): token: str @router.post("/revoke", status_code=202) async def receive_revocation( body: RevocationPayload, authorization: str = Header(...), db: AsyncSession = Depends(get_db), ): try: await _verify_mhp_token(authorization.removeprefix("Bearer "), db) except Exception as e: raise HTTPException(status_code=401, detail=str(e)) from meshbay_hub.api.revocation import broadcast_revocation sent = await broadcast_revocation(body.token) log.info("Propagated revocation to %d local nodes", sent) return {"propagated_to": sent} # ── Peer management (admin) ─────────────────────────────────────────────────── class PeerRegisterRequest(BaseModel): hub_id: str hub_url: str pk_hub_pem: str @router.post("/peers", status_code=201) async def register_peer( body: PeerRegisterRequest, current_user: User = Depends(require_admin), db: AsyncSession = Depends(get_db), ): """Admin: register a trusted peer hub.""" existing = await db.get(HubPeer, body.hub_id) if existing: existing.hub_url = body.hub_url existing.pk_hub_pem = body.pk_hub_pem else: db.add(HubPeer( hub_id=body.hub_id, hub_url=body.hub_url, pk_hub_pem=body.pk_hub_pem, )) await db.commit() log.info("Peer registered: %s (%s)", body.hub_id, body.hub_url) return {"status": "registered", "hub_id": body.hub_id} @router.get("/peers") async def list_peers( current_user: User = Depends(require_admin), db: AsyncSession = Depends(get_db), ): """Admin: list registered peer hubs.""" result = await db.execute(select(HubPeer)) peers = result.scalars().all() return { "peers": [ { "hub_id": p.hub_id, "url": p.hub_url, "trusted_since": p.trusted_since.isoformat(), } for p in peers ] }