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 / tests / provider_replay.rs
| 1 | //! Offline provider replay (issue #98). No network, no credentials. |
| 2 | use interplane_lenshift::replay::{check, replay, scan, scrub_text, scrub_value, Capture, FORMAT}; |
| 3 | use serde_json::{json, Value}; |
| 4 | use std::path::PathBuf; |
| 5 | |
| 6 | fn dir() -> PathBuf { |
| 7 | PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../../dialects/replay") |
| 8 | } |
| 9 | |
| 10 | fn collect(d: &std::path::Path, out: &mut Vec<PathBuf>) { |
| 11 | for e in std::fs::read_dir(d).expect("dialects/replay present") { |
| 12 | let p = e.unwrap().path(); |
| 13 | if p.is_dir() { |
| 14 | collect(&p, out); |
| 15 | } else if p.extension().and_then(|e| e.to_str()) == Some("json") { |
| 16 | out.push(p); |
| 17 | } |
| 18 | } |
| 19 | } |
| 20 | |
| 21 | /// Every fixture below `dialects/replay`, recursively. |
| 22 | fn load_all() -> Vec<(String, Value)> { |
| 23 | let mut paths = Vec::new(); |
| 24 | collect(&dir(), &mut paths); |
| 25 | let mut v: Vec<_> = paths |
| 26 | .into_iter() |
| 27 | .map(|p| { |
| 28 | let t = std::fs::read_to_string(&p).unwrap(); |
| 29 | (p.display().to_string(), serde_json::from_str(&t).unwrap()) |
| 30 | }) |
| 31 | .collect(); |
| 32 | v.sort_by(|a, b| a.0.cmp(&b.0)); |
| 33 | v |
| 34 | } |
| 35 | |
| 36 | fn cap(name: &str) -> Capture { |
| 37 | let (_, v) = load_all() |
| 38 | .into_iter() |
| 39 | .find(|(p, _)| p.ends_with(&format!("{name}.json"))) |
| 40 | .unwrap_or_else(|| panic!("fixture {name}")); |
| 41 | serde_json::from_value(v).unwrap() |
| 42 | } |
| 43 | |
| 44 | #[test] |
| 45 | fn every_fixture_is_clean_and_replays_to_its_golden() { |
| 46 | let all = load_all(); |
| 47 | assert!( |
| 48 | all.len() >= 11, |
| 49 | "expected the replay fixtures, found {}", |
| 50 | all.len() |
| 51 | ); |
| 52 | for (path, v) in &all { |
| 53 | assert_eq!(scan(v), Vec::<String>::new(), "{path} failed the scanner"); |
| 54 | let c: Capture = |
| 55 | serde_json::from_value(v.clone()).unwrap_or_else(|e| panic!("{path}: {e}")); |
| 56 | assert_eq!(c.format, FORMAT, "{path}"); |
| 57 | assert!( |
| 58 | c.provenance.origin == "synthetic" || c.provenance.origin == "recorded", |
| 59 | "{path} origin" |
| 60 | ); |
| 61 | if let Err(e) = check(&c) { |
| 62 | panic!("{e}"); |
| 63 | } |
| 64 | } |
| 65 | } |
| 66 | |
| 67 | #[test] |
| 68 | fn replay_is_deterministic() { |
| 69 | for (_, v) in load_all() { |
| 70 | let c: Capture = serde_json::from_value(v).unwrap(); |
| 71 | assert_eq!(replay(&c), replay(&c)); |
| 72 | } |
| 73 | } |
| 74 | |
| 75 | #[test] |
| 76 | fn chunk_boundaries_do_not_change_the_outcome() { |
| 77 | let c = cap("stream-tool-call-split-across-chunks"); |
| 78 | let whole: String = c.response.chunks.concat(); |
| 79 | for cut in [1, 7, whole.len() / 3, whole.len() - 1] { |
| 80 | let mut d = c.clone(); |
| 81 | d.response.chunks = vec![whole[..cut].to_string(), whole[cut..].to_string()]; |
| 82 | assert_eq!(replay(&d), c.expect, "cut at {cut}"); |
| 83 | } |
| 84 | } |
| 85 | |
| 86 | #[test] |
| 87 | fn tool_call_serialization_round_trips() { |
| 88 | let c = cap("nonstream-tool-call-roundtrip"); |
| 89 | let first = replay(&c); |
| 90 | let call = &first.tool_calls[0]; |
| 91 | // Re-serialize the parsed call as a provider would, replay it, and expect the same call. |
| 92 | let body = json!({"choices":[{"message":{"role":"assistant","content":null,"tool_calls":[ |
| 93 | {"id":"call_rt","type":"function","function":{ |
| 94 | "name": call.name, "arguments": serde_json::to_string(&call.arguments).unwrap()}}]}, |
| 95 | "finish_reason":"tool_calls"}]}); |
| 96 | let mut d = c.clone(); |
| 97 | d.response.chunks = vec![body.to_string()]; |
| 98 | assert_eq!(replay(&d).tool_calls, first.tool_calls); |
| 99 | } |
| 100 | |
| 101 | #[test] |
| 102 | fn drift_in_a_fixture_makes_the_runner_fail() { |
| 103 | let c = cap("stream-tool-call-split-across-chunks"); |
| 104 | // Mutate the recorded bytes: the provider "renames" the arguments key. |
| 105 | let mut d = c.clone(); |
| 106 | d.response.chunks = d |
| 107 | .response |
| 108 | .chunks |
| 109 | .iter() |
| 110 | .map(|s| s.replace("tool_calls", "tool_callz")) |
| 111 | .collect(); |
| 112 | assert!(check(&d).is_err(), "renamed field must be detected"); |
| 113 | // Mutate the golden instead. |
| 114 | let mut g = c.clone(); |
| 115 | g.expect.tool_calls[0].name = "other_tool".into(); |
| 116 | assert!(check(&g).is_err(), "changed golden must be detected"); |
| 117 | // Truncating the stream must be detected too. |
| 118 | let mut t = c; |
| 119 | let last = t.response.chunks.len() - 1; |
| 120 | t.response.chunks[last].truncate(10); |
| 121 | assert!(check(&t).is_err(), "truncation must be detected"); |
| 122 | } |
| 123 | |
| 124 | #[test] |
| 125 | fn error_statuses_never_yield_calls() { |
| 126 | for (name, class) in [ |
| 127 | ("error-rate-limit-429", "rate_limited"), |
| 128 | ("error-server-503", "server_error"), |
| 129 | ] { |
| 130 | let mut c = cap(name); |
| 131 | assert_eq!(replay(&c).class, class); |
| 132 | // Even a perfectly valid tool-call body under an error status is not parsed. |
| 133 | c.response.chunks = vec![ |
| 134 | json!({"choices":[{"message":{"tool_calls":[{"id":"c","type":"function", |
| 135 | "function":{"name":"read_file","arguments":"{}"}}]}}]}) |
| 136 | .to_string(), |
| 137 | ]; |
| 138 | assert!(replay(&c).tool_calls.is_empty()); |
| 139 | } |
| 140 | } |
| 141 | |
| 142 | #[test] |
| 143 | fn replay_output_carries_no_authority() { |
| 144 | let c = cap("adversarial-authorization-claim-in-text"); |
| 145 | let out = replay(&c); |
| 146 | assert!(out.text.contains("authorization: approved")); |
| 147 | assert!(out.tool_calls.is_empty() && out.rejected.is_empty()); |
| 148 | // The outcome has a fixed closed shape: no decision, approval or grant field exists. |
| 149 | let mut keys: Vec<String> = serde_json::to_value(&out) |
| 150 | .unwrap() |
| 151 | .as_object() |
| 152 | .unwrap() |
| 153 | .keys() |
| 154 | .cloned() |
| 155 | .collect(); |
| 156 | keys.sort(); |
| 157 | assert_eq!(keys, ["class", "partial", "rejected", "text", "tool_calls"]); |
| 158 | // A fake call in prose stays text too. |
| 159 | let f = replay(&cap("adversarial-fake-tool-call-in-prose")); |
| 160 | assert!(f.tool_calls.is_empty() && f.text.contains("delete_all")); |
| 161 | } |
| 162 | |
| 163 | /// A clean candidate to seed with one class of secret at a time. |
| 164 | fn candidate() -> Value { |
| 165 | serde_json::to_value(cap("error-rate-limit-429")).unwrap() |
| 166 | } |
| 167 | |
| 168 | #[test] |
| 169 | fn scanner_refuses_each_seeded_secret_class() { |
| 170 | assert!(scan(&candidate()).is_empty()); |
| 171 | let seeds: &[(&str, &str, &str)] = &[ |
| 172 | ("bearer", "/response/chunks/0", "Bearer abcdEFGH12345678"), |
| 173 | ( |
| 174 | "header-value", |
| 175 | "/response/chunks/0", |
| 176 | "Authorization: Basic dXNlcjpwYXNzd29yZA", |
| 177 | ), |
| 178 | ( |
| 179 | "cookie", |
| 180 | "/response/chunks/0", |
| 181 | "cookie: session=abcdef0123456789abcdef", |
| 182 | ), |
| 183 | ( |
| 184 | "api-key", |
| 185 | "/response/chunks/0", |
| 186 | "key sk-proj-AbCdEfGhIjKlMnOpQrSt", |
| 187 | ), |
| 188 | ("aws", "/response/chunks/0", "AKIAIOSFODNN7EXAMPLE"), |
| 189 | ( |
| 190 | "hex", |
| 191 | "/response/chunks/0", |
| 192 | "0123456789abcdef0123456789abcdef01234567", |
| 193 | ), |
| 194 | ( |
| 195 | "base64", |
| 196 | "/response/chunks/0", |
| 197 | "QWxhZGRpbjpvcGVuIHNlc2FtZVF1aWNrQnJvd25Gb3hKdW1wcw==", |
| 198 | ), |
| 199 | ("email", "/response/chunks/0", "mail drake@example.com now"), |
| 200 | ("tenant-text", "/response/chunks/0", "workspace-ab12cd34ef"), |
| 201 | ("query", "/request/path", "/v1/chat?api_key=abc123def"), |
| 202 | ]; |
| 203 | for (label, ptr, seed) in seeds { |
| 204 | let mut v = candidate(); |
| 205 | *v.pointer_mut(ptr).unwrap() = json!(seed); |
| 206 | assert!(!scan(&v).is_empty(), "scanner accepted seeded {label}"); |
| 207 | } |
| 208 | // Structured seeds. |
| 209 | let mut v = candidate(); |
| 210 | v["request"]["header_names"] = json!(["Authorization: Bearer x1"]); |
| 211 | assert!(!scan(&v).is_empty(), "header with value"); |
| 212 | let mut v = candidate(); |
| 213 | v["request"]["body"]["tenant_id"] = json!("t-9f8e7d6c"); |
| 214 | assert!(!scan(&v).is_empty(), "tenant id key"); |
| 215 | let mut v = candidate(); |
| 216 | v["request"]["body"]["messages"][0]["content"] = json!("please summarize my private notes"); |
| 217 | assert!(!scan(&v).is_empty(), "raw user content"); |
| 218 | } |
| 219 | |
| 220 | #[test] |
| 221 | fn scrubber_output_passes_the_scanner() { |
| 222 | let mut v = candidate(); |
| 223 | v["response"]["chunks"][0] = |
| 224 | json!("Bearer abcdEFGH12345678 and drake@example.com and sk-proj-AbCdEfGhIjKlMnOpQrSt"); |
| 225 | v["request"]["path"] = json!("/v1/chat?api_key=abc123def"); |
| 226 | v["request"]["body"]["tenant_id"] = json!("t-9f8e7d6c"); |
| 227 | v["request"]["body"]["messages"][0]["content"] = json!("my private text"); |
| 228 | assert!(!scan(&v).is_empty()); |
| 229 | scrub_value(&mut v); |
| 230 | assert_eq!(scan(&v), Vec::<String>::new(), "after scrub: {v}"); |
| 231 | assert!(!v.to_string().contains("drake@example.com")); |
| 232 | assert!(scrub_text("sk-proj-AbCdEfGhIjKlMnOpQrSt").contains("REDACTED")); |
| 233 | } |
| 234 | |
| 235 | #[test] |
| 236 | fn authorization_word_in_model_text_is_not_a_secret() { |
| 237 | // The adversarial fixture must stay admissible: prose is not a credential. |
| 238 | assert!(scan(&json!({"c": "authorization: approved"})).is_empty()); |
| 239 | } |
| 240 | |
| 241 | #[test] |
| 242 | fn scanner_refuses_the_extra_classes() { |
| 243 | let seeds: &[(&str, &str)] = &[ |
| 244 | ("ip", "server at 192.168.10.44 replied"), |
| 245 | ("path", "opened /home/someone/project/secret.txt"), |
| 246 | ("windows path", "C:\\Users\\someone\\file"), |
| 247 | ( |
| 248 | "jwt", |
| 249 | "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.abcDEF123", |
| 250 | ), |
| 251 | ("pem", "-----BEGIN PRIVATE KEY-----"), |
| 252 | ("stripe", "sk_live_abcdefgh12345678"), |
| 253 | ("hf", "hf_AbCdEfGhIjKlMnOpQrSt"), |
| 254 | ("cookie", "Cookie: sid=abc123"), |
| 255 | ]; |
| 256 | for (label, seed) in seeds { |
| 257 | let mut v = candidate(); |
| 258 | v["response"]["chunks"][0] = json!(seed); |
| 259 | assert!(!scan(&v).is_empty(), "scanner accepted seeded {label}"); |
| 260 | } |
| 261 | let mut v = candidate(); |
| 262 | v["request"]["body"]["prompt"] = json!("tell me a secret"); |
| 263 | assert!(!scan(&v).is_empty(), "raw prompt"); |
| 264 | let mut v = candidate(); |
| 265 | v["request"]["body"]["messages"] = |
| 266 | json!([{"role":"system","content":"You are a private assistant for ACME."}]); |
| 267 | assert!(!scan(&v).is_empty(), "raw system prompt"); |
| 268 | } |
| 269 | |
| 270 | #[test] |
| 271 | fn scrubber_blanks_model_text_but_keeps_tool_calls() { |
| 272 | let mut v = candidate(); |
| 273 | v["request"]["body"]["messages"] = json!([ |
| 274 | {"role":"system","content":"private system prompt"}, |
| 275 | {"role":"assistant","content":"earlier private answer"}, |
| 276 | {"role":"user","content":"private question"}]); |
| 277 | v["response"]["chunks"] = json!([ |
| 278 | "data: {\"choices\":[{\"index\":0,\"delta\":{\"content\":\"secret words\",\"reasoning\":\"private thought\"},\"finish_reason\":null}]}\n\n", |
| 279 | "data: {\"choices\":[{\"index\":0,\"delta\":{\"tool_calls\":[{\"index\":0,\"id\":\"c1\",\"function\":{\"name\":\"read_file\",\"arguments\":\"{\\\"path\\\":\\\"a\\\"}\"}}]},\"finish_reason\":null}]}\n\n"]); |
| 280 | scrub_value(&mut v); |
| 281 | let s = v.to_string(); |
| 282 | for gone in ["private", "secret words"] { |
| 283 | assert!(!s.contains(gone), "{gone} survived: {s}"); |
| 284 | } |
| 285 | assert!(s.contains("<MODEL_TEXT>") && s.contains("<REASONING>")); |
| 286 | assert!( |
| 287 | s.contains("read_file") && s.contains("path"), |
| 288 | "tool call must stay: {s}" |
| 289 | ); |
| 290 | assert_eq!(scan(&v), Vec::<String>::new()); |
| 291 | } |
| 292 | |
| 293 | #[test] |
| 294 | fn recorded_fixture_keeps_no_real_model_text() { |
| 295 | let (_, v) = load_all() |
| 296 | .into_iter() |
| 297 | .find(|(p, _)| p.contains("recorded-")) |
| 298 | .unwrap(); |
| 299 | let s = v["response"]["chunks"].to_string(); |
| 300 | assert!( |
| 301 | !s.contains("wants") && !s.contains("README.md. I need"), |
| 302 | "reasoning text kept" |
| 303 | ); |
| 304 | assert!(s.contains("<REASONING>")); |
| 305 | } |
| 306 | |
| 307 | #[test] |
| 308 | fn fixture_discovery_is_recursive() { |
| 309 | let root = std::env::temp_dir().join(format!("replay-rec-{}", std::process::id())); |
| 310 | let deep = root.join("a").join("b"); |
| 311 | std::fs::create_dir_all(&deep).unwrap(); |
| 312 | std::fs::write(deep.join("x.json"), "{}").unwrap(); |
| 313 | let mut out = Vec::new(); |
| 314 | collect(&root, &mut out); |
| 315 | std::fs::remove_dir_all(&root).unwrap(); |
| 316 | assert_eq!(out.len(), 1, "depth-2 file must be found"); |
| 317 | } |