-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_langchain.py
More file actions
317 lines (244 loc) · 9.46 KB
/
Copy pathtest_langchain.py
File metadata and controls
317 lines (244 loc) · 9.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
# Copyright (c) 2024-2026 Silmaril Security Inc. All rights reserved.
from __future__ import annotations
from typing import Any
from uuid import uuid4
import pytest
from silmaril_security.sdk import (
BlockResult,
ClassifyEvent,
Firewall,
FirewallBlockedException,
HookLabel,
SilmarilApiError,
)
from silmaril_security.sdk.firewall import _MAX_ERROR_BODY_BYTES
pytest.importorskip("langchain_core.callbacks")
def test_langchain_handlers_reject_invalid_mode_before_classification():
fw = Firewall(api_key="sk", api_url="https://api.test.invalid/classify")
with pytest.raises(ValueError, match="mode must be shadow, warn, or block"):
fw.as_langchain_handler(mode="audit") # type: ignore[arg-type]
with pytest.raises(ValueError, match="mode must be shadow, warn, or block"):
fw.as_async_langchain_handler(mode="audit") # type: ignore[arg-type]
def test_langchain_handler_blocks_last_user_message(monkeypatch):
events: list[ClassifyEvent] = []
fw = Firewall(api_key="sk", api_url="https://api.test.invalid/classify")
handler = fw.as_langchain_handler(on_classify=events.append)
calls = []
def fake_raw(text, *, hook=None, tool_name=None, request_id=None, mode=None):
calls.append((text, hook, tool_name, request_id))
return BlockResult(
prediction="MALICIOUS",
score=0.9,
threshold=0.5,
mode="block",
)
monkeypatch.setattr(fw, "_classify_raw", fake_raw)
run_id = uuid4()
with pytest.raises(FirewallBlockedException):
handler.on_chat_model_start(
serialized={},
messages=[
[
{"role": "system", "content": "system"},
{"role": "user", "content": "first"},
{"role": "assistant", "content": "answer"},
{"role": "user", "content": "second"},
]
],
run_id=run_id,
)
assert calls == [("second", HookLabel.USER_INPUT, None, str(run_id))]
assert len(events) == 1
assert events[0].blocked is True
def test_langchain_handler_fail_open(monkeypatch):
fw = Firewall(api_key="sk", api_url="https://api.test.invalid/classify")
handler = fw.as_langchain_handler()
def fake_raw(text, *, hook=None, tool_name=None, request_id=None, mode=None):
raise SilmarilApiError(status=500, status_text="Internal Server Error", body="boom")
monkeypatch.setattr(fw, "_classify_raw", fake_raw)
handler.on_chat_model_start(
serialized={},
messages=[[{"role": "user", "content": "hello"}]],
run_id=uuid4(),
)
def test_langchain_requested_warn_survives_legacy_mode_less_response(monkeypatch):
fw = Firewall(
api_key="sk",
api_url="https://api.test.invalid/classify",
mode="warn",
)
handler = fw.as_langchain_handler()
monkeypatch.setattr(
fw,
"_post_json",
lambda payload: {
"prediction": "MALICIOUS",
"score": 0.9,
"threshold": 0.5,
},
)
handler.on_chat_model_start(
serialized={},
messages=[[{"role": "user", "content": "attack"}]],
run_id=uuid4(),
)
def test_langchain_effective_warn_preserves_flow(monkeypatch):
events: list[ClassifyEvent] = []
fw = Firewall(api_key="sk", api_url="https://api.test.invalid/classify")
handler = fw.as_langchain_handler(on_classify=events.append)
def fake_raw(text, *, hook=None, tool_name=None, request_id=None, mode=None):
return BlockResult(
prediction="MALICIOUS",
score=0.9,
threshold=0.5,
mode="warn",
)
monkeypatch.setattr(fw, "_classify_raw", fake_raw)
handler.on_chat_model_start(
serialized={},
messages=[[{"role": "user", "content": "hello"}]],
run_id=uuid4(),
)
assert events[0].mode == "warn"
assert events[0].blocked is True
def test_langchain_handler_fail_closed(monkeypatch):
fw = Firewall(api_key="sk", api_url="https://api.test.invalid/classify")
handler = fw.as_langchain_handler(fail_open=False)
def fake_raw(text, *, hook=None, tool_name=None, request_id=None, mode=None):
raise SilmarilApiError(status=500, status_text="Internal Server Error", body="boom")
monkeypatch.setattr(fw, "_classify_raw", fake_raw)
with pytest.raises(SilmarilApiError):
handler.on_chat_model_start(
serialized={},
messages=[[{"role": "user", "content": "hello"}]],
run_id=uuid4(),
)
@pytest.mark.asyncio
async def test_async_langchain_handler_supports_async_callback(monkeypatch):
fw = Firewall(api_key="sk", api_url="https://api.test.invalid/classify")
events: list[ClassifyEvent] = []
async def on_classify(event: ClassifyEvent) -> None:
events.append(event)
handler = fw.as_async_langchain_handler(on_classify=on_classify, shadow_mode=True)
async def fake_async_raw(
firewall,
text,
*,
hook=None,
tool_name=None,
request_id=None,
mode=None,
):
return BlockResult(
prediction="MALICIOUS",
score=0.9,
threshold=0.5,
mode=mode or "block",
)
monkeypatch.setattr("silmaril_security.sdk.langchain._async_classify_raw", fake_async_raw)
await handler.on_chat_model_start(
serialized={},
messages=[[{"role": "user", "content": "hello"}]],
run_id=uuid4(),
)
assert len(events) == 1
assert events[0].blocked is True
assert events[0].shadow_mode is True
@pytest.mark.asyncio
async def test_async_classify_raw_sends_long_event_once(monkeypatch):
from silmaril_security.sdk.langchain import _async_classify_raw
fw = Firewall(api_key="sk", api_url="https://api.test.invalid/classify")
payloads = []
async def fake_post_json(client, firewall, payload):
payloads.append(payload)
return {
"prediction": "BENIGN",
"score": 0.1,
"threshold": 0.5,
"mode": "block",
}
monkeypatch.setattr("silmaril_security.sdk.langchain._async_post_json", fake_post_json)
result = await _async_classify_raw(
fw,
"a" * 4001,
hook=HookLabel.USER_INPUT,
tool_name="chat",
metadata={"langgraph": {"run_id": "async-run"}},
request_id="async-req",
)
assert result.score == 0.1
assert len(payloads) == 1
payload = payloads[0]
assert payload["text"] == "a" * 4001
assert payload["hook"] == "user_input"
assert payload["tool_name"] == "chat"
assert payload["metadata"]["langgraph"] == {"run_id": "async-run"}
assert payload["metadata"]["silmaril"] == {
"sdk_language": "python",
"sdk_version": "0.6.0",
"request_id": "async-req",
}
assert "threshold" not in payload
@pytest.mark.asyncio
async def test_async_langchain_requested_warn_survives_legacy_mode_less_response(monkeypatch):
fw = Firewall(
api_key="sk",
api_url="https://api.test.invalid/classify",
mode="warn",
)
handler = fw.as_async_langchain_handler()
async def fake_post_json(client, firewall, payload):
return {
"prediction": "MALICIOUS",
"score": 0.9,
"threshold": 0.5,
}
monkeypatch.setattr("silmaril_security.sdk.langchain._async_post_json", fake_post_json)
await handler.on_chat_model_start(
serialized={},
messages=[[{"role": "user", "content": "attack"}]],
run_id=uuid4(),
)
@pytest.mark.asyncio
async def test_async_post_json_rejects_redirects():
from silmaril_security.sdk.langchain import _async_post_json
class FakeAsyncResponse:
status_code = 302
headers: dict[str, str] = {}
reason_phrase = "Found"
text = "redirect"
async def aclose(self) -> None:
pass
class FakeAsyncClient:
calls: list[dict[str, Any]]
def __init__(self) -> None:
self.calls = []
async def post(self, url: str, **kwargs: Any) -> FakeAsyncResponse:
self.calls.append({"url": url, **kwargs})
return FakeAsyncResponse()
fw = Firewall(api_key="sk", api_url="https://api.test.invalid/classify")
client = FakeAsyncClient()
with pytest.raises(SilmarilApiError) as exc_info:
await _async_post_json(client, fw, {"text": "hello", "threshold": 0.5})
assert client.calls[0]["follow_redirects"] is False
assert exc_info.value.status == 302
assert exc_info.value.body == "redirect"
@pytest.mark.asyncio
async def test_async_post_json_caps_error_body_and_redacts_message():
from silmaril_security.sdk.langchain import _async_post_json
body = "x" * (_MAX_ERROR_BODY_BYTES + 1024)
class FakeAsyncResponse:
status_code = 500
headers: dict[str, str] = {}
reason_phrase = "Internal Server Error"
text = body
async def aclose(self) -> None:
pass
class FakeAsyncClient:
async def post(self, url: str, **kwargs: Any) -> FakeAsyncResponse:
return FakeAsyncResponse()
fw = Firewall(api_key="sk", api_url="https://api.test.invalid/classify", max_retries=0)
with pytest.raises(SilmarilApiError) as exc_info:
await _async_post_json(FakeAsyncClient(), fw, {"text": "hello", "threshold": 0.5})
assert exc_info.value.body == body[:_MAX_ERROR_BODY_BYTES]
assert body[:128] not in str(exc_info.value)