forked from ChelseaKR/fare-policy-assistant
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_smoke_production.py
More file actions
344 lines (311 loc) · 10.8 KB
/
Copy pathtest_smoke_production.py
File metadata and controls
344 lines (311 loc) · 10.8 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
"""Exercise the production smoke script through a deterministic fake transport."""
from __future__ import annotations
import os
import subprocess
import time
from pathlib import Path
from assistant import config
SMOKE_SCRIPT = config.REPO_ROOT / "scripts" / "smoke-production.sh"
def _install_fake_curl(tmp_path: Path) -> Path:
"""Install a curl-shaped transport so the shell is tested without sockets."""
bin_dir = tmp_path / "bin"
bin_dir.mkdir()
fake_curl = bin_dir / "curl"
fake_curl.write_text(
"""#!/usr/bin/env python3
import json
import os
import pathlib
import sys
import time
args = sys.argv[1:]
headers_path = pathlib.Path(args[args.index("--dump-header") + 1])
body_path = pathlib.Path(args[args.index("--output") + 1])
url = args[-1]
payload = args[args.index("--data") + 1] if "--data" in args else ""
disabled_documents = [
item
for item in os.environ.get("FAKE_DISABLED_DOC_IDS", "yolobus-fares").split(",")
if item
]
delay_seconds = float(os.environ.get("FAKE_CURL_DELAY_SECONDS", "0"))
if delay_seconds:
time.sleep(delay_seconds)
security = [
"cache-control: no-store",
"content-security-policy: default-src 'none'; connect-src 'self'; "
"form-action 'self'; base-uri 'none'; frame-ancestors 'self'",
"referrer-policy: no-referrer",
"x-content-type-options: nosniff",
]
if url.startswith("http://evidence.test"):
content_type = "text/html"
body = "<html><title>Public evaluation evidence</title></html>"
response_headers = []
elif url.endswith("/version"):
content_type = "application/json"
body = json.dumps({
"corpus_version": "test-corpus",
"as_of": "2026-07-29",
"agencies": ["MST"],
"matches_pin": True,
"disabled_documents": disabled_documents,
})
response_headers = security + ["x-frame-options: DENY"]
elif url.endswith("/api/ask"):
content_type = "application/json"
question = json.loads(payload)["question"]
if "Social Security" in question:
body = json.dumps({
"answer": "Please leave personal details out of your question.",
"kind": "refused_input",
"citations": [],
})
elif "Yolobus" in question:
if "yolobus-fares" in disabled_documents:
body = json.dumps({
"answer": "I do not have current published support for that answer.",
"kind": "refused_no_support",
"citations": [],
})
else:
body = json.dumps({
"answer": "The reviewed source is active.",
"kind": "answered",
"citations": [{
"agency": "Yolobus",
"title": "Fares",
"url": "https://yolobus.com/fares/",
"fetch_date": "2026-07-29",
}],
})
else:
body = json.dumps({
"answer": "Bring published proof.",
"kind": "answered",
"corpus_version": "test-corpus",
"as_of_date": "2026-07-29",
"citations": [{
"agency": "MST",
"title": "Veteran fares",
"url": "https://mst.org/fares/",
"fetch_date": "2026-07-29",
}],
})
response_headers = security + ["x-frame-options: DENY"]
else:
content_type = "text/html"
markers = {
"/": "Transit Fare Policy Assistant",
"/offline": "Offline fare reference",
"/guide": "Which fare applies to me?",
"/embed": "Transit fare policy assistant",
}
path = "/" + url.split("/", 3)[-1] if url.count("/") >= 3 else "/"
body = f"<html><title>{markers[path]}</title></html>"
# Simulates a genuine containment leak: yolobus-fares stays in
# disabled_documents (containment is still required), but the page's
# rendered body somehow carries the contained document's own marker
# text anyway. FAKE_LEAK_PATHS names which page(s) leak.
leak_marker = os.environ.get("FAKE_LEAK_MARKER", "")
leak_paths = os.environ.get("FAKE_LEAK_PATHS", "").split(",")
if leak_marker and path in leak_paths:
body = f"<html><title>{markers[path]}</title><p>{leak_marker}</p></html>"
response_headers = security
if path != "/embed":
response_headers.append("x-frame-options: DENY")
headers_path.write_text(
"\\r\\n".join(["HTTP/1.1 200 OK", f"content-type: {content_type}", *response_headers, "", ""])
)
body_path.write_text(body)
sys.stdout.write("200")
""",
encoding="utf-8",
)
fake_curl.chmod(0o755)
return bin_dir
def test_smoke_script_covers_both_public_surfaces_without_network(tmp_path):
fake_bin = _install_fake_curl(tmp_path)
result = subprocess.run(
[
str(SMOKE_SCRIPT),
"--evidence-base-url",
"http://evidence.test",
"--assistant-base-url",
"http://assistant.test",
"--connect-timeout",
"2",
"--max-time",
"5",
"--allow-legacy-release-identity",
],
cwd=config.REPO_ROOT,
env={**os.environ, "LC_ALL": "C", "PATH": f"{fake_bin}:{os.environ['PATH']}"},
check=False,
capture_output=True,
text=True,
timeout=30,
)
assert result.returncode == 0, result.stderr
assert "smoke: ok: assistant PII refusal" in result.stdout
assert "smoke: ok: assistant Yolobus containment" in result.stdout
assert "smoke: ok: assistant safe answer" in result.stdout
assert result.stdout.rstrip().endswith("smoke: PASS")
def test_smoke_script_rejects_an_invalid_base_url_before_curl():
result = subprocess.run(
[str(SMOKE_SCRIPT), "--assistant-base-url", "not-a-url"],
cwd=config.REPO_ROOT,
check=False,
capture_output=True,
text=True,
timeout=10,
)
assert result.returncode != 0
assert "assistant base URL must be an absolute http(s) URL" in result.stderr
def test_assistant_only_ignores_an_irrelevant_invalid_evidence_url(tmp_path):
fake_bin = _install_fake_curl(tmp_path)
result = subprocess.run(
[
str(SMOKE_SCRIPT),
"--assistant-only",
"--assistant-base-url",
"http://assistant.test",
"--allow-legacy-release-identity",
],
cwd=config.REPO_ROOT,
env={
**os.environ,
"LC_ALL": "C",
"PATH": f"{fake_bin}:{os.environ['PATH']}",
"FPA_SMOKE_EVIDENCE_BASE_URL": "not-a-url",
},
check=False,
capture_output=True,
text=True,
timeout=30,
)
assert result.returncode == 0, result.stderr
assert "evidence=" not in result.stdout
assert result.stdout.rstrip().endswith("smoke: PASS")
def test_explicit_empty_disabled_documents_skips_yolobus_containment(tmp_path):
fake_bin = _install_fake_curl(tmp_path)
result = subprocess.run(
[
str(SMOKE_SCRIPT),
"--assistant-only",
"--assistant-base-url",
"http://assistant.test",
"--expected-disabled-docs",
"",
"--allow-legacy-release-identity",
],
cwd=config.REPO_ROOT,
env={
**os.environ,
"LC_ALL": "C",
"PATH": f"{fake_bin}:{os.environ['PATH']}",
"FAKE_DISABLED_DOC_IDS": "",
},
check=False,
capture_output=True,
text=True,
timeout=30,
)
assert result.returncode == 0, result.stderr
assert "Yolobus containment" not in result.stdout
assert result.stdout.rstrip().endswith("smoke: PASS")
def test_offline_page_leaking_the_contained_yolobus_marker_fails_the_smoke_check(tmp_path):
"""Issue #145: the containment assertion must actually detect a leak, not
just pass on a fake body that was never going to contain the old literal
either. Derives the real marker the same way the script does, so this
test does not itself go stale the next time Yolobus republishes."""
from assistant import config as assistant_config
marker_script = assistant_config.REPO_ROOT / "scripts" / "yolobus_fare_period_marker.py"
marker = subprocess.run(
["uv", "run", "python", str(marker_script)],
cwd=config.REPO_ROOT,
check=True,
capture_output=True,
text=True,
).stdout.strip()
assert marker # sanity: a marker was actually derived
fake_bin = _install_fake_curl(tmp_path)
result = subprocess.run(
[
str(SMOKE_SCRIPT),
"--assistant-only",
"--assistant-base-url",
"http://assistant.test",
"--allow-legacy-release-identity",
],
cwd=config.REPO_ROOT,
env={
**os.environ,
"LC_ALL": "C",
"PATH": f"{fake_bin}:{os.environ['PATH']}",
# yolobus-fares stays disabled (containment is still required);
# the page body leaks its marker anyway.
"FAKE_LEAK_MARKER": marker,
"FAKE_LEAK_PATHS": "/offline",
},
check=False,
capture_output=True,
text=True,
timeout=30,
)
assert result.returncode != 0
assert "exposes the contained Yolobus fare period" in result.stderr
def test_default_disabled_document_requirement_detects_missing_containment(tmp_path):
fake_bin = _install_fake_curl(tmp_path)
result = subprocess.run(
[
str(SMOKE_SCRIPT),
"--assistant-only",
"--assistant-base-url",
"http://assistant.test",
"--allow-legacy-release-identity",
],
cwd=config.REPO_ROOT,
env={
**os.environ,
"LC_ALL": "C",
"PATH": f"{fake_bin}:{os.environ['PATH']}",
"FAKE_DISABLED_DOC_IDS": "",
},
check=False,
capture_output=True,
text=True,
timeout=30,
)
assert result.returncode != 0
assert "invalid explicit legacy release identity" in result.stderr
def test_deadline_terminates_a_slow_public_request(tmp_path):
fake_bin = _install_fake_curl(tmp_path)
deadline = int(time.time()) + 2
started = time.monotonic()
result = subprocess.run(
[
str(SMOKE_SCRIPT),
"--assistant-only",
"--assistant-base-url",
"http://assistant.test",
"--deadline-epoch",
str(deadline),
"--allow-legacy-release-identity",
],
cwd=config.REPO_ROOT,
env={
**os.environ,
"LC_ALL": "C",
"PATH": f"{fake_bin}:{os.environ['PATH']}",
"FAKE_CURL_DELAY_SECONDS": "30",
},
check=False,
capture_output=True,
text=True,
timeout=8,
)
elapsed = time.monotonic() - started
assert result.returncode != 0
assert elapsed < 5
assert "operation deadline" in result.stderr