Ham govde siniri, istek son tarihi, Host/CORS ve graceful shutdown
Browse files at this commit9f2f4ae7c967b56c55779df6d143d80ffa69029bParent: 8f84fd2- fix
- ham govde siniri, istek son tarihi, Host/CORS ve graceful shutdown
4 changed files +358 -16
- .env.example +13 -0
- docs/API-CONTRACT.md +13 -0
- src/service/http_app.py +176 -14
- tests/unit/test_http_hardening.py +156 -2
.env.examplemodified+13 -0
| @@ -50,3 +50,16 @@ HEZARFEN_AUDIT_RETENTION_DAYS=30 | |||
| 50 | # eval ve servis AYNI degeri okur. Varsayilan 0 = uretimin bugunku davranisi. | 50 | # eval ve servis AYNI degeri okur. Varsayilan 0 = uretimin bugunku davranisi. |
| 51 | # Gecmis olcumleri (parent ACIK) yeniden uretmek icin 1. | 51 | # Gecmis olcumleri (parent ACIK) yeniden uretmek icin 1. |
| 52 | RAG_INCLUDE_PARENTS=0 | 52 | RAG_INCLUDE_PARENTS=0 |
| 53 | + | ||
| 54 | +# --- HTTP servis sertlestirmesi (#50, EXP-010/SEC-09 + OPS-13) --- | ||
| 55 | +# Varsayilanlar GERIYE UYUMLU secildi (mevcut kurulum bozulmasin); uretimde | ||
| 56 | +# en az RAG_SERVICE_TOKEN ve RAG_ALLOWED_HOSTS doldurulmalidir. Servis | ||
| 57 | +# acilista eksik olanlari UYARI olarak yazar, /ready de makine-okunur raporlar. | ||
| 58 | +RAG_SERVICE_TOKEN= # bos -> kimlik dogrulama KAPALI (yalniz ic ag) | ||
| 59 | +RAG_RATE_LIMIT_PER_MIN=60 # 0 -> kapali. Surec-ici; cok-pod'da ters vekil sart | ||
| 60 | +RAG_MAX_BODY_BYTES=262144 # ham govde siniri (ayristirmadan ONCE), 0 -> kapali | ||
| 61 | +RAG_REQUEST_TIMEOUT_S=60 # istek basina son tarih; saglayici timeout'undan KISA | ||
| 62 | +RAG_EXPOSE_DOCS=0 # 1 -> /docs, /redoc, /openapi.json acilir | ||
| 63 | +RAG_ALLOWED_HOSTS=* # virgullu liste; '*' -> Host dogrulanmaz | ||
| 64 | +RAG_CORS_ORIGINS= # bos -> CORS basligi HIC gonderilmez (guvenli varsayilan) | ||
| 65 | +RAG_GRACEFUL_SHUTDOWN_S=20 # SIGTERM sonrasi ucusta olan istekler icin sure | ||
docs/API-CONTRACT.mdmodified+13 -0
| @@ -62,6 +62,19 @@ yanlış role = veri sızıntısı. RAG `role`'ü olduğu gibi uygular, doğrula | |||
| 62 | 9. sınıf öğrencisi `scope={"sinif":"9",...}` yazarak 12. sınıf içeriğini | 62 | 9. sınıf öğrencisi `scope={"sinif":"9",...}` yazarak 12. sınıf içeriğini |
| 63 | özetletebiliyordu. Backend bu alanları ya hiç göndermemeli ya da doğru | 63 | özetletebiliyordu. Backend bu alanları ya hiç göndermemeli ya da doğru |
| 64 | değerle göndermelidir. | 64 | değerle göndermelidir. |
| 65 | +- **`payload_too_large`** (2026-09-11, #50) → HTTP **413**. Gövde | ||
| 66 | + `RAG_MAX_BODY_BYTES`'ı aştı ve **ayrıştırılmadan** reddedildi. Backend | ||
| 67 | + isteği küçültmeden tekrar denememelidir. | ||
| 68 | +- **`timeout`** (2026-09-11, #50) → HTTP **504**. İstek `RAG_REQUEST_TIMEOUT_S` | ||
| 69 | + içinde bitmedi. Tekrar denenebilir (idempotent). | ||
| 70 | +- **`service_unavailable`** (2026-09-11, #50) → HTTP **503**. Yakalanmamış bir | ||
| 71 | + hata oluştu. Eskiden bu durumda gövde çıplak `"Internal Server Error"` idi ve | ||
| 72 | + backend sözleşmeye göre **parse edemiyordu** (OPS-06). | ||
| 73 | +- Ayrıca **401** (`X-Service-Token` eksik/yanlış, `RAG_SERVICE_TOKEN` doluysa) ve | ||
| 74 | + **429** (`Retry-After: 60` başlığıyla oran sınırı) dönebilir; bu ikisi FastAPI | ||
| 75 | + `detail` biçimindedir, gövde sözleşmesini taşımaz. | ||
| 76 | +- Her cevapta **`X-Request-Id`** başlığı vardır; istemci kendi değerini | ||
| 77 | + gönderirse aynen yansıtılır (uçtan uca izleme). | ||
| 65 | - boş reason + abstained=false → normal cevap; `citations`'ı tıklanabilir kaynak olarak render et | 78 | - boş reason + abstained=false → normal cevap; `citations`'ı tıklanabilir kaynak olarak render et |
| 66 | (her `[N]` → pages/span → PDF `#page=N` + highlight). **`[N]` metinde vardır; citations onu çözer.** | 79 | (her `[N]` → pages/span → PDF `#page=N` + highlight). **`[N]` metinde vardır; citations onu çözer.** |
| 67 | 80 | ||
src/service/http_app.pymodified+176 -14
| @@ -17,6 +17,8 @@ import os | |||
| 17 | from fastapi import FastAPI, Header, HTTPException, Request | 17 | from fastapi import FastAPI, Header, HTTPException, Request |
| 18 | from fastapi.responses import JSONResponse | 18 | from fastapi.responses import JSONResponse |
| 19 | from pydantic import BaseModel, Field | 19 | from pydantic import BaseModel, Field |
| 20 | +from starlette.middleware.cors import CORSMiddleware | ||
| 21 | +from starlette.middleware.trustedhost import TrustedHostMiddleware | ||
| 20 | 22 | ||
| 21 | # NOT: fastapi import'lari MODUL DUZEYINDE olmak ZORUNDA. `from __future__ import | 23 | # NOT: fastapi import'lari MODUL DUZEYINDE olmak ZORUNDA. `from __future__ import |
| 22 | # annotations` ile tum anotasyonlar STRING olur ve FastAPI bunlari modulun global | 24 | # annotations` ile tum anotasyonlar STRING olur ve FastAPI bunlari modulun global |
| @@ -87,6 +89,96 @@ SERVICE_TOKEN = os.environ.get("RAG_SERVICE_TOKEN") or None # None -> auth KAP | |||
| 87 | EXPOSE_DOCS = os.environ.get("RAG_EXPOSE_DOCS", "0") not in ("0", "", "false", "False") | 89 | EXPOSE_DOCS = os.environ.get("RAG_EXPOSE_DOCS", "0") not in ("0", "", "false", "False") |
| 88 | RATE_LIMIT_PER_MIN = int(os.environ.get("RAG_RATE_LIMIT_PER_MIN", "60")) | 90 | RATE_LIMIT_PER_MIN = int(os.environ.get("RAG_RATE_LIMIT_PER_MIN", "60")) |
| 89 | 91 | ||
| 92 | +# Ham govde siniri: Pydantic alan sinirlari govde AYRISTIRILDIKTAN sonra calisir, | ||
| 93 | +# yani 50 MB'lik bir JSON once tamamen okunur ve parse edilir (bellek + CPU). | ||
| 94 | +# Bu sinir okuma sirasinda, ayristirmadan ONCE uygulanir. | ||
| 95 | +MAX_BODY_BYTES = int(os.environ.get("RAG_MAX_BODY_BYTES", str(256 * 1024))) | ||
| 96 | +# Istek basina son tarih: bir LLM cagrisi asilirsa istek sonsuza kadar asili kalmasin. | ||
| 97 | +REQUEST_TIMEOUT_S = float(os.environ.get("RAG_REQUEST_TIMEOUT_S", "60")) | ||
| 98 | +# Host ve CORS. CORS varsayilan KAPALI: basligi hic gondermemek en guvenli | ||
| 99 | +# varsayilandir (tarayici capraz-kaynak cagriyi zaten reddeder). | ||
| 100 | +ALLOWED_HOSTS = [h.strip() for h in | ||
| 101 | + os.environ.get("RAG_ALLOWED_HOSTS", "*").split(",") if h.strip()] | ||
| 102 | +CORS_ORIGINS = [o.strip() for o in | ||
| 103 | + os.environ.get("RAG_CORS_ORIGINS", "").split(",") if o.strip()] | ||
| 104 | +# Kapanis: uvicorn'a verilir; ucusta olan istekler bitirilir. | ||
| 105 | +GRACEFUL_SHUTDOWN_S = float(os.environ.get("RAG_GRACEFUL_SHUTDOWN_S", "20")) | ||
| 106 | + | ||
| 107 | + | ||
| 108 | +class _BodyLimit: | ||
| 109 | + """Ham govde boyutu siniri (saf ASGI ara katmani). | ||
| 110 | + | ||
| 111 | + NEDEN BaseHTTPMiddleware DEGIL: govdeyi ayristirmadan ONCE, okuma akisi | ||
| 112 | + uzerinde saymak gerekiyor. `Content-Length` basligina GUVENILMEZ -- chunked | ||
| 113 | + aktarimda bu baslik hic gelmez. Bu yuzden hem baslik kontrol edilir hem de | ||
| 114 | + `receive` sarilarak gercekten okunan bayt sayilir; sinir asilirsa 413 doner. | ||
| 115 | + """ | ||
| 116 | + | ||
| 117 | + def __init__(self, app, max_bytes: int): | ||
| 118 | + self.app = app | ||
| 119 | + self.max_bytes = max_bytes | ||
| 120 | + | ||
| 121 | + async def __call__(self, scope, receive, send): | ||
| 122 | + if scope["type"] != "http" or self.max_bytes <= 0: | ||
| 123 | + await self.app(scope, receive, send) | ||
| 124 | + return | ||
| 125 | + for k, v in scope.get("headers", []): | ||
| 126 | + if k == b"content-length": | ||
| 127 | + try: | ||
| 128 | + if int(v) > self.max_bytes: | ||
| 129 | + await self._reddet(send) | ||
| 130 | + return | ||
| 131 | + except ValueError: | ||
| 132 | + pass | ||
| 133 | + okunan = 0 | ||
| 134 | + asildi = False | ||
| 135 | + cevap_verildi = False | ||
| 136 | + | ||
| 137 | + async def _receive(): | ||
| 138 | + # OLCULMUSTU: burada bir istisna FIRLATMAK ise yaramiyor -- FastAPI | ||
| 139 | + # govde ayristirma hatalarini yakalayip 400 "There was an error | ||
| 140 | + # parsing the body" donuyor, yani gercek sebep KAYBOLUYOR. Bu yuzden | ||
| 141 | + # akis kesilir (disconnect) ve 413 cevabini ara katman kendisi yazar. | ||
| 142 | + nonlocal okunan, asildi | ||
| 143 | + msg = await receive() | ||
| 144 | + if msg["type"] == "http.request": | ||
| 145 | + okunan += len(msg.get("body", b"")) | ||
| 146 | + if okunan > self.max_bytes: | ||
| 147 | + asildi = True | ||
| 148 | + return {"type": "http.disconnect"} | ||
| 149 | + return msg | ||
| 150 | + | ||
| 151 | + async def _send(msg): | ||
| 152 | + nonlocal cevap_verildi | ||
| 153 | + if not asildi: | ||
| 154 | + await send(msg) | ||
| 155 | + return | ||
| 156 | + if msg["type"] == "http.response.start" and not cevap_verildi: | ||
| 157 | + cevap_verildi = True | ||
| 158 | + await self._reddet(send) | ||
| 159 | + # sinir asildiktan sonra asagidan gelen govde yutulur | ||
| 160 | + | ||
| 161 | + try: | ||
| 162 | + await self.app(scope, _receive, _send) | ||
| 163 | + except Exception: | ||
| 164 | + if not asildi: | ||
| 165 | + raise # gercek hatalar yukariya, tipli cevaba gitsin | ||
| 166 | + if asildi and not cevap_verildi: | ||
| 167 | + cevap_verildi = True | ||
| 168 | + await self._reddet(send) | ||
| 169 | + | ||
| 170 | + @staticmethod | ||
| 171 | + async def _reddet(send): | ||
| 172 | + import json as _json | ||
| 173 | + govde = _json.dumps({"text": "İstek gövdesi çok büyük.", "abstained": True, | ||
| 174 | + "reason": "payload_too_large", "citations": [], | ||
| 175 | + "used_source_ids": [], "cost_usd": 0.0, | ||
| 176 | + "cache_hit": False}, ensure_ascii=False).encode("utf-8") | ||
| 177 | + await send({"type": "http.response.start", "status": 413, | ||
| 178 | + "headers": [(b"content-type", b"application/json; charset=utf-8"), | ||
| 179 | + (b"content-length", str(len(govde)).encode())]}) | ||
| 180 | + await send({"type": "http.response.body", "body": govde}) | ||
| 181 | + | ||
| 90 | 182 | ||
| 91 | class _RateLimiter: | 183 | class _RateLimiter: |
| 92 | """Cok basit, surec-ici kayan pencere sayaci. | 184 | """Cok basit, surec-ici kayan pencere sayaci. |
| @@ -120,7 +212,10 @@ class _RateLimiter: | |||
| 120 | 212 | ||
| 121 | 213 | ||
| 122 | def create_app(service, *, service_token: str | None = None, | 214 | def create_app(service, *, service_token: str | None = None, |
| 123 | - rate_limit_per_min: int | None = None, expose_docs: bool | None = None): | 215 | + rate_limit_per_min: int | None = None, expose_docs: bool | None = None, |
| 216 | + max_body_bytes: int | None = None, request_timeout_s: float | None = None, | ||
| 217 | + allowed_hosts: list[str] | None = None, | ||
| 218 | + cors_origins: list[str] | None = None): | ||
| 124 | """RagService'i saran FastAPI uygulaması. `service` enjekte edilir (test'te stub; | 219 | """RagService'i saran FastAPI uygulaması. `service` enjekte edilir (test'te stub; |
| 125 | üretimde build_service()). Model yüklemez — yalnız HTTP↔handler eşlemesi. | 220 | üretimde build_service()). Model yüklemez — yalnız HTTP↔handler eşlemesi. |
| 126 | 221 | ||
| @@ -132,6 +227,10 @@ def create_app(service, *, service_token: str | None = None, | |||
| 132 | docs_on = EXPOSE_DOCS if expose_docs is None else expose_docs | 227 | docs_on = EXPOSE_DOCS if expose_docs is None else expose_docs |
| 133 | limiter = _RateLimiter(RATE_LIMIT_PER_MIN if rate_limit_per_min is None | 228 | limiter = _RateLimiter(RATE_LIMIT_PER_MIN if rate_limit_per_min is None |
| 134 | else rate_limit_per_min) | 229 | else rate_limit_per_min) |
| 230 | + body_cap = MAX_BODY_BYTES if max_body_bytes is None else max_body_bytes | ||
| 231 | + deadline = REQUEST_TIMEOUT_S if request_timeout_s is None else request_timeout_s | ||
| 232 | + hosts = ALLOWED_HOSTS if allowed_hosts is None else allowed_hosts | ||
| 233 | + origins = CORS_ORIGINS if cors_origins is None else cors_origins | ||
| 135 | 234 | ||
| 136 | app = FastAPI(title="Hezarfen RAG", version="1.0", | 235 | app = FastAPI(title="Hezarfen RAG", version="1.0", |
| 137 | description="Kaynakla-konuşma + kanıtlı özet + benzer-soru (API-CONTRACT.md)", | 236 | description="Kaynakla-konuşma + kanıtlı özet + benzer-soru (API-CONTRACT.md)", |
| @@ -140,25 +239,58 @@ def create_app(service, *, service_token: str | None = None, | |||
| 140 | redoc_url="/redoc" if docs_on else None, | 239 | redoc_url="/redoc" if docs_on else None, |
| 141 | openapi_url="/openapi.json" if docs_on else None) | 240 | openapi_url="/openapi.json" if docs_on else None) |
| 142 | 241 | ||
| 242 | + def _tipli_hata(status: int, reason: str, metin: str, rid: str) -> JSONResponse: | ||
| 243 | + """API-CONTRACT sozlesmesi: backend her durumda ayni alanlari bekler.""" | ||
| 244 | + return JSONResponse( | ||
| 245 | + status_code=status, | ||
| 246 | + content={"text": metin, "abstained": True, "reason": reason, | ||
| 247 | + "citations": [], "used_source_ids": [], "cost_usd": 0.0, | ||
| 248 | + "cache_hit": False, "request_id": rid}, | ||
| 249 | + headers={"X-Request-Id": rid}) | ||
| 250 | + | ||
| 143 | @app.middleware("http") | 251 | @app.middleware("http") |
| 144 | async def _request_id_and_errors(request: Request, call_next): | 252 | async def _request_id_and_errors(request: Request, call_next): |
| 145 | """#50: her istege `request_id`; yakalanmamis hata CIPLAK 500 yerine | 253 | """#50: her istege `request_id`; yakalanmamis hata CIPLAK 500 yerine |
| 146 | API-CONTRACT'a uygun tipli cevaba cevrilir (OPS-06: stub 429 -> govde | 254 | API-CONTRACT'a uygun tipli cevaba cevrilir (OPS-06: stub 429 -> govde |
| 147 | - `"Internal Server Error"` doonuyordu, backend bunu parse edemiyordu).""" | 255 | + `"Internal Server Error"` doonuyordu, backend bunu parse edemiyordu). |
| 256 | + Ayrica istek basina SON TARIH uygulanir. | ||
| 257 | + | ||
| 258 | + DURUST SINIR: uc noktalar senkron `def` oldugu icin thread havuzunda | ||
| 259 | + kosar; zaman asimi istemciye zamaninda bir cevap DONER ama arkadaki | ||
| 260 | + thread'i iptal ETMEZ (Python'da bir thread disaridan kesilemez). Gercek | ||
| 261 | + iptal saglayici katmaninda timeout ile olur -- DeepSeek istemcisinde | ||
| 262 | + `timeout=120` zaten var; buradaki sinir ondan KISA tutulmali.""" | ||
| 263 | + import asyncio | ||
| 148 | rid = request.headers.get("X-Request-Id") or uuid.uuid4().hex[:16] | 264 | rid = request.headers.get("X-Request-Id") or uuid.uuid4().hex[:16] |
| 149 | try: | 265 | try: |
| 150 | - resp = await call_next(request) | 266 | + if deadline > 0: |
| 267 | + resp = await asyncio.wait_for(call_next(request), timeout=deadline) | ||
| 268 | + else: | ||
| 269 | + resp = await call_next(request) | ||
| 270 | + except (asyncio.TimeoutError, TimeoutError): | ||
| 271 | + return _tipli_hata(504, "timeout", | ||
| 272 | + "Cevap zamaninda hazir olmadi, tekrar dener misin?", rid) | ||
| 151 | except Exception: | 273 | except Exception: |
| 152 | - return JSONResponse( | 274 | + return _tipli_hata(503, "service_unavailable", |
| 153 | - status_code=503, | 275 | + "Şu anda cevap üretemiyorum, biraz sonra tekrar dene.", rid) |
| 154 | - content={"text": "Şu anda cevap üretemiyorum, biraz sonra tekrar dene.", | ||
| 155 | - "abstained": True, "reason": "service_unavailable", | ||
| 156 | - "citations": [], "used_source_ids": [], "cost_usd": 0.0, | ||
| 157 | - "cache_hit": False, "request_id": rid}, | ||
| 158 | - headers={"X-Request-Id": rid}) | ||
| 159 | resp.headers["X-Request-Id"] = rid | 276 | resp.headers["X-Request-Id"] = rid |
| 160 | return resp | 277 | return resp |
| 161 | 278 | ||
| 279 | + # NOT: ara katman sirasi TERSTEN kurulur -- en son eklenen EN DISTA calisir. | ||
| 280 | + # Istenen sira (distan ice): TrustedHost -> CORS -> govde siniri -> request_id. | ||
| 281 | + if body_cap > 0: | ||
| 282 | + app.add_middleware(_BodyLimit, max_bytes=body_cap) | ||
| 283 | + if origins: | ||
| 284 | + # Varsayilan KAPALI: baslik hic gonderilmezse tarayici capraz-kaynak | ||
| 285 | + # cagriyi zaten reddeder. Yalnizca acikca istenirse acilir. | ||
| 286 | + app.add_middleware(CORSMiddleware, allow_origins=origins, | ||
| 287 | + allow_methods=["POST", "GET"], | ||
| 288 | + allow_headers=["Content-Type", "X-Service-Token", | ||
| 289 | + "X-Request-Id"], | ||
| 290 | + max_age=600) | ||
| 291 | + if hosts and hosts != ["*"]: | ||
| 292 | + app.add_middleware(TrustedHostMiddleware, allowed_hosts=hosts) | ||
| 293 | + | ||
| 162 | def _auth(x_service_token: str | None, request: Request) -> None: | 294 | def _auth(x_service_token: str | None, request: Request) -> None: |
| 163 | if token: | 295 | if token: |
| 164 | import hmac | 296 | import hmac |
| @@ -182,7 +314,16 @@ def create_app(service, *, service_token: str | None = None, | |||
| 182 | return JSONResponse(status_code=200 if hazir else 503, | 314 | return JSONResponse(status_code=200 if hazir else 503, |
| 183 | content={"status": "ready" if hazir else "not_ready", | 315 | content={"status": "ready" if hazir else "not_ready", |
| 184 | "ozet": getattr(service, "doc", None) is not None, | 316 | "ozet": getattr(service, "doc", None) is not None, |
| 185 | - "soru": getattr(service, "question_gen", None) is not None}) | 317 | + "soru": getattr(service, "question_gen", None) is not None, |
| 318 | + # operator hangi frenlerin ACIK oldugunu | ||
| 319 | + # gorebilsin (sirrin KENDISI yazilmaz) | ||
| 320 | + "guvenlik": {"token": bool(token), | ||
| 321 | + "oran_limiti": limiter.per_min, | ||
| 322 | + "govde_siniri": body_cap, | ||
| 323 | + "son_tarih_s": deadline, | ||
| 324 | + "docs_acik": bool(docs_on), | ||
| 325 | + "host_siniri": hosts != ["*"], | ||
| 326 | + "cors": bool(origins)}}) | ||
| 186 | 327 | ||
| 187 | @app.post("/rag/chat") | 328 | @app.post("/rag/chat") |
| 188 | def chat(req: ChatRequest, request: Request, | 329 | def chat(req: ChatRequest, request: Request, |
| @@ -265,17 +406,38 @@ def build_service(book_path: str, *, sinif: str, ders: str, corpus_version: str | |||
| 265 | question_gen=QuestionGenerator(), ders=ders) | 406 | question_gen=QuestionGenerator(), ders=ders) |
| 266 | 407 | ||
| 267 | 408 | ||
| 409 | +def _yapilandirma_uyarilari() -> list[str]: | ||
| 410 | + """#50: varsayilanlar GERIYE UYUMLU secildi (mevcut kurulum bozulmasin) ama | ||
| 411 | + bu, uretimde sessizce korumasiz kalmak anlamina gelmemeli. Acilista acikca | ||
| 412 | + soylenir; ayrica `/ready` bunlari makine-okunur bicimde raporlar.""" | ||
| 413 | + u = [] | ||
| 414 | + if not SERVICE_TOKEN: | ||
| 415 | + u.append("RAG_SERVICE_TOKEN yok → uçlar kimlik doğrulamasız (yalnız iç ağda çalıştır)") | ||
| 416 | + if ALLOWED_HOSTS == ["*"]: | ||
| 417 | + u.append("RAG_ALLOWED_HOSTS='*' → Host başlığı doğrulanmıyor") | ||
| 418 | + if EXPOSE_DOCS: | ||
| 419 | + u.append("RAG_EXPOSE_DOCS açık → /docs ve /openapi.json dışarıya açık") | ||
| 420 | + if RATE_LIMIT_PER_MIN <= 0: | ||
| 421 | + u.append("RAG_RATE_LIMIT_PER_MIN=0 → oran sınırı kapalı") | ||
| 422 | + return u | ||
| 423 | + | ||
| 424 | + | ||
| 268 | def main() -> None: | 425 | def main() -> None: |
| 269 | import uvicorn | 426 | import uvicorn |
| 270 | book = os.environ.get("BOOK_PATH", "data/lise/12/biyoloji/kitap.pdf") | 427 | book = os.environ.get("BOOK_PATH", "data/lise/12/biyoloji/kitap.pdf") |
| 271 | sinif = os.environ.get("SINIF", "12") | 428 | sinif = os.environ.get("SINIF", "12") |
| 272 | ders = os.environ.get("DERS", "biyoloji") | 429 | ders = os.environ.get("DERS", "biyoloji") |
| 430 | + for uyari in _yapilandirma_uyarilari(): | ||
| 431 | + print(f"[http][UYARI] {uyari}") | ||
| 273 | print(f"[http] pipeline kuruluyor: {book} ({sinif}/{ders}) — model yüklenecek...") | 432 | print(f"[http] pipeline kuruluyor: {book} ({sinif}/{ders}) — model yüklenecek...") |
| 274 | service = build_service(book, sinif=sinif, ders=ders) | 433 | service = build_service(book, sinif=sinif, ders=ders) |
| 275 | app = create_app(service) | 434 | app = create_app(service) |
| 276 | - print("[http] hazır → http://127.0.0.1:8000 (/health, /rag/chat, /rag/summarize, /rag/questions)") | 435 | + host, port = os.environ.get("HOST", "127.0.0.1"), int(os.environ.get("PORT", "8000")) |
| 277 | - uvicorn.run(app, host=os.environ.get("HOST", "127.0.0.1"), | 436 | + print(f"[http] hazır → http://{host}:{port} (/health, /ready, /rag/*)") |
| 278 | - port=int(os.environ.get("PORT", "8000"))) | 437 | + # #50/OPS-13: graceful shutdown yoktu -- SIGTERM ucusta olan istekleri |
| 438 | + # kesiyordu. Artik acik sureli bekleme var. | ||
| 439 | + uvicorn.run(app, host=host, port=port, | ||
| 440 | + timeout_graceful_shutdown=int(GRACEFUL_SHUTDOWN_S)) | ||
| 279 | 441 | ||
| 280 | 442 | ||
| 281 | if __name__ == "__main__": | 443 | if __name__ == "__main__": |
tests/unit/test_http_hardening.pymodified+156 -2
| @@ -58,10 +58,17 @@ class RequestBoundsTests(unittest.TestCase): | |||
| 58 | def setUp(self): | 58 | def setUp(self): |
| 59 | self.c = _client() | 59 | self.c = _client() |
| 60 | 60 | ||
| 61 | - def test_oversized_query_rejected(self): | 61 | + def test_query_over_field_limit_rejected(self): |
| 62 | - r = self.c.post("/rag/chat", json={"query": "A" * 2_000_000}) | 62 | + """Govde sinirinin ALTINDA ama alan sinirinin USTUNDE -> Pydantic 422.""" |
| 63 | + r = self.c.post("/rag/chat", json={"query": "A" * 5000}) | ||
| 63 | self.assertEqual(r.status_code, 422) | 64 | self.assertEqual(r.status_code, 422) |
| 64 | 65 | ||
| 66 | + def test_oversized_query_rejected_before_parsing(self): | ||
| 67 | + """2 MB govde artik AYRISTIRILMADAN once 413 ile reddedilir.""" | ||
| 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 | + | ||
| 65 | def test_absurd_top_n_rejected(self): | 72 | def test_absurd_top_n_rejected(self): |
| 66 | r = self.c.post("/rag/chat", | 73 | r = self.c.post("/rag/chat", |
| 67 | json={"query": "q", "options": {"top_n": 10 ** 9}}) | 74 | json={"query": "q", "options": {"top_n": 10 ** 9}}) |
| @@ -82,6 +89,11 @@ class RequestBoundsTests(unittest.TestCase): | |||
| 82 | r = self.c.post("/rag/chat", json={"query": "q", "history": hist}) | 89 | r = self.c.post("/rag/chat", json={"query": "q", "history": hist}) |
| 83 | self.assertEqual(r.status_code, 422) | 90 | self.assertEqual(r.status_code, 422) |
| 84 | 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 | + | ||
| 85 | def test_non_numeric_top_n_is_422_not_500(self): | 97 | def test_non_numeric_top_n_is_422_not_500(self): |
| 86 | """Eskiden yakalanmamış ValueError → 500 dönüyordu.""" | 98 | """Eskiden yakalanmamış ValueError → 500 dönüyordu.""" |
| 87 | r = self.c.post("/rag/chat", | 99 | r = self.c.post("/rag/chat", |
| @@ -226,5 +238,147 @@ class ErrorContractTests(unittest.TestCase): | |||
| 226 | self.assertEqual(r.headers.get("X-Request-Id"), "izlenebilir-123") | 238 | self.assertEqual(r.headers.get("X-Request-Id"), "izlenebilir-123") |
| 227 | 239 | ||
| 228 | 240 | ||
| 241 | +@unittest.skipUnless(_HAS_FASTAPI, "fastapi yok") | ||
| 242 | +class BodyLimitTests(unittest.TestCase): | ||
| 243 | + """Ham govde siniri: Pydantic alan sinirlari govde AYRISTIRILDIKTAN sonra | ||
| 244 | + calisir; 50 MB'lik bir JSON once tamamen okunup parse edilirdi.""" | ||
| 245 | + | ||
| 246 | + def test_content_length_header_is_enforced(self): | ||
| 247 | + c = _client(max_body_bytes=1000) | ||
| 248 | + r = c.post("/rag/chat", content=b"x" * 5000, | ||
| 249 | + headers={"Content-Type": "application/json"}) | ||
| 250 | + self.assertEqual(r.status_code, 413) | ||
| 251 | + | ||
| 252 | + def test_chunked_body_without_content_length_is_enforced(self): | ||
| 253 | + """`Content-Length` basligina GUVENILMEZ: chunked aktarimda gelmez. | ||
| 254 | + Bu yuzden okunan bayt AKIS UZERINDE sayilir.""" | ||
| 255 | + def _parcali(): | ||
| 256 | + for _ in range(20): | ||
| 257 | + yield b"x" * 500 | ||
| 258 | + c = _client(max_body_bytes=1000) | ||
| 259 | + r = c.post("/rag/chat", content=_parcali(), | ||
| 260 | + headers={"Content-Type": "application/json"}) | ||
| 261 | + self.assertEqual(r.status_code, 413) | ||
| 262 | + | ||
| 263 | + def test_error_body_follows_the_contract(self): | ||
| 264 | + c = _client(max_body_bytes=100) | ||
| 265 | + body = c.post("/rag/chat", json={"query": "A" * 500}).json() | ||
| 266 | + self.assertTrue(body["abstained"]) | ||
| 267 | + self.assertEqual(body["reason"], "payload_too_large") | ||
| 268 | + self.assertEqual(body["citations"], []) | ||
| 269 | + | ||
| 270 | + def test_normal_body_passes(self): | ||
| 271 | + c = _client(max_body_bytes=256 * 1024) | ||
| 272 | + self.assertEqual(c.post("/rag/chat", json={"query": "q"}).status_code, 200) | ||
| 273 | + | ||
| 274 | + def test_zero_disables_the_limit(self): | ||
| 275 | + c = _client(max_body_bytes=0) | ||
| 276 | + r = c.post("/rag/chat", json={"query": "A" * 5000}) | ||
| 277 | + self.assertEqual(r.status_code, 422) # artik yalniz alan siniri | ||
| 278 | + | ||
| 279 | + | ||
| 280 | +@unittest.skipUnless(_HAS_FASTAPI, "fastapi yok") | ||
| 281 | +class DeadlineTests(unittest.TestCase): | ||
| 282 | + def test_slow_request_returns_typed_504(self): | ||
| 283 | + """Bir LLM cagrisi asilirsa istek sonsuza kadar asili kalmamali.""" | ||
| 284 | + class _Slow(_Service): | ||
| 285 | + def chat(self, req): | ||
| 286 | + import time | ||
| 287 | + time.sleep(0.5) | ||
| 288 | + return {"text": "gec", "abstained": False, "reason": ""} | ||
| 289 | + | ||
| 290 | + c = TestClient(create_app(_Slow(), rate_limit_per_min=0, | ||
| 291 | + request_timeout_s=0.05)) | ||
| 292 | + r = c.post("/rag/chat", json={"query": "q"}) | ||
| 293 | + self.assertEqual(r.status_code, 504) | ||
| 294 | + body = r.json() | ||
| 295 | + self.assertTrue(body["abstained"]) | ||
| 296 | + self.assertEqual(body["reason"], "timeout") | ||
| 297 | + self.assertIn("request_id", body) | ||
| 298 | + | ||
| 299 | + def test_fast_request_unaffected(self): | ||
| 300 | + c = TestClient(create_app(_Service(), rate_limit_per_min=0, | ||
| 301 | + request_timeout_s=5.0)) | ||
| 302 | + self.assertEqual(c.post("/rag/chat", json={"query": "q"}).status_code, 200) | ||
| 303 | + | ||
| 304 | + def test_zero_disables_the_deadline(self): | ||
| 305 | + c = TestClient(create_app(_Service(), rate_limit_per_min=0, | ||
| 306 | + request_timeout_s=0)) | ||
| 307 | + self.assertEqual(c.post("/rag/chat", json={"query": "q"}).status_code, 200) | ||
| 308 | + | ||
| 309 | + | ||
| 310 | +@unittest.skipUnless(_HAS_FASTAPI, "fastapi yok") | ||
| 311 | +class HostAndCorsTests(unittest.TestCase): | ||
| 312 | + def test_untrusted_host_rejected_when_configured(self): | ||
| 313 | + c = TestClient(create_app(_Service(), rate_limit_per_min=0, | ||
| 314 | + allowed_hosts=["rag.ic-ag"])) | ||
| 315 | + self.assertEqual(c.post("/rag/chat", json={"query": "q"}).status_code, 400) | ||
| 316 | + | ||
| 317 | + def test_trusted_host_passes(self): | ||
| 318 | + c = TestClient(create_app(_Service(), rate_limit_per_min=0, | ||
| 319 | + allowed_hosts=["testserver"])) | ||
| 320 | + self.assertEqual(c.post("/rag/chat", json={"query": "q"}).status_code, 200) | ||
| 321 | + | ||
| 322 | + def test_wildcard_keeps_backward_compatibility(self): | ||
| 323 | + c = TestClient(create_app(_Service(), rate_limit_per_min=0, | ||
| 324 | + allowed_hosts=["*"])) | ||
| 325 | + self.assertEqual(c.post("/rag/chat", json={"query": "q"}).status_code, 200) | ||
| 326 | + | ||
| 327 | + def test_cors_closed_by_default(self): | ||
| 328 | + """Basligi HIC gondermemek en guvenli varsayilan: tarayici capraz-kaynak | ||
| 329 | + cagriyi kendisi reddeder.""" | ||
| 330 | + r = _client().post("/rag/chat", json={"query": "q"}, | ||
| 331 | + headers={"Origin": "https://kotu.example"}) | ||
| 332 | + self.assertIsNone(r.headers.get("access-control-allow-origin")) | ||
| 333 | + | ||
| 334 | + def test_cors_only_for_declared_origin(self): | ||
| 335 | + c = TestClient(create_app(_Service(), rate_limit_per_min=0, | ||
| 336 | + cors_origins=["https://hezarfen.example"])) | ||
| 337 | + ok = c.post("/rag/chat", json={"query": "q"}, | ||
| 338 | + headers={"Origin": "https://hezarfen.example"}) | ||
| 339 | + self.assertEqual(ok.headers.get("access-control-allow-origin"), | ||
| 340 | + "https://hezarfen.example") | ||
| 341 | + kotu = c.post("/rag/chat", json={"query": "q"}, | ||
| 342 | + headers={"Origin": "https://kotu.example"}) | ||
| 343 | + self.assertIsNone(kotu.headers.get("access-control-allow-origin")) | ||
| 344 | + | ||
| 345 | + | ||
| 346 | +@unittest.skipUnless(_HAS_FASTAPI, "fastapi yok") | ||
| 347 | +class ConfigVisibilityTests(unittest.TestCase): | ||
| 348 | + def test_ready_reports_which_brakes_are_on(self): | ||
| 349 | + c = TestClient(create_app(_Service(), service_token="gizli", | ||
| 350 | + rate_limit_per_min=30, max_body_bytes=1234, | ||
| 351 | + request_timeout_s=45, allowed_hosts=["testserver"], | ||
| 352 | + cors_origins=[])) | ||
| 353 | + g = c.get("/ready").json()["guvenlik"] | ||
| 354 | + self.assertTrue(g["token"]) | ||
| 355 | + self.assertEqual(g["oran_limiti"], 30) | ||
| 356 | + self.assertEqual(g["govde_siniri"], 1234) | ||
| 357 | + self.assertEqual(g["son_tarih_s"], 45) | ||
| 358 | + self.assertFalse(g["docs_acik"]) | ||
| 359 | + self.assertTrue(g["host_siniri"]) | ||
| 360 | + self.assertFalse(g["cors"]) | ||
| 361 | + | ||
| 362 | + def test_secret_value_is_never_exposed(self): | ||
| 363 | + c = TestClient(create_app(_Service(), service_token="cok-gizli-sir", | ||
| 364 | + rate_limit_per_min=0)) | ||
| 365 | + self.assertNotIn("cok-gizli-sir", c.get("/ready").text) | ||
| 366 | + | ||
| 367 | + def test_unsafe_defaults_are_announced_at_startup(self): | ||
| 368 | + """Varsayilanlar geriye uyumlu (korumasiz) -- ama SESSIZ olmamali.""" | ||
| 369 | + import importlib | ||
| 370 | + from unittest import mock | ||
| 371 | + from src.service import http_app as m | ||
| 372 | + with mock.patch.dict("os.environ", {"RAG_SERVICE_TOKEN": "", | ||
| 373 | + "RAG_ALLOWED_HOSTS": "*"}, clear=False): | ||
| 374 | + m2 = importlib.reload(m) | ||
| 375 | + try: | ||
| 376 | + u = " ".join(m2._yapilandirma_uyarilari()) | ||
| 377 | + self.assertIn("RAG_SERVICE_TOKEN", u) | ||
| 378 | + self.assertIn("RAG_ALLOWED_HOSTS", u) | ||
| 379 | + finally: | ||
| 380 | + importlib.reload(m) | ||
| 381 | + | ||
| 382 | + | ||
| 229 | if __name__ == "__main__": | 383 | if __name__ == "__main__": |
| 230 | unittest.main() | 384 | unittest.main() |