| 1 | |
| 2 | |
| 3 | import asyncio |
| 4 | import hashlib |
| 5 | import io |
| 6 | import json |
| 7 | import os |
| 8 | import time |
| 9 | import unittest |
| 10 | from contextlib import redirect_stdout |
| 11 | from unittest import mock |
| 12 | |
| 13 | from src import bridge |
| 14 | from src.bridge_contract import resolve_session |
| 15 | from src.engine import Engine |
| 16 | |
| 17 | |
| 18 | |
| 19 | |
| 20 | |
| 21 | |
| 22 | CERT_PEM = """-----BEGIN CERTIFICATE----- |
| 23 | MIIBfDCCASOgAwIBAgIUTFL6mXX7RANF/ifo1dfMTZ/bfy0wCgYIKoZIzj0EAwIw |
| 24 | FDESMBAGA1UEAwwJbG9jYWxob3N0MB4XDTI2MDkxNzA1MzA1OFoXDTM2MDkxNDA1 |
| 25 | MzA1OFowFDESMBAGA1UEAwwJbG9jYWxob3N0MFkwEwYHKoZIzj0CAQYIKoZIzj0D |
| 26 | AQcDQgAEYE2oRVK5XtfcL9AxKi8TFVgWbszWqG2x2W1MGN58nm+/gk9f9xIB2zsB |
| 27 | Et4NPMxNDldeweLT3FB1+m7sml3PB6NTMFEwHQYDVR0OBBYEFJGmsXzrOhrFrnpk |
| 28 | iHBOgHbYm7l0MB8GA1UdIwQYMBaAFJGmsXzrOhrFrnpkiHBOgHbYm7l0MA8GA1Ud |
| 29 | EwEB/wQFMAMBAf8wCgYIKoZIzj0EAwIDRwAwRAIgSPvQ0AIKlWcDCvSubgRfn0Zo |
| 30 | 9JZGXKGsD5ms2ieHmwwCIHN3dRl3EH16APGviHy6jfT3jUqFBR5oEeorWNJ7bWMb |
| 31 | -----END CERTIFICATE----- |
| 32 | """ |
| 33 | CERT_FINGERPRINT = "40d2b5d99fb8ed0720d1948796f41c9c778b4aa11dff06815fd77985bf4b0f61" |
| 34 | |
| 35 | |
| 36 | class _StubEngine: |
| 37 | |
| 38 | |
| 39 | def __init__(self, text: str = "cevap", delay: float = 0.0) -> None: |
| 40 | self.text = text |
| 41 | self.delay = delay |
| 42 | |
| 43 | def handle(self, request: dict) -> dict: |
| 44 | if self.delay: |
| 45 | time.sleep(self.delay) |
| 46 | return {"text": self.text} |
| 47 | |
| 48 | |
| 49 | class _BoomEngine: |
| 50 | def handle(self, request: dict) -> dict: |
| 51 | raise ValueError("motor patladı") |
| 52 | |
| 53 | |
| 54 | class _FakeQuic: |
| 55 | |
| 56 | |
| 57 | def __init__(self) -> None: |
| 58 | self.sent: list[tuple[int, bytes, bool]] = [] |
| 59 | self._next_sid = 0 |
| 60 | |
| 61 | def get_next_available_stream_id(self) -> int: |
| 62 | sid = self._next_sid |
| 63 | self._next_sid += 4 |
| 64 | return sid |
| 65 | |
| 66 | def send_stream_data(self, sid: int, data: bytes, end_stream: bool = False) -> None: |
| 67 | self.sent.append((sid, bytes(data), end_stream)) |
| 68 | |
| 69 | |
| 70 | class _Harness(bridge.BridgeProtocol): |
| 71 | |
| 72 | |
| 73 | |
| 74 | |
| 75 | |
| 76 | |
| 77 | def __init__(self, config: bridge.BridgeConfig, engine: object) -> None: |
| 78 | self._config = config |
| 79 | self._engine = engine |
| 80 | self._streams: dict[int, bridge._FrameStream] = {} |
| 81 | self._control_sid: int | None = None |
| 82 | self._ping_uid = 0 |
| 83 | self._quic = _FakeQuic() |
| 84 | |
| 85 | def transmit(self) -> None: |
| 86 | pass |
| 87 | |
| 88 | |
| 89 | def _unwrap(frame: bytes) -> dict: |
| 90 | return json.loads(frame[4:]) |
| 91 | |
| 92 | |
| 93 | def _config(**env: str) -> bridge.BridgeConfig: |
| 94 | |
| 95 | base = { |
| 96 | "AI_BRIDGE_HOST": "127.0.0.1", |
| 97 | "AI_BACKEND_URL": "http://127.0.0.1:7656", |
| 98 | "AI_SHARED_TOKEN": "test-token", |
| 99 | "AI_TLS_FINGERPRINT": "", |
| 100 | "AI_RECONNECT_SECS": "3", |
| 101 | "AI_RECONNECT_MAX_SECS": "120", |
| 102 | } |
| 103 | base.update(env) |
| 104 | with mock.patch.dict(os.environ, base): |
| 105 | return bridge.BridgeConfig() |
| 106 | |
| 107 | |
| 108 | class TokenRefusalTests(unittest.TestCase): |
| 109 | |
| 110 | |
| 111 | def test_missing_token_is_refused_at_config(self) -> None: |
| 112 | with mock.patch.dict(os.environ, {"AI_SHARED_TOKEN": ""}): |
| 113 | with self.assertRaises(ValueError): |
| 114 | bridge.BridgeConfig() |
| 115 | |
| 116 | def test_placeholder_token_is_refused_at_config(self) -> None: |
| 117 | with mock.patch.dict(os.environ, {"AI_SHARED_TOKEN": "change-me"}): |
| 118 | with self.assertRaises(ValueError): |
| 119 | bridge.BridgeConfig() |
| 120 | |
| 121 | |
| 122 | class _FakeHttp: |
| 123 | def __init__(self, payload: dict) -> None: |
| 124 | self._payload = payload |
| 125 | |
| 126 | def __enter__(self) -> "_FakeHttp": |
| 127 | return self |
| 128 | |
| 129 | def __exit__(self, *exc: object) -> bool: |
| 130 | return False |
| 131 | |
| 132 | def read(self) -> bytes: |
| 133 | return json.dumps(self._payload).encode() |
| 134 | |
| 135 | |
| 136 | class BridgeRoleContractTests(unittest.TestCase): |
| 137 | def setUp(self) -> None: |
| 138 | self.engine = Engine() |
| 139 | |
| 140 | def test_backend_asker_role_is_accepted_for_every_school_role(self) -> None: |
| 141 | for role in ("parent", "student", "teacher", "manager", "admin"): |
| 142 | with self.subTest(role=role): |
| 143 | self.assertEqual( |
| 144 | resolve_session({"asker_role": role}, "ogrenci"), |
| 145 | (role, True), |
| 146 | ) |
| 147 | |
| 148 | def test_asker_role_wins_over_legacy_role_fields(self) -> None: |
| 149 | role, authenticated = resolve_session( |
| 150 | { |
| 151 | "asker_role": "admin", |
| 152 | "role": "teacher", |
| 153 | "session": {"role": "student", "authenticated": False}, |
| 154 | }, |
| 155 | "ogrenci", |
| 156 | ) |
| 157 | self.assertEqual(role, "admin") |
| 158 | self.assertTrue(authenticated) |
| 159 | |
| 160 | def test_legacy_session_role_remains_supported(self) -> None: |
| 161 | self.assertEqual( |
| 162 | resolve_session( |
| 163 | {"session": {"role": "teacher", "authenticated": True}}, |
| 164 | "ogrenci", |
| 165 | ), |
| 166 | ("teacher", True), |
| 167 | ) |
| 168 | |
| 169 | def test_missing_role_uses_configured_legacy_fallback(self) -> None: |
| 170 | self.assertEqual(resolve_session({}, "manager"), ("manager", True)) |
| 171 | |
| 172 | def test_backend_role_changes_the_rendered_answer_scope(self) -> None: |
| 173 | question = "sınav nasıl oluşturulur?" |
| 174 | student_role, student_auth = resolve_session( |
| 175 | {"asker_role": "student"}, "ogrenci" |
| 176 | ) |
| 177 | admin_role, admin_auth = resolve_session({"asker_role": "admin"}, "ogrenci") |
| 178 | student = self.engine.handle( |
| 179 | { |
| 180 | "query": question, |
| 181 | "session": {"role": student_role, "authenticated": student_auth}, |
| 182 | } |
| 183 | ) |
| 184 | admin = self.engine.handle( |
| 185 | { |
| 186 | "query": question, |
| 187 | "session": {"role": admin_role, "authenticated": admin_auth}, |
| 188 | } |
| 189 | ) |
| 190 | |
| 191 | self.assertEqual(student["auth_action"], "role_insufficient") |
| 192 | self.assertEqual(student["required_role"], "ogretmen") |
| 193 | self.assertIsNone(student["navigation"]) |
| 194 | self.assertIsNone(admin["auth_action"]) |
| 195 | self.assertIsNotNone(admin["navigation"]) |
| 196 | self.assertTrue(admin["navigation"]["available"]) |
| 197 | |
| 198 | |
| 199 | class BridgeWireTests(unittest.TestCase): |
| 200 | |
| 201 | |
| 202 | def test_protocol_marker_is_hab2(self) -> None: |
| 203 | |
| 204 | |
| 205 | self.assertEqual(bridge.PROTOCOL, "hab/2") |
| 206 | |
| 207 | def test_register_writes_a_hab2_hello_on_the_wire(self) -> None: |
| 208 | harness = _Harness(_config(), _StubEngine()) |
| 209 | greeting = {"type": "welcome", "worker_id": "w1", "protocol": "hab/2"} |
| 210 | |
| 211 | async def drive() -> None: |
| 212 | task = asyncio.ensure_future(harness.register()) |
| 213 | await asyncio.sleep(0) |
| 214 | stream = harness._streams[harness._control_sid] |
| 215 | stream.feed(bridge._encode_frame(greeting), end=False) |
| 216 | await task |
| 217 | |
| 218 | asyncio.run(drive()) |
| 219 | |
| 220 | sid, frame, end = harness._quic.sent[0] |
| 221 | hello = _unwrap(frame) |
| 222 | self.assertEqual(hello["protocol"], "hab/2") |
| 223 | self.assertEqual(hello["service"], "celebi") |
| 224 | self.assertEqual(hello["capabilities"], ["chat.reply"]) |
| 225 | |
| 226 | self.assertFalse(end) |
| 227 | self.assertEqual(sid, harness._control_sid) |
| 228 | |
| 229 | def test_welcome_echoing_another_protocol_is_rejected(self) -> None: |
| 230 | harness = _Harness(_config(), _StubEngine()) |
| 231 | greeting = {"type": "welcome", "worker_id": "w1", "protocol": "hab/1"} |
| 232 | |
| 233 | async def drive() -> None: |
| 234 | task = asyncio.ensure_future(harness.register()) |
| 235 | await asyncio.sleep(0) |
| 236 | harness._streams[harness._control_sid].feed( |
| 237 | bridge._encode_frame(greeting), end=False |
| 238 | ) |
| 239 | await task |
| 240 | |
| 241 | with self.assertRaises(bridge.HandshakeRejected) as ctx: |
| 242 | asyncio.run(drive()) |
| 243 | self.assertTrue(ctx.exception.permanent) |
| 244 | |
| 245 | def _serve(self, engine: object, request: dict) -> dict: |
| 246 | harness = _Harness(_config(), engine) |
| 247 | stream = bridge._FrameStream() |
| 248 | stream.feed(bridge._encode_frame(request), end=True) |
| 249 | asyncio.run(harness._serve_request(1, stream)) |
| 250 | sid, frame, end = harness._quic.sent[-1] |
| 251 | self.assertEqual(sid, 1) |
| 252 | self.assertTrue(end) |
| 253 | return _unwrap(frame) |
| 254 | |
| 255 | def test_ok_response_echoes_the_request_school(self) -> None: |
| 256 | response = self._serve( |
| 257 | _StubEngine("sınav menüsü"), |
| 258 | {"id": "r1", "school": "ataturk-ilkokulu", "capability": "chat.reply", |
| 259 | "deadline_ms": 5000, "payload": {"message": "sınav"}}, |
| 260 | ) |
| 261 | self.assertEqual(response["status"], "ok") |
| 262 | self.assertEqual(response["id"], "r1") |
| 263 | self.assertEqual(response["school"], "ataturk-ilkokulu") |
| 264 | self.assertEqual(response["payload"]["text"], "sınav menüsü") |
| 265 | |
| 266 | def test_every_error_branch_echoes_the_request_school(self) -> None: |
| 267 | |
| 268 | |
| 269 | cases = { |
| 270 | "unsupported_capability": ( |
| 271 | _StubEngine(), |
| 272 | {"capability": "rag.index", "payload": {"message": "x"}}, |
| 273 | ), |
| 274 | "timed_out": ( |
| 275 | _StubEngine(delay=0.05), |
| 276 | {"capability": "chat.reply", "deadline_ms": 1, "payload": {"message": "x"}}, |
| 277 | ), |
| 278 | "internal": ( |
| 279 | _BoomEngine(), |
| 280 | {"capability": "chat.reply", "deadline_ms": 5000, "payload": {"message": "x"}}, |
| 281 | ), |
| 282 | } |
| 283 | for expected_code, (engine, extra) in cases.items(): |
| 284 | with self.subTest(code=expected_code): |
| 285 | response = self._serve( |
| 286 | engine, |
| 287 | {"id": "r2", "school": "cumhuriyet-lisesi", "capability": "chat.reply", |
| 288 | "deadline_ms": 5000, "payload": {"message": "x"}, **extra}, |
| 289 | ) |
| 290 | self.assertEqual(response["status"], "err") |
| 291 | self.assertEqual(response["code"], expected_code) |
| 292 | self.assertEqual(response["school"], "cumhuriyet-lisesi") |
| 293 | |
| 294 | def test_bad_payload_is_a_refusal_not_a_traceback(self) -> None: |
| 295 | response = self._serve( |
| 296 | _StubEngine(), |
| 297 | {"id": "r3", "school": "okul", "capability": "chat.reply", |
| 298 | "deadline_ms": 5000, "payload": {"message": 42}}, |
| 299 | ) |
| 300 | self.assertEqual(response["status"], "err") |
| 301 | self.assertEqual(response["code"], "bad_request") |
| 302 | self.assertEqual(response["school"], "okul") |
| 303 | |
| 304 | |
| 305 | class PermanentRejectBackoffTests(unittest.TestCase): |
| 306 | |
| 307 | |
| 308 | def _loop(self, script: list[str], iterations: int) -> tuple[list[float], list[int], str]: |
| 309 | |
| 310 | config = _config() |
| 311 | self.config = config |
| 312 | delays: list[float] = [] |
| 313 | attempts = [0] |
| 314 | |
| 315 | async def connect_once(cfg: bridge.BridgeConfig, engine: object) -> None: |
| 316 | attempts[0] += 1 |
| 317 | step = script[min(attempts[0] - 1, len(script) - 1)] |
| 318 | if step == "ok": |
| 319 | return |
| 320 | if step == "down": |
| 321 | raise ConnectionError("backend yok") |
| 322 | raise bridge.HandshakeRejected("unauthorized", "token uyuşmuyor") |
| 323 | |
| 324 | async def sleeper(delay: float) -> None: |
| 325 | delays.append(delay) |
| 326 | if len(delays) >= iterations: |
| 327 | raise KeyboardInterrupt |
| 328 | |
| 329 | buf = io.StringIO() |
| 330 | with redirect_stdout(buf): |
| 331 | with self.assertRaises(KeyboardInterrupt): |
| 332 | asyncio.run( |
| 333 | bridge.run_forever(config, _StubEngine(), connect_once, sleeper) |
| 334 | ) |
| 335 | return delays, attempts, buf.getvalue() |
| 336 | |
| 337 | def test_permanent_reject_backs_off_instead_of_exiting(self) -> None: |
| 338 | delays, attempts, out = self._loop(["reject"], iterations=8) |
| 339 | |
| 340 | |
| 341 | self.assertEqual(attempts[0], 8) |
| 342 | |
| 343 | |
| 344 | self.assertGreaterEqual(delays[0], 120) |
| 345 | self.assertTrue(all(d >= 120 for d in delays)) |
| 346 | |
| 347 | self.assertLessEqual(max(delays), self.config.reconnect_max_secs + 5.0) |
| 348 | self.assertIn("yine de çıkmıyoruz", out) |
| 349 | |
| 350 | def test_permanent_reject_is_logged_once_per_state_change(self) -> None: |
| 351 | _, _, out = self._loop(["reject", "reject", "ok", "reject", "reject"], iterations=5) |
| 352 | |
| 353 | |
| 354 | |
| 355 | |
| 356 | self.assertEqual(out.count("kaydı reddetti"), 2) |
| 357 | self.assertEqual(out.count("yine de çıkmıyoruz"), 2) |
| 358 | |
| 359 | def test_backoff_resets_after_a_healthy_session(self) -> None: |
| 360 | delays, _, _ = self._loop(["reject", "reject", "ok", "reject", "reject"], iterations=4) |
| 361 | |
| 362 | self.assertGreaterEqual(delays[0], 3) |
| 363 | self.assertGreaterEqual(delays[1], 6) |
| 364 | |
| 365 | self.assertGreaterEqual(delays[2], 3) |
| 366 | self.assertLessEqual(delays[2], 8.0) |
| 367 | |
| 368 | def test_transient_failure_also_backs_off_without_exiting(self) -> None: |
| 369 | delays, attempts, out = self._loop(["down"], iterations=4) |
| 370 | self.assertEqual(attempts[0], 4) |
| 371 | self.assertGreaterEqual(delays[3], 24) |
| 372 | self.assertIn("backend'e ulaşılamadı", out) |
| 373 | |
| 374 | |
| 375 | class CertificatePinTests(unittest.TestCase): |
| 376 | |
| 377 | |
| 378 | def _fetch(self, payload: dict, config: bridge.BridgeConfig) -> str: |
| 379 | with mock.patch.object(bridge.urllib.request, "urlopen", return_value=_FakeHttp(payload)): |
| 380 | return bridge._fetch_certificate(config) |
| 381 | |
| 382 | def test_der_fingerprint_matches_openssl(self) -> None: |
| 383 | der = bridge._leaf_der_from_pem(CERT_PEM) |
| 384 | self.assertEqual(hashlib.sha256(der).hexdigest(), CERT_FINGERPRINT) |
| 385 | |
| 386 | def test_mismatched_reported_fingerprint_refuses_to_connect(self) -> None: |
| 387 | payload = {"certificate_pem": CERT_PEM, "fingerprint_sha256": "ab" * 32} |
| 388 | with self.assertRaises(RuntimeError) as ctx: |
| 389 | self._fetch(payload, _config()) |
| 390 | self.assertIn("tutarsız", str(ctx.exception)) |
| 391 | |
| 392 | def test_reported_fingerprint_agrees_so_fetch_succeeds(self) -> None: |
| 393 | payload = {"certificate_pem": CERT_PEM, "fingerprint_sha256": CERT_FINGERPRINT} |
| 394 | self.assertEqual(self._fetch(payload, _config()), CERT_PEM) |
| 395 | |
| 396 | def test_pinned_fingerprint_mismatch_refuses_to_connect(self) -> None: |
| 397 | payload = {"certificate_pem": CERT_PEM, "fingerprint_sha256": CERT_FINGERPRINT} |
| 398 | config = _config(AI_TLS_FINGERPRINT="cd" * 32) |
| 399 | with self.assertRaises(RuntimeError) as ctx: |
| 400 | self._fetch(payload, config) |
| 401 | self.assertIn("PINLENEN", str(ctx.exception)) |
| 402 | |
| 403 | def test_pinned_fingerprint_accepts_colon_separated_and_uppercase_hex(self) -> None: |
| 404 | spaced = ":".join( |
| 405 | CERT_FINGERPRINT[i:i + 2] for i in range(0, len(CERT_FINGERPRINT), 2) |
| 406 | ).upper() |
| 407 | payload = {"certificate_pem": CERT_PEM, "fingerprint_sha256": CERT_FINGERPRINT} |
| 408 | config = _config(AI_TLS_FINGERPRINT=spaced) |
| 409 | self.assertEqual(config.tls_fingerprint, CERT_FINGERPRINT) |
| 410 | self.assertEqual(self._fetch(payload, config), CERT_PEM) |
| 411 | |
| 412 | def test_unset_pin_warns_that_it_is_tofu(self) -> None: |
| 413 | payload = {"certificate_pem": CERT_PEM, "fingerprint_sha256": CERT_FINGERPRINT} |
| 414 | buf = io.StringIO() |
| 415 | with redirect_stdout(buf): |
| 416 | self._fetch(payload, _config()) |
| 417 | self.assertIn("TOFU", buf.getvalue()) |
| 418 | |
| 419 | def test_malformed_pin_is_a_config_error_not_a_silent_tofu(self) -> None: |
| 420 | |
| 421 | |
| 422 | with self.assertRaises(ValueError): |
| 423 | _config(AI_TLS_FINGERPRINT="40d2b5d9") |
| 424 | |
| 425 | |
| 426 | if __name__ == "__main__": |
| 427 | unittest.main() |