ag_ui/axum/extract.rs
1//! Reading a [`RunAgentInput`] out of the request.
2//!
3//! [`AgUiInput`] is a plain axum extractor, so an agent mounted by
4//! [`route_agui`](crate::axum::RouterExt::route_agui) and a hand-written handler that
5//! needs to look at the request first (auth, tenant routing, a
6//! [`Path`](axum::extract::Path) segment naming which agent to run) parse the
7//! body exactly the same way.
8//!
9//! ```
10//! use ag_ui::axum::AgUiInput;
11//! use axum::Router;
12//! use axum::extract::Path;
13//! use axum::routing::post;
14//!
15//! async fn handler(Path(agent): Path<String>, AgUiInput(input): AgUiInput) -> String {
16//! format!("{agent} runs thread {}", input.thread_id)
17//! }
18//!
19//! let app: Router = Router::new().route("/agents/{agent}", post(handler));
20//! # let _ = app;
21//! ```
22//!
23//! Every failure is a `4xx` carrying a message that names the problem — see
24//! [`Error`]. Nothing here can panic on a hostile body: the size cap is axum's
25//! [`DefaultBodyLimit`](axum::extract::DefaultBodyLimit), and past that it is
26//! `serde_json` on a `&[u8]`.
27
28use crate::RunAgentInput;
29use axum::body::Bytes;
30use axum::extract::{FromRequest, Request};
31use axum::http::{HeaderMap, header};
32
33use crate::axum::error::{Error, Result};
34
35/// The AG-UI run request, extracted from a JSON body.
36///
37/// Rejects with [`Error`], which renders as a `4xx` and a JSON body naming what
38/// was wrong. The decoding warnings are discarded; a handler that wants them
39/// takes the body as [`Bytes`] and calls [`decode_with_warnings`].
40///
41/// # The `Content-Type` is required
42///
43/// The request must say its body is JSON: `application/json`, `text/json` or
44/// a `+json` type, parameters allowed. Anything else is refused with `415`,
45/// and so is a request with no `Content-Type` at all — an unlabelled body is
46/// not assumed to be JSON.
47///
48/// Requiring a JSON media type has a second effect: a browser will not send
49/// such a request from another origin without a CORS preflight, so whether a
50/// page elsewhere can start a run is up to your CORS policy. That is all it
51/// does. It is not authentication, and an endpoint that relies on cookies
52/// still needs its own CSRF protection.
53///
54/// For clients that send no header and cannot be changed,
55/// [`AgentEndpoint::allow_missing_content_type`](crate::axum::AgentEndpoint::allow_missing_content_type)
56/// accepts an unlabelled body on a mounted endpoint. A hand-written handler
57/// opts out the same way by taking [`Bytes`] and calling [`decode`] itself.
58/// Either way, the effect above no longer holds.
59#[derive(Clone, Debug, PartialEq)]
60pub struct AgUiInput(pub RunAgentInput);
61
62impl AgUiInput {
63 /// Unwraps the input.
64 pub fn into_inner(self) -> RunAgentInput {
65 self.0
66 }
67
68 /// The extractor, with the one choice an endpoint can make about it:
69 /// whether a request with no `Content-Type` is read as JSON. Keeps the
70 /// decoding warnings, which the mounted endpoint hands to its hook.
71 pub(crate) async fn read<S>(
72 request: Request,
73 state: &S,
74 allow_missing_content_type: bool,
75 ) -> Result<(Self, Vec<String>)>
76 where
77 S: Send + Sync,
78 {
79 check_content_type(request.headers(), allow_missing_content_type)?;
80 // Through axum's own extractor rather than `to_bytes`, so a
81 // `DefaultBodyLimit` layer the user applied still applies here.
82 let bytes = Bytes::from_request(request, state)
83 .await
84 .map_err(|rejection| Error::Body {
85 status: rejection.status(),
86 message: rejection.body_text(),
87 })?;
88 let (input, warnings) = decode_with_warnings(&bytes)?;
89 Ok((Self(input), warnings))
90 }
91}
92
93impl<S> FromRequest<S> for AgUiInput
94where
95 S: Send + Sync,
96{
97 type Rejection = Error;
98
99 async fn from_request(request: Request, state: &S) -> Result<Self> {
100 let (input, _warnings) = Self::read(request, state, false).await?;
101 Ok(input)
102 }
103}
104
105/// Parses a `RunAgentInput` from raw JSON bytes.
106///
107/// Before typed decoding, unknown protocol additions are removed and malformed
108/// known fields are rejected against the same schema used by client streams.
109/// What was removed is discarded; [`decode_with_warnings`] returns it.
110///
111/// The transport-free half of the extractor, for tests and for callers that
112/// already hold the body.
113///
114/// ```
115/// # use ag_ui::axum::extract::decode;
116/// let input = decode(br#"{"threadId":"t","runId":"r","messages":[],"tools":[],"context":[]}"#)?;
117/// assert_eq!(input.run_id.as_str(), "r");
118///
119/// assert!(decode(b"").is_err());
120/// assert!(decode(b"{").is_err());
121/// # Ok::<(), ag_ui::axum::Error>(())
122/// ```
123pub fn decode(body: &[u8]) -> Result<RunAgentInput> {
124 decode_with_warnings(body).map(|(input, _warnings)| input)
125}
126
127/// [`decode`], also returning a warning for each thing it removed or read as
128/// omitted: an unrecognised field or enum member, a deprecated optional
129/// `null`. Each quotes at most 64 characters of the body, with control
130/// characters escaped. Nothing in this crate prints them; where they go is the
131/// caller's choice.
132///
133/// ```
134/// # use ag_ui::axum::extract::decode_with_warnings;
135/// let (input, warnings) = decode_with_warnings(
136/// br#"{"threadId":"t","runId":"r","messages":[],"somethingNewer":1}"#,
137/// )?;
138/// assert_eq!(input.run_id.as_str(), "r");
139/// assert_eq!(warnings, ["unrecognised property at /somethingNewer"]);
140/// # Ok::<(), ag_ui::axum::Error>(())
141/// ```
142pub fn decode_with_warnings(body: &[u8]) -> Result<(RunAgentInput, Vec<String>)> {
143 // serde's message for an empty body is "EOF while parsing a value at line 1
144 // column 0", which reads like a truncated payload rather than no payload.
145 if body.iter().all(u8::is_ascii_whitespace) {
146 return Err(Error::EmptyBody);
147 }
148 let value = serde_json::from_slice(body)?;
149 let mut warnings = Vec::new();
150 let value = crate::protocol::input(value, &mut warnings)
151 .map_err(<serde_json::Error as serde::de::Error>::custom)?;
152 Ok((serde_json::from_value(value)?, warnings))
153}
154
155/// Refuses a body that does not say it is JSON.
156///
157/// An absent header is refused unless `allow_missing` says otherwise: RFC 9110
158/// lets a recipient treat an unlabelled body as `application/octet-stream`,
159/// and that is not something this endpoint reads. See [`AgUiInput`] for what
160/// requiring the header does and does not buy.
161fn check_content_type(headers: &HeaderMap, allow_missing: bool) -> Result<()> {
162 let Some(value) = headers.get(header::CONTENT_TYPE) else {
163 return if allow_missing {
164 Ok(())
165 } else {
166 Err(Error::MissingContentType)
167 };
168 };
169 let found = String::from_utf8_lossy(value.as_bytes());
170 if is_json(&found) {
171 return Ok(());
172 }
173 Err(Error::ContentType {
174 found: found.into_owned(),
175 })
176}
177
178/// Whether a `Content-Type` value names JSON, parameters and all.
179fn is_json(value: &str) -> bool {
180 let essence = value.split(';').next().unwrap_or(value).trim();
181 essence.eq_ignore_ascii_case("application/json")
182 || essence.eq_ignore_ascii_case("text/json")
183 // `application/vnd.acme+json` and friends.
184 || essence
185 .rsplit_once('+')
186 .is_some_and(|(_, suffix)| suffix.eq_ignore_ascii_case("json"))
187}
188
189#[cfg(test)]
190mod tests {
191 use super::*;
192 use axum::http::StatusCode;
193
194 fn headers(content_type: &str) -> HeaderMap {
195 let mut headers = HeaderMap::new();
196 headers.insert(
197 header::CONTENT_TYPE,
198 content_type.parse().expect("a valid header value"),
199 );
200 headers
201 }
202
203 #[test]
204 fn json_content_types_are_accepted() {
205 for value in [
206 "application/json",
207 "application/json; charset=utf-8",
208 "APPLICATION/JSON",
209 "text/json",
210 "application/vnd.acme.run+json",
211 ] {
212 for allow_missing in [false, true] {
213 assert!(
214 check_content_type(&headers(value), allow_missing).is_ok(),
215 "should accept {value:?}"
216 );
217 }
218 }
219 }
220
221 #[test]
222 fn a_missing_content_type_is_refused_with_415() {
223 let error = check_content_type(&HeaderMap::new(), false)
224 .expect_err("an unlabelled body is not assumed to be JSON");
225 assert!(matches!(error, Error::MissingContentType), "{error}");
226 assert_eq!(error.status(), StatusCode::UNSUPPORTED_MEDIA_TYPE);
227 assert_eq!(error.code(), "UNSUPPORTED_MEDIA_TYPE");
228 }
229
230 #[test]
231 fn a_missing_content_type_passes_only_when_allowed() {
232 assert!(check_content_type(&HeaderMap::new(), true).is_ok());
233 }
234
235 #[test]
236 fn a_form_post_is_refused_with_415() {
237 for allow_missing in [false, true] {
238 let error =
239 check_content_type(&headers("application/x-www-form-urlencoded"), allow_missing)
240 .expect_err("should refuse a form body");
241 assert_eq!(error.status(), StatusCode::UNSUPPORTED_MEDIA_TYPE);
242 assert!(
243 error.to_string().contains("x-www-form-urlencoded"),
244 "{error}"
245 );
246 }
247 }
248
249 #[test]
250 fn a_media_type_that_only_mentions_json_is_refused() {
251 for value in [
252 "text/plain; application/json",
253 "text/plain;charset=application/json",
254 "application/json, text/plain",
255 "application/jsonx",
256 "",
257 ] {
258 assert!(
259 check_content_type(&headers(value), true).is_err(),
260 "should refuse {value:?}"
261 );
262 }
263 }
264
265 #[test]
266 fn a_missing_field_names_itself() {
267 let error = decode(br#"{"threadId":"t","runId":"r"}"#).expect_err("should not decode");
268 assert_eq!(error.status(), StatusCode::BAD_REQUEST);
269 assert!(error.to_string().contains("messages"), "{error}");
270 }
271
272 #[test]
273 fn whitespace_only_bodies_read_as_empty() {
274 assert!(matches!(decode(b" \n\t"), Err(Error::EmptyBody)));
275 }
276}