|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import argparse |
| 4 | +import asyncio |
| 5 | +import json |
| 6 | +import os |
| 7 | +from pathlib import Path |
| 8 | +from typing import Any |
| 9 | + |
| 10 | +from sipx import Harness, LLMChatClient, Verdict, scenario |
| 11 | + |
| 12 | + |
| 13 | +SAMPLE_TRACE = """ |
| 14 | +SIP RX 203.0.113.20:5060 |
| 15 | +SIP/2.0 401 Unauthorized |
| 16 | +WWW-Authenticate: Digest realm="pbx.example.com", nonce="n1", qop="auth" |
| 17 | +CSeq: 1 REGISTER |
| 18 | +
|
| 19 | +SIP TX 203.0.113.20:5060 |
| 20 | +REGISTER sip:pbx.example.com SIP/2.0 |
| 21 | +Authorization: [REDACTED] |
| 22 | +CSeq: 2 REGISTER |
| 23 | +
|
| 24 | +SIP RX 203.0.113.20:5060 |
| 25 | +SIP/2.0 200 OK |
| 26 | +CSeq: 2 REGISTER |
| 27 | +
|
| 28 | +SIP TX 203.0.113.20:5060 |
| 29 | +INVITE sip:ivr@example.com SIP/2.0 |
| 30 | +Content-Type: application/sdp |
| 31 | +CSeq: 1 INVITE |
| 32 | +
|
| 33 | +v=0 |
| 34 | +m=audio 41000 RTP/AVP 0 8 101 |
| 35 | +a=rtpmap:0 PCMU/8000 |
| 36 | +a=rtpmap:101 telephone-event/8000 |
| 37 | +
|
| 38 | +SIP RX 203.0.113.20:5060 |
| 39 | +SIP/2.0 180 Ringing |
| 40 | +CSeq: 1 INVITE |
| 41 | +
|
| 42 | +SIP RX 203.0.113.20:5060 |
| 43 | +SIP/2.0 200 OK |
| 44 | +Content-Type: application/sdp |
| 45 | +CSeq: 1 INVITE |
| 46 | +
|
| 47 | +v=0 |
| 48 | +m=audio 52000 RTP/AVP 0 101 |
| 49 | +a=rtpmap:0 PCMU/8000 |
| 50 | +a=rtpmap:101 telephone-event/8000 |
| 51 | +
|
| 52 | +SIP TX 203.0.113.20:5060 |
| 53 | +ACK sip:ivr@example.com SIP/2.0 |
| 54 | +CSeq: 1 ACK |
| 55 | +
|
| 56 | +SIP TX 203.0.113.20:5060 |
| 57 | +INFO sip:ivr@example.com SIP/2.0 |
| 58 | +Content-Type: application/dtmf-relay |
| 59 | +CSeq: 2 INFO |
| 60 | +
|
| 61 | +Signal=1 |
| 62 | +Duration=160 |
| 63 | +
|
| 64 | +SIP RX 203.0.113.20:5060 |
| 65 | +SIP/2.0 200 OK |
| 66 | +CSeq: 2 INFO |
| 67 | +
|
| 68 | +SIP TX 203.0.113.20:5060 |
| 69 | +BYE sip:ivr@example.com SIP/2.0 |
| 70 | +CSeq: 3 BYE |
| 71 | +
|
| 72 | +SIP RX 203.0.113.20:5060 |
| 73 | +SIP/2.0 200 OK |
| 74 | +CSeq: 3 BYE |
| 75 | +""".strip() |
| 76 | + |
| 77 | + |
| 78 | +@scenario("sip_flow_audit", provider="openai-compatible") |
| 79 | +async def scenario(h: Harness) -> Verdict: |
| 80 | + trace = _load_trace_from_env() |
| 81 | + result = await audit_trace(trace) |
| 82 | + h.timeline.record("llm", "sip_flow_audit", data=result) |
| 83 | + print(json.dumps(result, indent=2, sort_keys=True)) |
| 84 | + if result["status"] == "skipped": |
| 85 | + return Verdict.skipped(reason=str(result["reason"])) |
| 86 | + if result["deterministic"]["critical_findings"]: |
| 87 | + return Verdict.failed(reason="deterministic SIP audit found critical issues") |
| 88 | + return Verdict.passed(reason="SIP flow audit completed") |
| 89 | + |
| 90 | + |
| 91 | +async def audit_trace(trace: str) -> dict[str, Any]: |
| 92 | + deterministic = _deterministic_audit(trace) |
| 93 | + if not os.getenv("SIPX_LLM_API_KEY"): |
| 94 | + return { |
| 95 | + "status": "skipped", |
| 96 | + "reason": "SIPX_LLM_API_KEY not set", |
| 97 | + "deterministic": deterministic, |
| 98 | + } |
| 99 | + |
| 100 | + client = LLMChatClient.from_env() |
| 101 | + prompt = _audit_prompt(trace, deterministic) |
| 102 | + raw = await client.complete( |
| 103 | + prompt, |
| 104 | + system=( |
| 105 | + "You audit SIP call flows. Return strict JSON only. " |
| 106 | + "Do not include markdown fences. Do not include secrets." |
| 107 | + ), |
| 108 | + max_tokens=1200, |
| 109 | + ) |
| 110 | + llm = _parse_json_object(raw) |
| 111 | + return { |
| 112 | + "status": "completed", |
| 113 | + "deterministic": deterministic, |
| 114 | + "llm": llm, |
| 115 | + } |
| 116 | + |
| 117 | + |
| 118 | +def _load_trace_from_env() -> str: |
| 119 | + path = os.getenv("SIPX_LLM_TRACE_FILE") |
| 120 | + if path: |
| 121 | + return Path(path).read_text(encoding="utf-8") |
| 122 | + return SAMPLE_TRACE |
| 123 | + |
| 124 | + |
| 125 | +def _deterministic_audit(trace: str) -> dict[str, Any]: |
| 126 | + upper = trace.upper() |
| 127 | + critical: list[str] = [] |
| 128 | + warnings: list[str] = [] |
| 129 | + signals = { |
| 130 | + "register_digest_challenge": "401 UNAUTHORIZED" in upper |
| 131 | + and "REGISTER" in upper, |
| 132 | + "invite_has_sdp_offer": "INVITE " in upper |
| 133 | + and "CONTENT-TYPE: APPLICATION/SDP" in upper |
| 134 | + and "M=AUDIO" in upper, |
| 135 | + "dtmf_info": "INFO " in upper and "APPLICATION/DTMF-RELAY" in upper, |
| 136 | + "clean_bye": "BYE " in upper and "CSEQ: 3 BYE" in upper and "200 OK" in upper, |
| 137 | + } |
| 138 | + if "INVITE " in upper and "SIP/2.0 200 OK" in upper: |
| 139 | + invite_ok_index = upper.find("SIP/2.0 200 OK", upper.find("INVITE ")) |
| 140 | + invite_answer_window = upper[invite_ok_index : invite_ok_index + 500] |
| 141 | + if "CONTENT-TYPE: APPLICATION/SDP" not in invite_answer_window: |
| 142 | + critical.append("INVITE reached 200 OK without an SDP answer nearby") |
| 143 | + for line in trace.splitlines(): |
| 144 | + normalized = line.strip().upper() |
| 145 | + if ( |
| 146 | + normalized.startswith(("AUTHORIZATION:", "PROXY-AUTHORIZATION:")) |
| 147 | + and "[REDACTED]" not in normalized |
| 148 | + ): |
| 149 | + critical.append("trace contains an unredacted authorization header") |
| 150 | + break |
| 151 | + if "APPLICATION/DTMF-RELAY" in upper and "DURATION=" not in upper: |
| 152 | + warnings.append("DTMF relay body has no Duration field") |
| 153 | + return { |
| 154 | + "signals": signals, |
| 155 | + "critical_findings": critical, |
| 156 | + "warnings": warnings, |
| 157 | + } |
| 158 | + |
| 159 | + |
| 160 | +def _audit_prompt(trace: str, deterministic: dict[str, Any]) -> str: |
| 161 | + return json.dumps( |
| 162 | + { |
| 163 | + "task": "Audit this SIP flow for interoperability and behavior.", |
| 164 | + "required_json_shape": { |
| 165 | + "summary": "one paragraph", |
| 166 | + "behavior": "accepted|rejected|incomplete|unknown", |
| 167 | + "risk_score": "integer 0-100", |
| 168 | + "protocol_findings": [ |
| 169 | + { |
| 170 | + "severity": "info|warning|critical", |
| 171 | + "evidence": "quote from trace", |
| 172 | + "meaning": "what it implies", |
| 173 | + "recommendation": "what to do next", |
| 174 | + } |
| 175 | + ], |
| 176 | + "media_assessment": { |
| 177 | + "sdp": "short assessment", |
| 178 | + "dtmf": "short assessment", |
| 179 | + "rtp_readiness": "short assessment", |
| 180 | + }, |
| 181 | + "next_actions": ["ordered actions"], |
| 182 | + }, |
| 183 | + "deterministic_signals": deterministic, |
| 184 | + "sip_trace": trace, |
| 185 | + }, |
| 186 | + indent=2, |
| 187 | + ) |
| 188 | + |
| 189 | + |
| 190 | +def _parse_json_object(text: str) -> dict[str, Any]: |
| 191 | + stripped = text.strip() |
| 192 | + if stripped.startswith("```"): |
| 193 | + stripped = stripped.strip("`") |
| 194 | + if stripped.lower().startswith("json"): |
| 195 | + stripped = stripped[4:].strip() |
| 196 | + start = stripped.find("{") |
| 197 | + end = stripped.rfind("}") |
| 198 | + if start < 0 or end < start: |
| 199 | + raise ValueError("LLM response did not contain a JSON object") |
| 200 | + value = json.loads(stripped[start : end + 1]) |
| 201 | + if not isinstance(value, dict): |
| 202 | + raise ValueError("LLM response JSON must be an object") |
| 203 | + return value |
| 204 | + |
| 205 | + |
| 206 | +def main(argv: list[str] | None = None) -> int: |
| 207 | + parser = argparse.ArgumentParser(description="Audit a SIP trace with an LLM.") |
| 208 | + parser.add_argument( |
| 209 | + "--trace-file", |
| 210 | + help="Path to a text SIP trace. Defaults to the embedded healthy sample.", |
| 211 | + ) |
| 212 | + args = parser.parse_args(argv) |
| 213 | + |
| 214 | + if args.trace_file: |
| 215 | + os.environ["SIPX_LLM_TRACE_FILE"] = args.trace_file |
| 216 | + verdict = asyncio.run(Harness().run(scenario)) |
| 217 | + reason = f": {verdict.reason}" if verdict.reason else "" |
| 218 | + print(f"{verdict.status}{reason}") |
| 219 | + return 0 if verdict.status in {"passed", "skipped"} else 1 |
| 220 | + |
| 221 | + |
| 222 | +if __name__ == "__main__": |
| 223 | + raise SystemExit(main()) |
0 commit comments