interplane-mv
INTERPLANE: open interoperability protocol between AI models and agent runtimes. Models express intent. Runtimes retain authority.
Brought by drakestapleton
interplane-mv / rust / crates / interplane-lenshift / src / replay.rs
| 1 | //! Sanitized offline replay of provider HTTP responses (issue #98). |
| 2 | //! |
| 3 | //! A capture records what a provider sent (status, ordered body chunks) in a scrubbed form. The |
| 4 | //! replay feeds those chunks through the existing dialect parsers exactly as live bytes would be |
| 5 | //! (concatenated in order, then parsed) and reduces the result to an [`Outcome`]. An outcome is |
| 6 | //! observed provider behaviour plus parsed requests. It never carries a decision or any |
| 7 | //! authority: authorization stays in the runtime, and a capture is never evidence of it. |
| 8 | use regex::Regex; |
| 9 | use serde::{Deserialize, Serialize}; |
| 10 | use serde_json::{json, Value}; |
| 11 | |
| 12 | use crate::{DialectRegistry, ParseContext}; |
| 13 | |
| 14 | pub const FORMAT: &str = "interplane-replay/1"; |
| 15 | |
| 16 | #[derive(Debug, Clone, Deserialize, Serialize)] |
| 17 | #[serde(deny_unknown_fields)] |
| 18 | pub struct Provenance { |
| 19 | /// `synthetic` (hand written to model a behaviour) or `recorded` (scrubbed live capture). |
| 20 | pub origin: String, |
| 21 | pub source_commit: String, |
| 22 | pub captured_on: String, |
| 23 | #[serde(default)] |
| 24 | pub note: String, |
| 25 | } |
| 26 | |
| 27 | #[derive(Debug, Clone, Deserialize, Serialize)] |
| 28 | #[serde(deny_unknown_fields)] |
| 29 | pub struct Request { |
| 30 | pub method: String, |
| 31 | pub path: String, |
| 32 | /// Header NAMES only. A value (anything containing `:` or `=`) is refused by the scanner. |
| 33 | pub header_names: Vec<String>, |
| 34 | pub body: Value, |
| 35 | } |
| 36 | |
| 37 | #[derive(Debug, Clone, Deserialize, Serialize)] |
| 38 | #[serde(deny_unknown_fields)] |
| 39 | pub struct Response { |
| 40 | pub status: u16, |
| 41 | pub header_names: Vec<String>, |
| 42 | /// Transport chunks in arrival order. A chunk may end mid-event or mid-JSON. |
| 43 | pub chunks: Vec<String>, |
| 44 | /// Optional per-chunk delay in milliseconds. Informational; the replay never sleeps. |
| 45 | #[serde(default)] |
| 46 | pub timing_ms: Vec<u64>, |
| 47 | } |
| 48 | |
| 49 | #[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] |
| 50 | #[serde(deny_unknown_fields)] |
| 51 | pub struct Call { |
| 52 | pub name: String, |
| 53 | pub arguments: Value, |
| 54 | } |
| 55 | |
| 56 | /// The golden values and the replay result share this shape. |
| 57 | #[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] |
| 58 | #[serde(deny_unknown_fields)] |
| 59 | pub struct Outcome { |
| 60 | /// `parsed`, `rate_limited`, `server_error`, `client_error` or `unparsable_body`. |
| 61 | pub class: String, |
| 62 | pub text: String, |
| 63 | pub tool_calls: Vec<Call>, |
| 64 | /// Lenshift rejection codes, in order. |
| 65 | pub rejected: Vec<String>, |
| 66 | pub partial: bool, |
| 67 | } |
| 68 | |
| 69 | #[derive(Debug, Clone, Deserialize, Serialize)] |
| 70 | #[serde(deny_unknown_fields)] |
| 71 | pub struct Capture { |
| 72 | pub format: String, |
| 73 | pub name: String, |
| 74 | pub provider: String, |
| 75 | pub model: String, |
| 76 | /// `chat_completions_stream` or `chat_completions`. |
| 77 | pub endpoint_kind: String, |
| 78 | pub provenance: Provenance, |
| 79 | pub request: Request, |
| 80 | pub response: Response, |
| 81 | pub expect: Outcome, |
| 82 | } |
| 83 | |
| 84 | fn empty(class: &str) -> Outcome { |
| 85 | Outcome { |
| 86 | class: class.into(), |
| 87 | text: String::new(), |
| 88 | tool_calls: vec![], |
| 89 | rejected: vec![], |
| 90 | partial: false, |
| 91 | } |
| 92 | } |
| 93 | |
| 94 | /// Feed a capture through the dialect parsers. Never sleeps, never touches the network. |
| 95 | pub fn replay(c: &Capture) -> Outcome { |
| 96 | match c.response.status { |
| 97 | 429 => return empty("rate_limited"), |
| 98 | 500..=599 => return empty("server_error"), |
| 99 | s if s >= 400 => return empty("client_error"), |
| 100 | _ => {} |
| 101 | } |
| 102 | let body: String = c.response.chunks.concat(); |
| 103 | let (dialect, input) = if c.endpoint_kind == "chat_completions_stream" { |
| 104 | ("openai_stream", Value::String(body)) |
| 105 | } else { |
| 106 | match serde_json::from_str::<Value>(&body) { |
| 107 | // A non-stream body is `{choices:[{message}]}`; the `openai` dialect takes the message. |
| 108 | Ok(v) => match v.pointer("/choices/0/message") { |
| 109 | Some(m) => ("openai", m.clone()), |
| 110 | None => return empty("unparsable_body"), |
| 111 | }, |
| 112 | Err(_) => return empty("unparsable_body"), |
| 113 | } |
| 114 | }; |
| 115 | let ctx = ParseContext { |
| 116 | trace_id: "trace-replay".into(), |
| 117 | turn: 0, |
| 118 | model: c.model.clone(), |
| 119 | }; |
| 120 | let reg = DialectRegistry::with_defaults(); |
| 121 | let t = reg |
| 122 | .get(dialect) |
| 123 | .expect("dialect registered") |
| 124 | .parse(&input, &ctx); |
| 125 | Outcome { |
| 126 | class: "parsed".into(), |
| 127 | text: t.text, |
| 128 | tool_calls: t |
| 129 | .intents |
| 130 | .iter() |
| 131 | .map(|i| Call { |
| 132 | name: i.tool.name.clone(), |
| 133 | arguments: Value::Object(i.arguments.clone()), |
| 134 | }) |
| 135 | .collect(), |
| 136 | rejected: t |
| 137 | .rejected |
| 138 | .iter() |
| 139 | .map(|r| { |
| 140 | json!(r.code) |
| 141 | .as_str() |
| 142 | .map(String::from) |
| 143 | .unwrap_or_else(|| format!("{:?}", r.code)) |
| 144 | }) |
| 145 | .collect(), |
| 146 | partial: t.partial, |
| 147 | } |
| 148 | } |
| 149 | |
| 150 | /// Replay and compare to the golden values. `Err` carries the actual outcome for the report. |
| 151 | pub fn check(c: &Capture) -> Result<(), String> { |
| 152 | let got = replay(c); |
| 153 | if got == c.expect { |
| 154 | Ok(()) |
| 155 | } else { |
| 156 | Err(format!( |
| 157 | "{}: replay drifted from golden\n want {}\n got {}", |
| 158 | c.name, |
| 159 | json!(c.expect), |
| 160 | json!(got) |
| 161 | )) |
| 162 | } |
| 163 | } |
| 164 | |
| 165 | // --------------------------------------------------------------------------------------------- |
| 166 | // Scrubbing and scanning |
| 167 | // --------------------------------------------------------------------------------------------- |
| 168 | |
| 169 | /// One class of sensitive-looking text. |
| 170 | struct Rule { |
| 171 | class: &'static str, |
| 172 | re: &'static str, |
| 173 | } |
| 174 | |
| 175 | const RULES: &[Rule] = &[ |
| 176 | Rule { |
| 177 | class: "bearer-token", |
| 178 | re: r"(?i)\b(bearer|basic)\s+[A-Za-z0-9._~+/=-]{8,}", |
| 179 | }, |
| 180 | Rule { |
| 181 | class: "sensitive-header-with-value", |
| 182 | re: r"(?i)\b(authorization|proxy-authorization|cookie|set-cookie|x-api-key|api-key|x-auth-token)\s*[:=]\s*[A-Za-z0-9._~+/=-]{16,}", |
| 183 | }, |
| 184 | Rule { |
| 185 | class: "api-key", |
| 186 | re: r"\b(sk|pk|rk)-[A-Za-z0-9_-]{16,}", |
| 187 | }, |
| 188 | Rule { |
| 189 | class: "aws-key", |
| 190 | re: r"\b(AKIA|ASIA)[0-9A-Z]{16}\b", |
| 191 | }, |
| 192 | Rule { |
| 193 | class: "provider-token", |
| 194 | re: r"\b(ghp|gho|ghs|xox[abp]|AIza)[-_A-Za-z0-9]{16,}", |
| 195 | }, |
| 196 | Rule { |
| 197 | class: "cookie-value", |
| 198 | re: r"(?i)\b(cookie|set-cookie)\s*:\s*[^\s=;]+=\S+", |
| 199 | }, |
| 200 | Rule { |
| 201 | class: "jwt", |
| 202 | re: r"\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]*", |
| 203 | }, |
| 204 | Rule { |
| 205 | class: "pem-block", |
| 206 | re: r"-----BEGIN [A-Z ]+-----", |
| 207 | }, |
| 208 | Rule { |
| 209 | class: "payment-key", |
| 210 | re: r"\b(sk|pk|rk)_(live|test)_[A-Za-z0-9]{8,}", |
| 211 | }, |
| 212 | Rule { |
| 213 | class: "hf-token", |
| 214 | re: r"\bhf_[A-Za-z0-9]{16,}", |
| 215 | }, |
| 216 | Rule { |
| 217 | class: "ip-address", |
| 218 | re: r"\b(\d{1,3}\.){3}\d{1,3}\b", |
| 219 | }, |
| 220 | Rule { |
| 221 | class: "file-path", |
| 222 | re: r"(/home/|/Users/|/root/|/etc/|/var/|/tmp/|\b[A-Za-z]:\\)", |
| 223 | }, |
| 224 | Rule { |
| 225 | class: "long-hex", |
| 226 | re: r"\b[0-9a-fA-F]{32,}\b", |
| 227 | }, |
| 228 | Rule { |
| 229 | class: "long-base64", |
| 230 | re: r"[A-Za-z0-9+/_-]{40,}={0,2}", |
| 231 | }, |
| 232 | Rule { |
| 233 | class: "email", |
| 234 | re: r"[A-Za-z0-9._%+-]+@[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)*\.[A-Za-z]{2,}", |
| 235 | }, |
| 236 | Rule { |
| 237 | class: "tenant-id", |
| 238 | re: r"(?i)\b(org|ws|workspace|tenant|acct|account)[-_][A-Za-z0-9]{8,}", |
| 239 | }, |
| 240 | Rule { |
| 241 | class: "query-secret", |
| 242 | re: r"(?i)[?&](api[_-]?key|key|token|access_token|secret|sig|signature|password)=[^&\s\x22]{4,}", |
| 243 | }, |
| 244 | ]; |
| 245 | |
| 246 | fn compiled() -> Vec<(&'static str, Regex)> { |
| 247 | RULES |
| 248 | .iter() |
| 249 | .map(|r| (r.class, Regex::new(r.re).expect("rule compiles"))) |
| 250 | .collect() |
| 251 | } |
| 252 | |
| 253 | fn placeholder() -> Regex { |
| 254 | Regex::new(r"^<[A-Z0-9_ -]{1,40}>$").expect("placeholder") |
| 255 | } |
| 256 | |
| 257 | fn sensitive_key(k: &str) -> bool { |
| 258 | let k = k.to_ascii_lowercase(); |
| 259 | [ |
| 260 | "tenant_id", |
| 261 | "workspace_id", |
| 262 | "org_id", |
| 263 | "organization_id", |
| 264 | "account_id", |
| 265 | "organization", |
| 266 | "user_id", |
| 267 | ] |
| 268 | .iter() |
| 269 | .any(|s| k == *s) |
| 270 | } |
| 271 | |
| 272 | /// Replace every sensitive-looking span in `s` with `<REDACTED:class>`. |
| 273 | pub fn scrub_text(s: &str) -> String { |
| 274 | let mut out = s.to_string(); |
| 275 | for (class, re) in compiled() { |
| 276 | out = re |
| 277 | .replace_all(&out, format!("<REDACTED:{class}>")) |
| 278 | .into_owned(); |
| 279 | } |
| 280 | out |
| 281 | } |
| 282 | |
| 283 | fn walk(v: &mut Value, f: &mut dyn FnMut(&str, &mut Value)) { |
| 284 | match v { |
| 285 | Value::Object(m) => { |
| 286 | for (k, x) in m.iter_mut() { |
| 287 | f(k, x); |
| 288 | walk(x, f); |
| 289 | } |
| 290 | } |
| 291 | Value::Array(a) => { |
| 292 | for x in a.iter_mut() { |
| 293 | f("", x); |
| 294 | walk(x, f); |
| 295 | } |
| 296 | } |
| 297 | _ => {} |
| 298 | } |
| 299 | } |
| 300 | |
| 301 | /// Replace model-authored text in one decoded message or delta object. Tool-call fragments are |
| 302 | /// left alone: they are the golden under test. |
| 303 | fn blank_model_text(o: &mut serde_json::Map<String, Value>) { |
| 304 | for (k, label) in [ |
| 305 | ("content", "<MODEL_TEXT>"), |
| 306 | ("reasoning", "<REASONING>"), |
| 307 | ("reasoning_content", "<REASONING>"), |
| 308 | ] { |
| 309 | if let Some(Value::String(s)) = o.get_mut(k) { |
| 310 | if !s.is_empty() { |
| 311 | *s = label.into(); |
| 312 | } |
| 313 | } |
| 314 | } |
| 315 | } |
| 316 | |
| 317 | /// Blank model text in the response chunks. Complete SSE events (`data: {json}`) are rewritten |
| 318 | /// in place; a non-stream JSON body is rewritten whole. Chunks that are not self contained |
| 319 | /// (split mid-event) are left for the scanner and the human reviewer. |
| 320 | fn scrub_response_text(v: &mut Value) { |
| 321 | let Some(chunks) = v |
| 322 | .pointer_mut("/response/chunks") |
| 323 | .and_then(Value::as_array_mut) |
| 324 | else { |
| 325 | return; |
| 326 | }; |
| 327 | for c in chunks { |
| 328 | let Some(s) = c.as_str() else { continue }; |
| 329 | let new = if let Ok(Value::Object(mut body)) = serde_json::from_str::<Value>(s) { |
| 330 | if let Some(cs) = body.get_mut("choices").and_then(Value::as_array_mut) { |
| 331 | for ch in cs { |
| 332 | for key in ["message", "delta"] { |
| 333 | if let Some(Value::Object(m)) = ch.get_mut(key) { |
| 334 | blank_model_text(m); |
| 335 | } |
| 336 | } |
| 337 | } |
| 338 | } |
| 339 | Value::Object(body).to_string() |
| 340 | } else { |
| 341 | s.split_inclusive('\n') |
| 342 | .map(|line| { |
| 343 | let Some(data) = line.strip_prefix("data: ") else { |
| 344 | return line.to_string(); |
| 345 | }; |
| 346 | match serde_json::from_str::<Value>(data.trim_end()) { |
| 347 | Ok(Value::Object(mut ev)) => { |
| 348 | if let Some(cs) = ev.get_mut("choices").and_then(Value::as_array_mut) { |
| 349 | for ch in cs { |
| 350 | if let Some(Value::Object(d)) = ch.get_mut("delta") { |
| 351 | blank_model_text(d); |
| 352 | } |
| 353 | } |
| 354 | } |
| 355 | let tail = &line[data.trim_end().len() + 6..]; |
| 356 | format!("data: {}{}", Value::Object(ev), tail) |
| 357 | } |
| 358 | _ => line.to_string(), |
| 359 | } |
| 360 | }) |
| 361 | .collect() |
| 362 | }; |
| 363 | *c = Value::String(new); |
| 364 | } |
| 365 | } |
| 366 | |
| 367 | /// Scrub a capture value BEFORE it is written: header values dropped, user content replaced by a |
| 368 | /// placeholder, tenant-style ids replaced, every string passed through [`scrub_text`]. |
| 369 | pub fn scrub_value(v: &mut Value) { |
| 370 | walk(v, &mut |k, x| { |
| 371 | if sensitive_key(k) && x.is_string() { |
| 372 | *x = Value::String("<ID>".into()); |
| 373 | } |
| 374 | }); |
| 375 | // User and tool message content in the request body is never kept. |
| 376 | if let Some(msgs) = v |
| 377 | .pointer_mut("/request/body/messages") |
| 378 | .and_then(Value::as_array_mut) |
| 379 | { |
| 380 | for m in msgs { |
| 381 | let role = m |
| 382 | .get("role") |
| 383 | .and_then(Value::as_str) |
| 384 | .unwrap_or("") |
| 385 | .to_string(); |
| 386 | if matches!(role.as_str(), "user" | "tool" | "system" | "assistant") |
| 387 | && m.get("content").is_some_and(Value::is_string) |
| 388 | { |
| 389 | if let Some(c) = m.get_mut("content") { |
| 390 | *c = Value::String(format!("<{}_CONTENT>", role.to_ascii_uppercase())); |
| 391 | } |
| 392 | } |
| 393 | } |
| 394 | } |
| 395 | if let Some(p) = v.pointer_mut("/request/body/prompt") { |
| 396 | if p.is_string() { |
| 397 | *p = Value::String("<USER_CONTENT>".into()); |
| 398 | } |
| 399 | } |
| 400 | scrub_response_text(v); |
| 401 | walk(v, &mut |_, x| { |
| 402 | if let Value::String(s) = x { |
| 403 | *s = scrub_text(s); |
| 404 | } |
| 405 | }); |
| 406 | } |
| 407 | |
| 408 | /// Every refusal found in a candidate fixture. Empty means clean. Scans keys and string values. |
| 409 | pub fn scan(v: &Value) -> Vec<String> { |
| 410 | let rules = compiled(); |
| 411 | let ph = placeholder(); |
| 412 | let mut found = Vec::new(); |
| 413 | let mut text = |where_: &str, s: &str, found: &mut Vec<String>| { |
| 414 | for (class, re) in &rules { |
| 415 | if re.is_match(s) { |
| 416 | found.push(format!("{class} in {where_}")); |
| 417 | } |
| 418 | } |
| 419 | }; |
| 420 | fn rec( |
| 421 | v: &Value, |
| 422 | path: &str, |
| 423 | found: &mut Vec<String>, |
| 424 | text: &mut dyn FnMut(&str, &str, &mut Vec<String>), |
| 425 | ph: &Regex, |
| 426 | ) { |
| 427 | match v { |
| 428 | Value::Object(m) => { |
| 429 | for (k, x) in m { |
| 430 | let p = format!("{path}/{k}"); |
| 431 | text(&p, k, found); |
| 432 | if sensitive_key(k) && !x.as_str().is_some_and(|s| ph.is_match(s)) { |
| 433 | found.push(format!("tenant-id key {k} without placeholder in {p}")); |
| 434 | } |
| 435 | rec(x, &p, found, text, ph); |
| 436 | } |
| 437 | } |
| 438 | Value::Array(a) => { |
| 439 | for (i, x) in a.iter().enumerate() { |
| 440 | rec(x, &format!("{path}/{i}"), found, text, ph); |
| 441 | } |
| 442 | } |
| 443 | Value::String(s) => text(path, s, found), |
| 444 | _ => {} |
| 445 | } |
| 446 | } |
| 447 | rec(v, "", &mut found, &mut text, &ph); |
| 448 | // Header lists carry names only. |
| 449 | for side in ["/request/header_names", "/response/header_names"] { |
| 450 | if let Some(a) = v.pointer(side).and_then(Value::as_array) { |
| 451 | for h in a { |
| 452 | match h.as_str() { |
| 453 | Some(n) if !n.contains(':') && !n.contains('=') && !n.contains(' ') => {} |
| 454 | _ => found.push(format!("header with a value in {side}")), |
| 455 | } |
| 456 | } |
| 457 | } |
| 458 | } |
| 459 | // User and tool content in the request body must be a placeholder. |
| 460 | if let Some(msgs) = v |
| 461 | .pointer("/request/body/messages") |
| 462 | .and_then(Value::as_array) |
| 463 | { |
| 464 | for (i, m) in msgs.iter().enumerate() { |
| 465 | let role = m.get("role").and_then(Value::as_str).unwrap_or(""); |
| 466 | if matches!(role, "user" | "tool" | "system" | "assistant") |
| 467 | && m.get("content") |
| 468 | .and_then(Value::as_str) |
| 469 | .is_some_and(|s| !s.is_empty() && !ph.is_match(s)) |
| 470 | { |
| 471 | found.push(format!( |
| 472 | "unscrubbed {role} content in /request/body/messages/{i}" |
| 473 | )); |
| 474 | } |
| 475 | } |
| 476 | } |
| 477 | if let Some(p) = v.pointer("/request/body/prompt").and_then(Value::as_str) { |
| 478 | if !ph.is_match(p) { |
| 479 | found.push("unscrubbed prompt in /request/body/prompt".into()); |
| 480 | } |
| 481 | } |
| 482 | found |
| 483 | } |