Accept only application/json bodies on podcast endpoints
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
c51a9af9e5
commit
2eb27cfe77
2 files changed
+75
-1
No files matched your search
+71
-1
@@ -107,8 +107,29 @@ fn unauthorized() -> cot::response::Response {
|
||||
/// Largest JSON body accepted (a playback request carries one episode reference).
|
||||
const MAX_JSON_BODY: usize = 64 * 1024;
|
||||
|
||||
/// Request body as JSON (`null` when empty); malformed JSON is a 400.
|
||||
/// Whether a `Content-Type` value is `application/json` (parameters such
|
||||
/// as `charset` allowed).
|
||||
fn is_json_content_type(value: Option<&str>) -> bool {
|
||||
value
|
||||
.and_then(|value| value.split(';').next())
|
||||
.is_some_and(|essence| essence.trim().eq_ignore_ascii_case("application/json"))
|
||||
}
|
||||
|
||||
/// Request body as JSON (`{}` when empty); malformed JSON is a 400.
|
||||
///
|
||||
/// A body must be sent as `application/json` (415 otherwise), like cot's
|
||||
/// `Json` extractor requires on the other player endpoints: a cross-origin
|
||||
/// page can only send that type after a CORS preflight, while `text/plain`
|
||||
/// and form bodies need none and would carry the session cookie from a
|
||||
/// same-site page. `navigator.sendBeacon` sends a Blob typed
|
||||
/// `application/json`.
|
||||
async fn json_body(request: cot::request::Request) -> Result<serde_json::Value, ApiError> {
|
||||
let json = is_json_content_type(
|
||||
request
|
||||
.headers()
|
||||
.get(CONTENT_TYPE)
|
||||
.and_then(|value| value.to_str().ok()),
|
||||
);
|
||||
let bytes = request
|
||||
.into_body()
|
||||
.into_bytes_limited(MAX_JSON_BODY)
|
||||
@@ -117,6 +138,9 @@ async fn json_body(request: cot::request::Request) -> Result<serde_json::Value,
|
||||
if bytes.iter().all(u8::is_ascii_whitespace) {
|
||||
return Ok(serde_json::Value::Object(Default::default()));
|
||||
}
|
||||
if !json {
|
||||
return Err(ApiError::new(415, "the body must be application/json"));
|
||||
}
|
||||
serde_json::from_slice(&bytes).map_err(|error| ApiError::new(400, error.to_string()))
|
||||
}
|
||||
|
||||
@@ -709,3 +733,49 @@ impl App for PodcastsApp {
|
||||
])
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn request(content_type: Option<&str>, body: &'static str) -> cot::request::Request {
|
||||
let mut builder = cot::http::Request::builder()
|
||||
.method("POST")
|
||||
.uri("/api/podcasts/feeds");
|
||||
if let Some(value) = content_type {
|
||||
builder = builder.header(CONTENT_TYPE, value);
|
||||
}
|
||||
builder.body(Body::fixed(body)).unwrap()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn json_bodies_need_the_json_content_type() {
|
||||
let url = r#"{"url": "https://podcasts.example/feed.xml"}"#;
|
||||
for content_type in [
|
||||
"application/json",
|
||||
"application/json; charset=UTF-8",
|
||||
"Application/JSON",
|
||||
] {
|
||||
let body = json_body(request(Some(content_type), url)).await.unwrap();
|
||||
assert_eq!(body["url"], "https://podcasts.example/feed.xml");
|
||||
}
|
||||
// What a page can send cross-origin without a CORS preflight.
|
||||
for content_type in [
|
||||
Some("text/plain"),
|
||||
Some("text/plain;charset=UTF-8"),
|
||||
Some("application/x-www-form-urlencoded"),
|
||||
Some("multipart/form-data; boundary=x"),
|
||||
None,
|
||||
] {
|
||||
let error = json_body(request(content_type, url)).await.unwrap_err();
|
||||
assert_eq!(error.status, 415, "{content_type:?}");
|
||||
}
|
||||
// An empty body (a plain POST) is an empty object whatever the type.
|
||||
let empty = json_body(request(None, "")).await.unwrap();
|
||||
assert_eq!(empty, serde_json::json!({}));
|
||||
let malformed = json_body(request(Some("application/json"), "{"))
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(malformed.status, 400);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user