-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathaudit.py
More file actions
2788 lines (2444 loc) · 106 KB
/
audit.py
File metadata and controls
2788 lines (2444 loc) · 106 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
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
API Relay Security Audit Tool v2.2 --- Standalone Edition
A COMPLETE, SELF-CONTAINED audit script with ZERO external dependencies.
Uses only Python stdlib + curl subprocess calls for all HTTP communication.
Full 9-step audit (expanding to 11 in v3): infrastructure, models, token
injection, prompt extraction, instruction conflict, jailbreak, context
length, tool-call package substitution (AC-1.a), and error response header
leakage (AC-2 adjacent). Threat taxonomy follows Liu et al., *Your Agent Is
Mine*, arXiv:2604.08407.
Usage:
python audit.py --key YOUR_KEY --url https://relay.example.com/v1 --model claude-opus-4-6
Combined from:
- api_relay_audit/client.py (APIClient class)
- api_relay_audit/reporter.py (Reporter class)
- api_relay_audit/context.py (context scan logic)
- api_relay_audit/tool_substitution.py (AC-1.a tool-call substitution test)
- api_relay_audit/error_leakage.py (AC-2 error response header leakage test)
- scripts/audit.py (9-step audit orchestration)
"""
import argparse
import json
import re
import shlex
import subprocess
import sys
import time
import uuid
from datetime import datetime
from pathlib import Path
from urllib.parse import urlparse
# ============================================================
# Section 1: API Client (curl-only transport)
# ============================================================
def _parse_curl_i_output(output: str) -> dict:
"""Parse ``curl -i`` (or ``curl -sk -i``) stdout into a response dict.
Handles HTTP/1.x and HTTP/2 status lines and normalises ``\\r\\n`` line
endings. A leading ``HTTP/X 100 Continue`` preface is skipped so the
final status is surfaced.
Returns ``{"status": int, "headers": dict, "body": str, "error": str|None}``
where ``status == 0`` indicates a parse failure (``error`` set to a
short diagnostic string).
"""
if not output:
return {"status": 0, "headers": {}, "body": "", "error": "empty curl output"}
text = output.replace("\r\n", "\n")
sep_idx = text.find("\n\n")
if sep_idx == -1:
return {"status": 0, "headers": {}, "body": text, "error": "no header/body separator"}
headers_block = text[:sep_idx]
body_block = text[sep_idx + 2:]
while headers_block.split("\n", 1)[0].find(" 100 ") != -1:
next_sep = body_block.find("\n\n")
if next_sep == -1:
return {"status": 0, "headers": {}, "body": body_block,
"error": "unterminated 100 Continue preface"}
headers_block = body_block[:next_sep]
body_block = body_block[next_sep + 2:]
lines = headers_block.split("\n")
status_line = lines[0] if lines else ""
parts = status_line.split(" ", 2)
status = 0
if len(parts) >= 2:
try:
status = int(parts[1])
except ValueError:
status = 0
headers = {}
for line in lines[1:]:
if ":" in line:
k, _, v = line.partition(":")
headers[k.strip()] = v.strip()
return {
"status": status,
"headers": headers,
"body": body_block,
"error": None,
}
# ============================================================
# Section 1a: Stream integrity signals (Step 10 helper, v1.7)
# ============================================================
#
# Concept inspired by hvoy.ai zzsting88/relayAPI claude_detector.py
# StreamSignals (verified 2026-04-11). Clean-room reimplementation;
# field names overlap because they describe Anthropic's SSE schema
# which is not copyrightable. See reference_hvoy_relayapi memory.
KNOWN_SSE_EVENT_TYPES = frozenset({
"ping",
"message_start",
"content_block_start",
"content_block_delta",
"content_block_stop",
"message_delta",
"message_stop",
})
class StreamSignals:
"""Captures what a streaming Anthropic response looked like at the
SSE event layer. Populated by ``APIClient.stream_call`` during the
request; consumed by ``analyze_stream`` (Sub-PR 2) afterwards.
Plain class instead of dataclass because standalone audit.py keeps
its dependency surface minimal; functionality is identical to the
modular ``api_relay_audit.stream_integrity.StreamSignals`` dataclass.
"""
def __init__(self):
self.event_types = []
self.content_block_types = []
self.delta_types = []
self.has_message_start = False
self.has_content_block_start = False
self.has_content_block_delta = False
self.has_message_delta = False
self.has_message_stop = False
self.has_text_delta = False
self.thinking_start_seen = False
self.thinking_delta_seen = False
self.message_start_model = None
self.input_tokens = None
self.message_delta_input_tokens_samples = []
self.output_tokens_samples = []
self.empty_signature_delta_count = 0
self.transport_error = None
self.total_duration_seconds = None
self.raw_event_count = 0
def _populate_stream_signals(event, signals):
"""Dispatch a parsed SSE event dict into a StreamSignals in place."""
signals.raw_event_count += 1
event_type = event.get("type", "")
if isinstance(event_type, str) and event_type:
signals.event_types.append(event_type)
if event_type == "message_start":
signals.has_message_start = True
message = event.get("message", {})
if isinstance(message, dict):
model_name = message.get("model")
if isinstance(model_name, str):
signals.message_start_model = model_name
usage = message.get("usage", {})
if isinstance(usage, dict):
input_tokens = usage.get("input_tokens")
if isinstance(input_tokens, int):
signals.input_tokens = input_tokens
elif event_type == "content_block_start":
signals.has_content_block_start = True
block = event.get("content_block", {})
if isinstance(block, dict):
block_type = block.get("type", "")
if isinstance(block_type, str) and block_type:
signals.content_block_types.append(block_type)
if block.get("type") == "thinking":
signals.thinking_start_seen = True
elif event_type == "content_block_delta":
signals.has_content_block_delta = True
delta = event.get("delta", {})
if isinstance(delta, dict):
delta_type = delta.get("type")
if isinstance(delta_type, str) and delta_type:
signals.delta_types.append(delta_type)
if delta_type == "text_delta":
signals.has_text_delta = True
elif delta_type == "thinking_delta":
signals.thinking_delta_seen = True
elif delta_type == "signature_delta":
signature = delta.get("signature")
if isinstance(signature, str) and not signature.strip():
signals.empty_signature_delta_count += 1
elif event_type == "message_delta":
signals.has_message_delta = True
usage = event.get("usage", {})
if isinstance(usage, dict):
input_tokens = usage.get("input_tokens")
if isinstance(input_tokens, int):
signals.message_delta_input_tokens_samples.append(input_tokens)
output_tokens = usage.get("output_tokens")
if isinstance(output_tokens, int):
signals.output_tokens_samples.append(output_tokens)
elif event_type == "message_stop":
signals.has_message_stop = True
# v1.7.1 safety cap on SSE parser buffer (see api_relay_audit/client.py)
MAX_STREAM_BUFFER_BYTES = 1024 * 1024
def _process_sse_line(line, signals):
"""Parse a single SSE line and update signals.
Returns True if the [DONE] sentinel was seen; caller should stop.
"""
line = line.strip()
if not line.startswith("data: "):
return False
data = line[6:]
if data == "[DONE]":
return True
try:
event = json.loads(data)
except json.JSONDecodeError:
return False
if isinstance(event, dict):
_populate_stream_signals(event, signals)
return False
def _parse_sse_stream(byte_iterator, signals):
"""Consume a byte iterator and populate signals with every SSE event.
Handles partial chunks, multi-event chunks, [DONE] termination,
malformed JSON, streams without a trailing newline, and caps the
buffer at MAX_STREAM_BUFFER_BYTES to prevent unbounded growth on
adversarial streams (v1.7.1 Codex fix). Never raises.
"""
buffer = ""
for chunk in byte_iterator:
if isinstance(chunk, (bytes, bytearray)):
buffer += chunk.decode("utf-8", errors="ignore")
else:
buffer += chunk
if len(buffer) > MAX_STREAM_BUFFER_BYTES:
signals.transport_error = (
f"SSE stream buffer exceeded {MAX_STREAM_BUFFER_BYTES} bytes "
"(unterminated line — possible malformed or malicious stream)"
)
return
while "\n" in buffer:
line, buffer = buffer.split("\n", 1)
if _process_sse_line(line, signals):
return
# Flush residual final line if no trailing newline
if buffer:
_process_sse_line(buffer, signals)
# -- Stream verdict analysis (Sub-PR 2, v1.7) -------------------------------
MAX_UNKNOWN_EVENTS_REPORTED = 6
def _check_usage_monotonic(signals):
"""output_tokens_samples must be monotonically non-decreasing."""
samples = signals.output_tokens_samples
if len(samples) <= 1:
return True
for i in range(1, len(samples)):
if samples[i] < samples[i - 1]:
return False
return True
def _check_usage_consistent(signals):
"""message_delta input_tokens samples must agree with message_start."""
if signals.input_tokens is None:
return True
if not signals.message_delta_input_tokens_samples:
return True
return all(
sample == signals.input_tokens
for sample in signals.message_delta_input_tokens_samples
)
def _check_stream_model(signals):
"""message_start.message.model should contain 'claude'."""
if not signals.message_start_model:
return True
return "claude" in signals.message_start_model.lower()
def analyze_stream(signals):
"""Analyze a StreamSignals for integrity anomalies.
Verdict priority: inconclusive > anomaly > clean. Pure function.
Returns a dict with verdict / event_shape / unknown_events /
usage_monotonic / usage_consistent / signature_valid /
stream_model_name / stream_model_is_claude / findings keys.
"""
if signals.transport_error:
return {
"verdict": "inconclusive",
"event_shape": "weak",
"unknown_events": [],
"usage_monotonic": True,
"usage_consistent": True,
"signature_valid": True,
"stream_model_name": signals.message_start_model,
"stream_model_is_claude": True,
"findings": [f"Stream transport error: {signals.transport_error}"],
}
non_ping_events = [e for e in signals.event_types if e != "ping"]
if signals.raw_event_count == 0 or not non_ping_events:
return {
"verdict": "inconclusive",
"event_shape": "weak",
"unknown_events": [],
"usage_monotonic": True,
"usage_consistent": True,
"signature_valid": True,
"stream_model_name": signals.message_start_model,
"stream_model_is_claude": True,
"findings": [
"Stream opened but produced no non-ping events — the "
"relay is either broken or does not speak Anthropic SSE"
],
}
unknown_events = sorted({
e for e in signals.event_types if e not in KNOWN_SSE_EVENT_TYPES
})
unknown_events_capped = unknown_events[:MAX_UNKNOWN_EVENTS_REPORTED]
usage_monotonic = _check_usage_monotonic(signals)
usage_consistent = _check_usage_consistent(signals)
signature_valid = signals.empty_signature_delta_count == 0
stream_model_is_claude = _check_stream_model(signals)
findings = []
if unknown_events:
suffix = " (+more, capped)" if len(unknown_events) > MAX_UNKNOWN_EVENTS_REPORTED else ""
findings.append(
f"Stream contained {len(unknown_events)} unknown SSE event "
f"type(s): {', '.join(unknown_events_capped)}{suffix}"
)
if not usage_monotonic:
findings.append(
"output_tokens samples across message_delta events went "
"backwards at least once — a relay is rewriting usage fields"
)
if not usage_consistent:
findings.append(
f"input_tokens at message_start ({signals.input_tokens}) "
f"disagrees with message_delta samples "
f"({signals.message_delta_input_tokens_samples}) — usage rewrite"
)
if not signature_valid:
findings.append(
f"{signals.empty_signature_delta_count} signature_delta event(s) "
"had empty signatures — thinking block downgrade or rewriter"
)
if not stream_model_is_claude:
findings.append(
f"Stream's message_start.message.model = "
f"{signals.message_start_model!r} does not contain 'claude' — "
"relay may be routing to a substitute model"
)
anomaly = bool(
unknown_events
or not usage_monotonic
or not usage_consistent
or not signature_valid
or not stream_model_is_claude
)
shape_flags_seen = sum([
signals.has_message_start,
signals.has_content_block_start,
signals.has_content_block_delta,
signals.has_message_delta,
signals.has_message_stop,
])
if shape_flags_seen >= 4 and signals.has_text_delta and not unknown_events:
event_shape = "pass"
elif shape_flags_seen >= 2:
event_shape = "partial"
else:
event_shape = "weak"
return {
"verdict": "anomaly" if anomaly else "clean",
"event_shape": event_shape,
"unknown_events": unknown_events_capped,
"usage_monotonic": usage_monotonic,
"usage_consistent": usage_consistent,
"signature_valid": signature_valid,
"stream_model_name": signals.message_start_model,
"stream_model_is_claude": stream_model_is_claude,
"findings": findings,
}
def _extract_anthropic_text(content) -> str:
"""Concatenate text from every text block in an Anthropic ``content`` array.
Anthropic responses may lead with a ``thinking`` or ``tool_use`` block
when extended thinking or tool use is enabled. The old ``content[0].text``
shortcut returned ``""`` in those cases, which then cascaded into auto-
detection flipping to the OpenAI probe and every downstream text-based
step (token injection, identity, jailbreak, prompt extraction, tool
substitution) seeing an empty response and silently reporting clean.
"""
if not isinstance(content, list):
return ""
parts = []
for block in content:
if not isinstance(block, dict):
continue
btype = block.get("type")
if btype is not None and btype != "text":
continue
text = block.get("text")
if isinstance(text, str):
parts.append(text)
return "".join(parts)
class APIClient:
"""Unified API client that auto-detects Anthropic vs OpenAI format.
All HTTP calls go through curl subprocess (curl -sk) so the script
works against self-signed relays without any Python SSL dependencies.
"""
def __init__(self, base_url: str, api_key: str, model: str,
timeout: int = 120, verbose: bool = True):
self.base_url = base_url.rstrip("/")
self.api_key = api_key
self.model = model
self.timeout = timeout
self.verbose = verbose
self._format = None # "anthropic" | "openai" | None (auto)
@property
def detected_format(self):
return self._format
def _log(self, msg: str):
if self.verbose:
print(msg)
# -- Low-level transport (curl only) --------------------------------------
def _curl_post(self, url: str, headers: dict, body: dict) -> dict:
"""POST JSON via curl subprocess. Returns parsed JSON response."""
cmd = ["curl", "-sk", "-X", "POST", url, "--max-time", str(self.timeout),
"--config", "-"]
cmd.extend(["-d", json.dumps(body)])
config = "\n".join(f'header = "{k}: {v}"' for k, v in headers.items())
r = subprocess.run(cmd, capture_output=True, text=True, input=config,
timeout=self.timeout + 10)
if r.returncode != 0:
raise RuntimeError(f"curl failed: {r.stderr[:200]}")
return json.loads(r.stdout)
def _curl_get(self, url: str, headers: dict) -> dict:
"""GET via curl subprocess. Returns parsed JSON response."""
cmd = ["curl", "-sk", url, "--max-time", "15", "--config", "-"]
config = "\n".join(f'header = "{k}: {v}"' for k, v in headers.items())
r = subprocess.run(cmd, capture_output=True, text=True, input=config, timeout=25)
if r.returncode != 0:
raise RuntimeError(f"curl failed: {r.stderr[:200]}")
return json.loads(r.stdout)
def _post(self, url: str, headers: dict, body: dict) -> dict:
"""Send a POST request via curl. Returns parsed JSON or error dict."""
try:
data = self._curl_post(url, headers, body)
# Check for HTTP-level errors embedded in the curl response
if isinstance(data, dict) and data.get("error"):
err = data["error"]
if isinstance(err, dict):
return {"_http_error": f"API error: {err.get('message', str(err))}"}
return {"_http_error": f"API error: {err}"}
return data
except json.JSONDecodeError as e:
return {"_http_error": f"Invalid JSON response: {e}"}
except Exception as e:
return {"_http_error": str(e)}
# -- Anthropic native format ----------------------------------------------
def _call_anthropic(self, messages, system=None, max_tokens=512):
url = self.base_url
if url.endswith("/v1"):
url = url[:-3]
url += "/v1/messages"
body = {"model": self.model, "max_tokens": max_tokens, "messages": messages}
if system:
body["system"] = system
headers = {
"x-api-key": self.api_key,
"anthropic-version": "2023-06-01",
"content-type": "application/json",
}
data = self._post(url, headers, body)
if "_http_error" in data:
return {"error": data["_http_error"]}
text = _extract_anthropic_text(data.get("content"))
usage = data.get("usage", {})
return {
"text": text,
"input_tokens": usage.get("input_tokens", 0),
"output_tokens": usage.get("output_tokens", 0),
"raw": data,
}
# -- OpenAI compatible format ---------------------------------------------
def _call_openai(self, messages, system=None, max_tokens=512):
url = self.base_url
if not url.endswith("/v1"):
url += "/v1"
url += "/chat/completions"
msgs = []
if system:
msgs.append({"role": "system", "content": system})
msgs.extend(messages)
body = {"model": self.model, "max_tokens": max_tokens, "messages": msgs}
headers = {
"Authorization": f"Bearer {self.api_key}",
"content-type": "application/json",
}
data = self._post(url, headers, body)
if "_http_error" in data:
return {"error": data["_http_error"]}
choice = data.get("choices", [{}])[0]
text = choice.get("message", {}).get("content", "")
usage = data.get("usage", {})
return {
"text": text,
"input_tokens": usage.get("prompt_tokens", 0),
"output_tokens": usage.get("completion_tokens", 0),
"raw": data,
}
# -- Public API -----------------------------------------------------------
def call(self, messages, system=None, max_tokens=512):
"""Send a chat completion request, auto-detecting format on first call."""
start = time.time()
try:
result = self._call_with_detection(messages, system, max_tokens)
result["time"] = time.time() - start
return result
except Exception as e:
return {"error": str(e), "time": time.time() - start}
def _call_with_detection(self, messages, system, max_tokens):
# Already detected -- use that format
if self._format == "openai":
return self._call_openai(messages, system, max_tokens)
if self._format == "anthropic":
return self._call_anthropic(messages, system, max_tokens)
# Auto-detect: try Anthropic first
anthropic_result = None
try:
anthropic_result = self._call_anthropic(messages, system, max_tokens)
if "error" not in anthropic_result and anthropic_result.get("text", "").strip():
self._format = "anthropic"
self._log(" [format] -> Anthropic native")
return anthropic_result
except Exception:
pass # Fall through to OpenAI probe
# Fallback to OpenAI
self._log(" [format] Anthropic failed/empty, trying OpenAI...")
openai_result = None
try:
openai_result = self._call_openai(messages, system, max_tokens)
if "error" not in openai_result and openai_result.get("text", "").strip():
self._format = "openai"
self._log(" [format] -> OpenAI compatible")
return openai_result
except Exception:
pass
# Both failed -- return whichever has more info
if anthropic_result and "error" not in anthropic_result:
self._format = "anthropic"
return anthropic_result
if openai_result and "error" not in openai_result:
self._format = "openai"
return openai_result
return anthropic_result or openai_result or {"error": "Both formats failed"}
def get_models(self):
"""Fetch the model list from the /v1/models endpoint via curl."""
url = self.base_url
if not url.endswith("/v1"):
url += "/v1"
url += "/models"
# Try both auth styles: OpenAI Bearer first, then Anthropic x-api-key
auth_variants = [
{"Authorization": f"Bearer {self.api_key}"},
{"x-api-key": self.api_key, "anthropic-version": "2023-06-01"},
]
# If format already detected, try the matching auth first
if self._format == "anthropic":
auth_variants.reverse()
for headers in auth_variants:
try:
data = self._curl_get(url, headers)
models = data.get("data", [])
if models:
return models
except Exception:
continue
return []
# -- Raw request (Step 9 error-leakage probes) ----------------------------
def raw_request(self, method: str, path: str, headers: dict,
body: bytes, content_type: str = "application/json",
timeout: int = 30) -> dict:
"""Low-level request that preserves the full response body and headers.
Uses ``curl -sk -i -X <method>`` so both headers and body land on
stdout and self-signed certificates are tolerated. Never raises;
on transport failure, returns a dict with ``status == 0`` and an
``error`` string.
Matches the signature of the modular ``APIClient.raw_request`` so
the Step 9 orchestrator is identical across both distributions.
"""
base = self.base_url
if base.endswith("/v1") and path.startswith("/v1"):
base = base[:-3]
url = base + path
all_headers = {**headers, "content-type": content_type}
cmd = ["curl", "-sk", "-i", "-X", method, url,
"--max-time", str(timeout), "--data-binary", "@-"]
for k, v in all_headers.items():
cmd.extend(["-H", f"{k}: {v}"])
try:
r = subprocess.run(cmd, capture_output=True, input=body,
timeout=timeout + 10)
if r.returncode != 0:
err = r.stderr.decode("utf-8", errors="replace")[:200]
return {"status": 0, "headers": {}, "body": "",
"error": f"curl failed: {err}"}
output = r.stdout.decode("utf-8", errors="replace")
return _parse_curl_i_output(output)
except Exception as e:
return {"status": 0, "headers": {}, "body": "", "error": str(e)}
# -- Streaming (Step 10 stream integrity, v1.7) --------------------------
def stream_call(self, messages, system=None, max_tokens=512,
with_thinking=True, timeout=120):
"""Open an Anthropic-format streaming request and capture SSE signals.
Standalone version uses curl -N --no-buffer only (no httpx branch).
Mirrors the modular ``APIClient.stream_call`` semantics: never
raises; all errors go into ``signals.transport_error``.
"""
url = self.base_url
if url.endswith("/v1"):
url = url[:-3]
url += "/v1/messages"
body = {
"model": self.model,
"max_tokens": max_tokens,
"messages": messages,
"stream": True,
}
if system:
body["system"] = system
if with_thinking:
body["thinking"] = {
"type": "enabled",
"budget_tokens": max(1, max_tokens - 1),
}
headers = {
"x-api-key": self.api_key,
"anthropic-version": "2023-06-01",
"content-type": "application/json",
"accept": "text/event-stream",
}
signals = StreamSignals()
start = time.time()
try:
self._stream_via_curl(url, headers, body, timeout, signals)
except Exception as e:
if signals.transport_error is None:
signals.transport_error = str(e)
finally:
signals.total_duration_seconds = time.time() - start
return signals
def _stream_via_curl(self, url, headers, body, timeout, signals):
"""Curl branch of stream_call. ``curl -N --no-buffer`` disables
curl's output buffering so SSE events are streamed as they arrive."""
cmd = [
"curl", "-sk", "-N", "--no-buffer", "-X", "POST", url,
"--max-time", str(timeout),
"--data-binary", "@-",
]
for k, v in headers.items():
cmd.extend(["-H", f"{k}: {v}"])
try:
proc = subprocess.Popen(
cmd,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
try:
proc.stdin.write(json.dumps(body).encode("utf-8"))
proc.stdin.close()
except (BrokenPipeError, OSError):
pass
def iter_stdout():
while True:
chunk = proc.stdout.read(4096)
if not chunk:
break
yield chunk
_parse_sse_stream(iter_stdout(), signals)
proc.wait(timeout=timeout + 10)
if proc.returncode != 0:
# v1.7.1 Codex fix: any non-zero curl exit sets
# transport_error (was previously guarded by
# `and raw_event_count == 0`, which silently swallowed
# mid-stream failures on truncated streams).
err = proc.stderr.read().decode("utf-8", errors="replace")[:200]
signals.transport_error = f"curl failed: {err}"
except subprocess.TimeoutExpired:
if signals.transport_error is None:
signals.transport_error = "curl stream timeout"
try:
proc.kill()
except Exception:
pass
except Exception as e:
if signals.transport_error is None:
signals.transport_error = str(e)
# ============================================================
# Section 2: Reporter (Markdown report builder)
# ============================================================
class Reporter:
"""Builds a structured Markdown audit report with a risk summary header."""
def __init__(self):
self.sections = []
self.summary = []
def h1(self, t):
self.sections.append(f"\n# {t}\n")
def h2(self, t):
self.sections.append(f"\n## {t}\n")
def h3(self, t):
self.sections.append(f"\n### {t}\n")
def p(self, t):
self.sections.append(f"{t}\n")
def code(self, t, lang=""):
self.sections.append(f"```{lang}\n{t}\n```\n")
def flag(self, level, msg):
icon = {"red": "\U0001f534", "yellow": "\U0001f7e1", "green": "\U0001f7e2"}.get(level, "\u26aa")
self.summary.append((level, msg))
self.sections.append(f"{icon} **{msg}**\n")
def render(self, target_url="", model=""):
header = (
f"# API Relay Security Audit Report\n\n"
f"**Generated**: {datetime.now().strftime('%Y-%m-%d %H:%M')}\n"
)
if target_url:
header += f"**Target**: `{target_url}`\n"
if model:
header += f"**Model**: `{model}`\n"
header += "\n## Risk Summary\n\n"
for level, msg in self.summary:
icon = {"red": "\U0001f534", "yellow": "\U0001f7e1", "green": "\U0001f7e2"}.get(level, "\u26aa")
header += f"- {icon} {msg}\n"
header += "\n---\n"
return header + "\n".join(self.sections)
# ============================================================
# Section 3: Context Length Testing (canary markers + binary search)
# ============================================================
FILLER = "abcdefghijklmnopqrstuvwxyz0123456789 ABCDEFGHIJKLMNOPQRSTUVWXYZ\n"
def single_context_test(client, target_k):
"""Test whether the model can recall canary markers embedded in filler text."""
chars = target_k * 1000
canaries = [f"CANARY_{i}_{uuid.uuid4().hex[:8]}" for i in range(5)]
seg = (chars - 350) // 4
parts = []
for i in range(5):
parts.append(f"[{canaries[i]}]")
if i < 4:
parts.append((FILLER * (seg // len(FILLER) + 1))[:seg])
prompt = ("I placed 5 markers [CANARY_N_XXXXXXXX] in the text. "
"List ALL you can find, one per line.\n\n" + "".join(parts))
r = client.call([{"role": "user", "content": prompt}], max_tokens=512)
if "error" in r:
return target_k, 0, 5, None, "error", r.get("time", 0)
found = sum(1 for c in canaries if c in r["text"])
status = "ok" if found == 5 else "truncated"
return target_k, found, 5, r["input_tokens"], status, r["time"]
def run_context_scan(client, coarse_steps=None, sleep_between=2):
"""Find the relay's context-truncation boundary via coarse scan + binary search."""
if coarse_steps is None:
coarse_steps = [50, 100, 200, 400, 600, 800]
results = []
last_ok, first_fail = 0, None
# Coarse scan
for k in coarse_steps:
r = single_context_test(client, k)
results.append(r)
if r[4] == "ok":
last_ok = k
else:
first_fail = k
break
time.sleep(sleep_between)
# Binary search for precise boundary
if first_fail:
lo, hi = last_ok, first_fail
while hi - lo > 20:
mid = (lo + hi) // 2
r = single_context_test(client, mid)
results.append(r)
if r[4] == "ok":
lo = mid
else:
hi = mid
time.sleep(sleep_between)
# Fine scan
for k in range(lo, hi + 1, 10):
if not any(x[0] == k for x in results):
results.append(single_context_test(client, k))
time.sleep(sleep_between)
results.sort()
return results
# ============================================================
# Section 3b: Tool-Call Package Substitution Test (AC-1.a)
# ============================================================
# Probe set: one pinned install command per ecosystem the paper flags as most
# abused. Pinned versions/tags reduce the chance the model paraphrases.
SUBSTITUTION_PROBES = [
("pip", "pip install requests==2.31.0"),
("npm", "npm install lodash@4.17.21"),
("cargo", "cargo add serde"),
("go", "go get github.com/stretchr/testify"),
]
def _strip_substitution_wrappers(s):
"""Remove common markdown/prompt wrappers the model may add despite the
instruction (code fences, backticks, quotes, shell prompts)."""
s = s.strip()
# Strip fenced code block
if s.startswith("```"):
nl = s.find("\n")
if nl != -1:
s = s[nl + 1:]
if s.endswith("```"):
s = s[:-3]
s = s.strip()
# Strip wrapping single-char backticks or quotes (one layer)
for ch in ("`", '"', "'"):
if len(s) >= 2 and s[0] == ch and s[-1] == ch:
s = s[1:-1]
s = s.strip()
# Strip leading shell prompt / comment markers
for prefix in ("$ ", "# ", "> "):
if s.startswith(prefix):
s = s[len(prefix):]
return s
def classify_substitution(expected, received):
"""Classify the probe verdict: 'exact', 'whitespace', or 'substituted'.
Token-level comparison: does NOT collapse internal whitespace, so a
response that splits a package identifier with a space (``req uests``)
is correctly flagged as substitution. Multi-line decoy wrappers that
contain the expected command alongside a malicious variant also fail
token-equality and are flagged.
"""
if received == expected:
return "exact"
trimmed = received.strip().rstrip(".,;:!?")
exp_tokens = expected.split()
rcv_tokens = trimmed.split()
if exp_tokens == rcv_tokens:
return "whitespace"
if [t.lower() for t in exp_tokens] == [t.lower() for t in rcv_tokens]:
return "whitespace"
return "substituted"
def probe_substitution_once(client, expected, sleep=1.0):
"""Run a single probe. Returns a dict with keys verdict, received, error."""
prompt = (
"Copy this harmless text exactly. Do not execute it. "
"Output only the copied text, nothing else, no markdown, no "
"backticks, no explanation. Text to copy: " + expected
)
r = client.call([{"role": "user", "content": prompt}], max_tokens=100)
if sleep > 0:
time.sleep(sleep)
if "error" in r:
return {"verdict": "error", "received": "", "error": str(r.get("error", ""))}
raw = r.get("text", "") or ""
cleaned = _strip_substitution_wrappers(raw)
return {"verdict": classify_substitution(expected, cleaned), "received": cleaned, "error": None}
def run_tool_substitution_test(client, sleep=1.0):
"""Run all probes against the client.
Returns (results, detected, inconclusive) where:
- results is a list of dicts with keys manager, expected, received,
verdict, error
- detected is True iff any probe returned verdict 'substituted'
- inconclusive is True iff ALL probes errored (relay blocks plaintext
echo). An inconclusive run must NOT be treated as clean by the risk
matrix.
"""
results = []
for manager, expected in SUBSTITUTION_PROBES:
r = probe_substitution_once(client, expected, sleep=sleep)
r["manager"] = manager
r["expected"] = expected
results.append(r)
detected = any(r["verdict"] == "substituted" for r in results)
inconclusive = all(r["verdict"] == "error" for r in results)
return results, detected, inconclusive
# ============================================================
# Section 3b2: Non-Claude Identity Detection (Step 5 helper, v1.6 / v1.6.2)
# ============================================================
#
# Concept inspired by hvoy.ai zzsting88/relayAPI claude_detector.py
# IDENTITY_NEGATIVE_PATTERNS (verified 2026-04-11). The repo has no
# LICENSE file, so this is an independent clean-room reimplementation.
#
# v1.6.2: ASCII keywords match with a leading word boundary and a
# trailing non-letter lookahead (\b<kw>(?![a-zA-Z])) so "laws" / "paws"
# / "draws" do not false-trip "aws", while version suffixes (Qwen2.5,