Ogrenci metni ve ozel nitelikli cikarim loglardan cikarildi
Browse files at this commitcf4dea58705bcc6c7e3dafbc0831402e7b1541e4Parent: daada86- fix
- ogrenci metni ve ozel nitelikli cikarim loglardan cikarildi
7 changed files +367 -3
- .env.example +15 -0
- .gitignore +6 -0
- src/costlog.py +7 -1
- src/guard/audit.py +119 -0
- src/guard/llm_classifier.py +18 -1
- src/memory/history_rewrite.py +9 -1
- tests/unit/test_kvkk_logging.py +193 -0
.env.examplemodified+15 -0
| @@ -35,3 +35,18 @@ GOLDEN_PATH=tests/golden/golden_12bio_v1.json | |||
| 35 | # Optional machine-specific paths; uncomment after installing Tesseract. | 35 | # Optional machine-specific paths; uncomment after installing Tesseract. |
| 36 | # TESSERACT_CMD=C:/Program Files/Tesseract-OCR/tesseract.exe | 36 | # TESSERACT_CMD=C:/Program Files/Tesseract-OCR/tesseract.exe |
| 37 | # HF_HOME=C:/Users/YOUR_USER/.cache/huggingface | 37 | # HF_HOME=C:/Users/YOUR_USER/.cache/huggingface |
| 38 | + | ||
| 39 | +# --- Maliyet defteri + guvenlik olay kaydi (#49, KVKK) --- | ||
| 40 | +# Maliyet defteri yolu. ESKIDEN sabit bir Windows yoluydu (C:/Users/w/...) ve | ||
| 41 | +# Linux'ta calisma dizinine sizip repoya girebiliyordu. Varsayilan: ~/.hezarfen/cost | ||
| 42 | +HEZARFEN_COST_VAULT= | ||
| 43 | +# Guvenlik olay kaydi (zararli/injection kararlari). VARSAYILAN KAPALI -- | ||
| 44 | +# yol verilmezse hicbir sey yazilmaz (veri minimizasyonu). Yazilan kayitta | ||
| 45 | +# SORGU METNI YOKTUR (yalniz uzunluk + kisa hash) ve dosya 0600 izinlidir. | ||
| 46 | +HEZARFEN_AUDIT_PATH= | ||
| 47 | +HEZARFEN_AUDIT_RETENTION_DAYS=30 | ||
| 48 | + | ||
| 49 | +# --- Parent genisletme (#39) --- | ||
| 50 | +# eval ve servis AYNI degeri okur. Varsayilan 0 = uretimin bugunku davranisi. | ||
| 51 | +# Gecmis olcumleri (parent ACIK) yeniden uretmek icin 1. | ||
| 52 | +RAG_INCLUDE_PARENTS=0 | ||
.gitignoremodified+6 -0
| @@ -10,3 +10,9 @@ venv/ | |||
| 10 | .env | 10 | .env |
| 11 | .env.* | 11 | .env.* |
| 12 | !.env.example | 12 | !.env.example |
| 13 | + | ||
| 14 | +# Maliyet defteri (KVKK: PII tasiyabilir) -- asla commitlenmez | ||
| 15 | +C:/ | ||
| 16 | +.hezarfen/ | ||
| 17 | +runs.jsonl | ||
| 18 | +runs.jsonl.lock | ||
src/costlog.pymodified+7 -1
| @@ -37,7 +37,13 @@ except ImportError: | |||
| 37 | from .pricing import (Usage, cost_usd, price_table_rows, | 37 | from .pricing import (Usage, cost_usd, price_table_rows, |
| 38 | PRICING_UPDATED, PRICING_SOURCE, OFFPEAK_FACTOR) | 38 | PRICING_UPDATED, PRICING_SOURCE, OFFPEAK_FACTOR) |
| 39 | 39 | ||
| 40 | -VAULT = r"C:/Users/w/Documents/Hezarfen/rag" | 40 | +# #49 (EXP-010/SEC-10 + OPS-04): bu yol SABIT bir WINDOWS yoluydu ve env |
| 41 | +# override'i yoktu. Linux'ta goreceli cozuluyor ve calisma dizininde gercekten | ||
| 42 | +# `./C:/Users/w/...` klasoru olusuyordu (olculdu) -- `.gitignore`da karsiligi | ||
| 43 | +# olmadigi icin maliyet defteri (ve icindeki her sey) REPOYA SIZABILIYORDU. | ||
| 44 | +# Konteynerde ise imaj katmanina yazip restart'ta kayboluyordu. | ||
| 45 | +VAULT = os.environ.get("HEZARFEN_COST_VAULT") or os.path.join( | ||
| 46 | + os.path.expanduser("~"), ".hezarfen", "cost") | ||
| 41 | LEDGER = os.path.join(VAULT, "runs.jsonl") | 47 | LEDGER = os.path.join(VAULT, "runs.jsonl") |
| 42 | MALIYET = os.path.join(VAULT, "Maliyet.md") | 48 | MALIYET = os.path.join(VAULT, "Maliyet.md") |
| 43 | 49 | ||
src/guard/audit.pyadded+119 -0
| @@ -0,0 +1,119 @@ | |||
| 1 | +"""#49 — güvenlik olay kaydı (maliyet defterinden AYRI, erişimi kısıtlı). | ||
| 2 | + | ||
| 3 | +NEDEN (EXP-010/SEC-10): `llm_classifier` güvenlik kararını `cat=self_harm` gibi | ||
| 4 | +bir etiketle **maliyet defterine** yazıyordu. O defter (`runs.jsonl` + | ||
| 5 | +`Maliyet.md`) şifresiz, genel erişimli ve raporlama amaçlı bir dosya. Ama | ||
| 6 | +"bu kullanıcı self_harm kategorisinde bir soru sordu" bilgisi, **reşit olmayan | ||
| 7 | +bir kişiye ait özel nitelikli (sağlık) veri çıkarımıdır** (KVKK m.6). | ||
| 8 | + | ||
| 9 | +Bu olay kaydı yine de GEREKLİ: güvenlik katmanının çalışıp çalışmadığını | ||
| 10 | +ölçmek, kırmızı-takım sonuçlarını doğrulamak ve bir olay sonrası inceleme | ||
| 11 | +yapmak için lazım. Çözüm kaydı silmek değil, **ayırmak**: | ||
| 12 | + | ||
| 13 | +- ayrı dosya, `0600` izinle (yalnız servis kullanıcısı okur) | ||
| 14 | +- **sorgu metni ASLA yazılmaz** — yalnız uzunluk + kısa hash | ||
| 15 | +- kullanıcı kimliği yazılmaz; çağıran isterse kendi ürettiği opak bir | ||
| 16 | + `oturum_hash` verir (kimliğe geri götürülemez) | ||
| 17 | +- **saklama süresi**: `HEZARFEN_AUDIT_RETENTION_DAYS` (varsayılan 30); | ||
| 18 | + her yazımda süresi dolmuş satırlar atılır | ||
| 19 | +- varsayılan KAPALI: `HEZARFEN_AUDIT_PATH` verilmezse hiçbir şey yazılmaz | ||
| 20 | + (veri minimizasyonu — açıkça istenmediyse toplama) | ||
| 21 | + | ||
| 22 | +DÜRÜST SINIR: bu dosya-tabanlı basit bir kayıttır, tam bir denetim altyapısı | ||
| 23 | +değil. Üretimde erişim kontrolü + silme SLA'sı + şifreleme operasyon | ||
| 24 | +sorumluluğudur (bkz. #85 trace/sink işi). | ||
| 25 | +""" | ||
| 26 | +from __future__ import annotations | ||
| 27 | + | ||
| 28 | +import hashlib | ||
| 29 | +import json | ||
| 30 | +import os | ||
| 31 | +import time | ||
| 32 | +from datetime import datetime, timezone | ||
| 33 | + | ||
| 34 | +AUDIT_PATH = os.environ.get("HEZARFEN_AUDIT_PATH") # None -> kayıt KAPALI | ||
| 35 | +RETENTION_DAYS = int(os.environ.get("HEZARFEN_AUDIT_RETENTION_DAYS", "30")) | ||
| 36 | + | ||
| 37 | + | ||
| 38 | +def query_fingerprint(query: str | None) -> str: | ||
| 39 | + """Sorgunun içeriğini ifşa etmeyen, tekrar-tespitine yeten kısa parmak izi.""" | ||
| 40 | + return hashlib.sha256((query or "").encode("utf-8")).hexdigest()[:12] | ||
| 41 | + | ||
| 42 | + | ||
| 43 | +def _prune(rows: list[dict], now: float) -> list[dict]: | ||
| 44 | + if RETENTION_DAYS <= 0: | ||
| 45 | + return rows | ||
| 46 | + cutoff = now - RETENTION_DAYS * 86400 | ||
| 47 | + return [r for r in rows if float(r.get("ts", 0)) >= cutoff] | ||
| 48 | + | ||
| 49 | + | ||
| 50 | +def record_safety_event(*, category: str, action: str, layer: str, | ||
| 51 | + query: str | None = None, oturum_hash: str | None = None, | ||
| 52 | + path: str | None = None) -> bool: | ||
| 53 | + """Bir güvenlik kararını kaydeder. Döner: yazıldı mı. | ||
| 54 | + | ||
| 55 | + `query` YALNIZ uzunluk + hash üretmek için kullanılır; metin yazılmaz. | ||
| 56 | + `oturum_hash` çağıranın ürettiği opak değerdir (kimlik DEĞİL) — verilmezse | ||
| 57 | + hiç yazılmaz. | ||
| 58 | + | ||
| 59 | + Hata durumunda sessizce False döner: telemetri hatası ASLA bir cevabı | ||
| 60 | + düşürmemeli (aynı ilke `costlog` için #M4-10'da da geçerli). | ||
| 61 | + """ | ||
| 62 | + target = path or AUDIT_PATH | ||
| 63 | + if not target: | ||
| 64 | + return False | ||
| 65 | + now = time.time() | ||
| 66 | + row = { | ||
| 67 | + "ts": now, | ||
| 68 | + "utc": datetime.fromtimestamp(now, timezone.utc).isoformat(timespec="seconds"), | ||
| 69 | + "layer": layer, # "regex" | "llm" | "degraded" | "output" | ||
| 70 | + "action": action, # "refuse" | "allow" | ||
| 71 | + "category": category or "", | ||
| 72 | + "q_len": len(query or ""), | ||
| 73 | + "q_hash": query_fingerprint(query), | ||
| 74 | + } | ||
| 75 | + if oturum_hash: | ||
| 76 | + row["oturum_hash"] = str(oturum_hash)[:32] | ||
| 77 | + try: | ||
| 78 | + os.makedirs(os.path.dirname(target) or ".", exist_ok=True) | ||
| 79 | + rows = [] | ||
| 80 | + if os.path.exists(target): | ||
| 81 | + with open(target, encoding="utf-8") as fh: | ||
| 82 | + for line in fh: | ||
| 83 | + line = line.strip() | ||
| 84 | + if line: | ||
| 85 | + try: | ||
| 86 | + rows.append(json.loads(line)) | ||
| 87 | + except Exception: | ||
| 88 | + continue # bozuk satır kaydı düşürmez | ||
| 89 | + rows = _prune(rows, now) | ||
| 90 | + rows.append(row) | ||
| 91 | + tmp = target + ".tmp" | ||
| 92 | + with open(tmp, "w", encoding="utf-8") as fh: | ||
| 93 | + for r in rows: | ||
| 94 | + fh.write(json.dumps(r, ensure_ascii=False) + "\n") | ||
| 95 | + os.replace(tmp, target) | ||
| 96 | + try: | ||
| 97 | + os.chmod(target, 0o600) # yalnız sahibi okur | ||
| 98 | + except OSError: | ||
| 99 | + pass | ||
| 100 | + return True | ||
| 101 | + except Exception: | ||
| 102 | + return False | ||
| 103 | + | ||
| 104 | + | ||
| 105 | +def read_events(path: str | None = None) -> list[dict]: | ||
| 106 | + """Kayıtları okur (ölçüm/inceleme için). Dosya yoksa boş liste.""" | ||
| 107 | + target = path or AUDIT_PATH | ||
| 108 | + if not target or not os.path.exists(target): | ||
| 109 | + return [] | ||
| 110 | + out = [] | ||
| 111 | + with open(target, encoding="utf-8") as fh: | ||
| 112 | + for line in fh: | ||
| 113 | + line = line.strip() | ||
| 114 | + if line: | ||
| 115 | + try: | ||
| 116 | + out.append(json.loads(line)) | ||
| 117 | + except Exception: | ||
| 118 | + continue | ||
| 119 | + return out | ||
src/guard/llm_classifier.pymodified+18 -1
| @@ -52,6 +52,16 @@ pozitif üretme. YALNIZCA şu JSON'u döndür: \ | |||
| 52 | {"safe": true veya false, "category": "<kategori adı veya null>", "reason": "<kısa gerekçe>"}""" | 52 | {"safe": true veya false, "category": "<kategori adı veya null>", "reason": "<kısa gerekçe>"}""" |
| 53 | 53 | ||
| 54 | 54 | ||
| 55 | +def _audit(category: str, action: str, layer: str, query: str | None) -> None: | ||
| 56 | + """#49: guvenlik karari AYRI, erisimi kisitli olay kaydina yazilir | ||
| 57 | + (maliyet defterine DEGIL). Varsayilan KAPALI; hata cevabi dusurmez.""" | ||
| 58 | + try: | ||
| 59 | + from .audit import record_safety_event | ||
| 60 | + record_safety_event(category=category, action=action, layer=layer, query=query) | ||
| 61 | + except Exception: | ||
| 62 | + pass | ||
| 63 | + | ||
| 64 | + | ||
| 55 | # #44 -- DEGRADE MOD taramasi. YALNIZ LLM katmani erisilemez oldugunda calisir. | 65 | # #44 -- DEGRADE MOD taramasi. YALNIZ LLM katmani erisilemez oldugunda calisir. |
| 56 | # input_guard'dan DAHA GENIS tutulur: burada amac precision degil RECALL. | 66 | # input_guard'dan DAHA GENIS tutulur: burada amac precision degil RECALL. |
| 57 | # Yanlis pozitif bedeli "bir soru reddedildi"; kacirma bedeli resit olmayan bir | 67 | # Yanlis pozitif bedeli "bir soru reddedildi"; kacirma bedeli resit olmayan bir |
| @@ -84,6 +94,7 @@ def _degraded_scan(query: str) -> GuardVerdict: | |||
| 84 | if not _ud.combining(c)).replace("ı", "i") | 94 | if not _ud.combining(c)).replace("ı", "i") |
| 85 | for pat, cat in _DEGRADED_PATTERNS: | 95 | for pat, cat in _DEGRADED_PATTERNS: |
| 86 | if _re.search(pat, ascii_folded, _re.IGNORECASE): | 96 | if _re.search(pat, ascii_folded, _re.IGNORECASE): |
| 97 | + _audit(cat, "refuse", "degraded", query) | ||
| 87 | return GuardVerdict(action="refuse", category=cat, | 98 | return GuardVerdict(action="refuse", category=cat, |
| 88 | message=_CLASSIFIER_MESSAGES.get( | 99 | message=_CLASSIFIER_MESSAGES.get( |
| 89 | cat, _HARM_MESSAGES["hate_harassment"]), | 100 | cat, _HARM_MESSAGES["hate_harassment"]), |
| @@ -131,8 +142,13 @@ class LLMSafetyClassifier: | |||
| 131 | 142 | ||
| 132 | # maliyet kaydı (gerçek DeepSeek çağrısı) — costlog başarısız olsa bile karar etkilenmez | 143 | # maliyet kaydı (gerçek DeepSeek çağrısı) — costlog başarısız olsa bile karar etkilenmez |
| 133 | try: | 144 | try: |
| 145 | + # #49 (EXP-010/SEC-10) KVKK: `cat=self_harm` gibi bir ETIKET, resit | ||
| 146 | + # olmayan bir kullaniciya ait OZEL NITELIKLI (saglik) veri cikarimidir | ||
| 147 | + # ve maliyet defteri sifresiz + genel erisimli bir dosyadir. Maliyet | ||
| 148 | + # kaydinda artik yalnizca "bir karar verildi" bilgisi durur; kategori | ||
| 149 | + # erisimi kisitli guvenlik olay kaydina aittir (bkz. asagi). | ||
| 134 | self._record(module=self.module, model=r.model, usage=r.usage, items=1, | 150 | self._record(module=self.module, model=r.model, usage=r.usage, items=1, |
| 135 | - note=f"llm-safety: safe={data.get('safe')} cat={data.get('category')}") | 151 | + note="llm-safety: karar kaydedildi") |
| 136 | except Exception: | 152 | except Exception: |
| 137 | pass | 153 | pass |
| 138 | 154 | ||
| @@ -151,6 +167,7 @@ class LLMSafetyClassifier: | |||
| 151 | cat = cat_raw or "hate_harassment" | 167 | cat = cat_raw or "hate_harassment" |
| 152 | if cat not in _CLASSIFIER_MESSAGES: | 168 | if cat not in _CLASSIFIER_MESSAGES: |
| 153 | cat = "hate_harassment" | 169 | cat = "hate_harassment" |
| 170 | + _audit(cat, "refuse", "llm", query) | ||
| 154 | return GuardVerdict(action="refuse", category=cat, | 171 | return GuardVerdict(action="refuse", category=cat, |
| 155 | message=_CLASSIFIER_MESSAGES[cat], score=1.0) | 172 | message=_CLASSIFIER_MESSAGES[cat], score=1.0) |
| 156 | return GuardVerdict(action="allow", category="", message="", score=0.0) | 173 | return GuardVerdict(action="allow", category="", message="", score=0.0) |
src/memory/history_rewrite.pymodified+9 -1
| @@ -56,8 +56,16 @@ class HistoryAwareRewriter: | |||
| 56 | except Exception: | 56 | except Exception: |
| 57 | return query # FAIL-SAFE: hata → orijinal sorgu (tek-turlu davran) | 57 | return query # FAIL-SAFE: hata → orijinal sorgu (tek-turlu davran) |
| 58 | try: | 58 | try: |
| 59 | + # #49 (EXP-010/SEC-10) KVKK: burada ogrencinin YAZDIGI metnin ilk 30 | ||
| 60 | + # karakteri `runs.jsonl`a ve oradan `Maliyet.md` tablosuna DUZ METIN | ||
| 61 | + # olarak geciyordu. Veri minimizasyonu geregi metin artik yazilmaz; | ||
| 62 | + # teshis icin uzunluk + kisa hash yeter (ayni sorgu tekrar mi geldi | ||
| 63 | + # sorusu hash ile hâlâ cevaplanabilir, icerik ifsa olmadan). | ||
| 64 | + import hashlib | ||
| 65 | + qh = hashlib.sha256((query or "").encode("utf-8")).hexdigest()[:8] | ||
| 59 | self._record(module=self.module, model=r.model, usage=r.usage, items=1, | 66 | self._record(module=self.module, model=r.model, usage=r.usage, items=1, |
| 60 | - note=f"history-rewrite: '{query[:30]}' -> '{rewritten[:30]}'") | 67 | + note=(f"history-rewrite: q_len={len(query or '')} " |
| 68 | + f"q_hash={qh} rewritten_len={len(rewritten)}")) | ||
| 61 | except Exception: | 69 | except Exception: |
| 62 | pass | 70 | pass |
| 63 | return rewritten | 71 | return rewritten |
tests/unit/test_kvkk_logging.pyadded+193 -0
| @@ -0,0 +1,193 @@ | |||
| 1 | +"""#49 — KVKK: öğrenci metni ve özel nitelikli çıkarım loglardan çıkarıldı. | ||
| 2 | + | ||
| 3 | +NEDEN (EXP-010/SEC-10 + OPS-04): | ||
| 4 | +- `memory/history_rewrite.py` `note=f"history-rewrite: '{query[:30]}' -> ..."` | ||
| 5 | + ile **öğrencinin yazdığı metni** `runs.jsonl`'a ve oradan `Maliyet.md` | ||
| 6 | + tablosuna **düz metin** olarak yazıyordu. | ||
| 7 | +- `guard/llm_classifier.py` `cat=self_harm` yazıyordu → reşit olmayan bir | ||
| 8 | + kişiye ait **özel nitelikli (sağlık) veri çıkarımı**, zaman damgasıyla, | ||
| 9 | + şifresiz ve genel erişimli bir dosyada (KVKK m.6 + veri minimizasyonu). | ||
| 10 | +- `costlog.VAULT` sabit bir **Windows** yoluydu (`C:/Users/w/...`), env override | ||
| 11 | + yoktu → Linux'ta çalışma dizininde gerçekten `./C:/Users/w/...` klasörü | ||
| 12 | + oluşuyordu (ölçüldü) ve `.gitignore`'da karşılığı olmadığı için **PII repoya | ||
| 13 | + sızabiliyordu**. | ||
| 14 | + | ||
| 15 | +Çözüm kaydı silmek değil AYIRMAK: güvenlik olayları erişimi kısıtlı, saklama | ||
| 16 | +süreli ayrı bir dosyaya; maliyet defterinde yalnız sayısal telemetri. | ||
| 17 | +""" | ||
| 18 | +import json | ||
| 19 | +import os | ||
| 20 | +import tempfile | ||
| 21 | +import unittest | ||
| 22 | +from unittest import mock | ||
| 23 | + | ||
| 24 | +from src.guard import audit | ||
| 25 | + | ||
| 26 | + | ||
| 27 | +class CostLedgerHasNoUserTextTests(unittest.TestCase): | ||
| 28 | + def test_history_rewrite_note_carries_no_query_text(self): | ||
| 29 | + from src.memory.history_rewrite import HistoryAwareRewriter | ||
| 30 | + notes = [] | ||
| 31 | + | ||
| 32 | + class _P: | ||
| 33 | + _api_key = "x" | ||
| 34 | + | ||
| 35 | + def chat(self, prompt, system=None, **kw): | ||
| 36 | + from src.pricing import Usage | ||
| 37 | + from src.providers.deepseek import ChatResult | ||
| 38 | + return ChatResult(text="Bağımsız soru", usage=Usage(), model="stub") | ||
| 39 | + | ||
| 40 | + r = HistoryAwareRewriter(_P(), cost_recorder=lambda **kw: notes.append(kw)) | ||
| 41 | + gizli = "Ben çok kötüyüm ve kendime zarar vermek istiyorum" | ||
| 42 | + r.rewrite([{"role": "user", "content": "önceki"}], gizli) | ||
| 43 | + | ||
| 44 | + self.assertTrue(notes) | ||
| 45 | + note = notes[0]["note"] | ||
| 46 | + self.assertNotIn("kötüyüm", note) | ||
| 47 | + self.assertNotIn("zarar", note) | ||
| 48 | + self.assertNotIn(gizli[:20], note) | ||
| 49 | + # teşhis için gereken şey DURUYOR | ||
| 50 | + self.assertIn("q_len=", note) | ||
| 51 | + self.assertIn("q_hash=", note) | ||
| 52 | + | ||
| 53 | + def test_safety_category_not_written_to_cost_ledger(self): | ||
| 54 | + from src.guard.llm_classifier import LLMSafetyClassifier | ||
| 55 | + notes = [] | ||
| 56 | + | ||
| 57 | + class _P: | ||
| 58 | + _api_key = "x" | ||
| 59 | + | ||
| 60 | + def chat(self, *a, **kw): | ||
| 61 | + from src.pricing import Usage | ||
| 62 | + from src.providers.deepseek import ChatResult | ||
| 63 | + return ChatResult(text='{"safe": false, "category": "self_harm"}', | ||
| 64 | + usage=Usage(), model="stub") | ||
| 65 | + | ||
| 66 | + c = LLMSafetyClassifier(_P(), cost_recorder=lambda **kw: notes.append(kw)) | ||
| 67 | + c.classify("gizli bir soru") | ||
| 68 | + self.assertTrue(notes) | ||
| 69 | + self.assertNotIn("self_harm", notes[0]["note"]) | ||
| 70 | + | ||
| 71 | + def test_cost_vault_is_configurable_and_not_windows(self): | ||
| 72 | + import importlib | ||
| 73 | + from src import costlog | ||
| 74 | + self.assertNotIn("C:/Users", costlog.VAULT) | ||
| 75 | + with mock.patch.dict(os.environ, {"HEZARFEN_COST_VAULT": "/tmp/hz-test"}): | ||
| 76 | + m = importlib.reload(costlog) | ||
| 77 | + try: | ||
| 78 | + self.assertEqual(m.VAULT, "/tmp/hz-test") | ||
| 79 | + finally: | ||
| 80 | + importlib.reload(costlog) | ||
| 81 | + | ||
| 82 | + def test_gitignore_blocks_the_ledger(self): | ||
| 83 | + with open(".gitignore", encoding="utf-8") as fh: | ||
| 84 | + ig = fh.read() | ||
| 85 | + for pat in ("runs.jsonl", ".hezarfen/", "C:/"): | ||
| 86 | + self.assertIn(pat, ig, f"{pat} .gitignore'da yok") | ||
| 87 | + | ||
| 88 | + | ||
| 89 | +class SafetyAuditLogTests(unittest.TestCase): | ||
| 90 | + def setUp(self): | ||
| 91 | + self.d = tempfile.mkdtemp() | ||
| 92 | + self.path = os.path.join(self.d, "sec.jsonl") | ||
| 93 | + | ||
| 94 | + def test_disabled_by_default(self): | ||
| 95 | + """Veri minimizasyonu: açıkça istenmediyse hiçbir şey toplanmaz.""" | ||
| 96 | + with mock.patch.object(audit, "AUDIT_PATH", None): | ||
| 97 | + self.assertFalse(audit.record_safety_event( | ||
| 98 | + category="self_harm", action="refuse", layer="llm", query="x")) | ||
| 99 | + | ||
| 100 | + def test_records_without_query_text(self): | ||
| 101 | + gizli = "kendime zarar vermek istiyorum çünkü ..." | ||
| 102 | + audit.record_safety_event(category="self_harm", action="refuse", | ||
| 103 | + layer="llm", query=gizli, path=self.path) | ||
| 104 | + with open(self.path, encoding="utf-8") as fh: | ||
| 105 | + raw = fh.read() | ||
| 106 | + self.assertNotIn("zarar", raw) | ||
| 107 | + self.assertNotIn("çünkü", raw) | ||
| 108 | + row = json.loads(raw.strip()) | ||
| 109 | + self.assertEqual(row["category"], "self_harm") | ||
| 110 | + self.assertEqual(row["q_len"], len(gizli)) | ||
| 111 | + self.assertEqual(len(row["q_hash"]), 12) | ||
| 112 | + | ||
| 113 | + def test_no_user_identity_unless_opaque_hash_given(self): | ||
| 114 | + audit.record_safety_event(category="violence_weapons", action="refuse", | ||
| 115 | + layer="regex", query="q", path=self.path) | ||
| 116 | + with open(self.path, encoding="utf-8") as fh: | ||
| 117 | + row = json.loads(fh.read().strip()) | ||
| 118 | + self.assertNotIn("oturum_hash", row) | ||
| 119 | + audit.record_safety_event(category="violence_weapons", action="refuse", | ||
| 120 | + layer="regex", query="q", path=self.path, | ||
| 121 | + oturum_hash="opak-deger") | ||
| 122 | + rows = audit.read_events(self.path) | ||
| 123 | + self.assertEqual(rows[-1]["oturum_hash"], "opak-deger") | ||
| 124 | + | ||
| 125 | + def test_file_permissions_are_owner_only(self): | ||
| 126 | + audit.record_safety_event(category="self_harm", action="refuse", | ||
| 127 | + layer="llm", query="x", path=self.path) | ||
| 128 | + self.assertEqual(os.stat(self.path).st_mode & 0o777, 0o600) | ||
| 129 | + | ||
| 130 | + def test_retention_drops_old_rows(self): | ||
| 131 | + import time | ||
| 132 | + old = {"ts": time.time() - 400 * 86400, "category": "eski"} | ||
| 133 | + with open(self.path, "w", encoding="utf-8") as fh: | ||
| 134 | + fh.write(json.dumps(old) + "\n") | ||
| 135 | + audit.record_safety_event(category="self_harm", action="refuse", | ||
| 136 | + layer="llm", query="x", path=self.path) | ||
| 137 | + rows = audit.read_events(self.path) | ||
| 138 | + self.assertEqual(len(rows), 1) | ||
| 139 | + self.assertEqual(rows[0]["category"], "self_harm") | ||
| 140 | + | ||
| 141 | + def test_corrupt_line_does_not_lose_the_log(self): | ||
| 142 | + with open(self.path, "w", encoding="utf-8") as fh: | ||
| 143 | + fh.write("{bozuk\n") | ||
| 144 | + self.assertTrue(audit.record_safety_event( | ||
| 145 | + category="self_harm", action="refuse", layer="llm", query="x", | ||
| 146 | + path=self.path)) | ||
| 147 | + self.assertEqual(len(audit.read_events(self.path)), 1) | ||
| 148 | + | ||
| 149 | + def test_failure_never_raises(self): | ||
| 150 | + """Telemetri hatası bir cevabı ASLA düşürmemeli. | ||
| 151 | + `/dev/null` bir DOSYA olduğu için altına dizin açılamaz → yazım başarısız, | ||
| 152 | + ama fonksiyon istisna fırlatmaz, False döner.""" | ||
| 153 | + try: | ||
| 154 | + ok = audit.record_safety_event( | ||
| 155 | + category="x", action="refuse", layer="llm", query="q", | ||
| 156 | + path="/dev/null/alt/sec.jsonl") | ||
| 157 | + except Exception as e: # pragma: no cover | ||
| 158 | + self.fail(f"telemetri hatası istisna fırlattı: {e!r}") | ||
| 159 | + self.assertFalse(ok) | ||
| 160 | + | ||
| 161 | + def test_fingerprint_is_stable_and_opaque(self): | ||
| 162 | + a = audit.query_fingerprint("aynı soru") | ||
| 163 | + b = audit.query_fingerprint("aynı soru") | ||
| 164 | + c = audit.query_fingerprint("başka soru") | ||
| 165 | + self.assertEqual(a, b) # tekrar tespiti mümkün | ||
| 166 | + self.assertNotEqual(a, c) | ||
| 167 | + self.assertEqual(len(a), 12) # geri çevrilemez | ||
| 168 | + | ||
| 169 | + | ||
| 170 | +class ClassifierWritesToAuditTests(unittest.TestCase): | ||
| 171 | + def test_refusal_is_recorded_allow_is_not(self): | ||
| 172 | + from src.guard.llm_classifier import LLMSafetyClassifier | ||
| 173 | + d = tempfile.mkdtemp() | ||
| 174 | + path = os.path.join(d, "sec.jsonl") | ||
| 175 | + | ||
| 176 | + class _Broken: | ||
| 177 | + _api_key = "x" | ||
| 178 | + | ||
| 179 | + def chat(self, *a, **kw): | ||
| 180 | + raise RuntimeError("429") | ||
| 181 | + | ||
| 182 | + with mock.patch.object(audit, "AUDIT_PATH", path): | ||
| 183 | + c = LLMSafetyClassifier(_Broken(), cost_recorder=lambda **kw: None) | ||
| 184 | + c.classify("intihar etmek istiyorum") # refuse | ||
| 185 | + c.classify("fotosentez nedir") # allow | ||
| 186 | + rows = audit.read_events(path) | ||
| 187 | + self.assertEqual(len(rows), 1) | ||
| 188 | + self.assertEqual(rows[0]["action"], "refuse") | ||
| 189 | + self.assertEqual(rows[0]["layer"], "degraded") | ||
| 190 | + | ||
| 191 | + | ||
| 192 | +if __name__ == "__main__": | ||
| 193 | + unittest.main() | ||