| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | |
| 15 | |
| 16 | |
| 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.llm 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 | |
| 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.llm 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 | |
| 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 | |
| 151 | |
| 152 | |
| 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: |
| 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) |
| 166 | self.assertNotEqual(a, c) |
| 167 | self.assertEqual(len(a), 12) |
| 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") |
| 185 | c.classify("fotosentez nedir") |
| 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() |