Skip to main content

guardrail_proxy/
translate.rs

1//! Conversion between raw JSON request bodies and [`GuardrailRequest`].
2//!
3//! The original JSON body is the source of truth. [`parse_body`] walks it
4//! and pulls out every string the stages should scan, remembering where
5//! each one came from (a JSON pointer). Stages see those strings as a
6//! [`GuardrailRequest`]. [`ScannedBody::apply`] then writes the (possibly
7//! redacted) strings back to the same places in the original body.
8//! Everything else in the body (tool calls, images, `cache_control`,
9//! unknown fields and part types) is never rebuilt, so it reaches the
10//! upstream exactly as the client sent it.
11//!
12//! # What is scanned
13//!
14//! | Provider | Strings |
15//! |----------|---------|
16//! | OpenAI-compatible | message `content` strings, `text` and `refusal` parts, assistant `refusal`, `tool_calls[].function.arguments`, legacy `function_call.arguments` |
17//! | Anthropic | top-level `system` (string or text blocks), message `content` strings, `text` blocks, `tool_use` input (every string value), `tool_result` content (string or text blocks), plain-text `document` sources |
18//! | OpenAI Responses | `instructions`, `input` (a string, or items: message `content` strings and `input_text` / `output_text` / `refusal` parts, `function_call` arguments, `function_call_output` output) |
19//!
20//! Images, audio and files are not scanned (there is no text to scan), and
21//! Anthropic `thinking` blocks are left alone: they are signed, and
22//! changing them would make the upstream reject the request.
23
24use guardrail_core::{
25    request::{
26        ChatMessage, ContentPart, GuardrailRequest, ImageUrl, MessageContent, Provider, Role,
27    },
28    GuardrailError,
29};
30use serde_json::{json, Value};
31
32/// A parsed request body, with the location of every string the stages
33/// scan. Produced by [`parse_body`].
34#[derive(Debug, Clone)]
35pub struct ScannedBody {
36    body: Value,
37    /// For each message of the [`GuardrailRequest`], the JSON pointers of
38    /// its text, in the order the message's text parts appear.
39    pointers: Vec<Vec<String>>,
40}
41
42impl ScannedBody {
43    /// The original body.
44    pub fn body(&self) -> &Value {
45        &self.body
46    }
47
48    /// Write the text of `req` (normally the pipeline's final, possibly
49    /// redacted request) back into the original body and return it.
50    ///
51    /// # Errors
52    ///
53    /// Returns [`GuardrailError::Internal`] if `req` no longer lines up
54    /// with the body: a different number of messages, or of text parts in a
55    /// message. Built-in stages never do that; the caller should refuse to
56    /// forward rather than send text that may not have been redacted.
57    ///
58    /// # Examples
59    ///
60    /// ```rust
61    /// use guardrail_core::request::{MessageContent, Provider};
62    /// use guardrail_proxy::translate::parse_body;
63    ///
64    /// let body = br#"{"model":"gpt-4o","messages":[{"role":"user","name":"al","content":"hi al@example.com"}]}"#;
65    /// let (mut req, scanned) = parse_body(body, Provider::OpenAI).unwrap();
66    /// req.messages[0].content = MessageContent::Text("hi [EMAIL]".into());
67    ///
68    /// let out = scanned.apply(&req).unwrap();
69    /// assert_eq!(out["messages"][0]["content"], "hi [EMAIL]");
70    /// assert_eq!(out["messages"][0]["name"], "al");
71    /// ```
72    pub fn apply(mut self, req: &GuardrailRequest) -> Result<Value, GuardrailError> {
73        if req.messages.len() != self.pointers.len() {
74            return Err(GuardrailError::Internal(format!(
75                "request has {} messages after the pipeline, expected {}",
76                req.messages.len(),
77                self.pointers.len()
78            )));
79        }
80        for (i, (message, pointers)) in req.messages.iter().zip(&self.pointers).enumerate() {
81            let texts = message_texts(&message.content);
82            if texts.len() != pointers.len() {
83                // A message with no text (e.g. only an image) is `Text("")`.
84                if pointers.is_empty() && texts.iter().all(|t| t.is_empty()) {
85                    continue;
86                }
87                return Err(GuardrailError::Internal(format!(
88                    "message {i} has {} text parts after the pipeline, expected {}",
89                    texts.len(),
90                    pointers.len()
91                )));
92            }
93            for (pointer, text) in pointers.iter().zip(texts) {
94                let slot = self.body.pointer_mut(pointer).ok_or_else(|| {
95                    GuardrailError::Internal(format!("request body has no {pointer}"))
96                })?;
97                if slot.as_str() != Some(text) {
98                    *slot = Value::String(text.to_string());
99                }
100            }
101        }
102        Ok(self.body)
103    }
104}
105
106/// The text parts of `content`, in order.
107fn message_texts(content: &MessageContent) -> Vec<&str> {
108    match content {
109        MessageContent::Text(text) => vec![text.as_str()],
110        MessageContent::Parts(parts) => parts
111            .iter()
112            .filter_map(|p| match p {
113                ContentPart::Text { text } => Some(text.as_str()),
114                ContentPart::ImageUrl { .. } => None,
115            })
116            .collect(),
117    }
118}
119
120/// Parse a raw JSON request body into a [`GuardrailRequest`].
121///
122/// Shorthand for [`parse_body`] when the body itself isn't needed.
123///
124/// # Errors
125///
126/// As for [`parse_body`].
127///
128/// # Examples
129///
130/// ```rust
131/// use guardrail_proxy::translate::parse_request;
132/// use guardrail_core::request::Provider;
133///
134/// let body = br#"{
135///     "model": "gpt-4o",
136///     "messages": [{"role": "user", "content": "Hello"}]
137/// }"#;
138///
139/// let req = parse_request(body, Provider::OpenAI).unwrap();
140/// assert_eq!(req.model, "gpt-4o");
141/// assert_eq!(req.messages.len(), 1);
142/// ```
143pub fn parse_request(body: &[u8], provider: Provider) -> Result<GuardrailRequest, GuardrailError> {
144    parse_body(body, provider).map(|(req, _)| req)
145}
146
147/// The shape of a scanned request body.
148#[derive(Debug, Clone, Copy, PartialEq, Eq)]
149pub enum Api {
150    /// OpenAI-compatible `/v1/chat/completions` (also Azure OpenAI).
151    ChatCompletions,
152    /// Anthropic `/v1/messages`.
153    Messages,
154    /// OpenAI `/v1/responses`.
155    Responses,
156}
157
158/// Like [`parse_body`], for any [`Api`]. `default_model` is used when the
159/// body has no `model` (Azure OpenAI puts the deployment in the path
160/// instead); with `None`, a missing `model` is an error for chat
161/// completions and messages. A Responses body may omit both `model` and
162/// `input`.
163///
164/// # Errors
165///
166/// As for [`parse_body`].
167///
168/// # Examples
169///
170/// ```rust
171/// use guardrail_core::request::{Provider, Role};
172/// use guardrail_proxy::translate::{parse_api_body, Api};
173///
174/// let body = br#"{"model": "gpt-4.1", "instructions": "Be brief.", "input": "Hi"}"#;
175/// let (req, _) = parse_api_body(body, Api::Responses, Provider::OpenAI, None).unwrap();
176/// assert_eq!(req.messages[0].role, Role::System);
177/// assert_eq!(req.messages[1].role, Role::User);
178/// ```
179pub fn parse_api_body(
180    body: &[u8],
181    api: Api,
182    provider: Provider,
183    default_model: Option<&str>,
184) -> Result<(GuardrailRequest, ScannedBody), GuardrailError> {
185    let value: Value = serde_json::from_slice(body)?;
186
187    let model = match (value.get("model").and_then(Value::as_str), default_model) {
188        (Some(model), _) => model.to_string(),
189        (None, Some(default)) => default.to_string(),
190        (None, None) if api == Api::Responses => String::new(),
191        (None, None) => {
192            return Err(GuardrailError::Internal(
193                "missing or invalid 'model' field".into(),
194            ))
195        }
196    };
197    let stream = value
198        .get("stream")
199        .and_then(Value::as_bool)
200        .unwrap_or(false);
201
202    let extracted = match api {
203        Api::ChatCompletions | Api::Messages => extract_chat(&value, api)?,
204        Api::Responses => extract_responses(&value)?,
205    };
206
207    let mut extra = value.clone();
208    if let Value::Object(map) = &mut extra {
209        map.remove("model");
210        map.remove("messages");
211        map.remove("stream");
212    }
213
214    let (messages, pointers) = extracted.into_iter().map(Extracted::finish).unzip();
215    let req = GuardrailRequest {
216        id: uuid::Uuid::new_v4(),
217        received_at: std::time::SystemTime::now(),
218        messages,
219        provider,
220        model,
221        stream,
222        extra,
223    };
224    Ok((
225        req,
226        ScannedBody {
227            body: value,
228            pointers,
229        },
230    ))
231}
232
233/// Parse a raw JSON request body into the [`GuardrailRequest`] the stages
234/// see, plus a [`ScannedBody`] to write their changes back with.
235///
236/// `GuardrailRequest::extra` holds the body without `model`, `messages` and
237/// `stream`, for stages that want other fields. An Anthropic top-level
238/// `system` becomes a leading system message.
239///
240/// # Errors
241///
242/// Returns [`GuardrailError::Serialization`] if `body` is not valid JSON, or
243/// [`GuardrailError::Internal`] if `model` or `messages` is missing or
244/// malformed, or a message has an unknown role.
245pub fn parse_body(
246    body: &[u8],
247    provider: Provider,
248) -> Result<(GuardrailRequest, ScannedBody), GuardrailError> {
249    let api = if provider == Provider::Anthropic {
250        Api::Messages
251    } else {
252        Api::ChatCompletions
253    };
254    parse_api_body(body, api, provider, None)
255}
256
257/// Chat completions and Anthropic messages: `messages`, plus the Anthropic
258/// top-level `system`.
259fn extract_chat(value: &Value, api: Api) -> Result<Vec<Extracted>, GuardrailError> {
260    let messages = value
261        .get("messages")
262        .ok_or_else(|| GuardrailError::Internal("missing 'messages' field".into()))?
263        .as_array()
264        .ok_or_else(|| GuardrailError::Internal("'messages' must be an array".into()))?;
265
266    let mut extracted = Vec::with_capacity(messages.len() + 1);
267    if api == Api::Messages {
268        if let Some(system) = extract_anthropic_system(value.get("system"))? {
269            extracted.push(system);
270        }
271    }
272    for (i, message) in messages.iter().enumerate() {
273        extracted.push(extract_message(message, i, api)?);
274    }
275    Ok(extracted)
276}
277
278/// OpenAI Responses: `instructions` and `input`.
279fn extract_responses(value: &Value) -> Result<Vec<Extracted>, GuardrailError> {
280    let mut extracted = Vec::new();
281    if let Some(instructions) = value.get("instructions").and_then(Value::as_str) {
282        let mut system = Extracted::new(Role::System);
283        system.plain_text("/instructions".into(), instructions);
284        extracted.push(system);
285    }
286    match value.get("input") {
287        None | Some(Value::Null) => {}
288        Some(Value::String(s)) => {
289            let mut user = Extracted::new(Role::User);
290            user.plain_text("/input".into(), s);
291            extracted.push(user);
292        }
293        Some(Value::Array(items)) => {
294            for (i, item) in items.iter().enumerate() {
295                if let Some(message) = extract_responses_item(item, i)? {
296                    extracted.push(message);
297                }
298            }
299        }
300        Some(other) => {
301            return Err(GuardrailError::Internal(format!(
302                "'input' has unsupported JSON type: {other}"
303            )))
304        }
305    }
306    Ok(extracted)
307}
308
309/// One Responses `input` item. Items with no text (reasoning, item
310/// references, built-in tool calls) are skipped.
311fn extract_responses_item(item: &Value, i: usize) -> Result<Option<Extracted>, GuardrailError> {
312    let base = format!("/input/{i}");
313    let kind = item.get("type").and_then(Value::as_str);
314    match kind {
315        None | Some("message") => {
316            let role = item
317                .get("role")
318                .and_then(Value::as_str)
319                .ok_or_else(|| GuardrailError::Internal(format!("input[{i}] missing 'role'")))?;
320            let mut out = Extracted::new(role_from_str(role, &format!("input[{i}]"))?);
321            match item.get("content") {
322                Some(Value::String(s)) => out.plain_text(format!("{base}/content"), s),
323                Some(Value::Array(parts)) => {
324                    for (j, part) in parts.iter().enumerate() {
325                        let at = format!("{base}/content/{j}");
326                        match part.get("type").and_then(Value::as_str) {
327                            Some("input_text" | "output_text" | "text") => {
328                                if let Some(text) = part.get("text").and_then(Value::as_str) {
329                                    out.text(format!("{at}/text"), text);
330                                }
331                            }
332                            Some("refusal") => {
333                                if let Some(text) = part.get("refusal").and_then(Value::as_str) {
334                                    out.text(format!("{at}/refusal"), text);
335                                }
336                            }
337                            Some("input_image") => {
338                                if let Some(url) = part.get("image_url").and_then(Value::as_str) {
339                                    out.segments.push(Segment::Image(ImageUrl {
340                                        url: url.to_string(),
341                                        detail: part
342                                            .get("detail")
343                                            .and_then(Value::as_str)
344                                            .map(String::from),
345                                    }));
346                                }
347                            }
348                            _ => {}
349                        }
350                    }
351                }
352                _ => {}
353            }
354            Ok(Some(out))
355        }
356        Some("function_call") => {
357            let mut out = Extracted::new(Role::Assistant);
358            if let Some(args) = item.get("arguments").and_then(Value::as_str) {
359                out.text(format!("{base}/arguments"), args);
360            }
361            Ok(Some(out))
362        }
363        Some("function_call_output") => {
364            let mut out = Extracted::new(Role::Tool);
365            match item.get("output") {
366                Some(Value::String(s)) => out.text(format!("{base}/output"), s),
367                Some(Value::Array(parts)) => {
368                    for (j, part) in parts.iter().enumerate() {
369                        if let Some(text) = part.get("text").and_then(Value::as_str) {
370                            out.text(format!("{base}/output/{j}/text"), text);
371                        }
372                    }
373                }
374                _ => {}
375            }
376            Ok(Some(out))
377        }
378        Some(_) => Ok(None),
379    }
380}
381
382/// One message's scannable text, with where each piece came from.
383struct Extracted {
384    role: Role,
385    segments: Vec<Segment>,
386    /// The message's content is a single string with nothing else
387    /// extracted: it is presented as `MessageContent::Text`.
388    plain: bool,
389}
390
391enum Segment {
392    Text { pointer: String, text: String },
393    Image(ImageUrl),
394}
395
396impl Extracted {
397    fn new(role: Role) -> Self {
398        Self {
399            role,
400            segments: Vec::new(),
401            plain: false,
402        }
403    }
404
405    /// Text from a content field that is a plain string.
406    fn plain_text(&mut self, pointer: String, text: &str) {
407        self.plain = self.segments.is_empty();
408        self.text(pointer, text);
409    }
410
411    fn text(&mut self, pointer: String, text: &str) {
412        if !self.segments.is_empty() {
413            self.plain = false;
414        }
415        self.segments.push(Segment::Text {
416            pointer,
417            text: text.to_string(),
418        });
419    }
420
421    fn finish(self) -> (ChatMessage, Vec<String>) {
422        let mut pointers = Vec::new();
423        let mut parts = Vec::with_capacity(self.segments.len());
424        for segment in self.segments {
425            match segment {
426                Segment::Text { pointer, text } => {
427                    pointers.push(pointer);
428                    parts.push(ContentPart::Text { text });
429                }
430                Segment::Image(image_url) => parts.push(ContentPart::ImageUrl { image_url }),
431            }
432        }
433        let content = match parts.as_slice() {
434            [] => MessageContent::Text(String::new()),
435            [ContentPart::Text { text }] if self.plain => MessageContent::Text(text.clone()),
436            _ => MessageContent::Parts(parts),
437        };
438        (
439            ChatMessage {
440                role: self.role,
441                content,
442            },
443            pointers,
444        )
445    }
446}
447
448/// The Anthropic top-level `system`: a string, or an array of text blocks.
449fn extract_anthropic_system(system: Option<&Value>) -> Result<Option<Extracted>, GuardrailError> {
450    let mut out = Extracted::new(Role::System);
451    match system {
452        None | Some(Value::Null) => {}
453        Some(Value::String(s)) => out.plain_text("/system".into(), s),
454        Some(Value::Array(blocks)) => {
455            for (j, block) in blocks.iter().enumerate() {
456                if let Some(text) = text_block(block) {
457                    out.text(format!("/system/{j}/text"), text);
458                }
459            }
460        }
461        Some(other) => {
462            return Err(GuardrailError::Internal(format!(
463                "'system' has unsupported JSON type: {other}"
464            )))
465        }
466    }
467    Ok((!out.segments.is_empty()).then_some(out))
468}
469
470fn parse_role(message: &Value, i: usize) -> Result<Role, GuardrailError> {
471    let role = message
472        .get("role")
473        .and_then(Value::as_str)
474        .ok_or_else(|| GuardrailError::Internal(format!("messages[{i}] missing 'role' field")))?;
475    role_from_str(role, &format!("messages[{i}]"))
476}
477
478fn role_from_str(role: &str, location: &str) -> Result<Role, GuardrailError> {
479    match role {
480        "system" | "developer" => Ok(Role::System),
481        "user" => Ok(Role::User),
482        "assistant" => Ok(Role::Assistant),
483        "tool" | "function" => Ok(Role::Tool),
484        other => Err(GuardrailError::Internal(format!(
485            "{location} has unknown role '{other}'"
486        ))),
487    }
488}
489
490fn extract_message(message: &Value, i: usize, api: Api) -> Result<Extracted, GuardrailError> {
491    let mut out = Extracted::new(parse_role(message, i)?);
492    let base = format!("/messages/{i}");
493    let anthropic = api == Api::Messages;
494
495    match message.get("content") {
496        None | Some(Value::Null) => {}
497        Some(Value::String(s)) => out.plain_text(format!("{base}/content"), s),
498        Some(Value::Array(parts)) => {
499            for (j, part) in parts.iter().enumerate() {
500                let at = format!("{base}/content/{j}");
501                if anthropic {
502                    extract_anthropic_block(part, &at, &mut out);
503                } else {
504                    extract_openai_part(part, &at, &mut out);
505                }
506            }
507        }
508        Some(other) => {
509            return Err(GuardrailError::Internal(format!(
510                "messages[{i}] 'content' has unsupported JSON type: {other}"
511            )))
512        }
513    }
514
515    if !anthropic {
516        if let Some(refusal) = message.get("refusal").and_then(Value::as_str) {
517            out.text(format!("{base}/refusal"), refusal);
518        }
519        if let Some(calls) = message.get("tool_calls").and_then(Value::as_array) {
520            for (k, call) in calls.iter().enumerate() {
521                if let Some(args) = call.pointer("/function/arguments").and_then(Value::as_str) {
522                    out.text(format!("{base}/tool_calls/{k}/function/arguments"), args);
523                }
524            }
525        }
526        if let Some(args) = message
527            .pointer("/function_call/arguments")
528            .and_then(Value::as_str)
529        {
530            out.text(format!("{base}/function_call/arguments"), args);
531        }
532    }
533    Ok(out)
534}
535
536/// An OpenAI content part. Parts with no text (audio, files, unknown
537/// types) are skipped.
538fn extract_openai_part(part: &Value, at: &str, out: &mut Extracted) {
539    match part.get("type").and_then(Value::as_str).unwrap_or("text") {
540        "text" => {
541            if let Some(text) = part.get("text").and_then(Value::as_str) {
542                out.text(format!("{at}/text"), text);
543            }
544        }
545        "refusal" => {
546            if let Some(text) = part.get("refusal").and_then(Value::as_str) {
547                out.text(format!("{at}/refusal"), text);
548            }
549        }
550        "image_url" => {
551            if let Some(url) = part.pointer("/image_url/url").and_then(Value::as_str) {
552                out.segments.push(Segment::Image(ImageUrl {
553                    url: url.to_string(),
554                    detail: part
555                        .pointer("/image_url/detail")
556                        .and_then(Value::as_str)
557                        .map(String::from),
558                }));
559            }
560        }
561        _ => {}
562    }
563}
564
565/// An Anthropic content block. Blocks with no text (images, `thinking`,
566/// unknown types) are skipped.
567fn extract_anthropic_block(block: &Value, at: &str, out: &mut Extracted) {
568    match block.get("type").and_then(Value::as_str) {
569        Some("text") => {
570            if let Some(text) = block.get("text").and_then(Value::as_str) {
571                out.text(format!("{at}/text"), text);
572            }
573        }
574        Some("tool_use") => {
575            if let Some(input) = block.get("input") {
576                extract_strings(input, &format!("{at}/input"), out);
577            }
578        }
579        Some("tool_result") => match block.get("content") {
580            Some(Value::String(s)) => out.text(format!("{at}/content"), s),
581            Some(Value::Array(inner)) => {
582                for (m, inner_block) in inner.iter().enumerate() {
583                    if let Some(text) = text_block(inner_block) {
584                        out.text(format!("{at}/content/{m}/text"), text);
585                    }
586                }
587            }
588            _ => {}
589        },
590        Some("document")
591            if block.pointer("/source/type").and_then(Value::as_str) == Some("text") =>
592        {
593            if let Some(data) = block.pointer("/source/data").and_then(Value::as_str) {
594                out.text(format!("{at}/source/data"), data);
595            }
596        }
597        _ => {}
598    }
599}
600
601/// Every string inside `value` (tool-call input), depth first.
602fn extract_strings(value: &Value, at: &str, out: &mut Extracted) {
603    match value {
604        Value::String(s) => out.text(at.to_string(), s),
605        Value::Array(items) => {
606            for (n, item) in items.iter().enumerate() {
607                extract_strings(item, &format!("{at}/{n}"), out);
608            }
609        }
610        Value::Object(map) => {
611            for (key, item) in map {
612                extract_strings(item, &format!("{at}/{}", escape_pointer(key)), out);
613            }
614        }
615        _ => {}
616    }
617}
618
619/// Escape an object key for use in a JSON pointer (RFC 6901).
620fn escape_pointer(key: &str) -> String {
621    key.replace('~', "~0").replace('/', "~1")
622}
623
624/// The `text` of a `{"type": "text", "text": ..}` block.
625fn text_block(block: &Value) -> Option<&str> {
626    if block.get("type").and_then(Value::as_str) != Some("text") {
627        return None;
628    }
629    block.get("text").and_then(Value::as_str)
630}
631
632/// Build a JSON error body for a blocked request, matching the OpenAI error
633/// envelope shape so client SDKs can parse it without special-casing.
634///
635/// # Examples
636///
637/// ```rust
638/// use guardrail_proxy::translate::block_response_body;
639/// use guardrail_core::decision::BlockCode;
640///
641/// let body = block_response_body("Prompt injection detected.", &BlockCode::PromptInjection, "req-123");
642/// assert_eq!(body["error"]["code"], "prompt_injection");
643/// assert_eq!(body["error"]["guardrail_request_id"], "req-123");
644/// ```
645pub fn block_response_body(
646    reason: &str,
647    code: &guardrail_core::decision::BlockCode,
648    request_id: &str,
649) -> Value {
650    json!({
651        "error": {
652            "message": reason,
653            "type": "guardrail_block",
654            "code": code.as_str(),
655            "guardrail_request_id": request_id,
656        }
657    })
658}
659
660#[cfg(test)]
661mod tests {
662    use super::*;
663
664    fn openai(body: &[u8]) -> (GuardrailRequest, ScannedBody) {
665        parse_body(body, Provider::OpenAI).unwrap()
666    }
667
668    fn anthropic(body: &[u8]) -> (GuardrailRequest, ScannedBody) {
669        parse_body(body, Provider::Anthropic).unwrap()
670    }
671
672    /// Run the default PII redactor over `req` the way the pipeline would,
673    /// and write the result back.
674    fn redact_and_apply(req: GuardrailRequest, scanned: ScannedBody) -> Value {
675        let redactor = guardrail_classifiers::PiiRedactor::default();
676        let req = match redactor.redact_request(&req) {
677            Some((mutated, _)) => mutated,
678            None => req,
679        };
680        scanned.apply(&req).unwrap()
681    }
682
683    #[test]
684    fn test_parse_simple_openai_request() {
685        let (req, _) = openai(
686            br#"{
687            "model": "gpt-4o",
688            "messages": [
689                {"role": "system", "content": "You are helpful."},
690                {"role": "user", "content": "Hello!"}
691            ],
692            "temperature": 0.5
693        }"#,
694        );
695        assert_eq!(req.model, "gpt-4o");
696        assert_eq!(req.messages.len(), 2);
697        assert_eq!(
698            req.messages[1].content,
699            MessageContent::Text("Hello!".into())
700        );
701        assert_eq!(req.extra["temperature"], 0.5);
702        assert!(req.extra.get("messages").is_none());
703    }
704
705    #[test]
706    fn test_parse_errors() {
707        for body in [
708            &br#"{"messages": []}"#[..],
709            br#"{"model": "gpt-4o"}"#,
710            b"not json",
711            br#"{"model": "gpt-4o", "messages": "not-an-array"}"#,
712            br#"{"model": "gpt-4o", "messages": [{"content": "Hi"}]}"#,
713            br#"{"model": "gpt-4o", "messages": [{"role": "alien", "content": "Hi"}]}"#,
714            br#"{"model": "gpt-4o", "messages": [{"role": "user", "content": 42}]}"#,
715        ] {
716            assert!(
717                parse_body(body, Provider::OpenAI).is_err(),
718                "{}",
719                String::from_utf8_lossy(body)
720            );
721        }
722    }
723
724    #[test]
725    fn test_roles() {
726        let (req, _) = openai(
727            br#"{"model": "m", "messages": [
728                {"role": "system", "content": "a"},
729                {"role": "developer", "content": "b"},
730                {"role": "user", "content": "c"},
731                {"role": "assistant", "content": "d"},
732                {"role": "tool", "tool_call_id": "t", "content": "e"},
733                {"role": "function", "name": "f", "content": "f"}
734            ]}"#,
735        );
736        let roles: Vec<Role> = req.messages.iter().map(|m| m.role.clone()).collect();
737        assert_eq!(
738            roles,
739            [
740                Role::System,
741                Role::System,
742                Role::User,
743                Role::Assistant,
744                Role::Tool,
745                Role::Tool
746            ]
747        );
748    }
749
750    #[test]
751    fn test_message_without_content_is_allowed() {
752        let body = br#"{"model": "m", "messages": [{"role": "user"}]}"#;
753        let (req, scanned) = openai(body);
754        assert_eq!(req.messages[0].content, MessageContent::Text(String::new()));
755        let original: Value = serde_json::from_slice(body).unwrap();
756        assert_eq!(scanned.apply(&req).unwrap(), original);
757    }
758
759    #[test]
760    fn test_multipart_text_and_images_are_extracted() {
761        let (req, _) = openai(
762            br#"{"model": "gpt-4o", "messages": [{"role": "user", "content": [
763                {"type": "text", "text": "What's in this image?"},
764                {"type": "image_url", "image_url": {"url": "https://example.com/img.png", "detail": "high"}},
765                {"type": "input_audio", "input_audio": {"data": "AAAA", "format": "wav"}},
766                {"type": "video", "video": "x"}
767            ]}]}"#,
768        );
769        let MessageContent::Parts(parts) = &req.messages[0].content else {
770            panic!("expected parts")
771        };
772        assert_eq!(parts.len(), 2);
773        assert_eq!(req.messages[0].content.as_text(), "What's in this image?");
774        assert!(
775            matches!(&parts[1], ContentPart::ImageUrl { image_url } if image_url.detail.as_deref() == Some("high"))
776        );
777    }
778
779    #[test]
780    fn test_tool_call_arguments_and_refusals_are_scanned() {
781        let (req, _) = openai(
782            br#"{"model": "m", "messages": [{"role": "assistant", "content": "calling",
783                "refusal": "no",
784                "tool_calls": [{"id": "c", "type": "function", "function": {"name": "f", "arguments": "{\"q\":1}"}}],
785                "function_call": {"name": "g", "arguments": "{\"r\":2}"}
786            }]}"#,
787        );
788        let texts = message_texts(&req.messages[0].content);
789        assert_eq!(texts, ["calling", "no", "{\"q\":1}", "{\"r\":2}"]);
790    }
791
792    #[test]
793    fn test_body_is_returned_unchanged_when_nothing_is_redacted() {
794        let body = br#"{
795            "model": "gpt-4o",
796            "messages": [
797                {"role": "user", "name": "alice", "content": "Hi"},
798                {"role": "assistant", "content": null, "tool_calls": [
799                    {"id": "c1", "type": "function", "function": {"name": "f", "arguments": "{}"}}
800                ]},
801                {"role": "tool", "tool_call_id": "c1", "content": "ok"}
802            ],
803            "tools": [{"type": "function", "function": {"name": "f"}}],
804            "temperature": 0.7
805        }"#;
806        let (req, scanned) = openai(body);
807        let original: Value = serde_json::from_slice(body).unwrap();
808        let out = redact_and_apply(req, scanned);
809        assert_eq!(out, original);
810        assert!(out.get("stream").is_none(), "no stream key is added");
811    }
812
813    #[test]
814    fn test_redactions_land_on_their_own_pointers() {
815        let (req, scanned) = openai(
816            br#"{"model": "m", "messages": [{"role": "assistant", "content": [
817                {"type": "text", "text": "a@example.com"},
818                {"type": "image_url", "image_url": {"url": "https://example.com/x.png"}},
819                {"type": "text", "text": "clean"}
820            ], "tool_calls": [{"id": "c", "type": "function",
821                "function": {"name": "f", "arguments": "{\"to\":\"b@example.com\"}"}}]}]}"#,
822        );
823        let out = redact_and_apply(req, scanned);
824        let msg = &out["messages"][0];
825        assert_eq!(msg["content"][0]["text"], "[EMAIL]");
826        assert_eq!(
827            msg["content"][1]["image_url"]["url"],
828            "https://example.com/x.png"
829        );
830        assert_eq!(msg["content"][2]["text"], "clean");
831        assert_eq!(
832            msg["tool_calls"][0]["function"]["arguments"],
833            "{\"to\":\"[EMAIL]\"}"
834        );
835    }
836
837    #[test]
838    fn test_anthropic_system_string_is_scanned_and_written_back() {
839        let (req, scanned) = anthropic(
840            br#"{"model": "m", "system": "mail bob@example.com", "messages": [{"role": "user", "content": "Hi"}]}"#,
841        );
842        assert_eq!(req.messages.len(), 2);
843        assert_eq!(req.messages[0].role, Role::System);
844        let out = redact_and_apply(req, scanned);
845        assert_eq!(out["system"], "mail [EMAIL]");
846        assert_eq!(out["messages"].as_array().unwrap().len(), 1);
847    }
848
849    #[test]
850    fn test_anthropic_system_blocks_keep_cache_control() {
851        let (req, scanned) = anthropic(
852            br#"{"model": "m", "system": [
853                {"type": "text", "text": "You are a support bot."},
854                {"type": "text", "text": "mail bob@example.com", "cache_control": {"type": "ephemeral"}}
855            ], "messages": [{"role": "user", "content": "Hi"}]}"#,
856        );
857        assert!(req.all_text().contains("bob@example.com"));
858        let out = redact_and_apply(req, scanned);
859        assert_eq!(out["system"][0]["text"], "You are a support bot.");
860        assert_eq!(out["system"][1]["text"], "mail [EMAIL]");
861        assert_eq!(out["system"][1]["cache_control"]["type"], "ephemeral");
862    }
863
864    #[test]
865    fn test_anthropic_blocks() {
866        let (req, scanned) = anthropic(
867            br#"{"model": "m", "messages": [
868                {"role": "user", "content": [
869                    {"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": "iVBOR"}},
870                    {"type": "document", "source": {"type": "text", "media_type": "text/plain", "data": "doc e@example.com"}},
871                    {"type": "tool_result", "tool_use_id": "t", "content": "result f@example.com"}
872                ]},
873                {"role": "assistant", "content": [
874                    {"type": "thinking", "thinking": "g@example.com", "signature": "sig"},
875                    {"type": "tool_use", "id": "t", "name": "n", "input": {"a/b": ["h@example.com", 3], "c~d": {"e": "x"}}}
876                ]}
877            ]}"#,
878        );
879        assert_eq!(
880            message_texts(&req.messages[0].content),
881            ["doc e@example.com", "result f@example.com"]
882        );
883        // Thinking is not scanned; tool_use input strings are.
884        assert_eq!(
885            message_texts(&req.messages[1].content),
886            ["h@example.com", "x"]
887        );
888
889        let out = redact_and_apply(req, scanned);
890        let user = &out["messages"][0]["content"];
891        assert_eq!(user[1]["source"]["data"], "doc [EMAIL]");
892        assert_eq!(user[2]["content"], "result [EMAIL]");
893        let assistant = &out["messages"][1]["content"];
894        assert_eq!(assistant[0]["thinking"], "g@example.com");
895        assert_eq!(assistant[1]["input"]["a/b"][0], "[EMAIL]");
896        assert_eq!(assistant[1]["input"]["a/b"][1], 3);
897        assert_eq!(assistant[1]["input"]["c~d"]["e"], "x");
898    }
899
900    #[test]
901    fn test_apply_refuses_a_request_that_no_longer_lines_up() {
902        let (mut req, scanned) = openai(
903            br#"{"model": "m", "messages": [{"role": "user", "content": [
904                {"type": "text", "text": "a"}, {"type": "text", "text": "b"}
905            ]}]}"#,
906        );
907        req.messages[0].content = MessageContent::Text("ab".into());
908        assert!(scanned.clone().apply(&req).is_err());
909        req.messages.clear();
910        assert!(scanned.apply(&req).is_err());
911    }
912
913    #[test]
914    fn test_block_response_body_shape() {
915        let body = block_response_body(
916            "test reason",
917            &guardrail_core::decision::BlockCode::PromptInjection,
918            "req-abc",
919        );
920        assert_eq!(body["error"]["message"], "test reason");
921        assert_eq!(body["error"]["code"], "prompt_injection");
922        assert_eq!(body["error"]["guardrail_request_id"], "req-abc");
923        assert_eq!(body["error"]["type"], "guardrail_block");
924    }
925
926    #[test]
927    fn test_responses_body() {
928        let body = br#"{
929            "model": "gpt-4.1",
930            "instructions": "Be brief.",
931            "input": [
932                {"role": "developer", "content": "dev a@example.com"},
933                {"type": "message", "role": "user", "content": [
934                    {"type": "input_text", "text": "hi b@example.com"},
935                    {"type": "input_image", "image_url": "https://example.com/i.png"}
936                ]},
937                {"type": "reasoning", "id": "rs_1", "summary": []},
938                {"type": "function_call", "call_id": "c", "name": "f", "arguments": "{\"to\":\"c@example.com\"}"},
939                {"type": "function_call_output", "call_id": "c", "output": "d@example.com"}
940            ],
941            "store": false
942        }"#;
943        let (req, scanned) = parse_api_body(body, Api::Responses, Provider::OpenAI, None).unwrap();
944        let roles: Vec<Role> = req.messages.iter().map(|m| m.role.clone()).collect();
945        assert_eq!(
946            roles,
947            [
948                Role::System,
949                Role::System,
950                Role::User,
951                Role::Assistant,
952                Role::Tool
953            ]
954        );
955        let out = redact_and_apply(req, scanned);
956        assert_eq!(out["instructions"], "Be brief.");
957        assert_eq!(out["input"][0]["content"], "dev [EMAIL]");
958        assert_eq!(out["input"][1]["content"][0]["text"], "hi [EMAIL]");
959        assert_eq!(
960            out["input"][1]["content"][1]["image_url"],
961            "https://example.com/i.png"
962        );
963        assert_eq!(out["input"][2]["type"], "reasoning");
964        assert_eq!(out["input"][3]["arguments"], "{\"to\":\"[EMAIL]\"}");
965        assert_eq!(out["input"][4]["output"], "[EMAIL]");
966        assert_eq!(out["store"], false);
967    }
968
969    #[test]
970    fn test_model_defaults() {
971        let azure = br#"{"messages": [{"role": "user", "content": "hi"}]}"#;
972        assert!(parse_body(azure, Provider::Azure).is_err());
973        let (req, scanned) =
974            parse_api_body(azure, Api::ChatCompletions, Provider::Azure, Some("prod")).unwrap();
975        assert_eq!(req.model, "prod");
976        assert!(scanned.apply(&req).unwrap().get("model").is_none());
977
978        let (req, _) = parse_api_body(
979            br#"{"previous_response_id": "r"}"#,
980            Api::Responses,
981            Provider::OpenAI,
982            None,
983        )
984        .unwrap();
985        assert!(req.messages.is_empty());
986    }
987
988    #[test]
989    fn test_stream_flag() {
990        let (req, _) = openai(br#"{"model": "m", "messages": [], "stream": true}"#);
991        assert!(req.stream);
992    }
993}