Repository navigation
Expand file tree
/
Copy pathtest_hooks.py
More file actions
440 lines (341 loc) · 15.1 KB
/
Copy pathtest_hooks.py
File metadata and controls
440 lines (341 loc) · 15.1 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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
"""Tests for airlock.hooks — Claude Code hook scripts and _common utilities."""
from __future__ import annotations
import http.server
import json
import threading
from io import StringIO
import pytest
from airlock.hooks._common import (
block,
get_blocked_keywords,
probe_health,
proceed,
read_hook_input,
respond_json,
)
# ===================================================================
# _common.py
# ===================================================================
class TestReadHookInput:
def test_parses_json_from_stdin(self, monkeypatch):
monkeypatch.setattr("sys.stdin", StringIO('{"prompt": "hello"}'))
result = read_hook_input()
assert result == {"prompt": "hello"}
def test_raises_on_invalid_json(self, monkeypatch):
monkeypatch.setattr("sys.stdin", StringIO("not json"))
with pytest.raises(json.JSONDecodeError):
read_hook_input()
class TestBlock:
def test_exits_with_code_2(self, capsys):
with pytest.raises(SystemExit) as exc_info:
block("denied")
assert exc_info.value.code == 2
assert "denied" in capsys.readouterr().err
class TestProceed:
def test_exits_with_code_0(self):
with pytest.raises(SystemExit) as exc_info:
proceed()
assert exc_info.value.code == 0
class TestRespondJson:
def test_outputs_json_to_stdout(self, capsys):
with pytest.raises(SystemExit) as exc_info:
respond_json({"key": "value"})
assert exc_info.value.code == 0
out = capsys.readouterr().out
assert json.loads(out) == {"key": "value"}
class TestGetBlockedKeywords:
def test_empty_when_unset(self, monkeypatch):
monkeypatch.delenv("AIRLOCK_BLOCKED_KEYWORDS", raising=False)
assert get_blocked_keywords() == []
def test_parses_comma_separated(self, monkeypatch):
monkeypatch.setenv("AIRLOCK_BLOCKED_KEYWORDS", "secret, Project X ,alpha")
result = get_blocked_keywords()
assert result == ["secret", "project x", "alpha"]
def test_ignores_empty_entries(self, monkeypatch):
monkeypatch.setenv("AIRLOCK_BLOCKED_KEYWORDS", "foo,,bar,")
assert get_blocked_keywords() == ["foo", "bar"]
class TestProbeHealth:
@pytest.fixture()
def _auth_server(self):
"""HTTP server that requires Bearer auth and records request headers."""
self.last_headers: dict = {}
self.last_path: str = ""
parent = self
class _Handler(http.server.BaseHTTPRequestHandler):
def do_GET(self): # noqa: N802
parent.last_headers = dict(self.headers)
parent.last_path = self.path
auth = self.headers.get("Authorization", "")
if auth == "Bearer test-key-123":
self.send_response(200)
else:
self.send_response(400)
self.end_headers()
self.wfile.write(b"OK")
def log_message(self, *_args): # noqa: ANN002
pass
server = http.server.HTTPServer(("127.0.0.1", 0), _Handler)
port = server.server_address[1]
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
self.host = "127.0.0.1"
self.port = str(port)
yield
server.shutdown()
def test_returns_true_when_healthy(self, _auth_server, monkeypatch):
monkeypatch.setenv("AIRLOCK_MASTER_KEY", "test-key-123")
assert probe_health(self.host, self.port) is True
def test_returns_false_when_unreachable(self):
assert probe_health("127.0.0.1", "19999", timeout=1) is False
def test_sends_auth_header_when_master_key_set(self, _auth_server, monkeypatch):
"""Regression: hooks must send Authorization header when master key is set."""
monkeypatch.setenv("AIRLOCK_MASTER_KEY", "test-key-123")
probe_health(self.host, self.port)
assert self.last_headers.get("Authorization") == "Bearer test-key-123"
def test_sends_airlock_client_header_when_set(self, _auth_server, monkeypatch):
monkeypatch.setenv("AIRLOCK_MASTER_KEY", "test-key-123")
monkeypatch.setenv("AIRLOCK_CLIENT", "codex-review")
probe_health(self.host, self.port, client="test-client")
assert self.last_headers.get("X-Airlock-Client") == "codex-review"
def test_includes_client_query_param(self, _auth_server, monkeypatch):
"""Health probes include ?client= for identification in proxy logs."""
monkeypatch.setenv("AIRLOCK_MASTER_KEY", "test-key-123")
self.last_path = ""
probe_health(self.host, self.port, client="test-client")
assert "client=test-client" in self.last_path
def test_default_client_is_hook(self, _auth_server, monkeypatch):
"""Default client identifier is 'hook'."""
monkeypatch.setenv("AIRLOCK_MASTER_KEY", "test-key-123")
self.last_path = ""
probe_health(self.host, self.port)
assert "client=hook" in self.last_path
def test_no_auth_header_when_master_key_unset(self, _auth_server, monkeypatch):
monkeypatch.delenv("AIRLOCK_MASTER_KEY", raising=False)
probe_health(self.host, self.port)
assert "Authorization" not in self.last_headers
def test_returns_false_without_auth_on_protected_server(
self, _auth_server, monkeypatch
):
"""Server requiring auth returns 400 — probe must fail without key."""
monkeypatch.delenv("AIRLOCK_MASTER_KEY", raising=False)
# Server returns 400 for missing/wrong auth; urllib raises HTTPError
# probe_health catches all exceptions → returns False
assert probe_health(self.host, self.port) is False
class TestDotenvLoading:
"""Hooks run as separate processes — they must load .env for env vars."""
def test_common_module_calls_load_dotenv(self):
"""Regression: _common.py must call load_dotenv() at import time.
Without this, hooks spawned as separate processes by Claude Code
won't pick up AIRLOCK_MASTER_KEY from .env, causing health probes
to hit /health without auth → 400 spam in LiteLLM logs.
"""
import ast
import inspect
source = inspect.getsource(
__import__("airlock.hooks._common", fromlist=["_common"])
)
tree = ast.parse(source)
# Check for load_dotenv() call at module level
has_load_dotenv = False
for node in ast.walk(tree):
if isinstance(node, ast.Call):
func = node.func
if isinstance(func, ast.Name) and func.id == "load_dotenv":
has_load_dotenv = True
elif isinstance(func, ast.Attribute) and func.attr == "load_dotenv":
has_load_dotenv = True
assert has_load_dotenv, (
"airlock.hooks._common must call load_dotenv() at module level "
"so hooks spawned as separate processes pick up .env values"
)
def test_common_imports_dotenv(self):
"""_common.py must import from dotenv."""
# Module should have loaded dotenv — verify the function is accessible
import dotenv
assert hasattr(dotenv, "load_dotenv")
# ===================================================================
# session_start.py
# ===================================================================
class TestSessionStart:
def test_reports_proxy_running(self, monkeypatch, capsys):
monkeypatch.setattr(
"airlock.hooks.session_start.probe_health", lambda *a, **kw: True
)
monkeypatch.setenv("AIRLOCK_HOST", "localhost")
monkeypatch.setenv("AIRLOCK_PORT", "4000")
from airlock.hooks.session_start import main
with pytest.raises(SystemExit) as exc_info:
main()
assert exc_info.value.code == 0
out = json.loads(capsys.readouterr().out)
assert "running" in out["additionalContext"]
def test_reports_proxy_down(self, monkeypatch, capsys):
monkeypatch.setattr(
"airlock.hooks.session_start.probe_health", lambda *a, **kw: False
)
monkeypatch.setenv("AIRLOCK_HOST", "localhost")
monkeypatch.setenv("AIRLOCK_PORT", "4000")
from airlock.hooks.session_start import main
with pytest.raises(SystemExit) as exc_info:
main()
assert exc_info.value.code == 0
out = json.loads(capsys.readouterr().out)
ctx = out["additionalContext"]
assert "NOT reachable" in ctx
assert "airlock start" in ctx
assert "unset ANTHROPIC_BASE_URL" in ctx
# ===================================================================
# pre_submit.py
# ===================================================================
class TestPreSubmit:
def test_proceeds_when_no_keywords(self, monkeypatch):
monkeypatch.delenv("AIRLOCK_BLOCKED_KEYWORDS", raising=False)
from airlock.hooks.pre_submit import main
with pytest.raises(SystemExit) as exc_info:
main()
assert exc_info.value.code == 0
def test_proceeds_when_clean(self, monkeypatch):
monkeypatch.setenv("AIRLOCK_BLOCKED_KEYWORDS", "secret")
monkeypatch.setattr("sys.stdin", StringIO('{"prompt": "hello world"}'))
from airlock.hooks.pre_submit import main
with pytest.raises(SystemExit) as exc_info:
main()
assert exc_info.value.code == 0
def test_blocks_on_keyword_match(self, monkeypatch, capsys):
monkeypatch.setenv("AIRLOCK_BLOCKED_KEYWORDS", "secret,classified")
monkeypatch.setattr(
"sys.stdin", StringIO('{"prompt": "tell me the Secret plan"}')
)
from airlock.hooks.pre_submit import main
with pytest.raises(SystemExit) as exc_info:
main()
assert exc_info.value.code == 2
err = capsys.readouterr().err
assert "restricted content" in err
# Should not echo the keyword back
assert "secret" not in err.lower().replace("restricted", "")
def test_case_insensitive_matching(self, monkeypatch, capsys):
monkeypatch.setenv("AIRLOCK_BLOCKED_KEYWORDS", "Project X")
monkeypatch.setattr(
"sys.stdin", StringIO('{"prompt": "what about PROJECT X?"}')
)
from airlock.hooks.pre_submit import main
with pytest.raises(SystemExit) as exc_info:
main()
assert exc_info.value.code == 2
# ===================================================================
# pre_tool.py
# ===================================================================
class TestPreTool:
def test_blocks_env_file(self, monkeypatch, capsys):
monkeypatch.setattr(
"sys.stdin",
StringIO(json.dumps({"tool_input": {"file_path": "/project/.env"}})),
)
monkeypatch.delenv("AIRLOCK_PROTECTED_PATHS", raising=False)
from airlock.hooks.pre_tool import main
with pytest.raises(SystemExit) as exc_info:
main()
assert exc_info.value.code == 2
assert ".env" in capsys.readouterr().err
def test_blocks_config_yaml(self, monkeypatch, capsys):
monkeypatch.setattr(
"sys.stdin",
StringIO(json.dumps({"tool_input": {"file_path": "/project/config.yaml"}})),
)
monkeypatch.delenv("AIRLOCK_PROTECTED_PATHS", raising=False)
from airlock.hooks.pre_tool import main
with pytest.raises(SystemExit) as exc_info:
main()
assert exc_info.value.code == 2
assert "config.yaml" in capsys.readouterr().err
def test_allows_other_files(self, monkeypatch):
monkeypatch.setattr(
"sys.stdin",
StringIO(json.dumps({"tool_input": {"file_path": "/project/src/app.py"}})),
)
monkeypatch.delenv("AIRLOCK_PROTECTED_PATHS", raising=False)
from airlock.hooks.pre_tool import main
with pytest.raises(SystemExit) as exc_info:
main()
assert exc_info.value.code == 0
def test_custom_protected_paths(self, monkeypatch, capsys):
monkeypatch.setenv("AIRLOCK_PROTECTED_PATHS", "secrets.json,credentials.yaml")
monkeypatch.setattr(
"sys.stdin",
StringIO(json.dumps({"tool_input": {"file_path": "/x/secrets.json"}})),
)
from airlock.hooks.pre_tool import main
with pytest.raises(SystemExit) as exc_info:
main()
assert exc_info.value.code == 2
def test_proceeds_when_no_file_path(self, monkeypatch):
monkeypatch.setattr(
"sys.stdin",
StringIO(json.dumps({"tool_input": {}})),
)
monkeypatch.delenv("AIRLOCK_PROTECTED_PATHS", raising=False)
from airlock.hooks.pre_tool import main
with pytest.raises(SystemExit) as exc_info:
main()
assert exc_info.value.code == 0
# ===================================================================
# post_tool.py
# ===================================================================
class TestPostTool:
def test_writes_jsonl_log(self, monkeypatch, tmp_path):
log_dir = tmp_path / "logs"
monkeypatch.setenv("AIRLOCK_LOG_DIR", str(log_dir))
monkeypatch.setattr(
"sys.stdin",
StringIO(
json.dumps(
{
"tool_name": "Bash",
"tool_input": {"command": "ls"},
"tool_output": "file1.py\nfile2.py",
}
)
),
)
from airlock.hooks.post_tool import main
with pytest.raises(SystemExit) as exc_info:
main()
assert exc_info.value.code == 0
log_files = list(log_dir.glob("claude-hooks-*.jsonl"))
assert len(log_files) == 1
record = json.loads(log_files[0].read_text().strip())
assert record["tool_name"] == "Bash"
assert record["hook"] == "PostToolUse"
def test_truncates_large_output(self, monkeypatch, tmp_path):
log_dir = tmp_path / "logs"
monkeypatch.setenv("AIRLOCK_LOG_DIR", str(log_dir))
monkeypatch.setattr(
"sys.stdin",
StringIO(
json.dumps(
{
"tool_name": "Read",
"tool_input": {},
"tool_output": "x" * 5000,
}
)
),
)
from airlock.hooks.post_tool import main
with pytest.raises(SystemExit) as exc_info:
main()
assert exc_info.value.code == 0
record = json.loads(list(log_dir.glob("*.jsonl"))[0].read_text().strip())
assert len(record["tool_output"]) < 3000
assert "truncated" in record["tool_output"]
def test_never_fails_on_bad_log_dir(self, monkeypatch):
monkeypatch.setenv("AIRLOCK_LOG_DIR", "/nonexistent/readonly/path")
monkeypatch.setattr(
"sys.stdin",
StringIO(json.dumps({"tool_name": "Bash"})),
)
from airlock.hooks.post_tool import main
with pytest.raises(SystemExit) as exc_info:
main()
assert exc_info.value.code == 0