|
| 1 | +"""Phase 17.0 — hub identity + signed peer routing.""" |
| 2 | + |
| 3 | +import asyncio |
| 4 | +import os |
| 5 | +import socket |
| 6 | +import threading |
| 7 | +import time |
| 8 | + |
| 9 | +import pytest |
| 10 | + |
| 11 | +try: |
| 12 | + import fastapi # noqa |
| 13 | + import uvicorn # noqa |
| 14 | + import httpx # noqa |
| 15 | + DEPS_AVAILABLE = True |
| 16 | +except ImportError: |
| 17 | + DEPS_AVAILABLE = False |
| 18 | + |
| 19 | +if DEPS_AVAILABLE: |
| 20 | + from zhub.server import create_app |
| 21 | + from zhub.persistence import Storage |
| 22 | + |
| 23 | +# Crypto-dependent tests skip when [crypto] extras aren't installed |
| 24 | +try: |
| 25 | + from zhub.hub_identity import HubIdentity, verify_signature |
| 26 | + CRYPTO_OK = HubIdentity().available |
| 27 | +except Exception: |
| 28 | + CRYPTO_OK = False |
| 29 | + |
| 30 | +from zhub import publish |
| 31 | + |
| 32 | + |
| 33 | +def _free_port() -> int: |
| 34 | + with socket.socket() as s: |
| 35 | + s.bind(("", 0)) |
| 36 | + return s.getsockname()[1] |
| 37 | + |
| 38 | + |
| 39 | +def _start_hub(port: int, db_path: str, peers_env: str = "", |
| 40 | + hub_id: str = "", strict: bool = False) -> None: |
| 41 | + if peers_env: |
| 42 | + os.environ["ZHUB_PEERS"] = peers_env |
| 43 | + else: |
| 44 | + os.environ.pop("ZHUB_PEERS", None) |
| 45 | + if hub_id: |
| 46 | + os.environ["ZHUB_HUB_ID"] = hub_id |
| 47 | + else: |
| 48 | + os.environ.pop("ZHUB_HUB_ID", None) |
| 49 | + if strict: |
| 50 | + os.environ["ZHUB_REQUIRE_VERIFIED_PEERS"] = "1" |
| 51 | + else: |
| 52 | + os.environ.pop("ZHUB_REQUIRE_VERIFIED_PEERS", None) |
| 53 | + config = uvicorn.Config(create_app(db_path=db_path), |
| 54 | + host="127.0.0.1", port=port, log_level="warning") |
| 55 | + asyncio.run(uvicorn.Server(config).serve()) |
| 56 | + |
| 57 | + |
| 58 | +def _wait(port: int) -> None: |
| 59 | + for _ in range(40): |
| 60 | + try: |
| 61 | + with socket.create_connection(("127.0.0.1", port), timeout=0.1): |
| 62 | + return |
| 63 | + except OSError: |
| 64 | + time.sleep(0.1) |
| 65 | + |
| 66 | + |
| 67 | +# -------- pure unit tests on HubIdentity --------------------------------- |
| 68 | + |
| 69 | +@pytest.mark.skipif(not CRYPTO_OK, reason="crypto extras not installed") |
| 70 | +def test_hub_identity_generates_and_persists(tmp_path): |
| 71 | + db = Storage(tmp_path / "id.db") |
| 72 | + a = HubIdentity(storage=db) |
| 73 | + pk1 = a.public_key_hex() |
| 74 | + assert pk1 and len(pk1) == 64 # 32-byte ed25519 public key in hex |
| 75 | + |
| 76 | + # New instance with same storage reads the persisted private key |
| 77 | + b = HubIdentity(storage=db) |
| 78 | + assert b.public_key_hex() == pk1 |
| 79 | + |
| 80 | + |
| 81 | +@pytest.mark.skipif(not CRYPTO_OK, reason="crypto extras not installed") |
| 82 | +def test_sign_and_verify_round_trip(tmp_path): |
| 83 | + db = Storage(tmp_path / "id2.db") |
| 84 | + ident = HubIdentity(storage=db) |
| 85 | + pk = ident.public_key_hex() |
| 86 | + msg = b"hub-a,hub-b" |
| 87 | + sig = ident.sign(msg) |
| 88 | + assert sig is not None |
| 89 | + assert verify_signature(pk, msg, sig) is True |
| 90 | + # tampered message |
| 91 | + assert verify_signature(pk, b"hub-a,hub-c", sig) is False |
| 92 | + # bad signature |
| 93 | + assert verify_signature(pk, msg, "00" * 64) is False |
| 94 | + |
| 95 | + |
| 96 | +# -------- HTTP endpoint -------------------------------------------------- |
| 97 | + |
| 98 | +@pytest.fixture |
| 99 | +def hub_solo(tmp_path): |
| 100 | + if not DEPS_AVAILABLE: |
| 101 | + pytest.skip("fastapi/uvicorn not installed") |
| 102 | + port = _free_port() |
| 103 | + threading.Thread( |
| 104 | + target=_start_hub, |
| 105 | + args=(port, str(tmp_path / "solo.db")), |
| 106 | + kwargs={"hub_id": "solo-hub"}, |
| 107 | + daemon=True, |
| 108 | + ).start() |
| 109 | + _wait(port) |
| 110 | + yield port |
| 111 | + |
| 112 | + |
| 113 | +@pytest.mark.asyncio |
| 114 | +async def test_hub_identity_endpoint(hub_solo): |
| 115 | + async with httpx.AsyncClient(timeout=5.0) as c: |
| 116 | + r = await c.get(f"http://127.0.0.1:{hub_solo}/hub/identity") |
| 117 | + assert r.status_code == 200 |
| 118 | + d = r.json() |
| 119 | + assert d["hub_id"] == "solo-hub" |
| 120 | + assert d["version"] == "1" |
| 121 | + if CRYPTO_OK: |
| 122 | + assert d["signed"] is True |
| 123 | + assert d["public_key"] and len(d["public_key"]) == 64 |
| 124 | + else: |
| 125 | + assert d["signed"] is False |
| 126 | + assert d["public_key"] is None |
| 127 | + |
| 128 | + |
| 129 | +# -------- two-hub federation with signed routing ------------------------- |
| 130 | + |
| 131 | +@pytest.mark.skipif(not CRYPTO_OK, reason="crypto extras not installed") |
| 132 | +@pytest.mark.asyncio |
| 133 | +async def test_signed_chain_verified_across_hubs(tmp_path): |
| 134 | + """Hub A peers hub B. Publish AI on B. POST chat to A → A signs + forwards |
| 135 | + to B → B's middleware verifies the signature successfully.""" |
| 136 | + if not DEPS_AVAILABLE: |
| 137 | + pytest.skip("fastapi/uvicorn not installed") |
| 138 | + port_a = _free_port() |
| 139 | + port_b = _free_port() |
| 140 | + db_a = str(tmp_path / "a.db") |
| 141 | + db_b = str(tmp_path / "b.db") |
| 142 | + |
| 143 | + threading.Thread(target=_start_hub, |
| 144 | + args=(port_b, db_b), |
| 145 | + kwargs={"hub_id": "hub-b"}, |
| 146 | + daemon=True).start() |
| 147 | + _wait(port_b) |
| 148 | + threading.Thread(target=_start_hub, |
| 149 | + args=(port_a, db_a), |
| 150 | + kwargs={"hub_id": "hub-a", |
| 151 | + "peers_env": f"http://127.0.0.1:{port_b}"}, |
| 152 | + daemon=True).start() |
| 153 | + _wait(port_a) |
| 154 | + |
| 155 | + pub = publish( |
| 156 | + name="signed-bot", |
| 157 | + description="x", |
| 158 | + chat_handler=lambda m, o: f"served-by-B saw {len(m)} msgs", |
| 159 | + hub_url=f"ws://127.0.0.1:{port_b}", |
| 160 | + public=True, |
| 161 | + ) |
| 162 | + for _ in range(50): |
| 163 | + if pub.api_key: |
| 164 | + break |
| 165 | + await asyncio.sleep(0.1) |
| 166 | + |
| 167 | + async with httpx.AsyncClient(timeout=8.0) as c: |
| 168 | + resp = await c.post( |
| 169 | + f"http://127.0.0.1:{port_a}/{pub.name}/v1/chat/completions", |
| 170 | + json={"messages": [{"role": "user", "content": "ping"}]}, |
| 171 | + headers={"Authorization": f"Bearer {pub.api_key}"}, |
| 172 | + ) |
| 173 | + assert resp.status_code == 200 |
| 174 | + body = resp.json() |
| 175 | + assert "served-by-B" in body["choices"][0]["message"]["content"] |
| 176 | + # X-Zhub-Origin header should also be present (Phase 1.1 behavior preserved) |
| 177 | + assert resp.headers.get("x-zhub-origin", "").startswith("http://127.0.0.1:") |
0 commit comments