"""Voice session endpoint tests (HEL-877): honest refusal, server-side dispatch, token room isolation, end/invalidation cleanup — all against the real router and real service with a fake LiveKit Twirp transport. Zero network.""" from __future__ import annotations import json import sys import time from pathlib import Path import httpx import pytest sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src")) sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests")) from test_r2 import R2LLM # noqa: E402 from cybergril.api.app import create_app # noqa: E402 from cybergril.life.runtime import LifeConfig # noqa: E402 from cybergril.think.router import build_router # noqa: E402 from cybergril.think.scenes import Tier # noqa: E402 from cybergril.voice import livekit_wire # noqa: E402 from cybergril.voice.session import VoiceConfig, VoiceSessionService # noqa: E402 CREATE = {"name": "语音测试", "birth": "2000-10-18", "hour": "亥时", "relation": "朋友"} class FakeLiveKit: """Fake Twirp LiveKit server: records dispatches, room deletes, auth tokens.""" def __init__(self) -> None: self.dispatches: list[dict] = [] self.deleted_rooms: list[str] = [] self.auth_tokens: list[str] = [] self.fail = False self.transport = httpx.MockTransport(self._handle) self._dispatch_seq = 0 def _handle(self, request: httpx.Request) -> httpx.Response: self.auth_tokens.append(request.headers.get("authorization", "")) if self.fail: return httpx.Response(500, text="livekit down") path = request.url.path if path == "/twirp/livekit.AgentDispatchService/CreateDispatch": body = request.content agent_name, room = _parse_dispatch(body) self._dispatch_seq += 1 self.dispatches.append({"agent_name": agent_name, "room": room, "proto": True, "content_type": request.headers.get("content-type", "")}) return httpx.Response(200, json={"id": f"AD_{self._dispatch_seq}", "agentName": agent_name, "room": room}) if path == "/twirp/livekit.RoomService/DeleteRoom": self.deleted_rooms.append(_parse_room(request.content)) return httpx.Response(200, content=b"") return httpx.Response(404, text="unknown twirp route") def service(self) -> VoiceSessionService: config = VoiceConfig( livekit_url="ws://voice.test:7880", livekit_internal="http://livekit.test", api_key="devkey", api_secret="test-secret-not-real", tts_health_url="http://tts.test/health", ) return VoiceSessionService(config=config, http=httpx.AsyncClient(transport=self.transport)) def _read_varint(data: bytes, index: int) -> tuple[int, int]: shift = 0 value = 0 while True: byte = data[index] value |= (byte & 0x7F) << shift index += 1 if not byte & 0x80: return value, index shift += 7 def _parse_dispatch(body: bytes) -> tuple[str, str]: fields = _parse_proto_strings(body) return fields.get(1, ""), fields.get(2, "") def _parse_room(body: bytes) -> str: return _parse_proto_strings(body).get(1, "") def _parse_proto_strings(data: bytes) -> dict[int, str]: out = {} index = 0 while index < len(data): tag, index = _read_varint(data, index) field, wire = tag >> 3, tag & 7 if wire != 2: break length, index = _read_varint(data, index) out[field] = data[index: index + length].decode() index += length return out @pytest.fixture def fake_livekit(): return FakeLiveKit() class FakeTTS: def __init__(self) -> None: self.ok = True self.calls = 0 def handler(self, request: httpx.Request) -> httpx.Response: self.calls += 1 return httpx.Response(200) if self.ok else httpx.Response(503) def make_app(fake_livekit: FakeLiveKit, tts: FakeTTS): provider = R2LLM() router = build_router(providers={t: provider for t in (Tier.HIGH, Tier.STANDARD, Tier.LOW)}) service = fake_livekit.service() service.http = httpx.AsyncClient(transport=_combined_transport(fake_livekit, tts)) app = create_app(db_path=":memory:", router=router, life_config=LifeConfig(enabled=True, poll_seconds=3600), semantic_mode="stub", voice_service=service) return app, service, provider def _combined_transport(fake_livekit: FakeLiveKit, tts: FakeTTS) -> httpx.MockTransport: def handler(request: httpx.Request) -> httpx.Response: if request.url.host == "tts.test": return tts.handler(request) return fake_livekit._handle(request) return httpx.MockTransport(handler) @pytest.fixture def instance(fake_livekit): tts = FakeTTS() app, service, provider = make_app(fake_livekit, tts) from fastapi.testclient import TestClient with TestClient(app) as client: client.post("/api/companion", json=CREATE) yield client, fake_livekit, service, provider, tts def test_status_unconfigured_honest(): from fastapi.testclient import TestClient app = create_app(db_path=":memory:", router=build_router( providers={t: R2LLM() for t in (Tier.HIGH, Tier.STANDARD, Tier.LOW)}), life_config=LifeConfig(enabled=False), semantic_mode="stub") with TestClient(app) as client: status = client.get("/api/voice/status").json() assert status == {"configured": False, "tts_ok": False, "agent_name": None, "voice": False} # health stays honest: capabilities.voice never faked on assert client.get("/api/health").json()["capabilities"]["voice"] is False refusal = client.post("/api/voice/session") assert refusal.status_code == 503 assert "语音还没有在这台服务上配置" in refusal.json()["detail"] def test_open_session_dispatches_dedicated_worker(instance): client, livekit, service, _, _ = instance response = client.post("/api/voice/session") assert response.status_code == 201, response.text body = response.json() # dedicated dispatch, not the generic cascade-voice-agent assert livekit.dispatches[-1]["agent_name"] == "cybergril-voice-agent" assert livekit.dispatches[-1]["room"] == body["room"] assert livekit.dispatches[-1]["proto"] is True assert livekit.dispatches[-1]["content_type"] == "application/protobuf" assert body["url"] == "ws://voice.test:7880" assert body["agent_name"] == "cybergril-voice-agent" # no livekit key material leaks into the browser payload assert "devkey" not in json.dumps(body) and "test-secret-not-real" not in json.dumps(body) def test_token_is_real_short_ttl_and_room_scoped(instance): client, livekit, _, _, _ = instance secret = "test-secret-not-real" first = client.post("/api/voice/session").json() second = client.post("/api/voice/session").json() assert first["room"] != second["room"], "each session gets its own room" for body in (first, second): claims, signing_input = livekit_wire.decode_token(body["token"]) assert livekit_wire.verify_signature(body["token"], secret) assert claims["iss"] == "devkey" assert claims["sub"].startswith("user-") video = claims["video"] assert video["roomJoin"] is True and video["room"] == body["room"] assert video["canPublish"] is True and video["canSubscribe"] is True assert claims["exp"] - claims["nbf"] <= 300, "token must be short-lived" # token for room A grants nothing about room B (room isolation) claims_a, _ = livekit_wire.decode_token(first["token"]) claims_b, _ = livekit_wire.decode_token(second["token"]) assert claims_a["video"]["room"] != claims_b["video"]["room"] def test_open_session_refuses_without_companion(fake_livekit): tts = FakeTTS() app, service, _ = make_app(fake_livekit, tts) from fastapi.testclient import TestClient with TestClient(app) as client: refusal = client.post("/api/voice/session") assert refusal.status_code == 409 assert "还没有创建真实伴侣" in refusal.json()["detail"] assert not fake_livekit.dispatches, "no dispatch may happen without a profile" def test_open_session_refuses_when_tts_down(instance): client, livekit, service, _, tts = instance tts.ok = False service._tts_health.checked = -1e9 # bust cache refusal = client.post("/api/voice/session") assert refusal.status_code == 503 assert "她的声音服务这会儿不在" in refusal.json()["detail"] assert not livekit.dispatches tts.ok = True service._tts_health.checked = -1e9 assert client.post("/api/voice/session").status_code == 201 def test_open_session_refuses_when_livekit_down(instance): client, livekit, _, _, _ = instance livekit.fail = True refusal = client.post("/api/voice/session") assert refusal.status_code == 503 assert "通话服务暂时连不上" in refusal.json()["detail"] def test_end_session_deletes_room_and_cleans_registry(instance): client, livekit, service, _, _ = instance body = client.post("/api/voice/session").json() assert service.get(body["session_id"]) is not None ended = client.delete(f"/api/voice/session/{body['session_id']}") assert ended.status_code == 200 and ended.json()["ended"] is True assert livekit.deleted_rooms == [body["room"]] assert service.get(body["session_id"]) is None again = client.delete(f"/api/voice/session/{body['session_id']}") assert again.status_code == 404 def test_registry_expiry_prunes_old_sessions(fake_livekit): import asyncio service = fake_livekit.service() now = time.time() session = asyncio.run(service.open_session(epoch=7)) assert service.get(session.session_id) is not None service.clock = lambda: now + service.config.session_ttl_seconds + 1 assert service.get(session.session_id) is None, "expired registry entry pruned" asyncio.run(service.aclose()) def test_worker_auth_tokens_are_server_jwt(instance): client, livekit, _, _, _ = instance client.post("/api/voice/session") auth = livekit.auth_tokens[-1] assert auth.startswith("Bearer ") token = auth.removeprefix("Bearer ") claims, _ = livekit_wire.decode_token(token) assert claims["iss"] == "devkey" and claims["sub"] == "" assert claims["exp"] - claims["nbf"] <= 60