| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | |
| 15 | |
| 16 | |
| 17 | |
| 18 | |
| 19 | import unittest |
| 20 | |
| 21 | try: |
| 22 | from fastapi.testclient import TestClient |
| 23 | from src.service.http_app import create_app |
| 24 | _HAS_FASTAPI = True |
| 25 | except Exception: |
| 26 | _HAS_FASTAPI = False |
| 27 | |
| 28 | |
| 29 | class _Service: |
| 30 | generator = object() |
| 31 | doc = object() |
| 32 | question_gen = object() |
| 33 | |
| 34 | def chat(self, req): |
| 35 | return {"text": "ok", "abstained": False, "reason": ""} |
| 36 | |
| 37 | def summarize(self, req): |
| 38 | return {"text": "ok", "abstained": False, "reason": ""} |
| 39 | |
| 40 | def generate_questions(self, req): |
| 41 | return {"items": [], "abstained": False, "reason": ""} |
| 42 | |
| 43 | |
| 44 | class _Exploding(_Service): |
| 45 | def chat(self, req): |
| 46 | raise RuntimeError("DeepSeek 429 Too Many Requests") |
| 47 | |
| 48 | |
| 49 | def _client(**kw): |
| 50 | kw.setdefault("rate_limit_per_min", 0) |
| 51 | return TestClient(create_app(_Service(), **kw)) |
| 52 | |
| 53 | |
| 54 | @unittest.skipUnless(_HAS_FASTAPI, "fastapi yok") |
| 55 | class RequestBoundsTests(unittest.TestCase): |
| 56 | |
| 57 | |
| 58 | def setUp(self): |
| 59 | self.c = _client() |
| 60 | |
| 61 | def test_query_over_field_limit_rejected(self): |
| 62 | |
| 63 | r = self.c.post("/rag/chat", json={"query": "A" * 5000}) |
| 64 | self.assertEqual(r.status_code, 422) |
| 65 | |
| 66 | def test_oversized_query_rejected_before_parsing(self): |
| 67 | |
| 68 | r = self.c.post("/rag/chat", json={"query": "A" * 2_000_000}) |
| 69 | self.assertEqual(r.status_code, 413) |
| 70 | self.assertEqual(r.json()["reason"], "payload_too_large") |
| 71 | |
| 72 | def test_absurd_top_n_rejected(self): |
| 73 | r = self.c.post("/rag/chat", |
| 74 | json={"query": "q", "options": {"top_n": 10 ** 9}}) |
| 75 | self.assertEqual(r.status_code, 422) |
| 76 | |
| 77 | def test_absurd_candidate_n_rejected(self): |
| 78 | r = self.c.post("/rag/chat", |
| 79 | json={"query": "q", "options": {"candidate_n": 10 ** 9}}) |
| 80 | self.assertEqual(r.status_code, 422) |
| 81 | |
| 82 | def test_absurd_question_count_rejected(self): |
| 83 | r = self.c.post("/rag/questions", |
| 84 | json={"scope": {"pages": [1]}, "n": 10 ** 6}) |
| 85 | self.assertEqual(r.status_code, 422) |
| 86 | |
| 87 | def test_huge_history_rejected(self): |
| 88 | hist = [{"role": "user", "content": "x"}] * 500 |
| 89 | r = self.c.post("/rag/chat", json={"query": "q", "history": hist}) |
| 90 | self.assertEqual(r.status_code, 422) |
| 91 | |
| 92 | def test_oversized_scope_span_ids_rejected(self): |
| 93 | r = self.c.post("/rag/summarize", |
| 94 | json={"scope": {"span_ids": [f"d#1.{i}" for i in range(2000)]}}) |
| 95 | self.assertIn(r.status_code, (413, 422)) |
| 96 | |
| 97 | def test_non_numeric_top_n_is_422_not_500(self): |
| 98 | |
| 99 | r = self.c.post("/rag/chat", |
| 100 | json={"query": "q", "options": {"top_n": "abc"}}) |
| 101 | self.assertEqual(r.status_code, 422) |
| 102 | |
| 103 | def test_empty_query_rejected(self): |
| 104 | self.assertEqual(self.c.post("/rag/chat", json={"query": ""}).status_code, 422) |
| 105 | |
| 106 | def test_oversized_scope_page_list_rejected(self): |
| 107 | r = self.c.post("/rag/summarize", |
| 108 | json={"scope": {"pages": list(range(1, 5000))}}) |
| 109 | self.assertEqual(r.status_code, 422) |
| 110 | |
| 111 | def test_oversized_scope_label_rejected(self): |
| 112 | r = self.c.post("/rag/summarize", |
| 113 | json={"scope": {"pages": [1], "scope_label": "A" * 5000}}) |
| 114 | self.assertEqual(r.status_code, 422) |
| 115 | |
| 116 | def test_normal_request_still_works(self): |
| 117 | r = self.c.post("/rag/chat", |
| 118 | json={"query": "DNA nedir?", "options": {"top_n": 6}}) |
| 119 | self.assertEqual(r.status_code, 200) |
| 120 | |
| 121 | |
| 122 | @unittest.skipUnless(_HAS_FASTAPI, "fastapi yok") |
| 123 | class DocsExposureTests(unittest.TestCase): |
| 124 | def test_docs_closed_by_default(self): |
| 125 | c = _client() |
| 126 | for path in ("/docs", "/redoc", "/openapi.json"): |
| 127 | with self.subTest(path): |
| 128 | self.assertEqual(c.get(path).status_code, 404) |
| 129 | |
| 130 | def test_docs_can_be_opened_explicitly(self): |
| 131 | c = _client(expose_docs=True) |
| 132 | self.assertEqual(c.get("/openapi.json").status_code, 200) |
| 133 | |
| 134 | |
| 135 | @unittest.skipUnless(_HAS_FASTAPI, "fastapi yok") |
| 136 | class HealthReadyTests(unittest.TestCase): |
| 137 | def test_health_is_liveness_only(self): |
| 138 | self.assertEqual(_client().get("/health").status_code, 200) |
| 139 | |
| 140 | def test_ready_reports_not_ready_when_generator_missing(self): |
| 141 | |
| 142 | class _Broken(_Service): |
| 143 | generator = None |
| 144 | c = TestClient(create_app(_Broken(), rate_limit_per_min=0)) |
| 145 | r = c.get("/ready") |
| 146 | self.assertEqual(r.status_code, 503) |
| 147 | self.assertEqual(r.json()["status"], "not_ready") |
| 148 | |
| 149 | def test_ready_reports_capabilities(self): |
| 150 | body = _client().get("/ready").json() |
| 151 | self.assertTrue(body["ozet"]) |
| 152 | self.assertTrue(body["soru"]) |
| 153 | |
| 154 | |
| 155 | @unittest.skipUnless(_HAS_FASTAPI, "fastapi yok") |
| 156 | class AuthTests(unittest.TestCase): |
| 157 | def test_auth_disabled_by_default(self): |
| 158 | |
| 159 | self.assertEqual(_client().post("/rag/chat", |
| 160 | json={"query": "q"}).status_code, 200) |
| 161 | |
| 162 | def test_token_required_when_configured(self): |
| 163 | c = _client(service_token="gizli") |
| 164 | self.assertEqual(c.post("/rag/chat", json={"query": "q"}).status_code, 401) |
| 165 | |
| 166 | def test_wrong_token_rejected(self): |
| 167 | c = _client(service_token="gizli") |
| 168 | r = c.post("/rag/chat", json={"query": "q"}, |
| 169 | headers={"X-Service-Token": "yanlis"}) |
| 170 | self.assertEqual(r.status_code, 401) |
| 171 | |
| 172 | def test_correct_token_accepted(self): |
| 173 | c = _client(service_token="gizli") |
| 174 | r = c.post("/rag/chat", json={"query": "q"}, |
| 175 | headers={"X-Service-Token": "gizli"}) |
| 176 | self.assertEqual(r.status_code, 200) |
| 177 | |
| 178 | def test_all_rag_paths_are_protected(self): |
| 179 | c = _client(service_token="gizli") |
| 180 | for path, body in (("/rag/chat", {"query": "q"}), |
| 181 | ("/rag/summarize", {"scope": {"pages": [1]}}), |
| 182 | ("/rag/questions", {"scope": {"pages": [1]}})): |
| 183 | with self.subTest(path): |
| 184 | self.assertEqual(c.post(path, json=body).status_code, 401) |
| 185 | |
| 186 | def test_health_stays_open_for_probes(self): |
| 187 | |
| 188 | c = _client(service_token="gizli") |
| 189 | self.assertEqual(c.get("/health").status_code, 200) |
| 190 | |
| 191 | |
| 192 | @unittest.skipUnless(_HAS_FASTAPI, "fastapi yok") |
| 193 | class RateLimitTests(unittest.TestCase): |
| 194 | def test_limit_blocks_after_threshold(self): |
| 195 | c = TestClient(create_app(_Service(), rate_limit_per_min=3)) |
| 196 | codes = [c.post("/rag/chat", json={"query": "q"}).status_code |
| 197 | for _ in range(5)] |
| 198 | self.assertEqual(codes[:3], [200, 200, 200]) |
| 199 | self.assertEqual(codes[3:], [429, 429]) |
| 200 | |
| 201 | def test_retry_after_header_present(self): |
| 202 | c = TestClient(create_app(_Service(), rate_limit_per_min=1)) |
| 203 | c.post("/rag/chat", json={"query": "q"}) |
| 204 | r = c.post("/rag/chat", json={"query": "q"}) |
| 205 | self.assertEqual(r.status_code, 429) |
| 206 | self.assertEqual(r.headers.get("Retry-After"), "60") |
| 207 | |
| 208 | def test_zero_disables_limit(self): |
| 209 | c = TestClient(create_app(_Service(), rate_limit_per_min=0)) |
| 210 | for _ in range(30): |
| 211 | self.assertEqual(c.post("/rag/chat", |
| 212 | json={"query": "q"}).status_code, 200) |
| 213 | |
| 214 | |
| 215 | @unittest.skipUnless(_HAS_FASTAPI, "fastapi yok") |
| 216 | class ErrorContractTests(unittest.TestCase): |
| 217 | def test_unhandled_error_returns_typed_contract_not_bare_500(self): |
| 218 | |
| 219 | |
| 220 | c = TestClient(create_app(_Exploding(), rate_limit_per_min=0), |
| 221 | raise_server_exceptions=False) |
| 222 | r = c.post("/rag/chat", json={"query": "q"}) |
| 223 | self.assertEqual(r.status_code, 503) |
| 224 | body = r.json() |
| 225 | self.assertTrue(body["abstained"]) |
| 226 | self.assertEqual(body["reason"], "service_unavailable") |
| 227 | self.assertIn("citations", body) |
| 228 | self.assertTrue(body["text"]) |
| 229 | self.assertIn("request_id", body) |
| 230 | |
| 231 | def test_unhandled_error_is_also_logged_with_its_cause(self): |
| 232 | |
| 233 | |
| 234 | import contextlib |
| 235 | import io |
| 236 | err = io.StringIO() |
| 237 | c = TestClient(create_app(_Exploding(), rate_limit_per_min=0), |
| 238 | raise_server_exceptions=False) |
| 239 | with contextlib.redirect_stderr(err): |
| 240 | r = c.post("/rag/chat", json={"query": "q"}) |
| 241 | self.assertEqual(r.status_code, 503) |
| 242 | iz = err.getvalue() |
| 243 | self.assertIn("[http][HATA]", iz) |
| 244 | self.assertIn("RuntimeError", iz) |
| 245 | self.assertIn("429", iz) |
| 246 | |
| 247 | def test_request_id_header_on_success(self): |
| 248 | r = _client().post("/rag/chat", json={"query": "q"}) |
| 249 | self.assertTrue(r.headers.get("X-Request-Id")) |
| 250 | |
| 251 | def test_client_request_id_is_echoed(self): |
| 252 | r = _client().post("/rag/chat", json={"query": "q"}, |
| 253 | headers={"X-Request-Id": "izlenebilir-123"}) |
| 254 | self.assertEqual(r.headers.get("X-Request-Id"), "izlenebilir-123") |
| 255 | |
| 256 | |
| 257 | @unittest.skipUnless(_HAS_FASTAPI, "fastapi yok") |
| 258 | class BodyLimitTests(unittest.TestCase): |
| 259 | |
| 260 | |
| 261 | |
| 262 | def test_content_length_header_is_enforced(self): |
| 263 | c = _client(max_body_bytes=1000) |
| 264 | r = c.post("/rag/chat", content=b"x" * 5000, |
| 265 | headers={"Content-Type": "application/json"}) |
| 266 | self.assertEqual(r.status_code, 413) |
| 267 | |
| 268 | def test_chunked_body_without_content_length_is_enforced(self): |
| 269 | |
| 270 | |
| 271 | def _parcali(): |
| 272 | for _ in range(20): |
| 273 | yield b"x" * 500 |
| 274 | c = _client(max_body_bytes=1000) |
| 275 | r = c.post("/rag/chat", content=_parcali(), |
| 276 | headers={"Content-Type": "application/json"}) |
| 277 | self.assertEqual(r.status_code, 413) |
| 278 | |
| 279 | def test_error_body_follows_the_contract(self): |
| 280 | c = _client(max_body_bytes=100) |
| 281 | body = c.post("/rag/chat", json={"query": "A" * 500}).json() |
| 282 | self.assertTrue(body["abstained"]) |
| 283 | self.assertEqual(body["reason"], "payload_too_large") |
| 284 | self.assertEqual(body["citations"], []) |
| 285 | |
| 286 | def test_normal_body_passes(self): |
| 287 | c = _client(max_body_bytes=256 * 1024) |
| 288 | self.assertEqual(c.post("/rag/chat", json={"query": "q"}).status_code, 200) |
| 289 | |
| 290 | def test_zero_disables_the_limit(self): |
| 291 | c = _client(max_body_bytes=0) |
| 292 | r = c.post("/rag/chat", json={"query": "A" * 5000}) |
| 293 | self.assertEqual(r.status_code, 422) |
| 294 | |
| 295 | |
| 296 | @unittest.skipUnless(_HAS_FASTAPI, "fastapi yok") |
| 297 | class DeadlineTests(unittest.TestCase): |
| 298 | def test_slow_request_returns_typed_504(self): |
| 299 | |
| 300 | class _Slow(_Service): |
| 301 | def chat(self, req): |
| 302 | import time |
| 303 | time.sleep(0.5) |
| 304 | return {"text": "gec", "abstained": False, "reason": ""} |
| 305 | |
| 306 | c = TestClient(create_app(_Slow(), rate_limit_per_min=0, |
| 307 | request_timeout_s=0.05)) |
| 308 | r = c.post("/rag/chat", json={"query": "q"}) |
| 309 | self.assertEqual(r.status_code, 504) |
| 310 | body = r.json() |
| 311 | self.assertTrue(body["abstained"]) |
| 312 | self.assertEqual(body["reason"], "timeout") |
| 313 | self.assertIn("request_id", body) |
| 314 | |
| 315 | def test_fast_request_unaffected(self): |
| 316 | c = TestClient(create_app(_Service(), rate_limit_per_min=0, |
| 317 | request_timeout_s=5.0)) |
| 318 | self.assertEqual(c.post("/rag/chat", json={"query": "q"}).status_code, 200) |
| 319 | |
| 320 | def test_zero_disables_the_deadline(self): |
| 321 | c = TestClient(create_app(_Service(), rate_limit_per_min=0, |
| 322 | request_timeout_s=0)) |
| 323 | self.assertEqual(c.post("/rag/chat", json={"query": "q"}).status_code, 200) |
| 324 | |
| 325 | |
| 326 | @unittest.skipUnless(_HAS_FASTAPI, "fastapi yok") |
| 327 | class HostAndCorsTests(unittest.TestCase): |
| 328 | def test_untrusted_host_rejected_when_configured(self): |
| 329 | c = TestClient(create_app(_Service(), rate_limit_per_min=0, |
| 330 | allowed_hosts=["rag.ic-ag"])) |
| 331 | self.assertEqual(c.post("/rag/chat", json={"query": "q"}).status_code, 400) |
| 332 | |
| 333 | def test_trusted_host_passes(self): |
| 334 | c = TestClient(create_app(_Service(), rate_limit_per_min=0, |
| 335 | allowed_hosts=["testserver"])) |
| 336 | self.assertEqual(c.post("/rag/chat", json={"query": "q"}).status_code, 200) |
| 337 | |
| 338 | def test_wildcard_keeps_backward_compatibility(self): |
| 339 | c = TestClient(create_app(_Service(), rate_limit_per_min=0, |
| 340 | allowed_hosts=["*"])) |
| 341 | self.assertEqual(c.post("/rag/chat", json={"query": "q"}).status_code, 200) |
| 342 | |
| 343 | def test_cors_closed_by_default(self): |
| 344 | |
| 345 | |
| 346 | r = _client().post("/rag/chat", json={"query": "q"}, |
| 347 | headers={"Origin": "https://kotu.example"}) |
| 348 | self.assertIsNone(r.headers.get("access-control-allow-origin")) |
| 349 | |
| 350 | def test_cors_only_for_declared_origin(self): |
| 351 | c = TestClient(create_app(_Service(), rate_limit_per_min=0, |
| 352 | cors_origins=["https://hezarfen.example"])) |
| 353 | ok = c.post("/rag/chat", json={"query": "q"}, |
| 354 | headers={"Origin": "https://hezarfen.example"}) |
| 355 | self.assertEqual(ok.headers.get("access-control-allow-origin"), |
| 356 | "https://hezarfen.example") |
| 357 | kotu = c.post("/rag/chat", json={"query": "q"}, |
| 358 | headers={"Origin": "https://kotu.example"}) |
| 359 | self.assertIsNone(kotu.headers.get("access-control-allow-origin")) |
| 360 | |
| 361 | |
| 362 | @unittest.skipUnless(_HAS_FASTAPI, "fastapi yok") |
| 363 | class ConfigVisibilityTests(unittest.TestCase): |
| 364 | def test_ready_reports_which_brakes_are_on(self): |
| 365 | c = TestClient(create_app(_Service(), service_token="gizli", |
| 366 | rate_limit_per_min=30, max_body_bytes=1234, |
| 367 | request_timeout_s=45, allowed_hosts=["testserver"], |
| 368 | cors_origins=[])) |
| 369 | g = c.get("/ready").json()["guvenlik"] |
| 370 | self.assertTrue(g["token"]) |
| 371 | self.assertEqual(g["oran_limiti"], 30) |
| 372 | self.assertEqual(g["govde_siniri"], 1234) |
| 373 | self.assertEqual(g["son_tarih_s"], 45) |
| 374 | self.assertFalse(g["docs_acik"]) |
| 375 | self.assertTrue(g["host_siniri"]) |
| 376 | self.assertFalse(g["cors"]) |
| 377 | |
| 378 | def test_secret_value_is_never_exposed(self): |
| 379 | c = TestClient(create_app(_Service(), service_token="cok-gizli-sir", |
| 380 | rate_limit_per_min=0)) |
| 381 | self.assertNotIn("cok-gizli-sir", c.get("/ready").text) |
| 382 | |
| 383 | def test_unsafe_defaults_are_announced_at_startup(self): |
| 384 | |
| 385 | import importlib |
| 386 | from unittest import mock |
| 387 | from src.service import http_app as m |
| 388 | with mock.patch.dict("os.environ", {"RAG_SERVICE_TOKEN": "", |
| 389 | "RAG_ALLOWED_HOSTS": "*"}, clear=False): |
| 390 | m2 = importlib.reload(m) |
| 391 | try: |
| 392 | u = " ".join(m2._yapilandirma_uyarilari()) |
| 393 | self.assertIn("RAG_SERVICE_TOKEN", u) |
| 394 | self.assertIn("RAG_ALLOWED_HOSTS", u) |
| 395 | finally: |
| 396 | importlib.reload(m) |
| 397 | |
| 398 | |
| 399 | if __name__ == "__main__": |
| 400 | unittest.main() |