From 72b947130572fdaaf353ddbe737580c80d3c75ec Mon Sep 17 00:00:00 2001 From: piquel Date: Sun, 22 Nov 2026 20:33:46 +0100 Subject: [PATCH] fix(http): refuse malformed requests as an ApiError A request whose path, query or JSON body axum's extractors refused got axum's plain-text rejection, not the ApiError every other failure is, so clients couldn't read why. The routes now extract through Path, Query and Json wrappers whose rejection is an HttpError: a client error is a bad_request ApiError, and a route that doesn't match its handler an internal one, logged. --- Cargo.lock | 1 + apps/origin-src/Cargo.toml | 2 ++ apps/origin-src/src/http.rs | 63 +++++++++++++++++++++++++++++++++-- apps/origin-src/tests/http.rs | 26 +++++++++++++-- 4 files changed, 87 insertions(+), 5 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 5dbcdba5..3c4c70fa 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -886,6 +886,7 @@ dependencies = [ "origin-platform", "origin-shared", "origin-src", + "reqwest", "serde", "serde_json", "similar", diff --git a/apps/origin-src/Cargo.toml b/apps/origin-src/Cargo.toml index 273e930a..7ff817cd 100644 --- a/apps/origin-src/Cargo.toml +++ b/apps/origin-src/Cargo.toml @@ -40,6 +40,8 @@ zstd.workspace = true divan.workspace = true # The benchmarks build their working trees with the fixtures. origin-src = { workspace = true, features = ["fixture"] } +# Requests the SDK never sends, to test how the server refuses them. +reqwest.workspace = true tempfile.workspace = true [[bench]] diff --git a/apps/origin-src/src/http.rs b/apps/origin-src/src/http.rs index a560a93e..2c1bdd95 100644 --- a/apps/origin-src/src/http.rs +++ b/apps/origin-src/src/http.rs @@ -8,9 +8,9 @@ use std::sync::Arc; -use axum::Json; use axum::body::Bytes; -use axum::extract::{DefaultBodyLimit, FromRequestParts, Path, Query, State}; +use axum::extract::rejection::{JsonRejection, PathRejection, QueryRejection}; +use axum::extract::{DefaultBodyLimit, FromRequest, FromRequestParts, Request, State}; use axum::http::request::Parts; use axum::http::{StatusCode, header}; use axum::response::{IntoResponse, Response}; @@ -26,6 +26,7 @@ use origin_shared::api::{ use origin_shared::event::Page; use origin_shared::landing::Pending; use origin_shared::pack::{Pack, PackError, Part}; +use serde::Serialize; use utoipa::OpenApi; use utoipa_axum::router::OpenApiRouter; use utoipa_axum::routes; @@ -110,6 +111,56 @@ impl FromRequestParts> for Caller { } } +/// Declares extractors like axum's, of the same names, so `utoipa` documents +/// them alike, but refusing a request as an [`ApiError`], as every other +/// failure is, rather than in axum's plain text. +macro_rules! extractors { + ($( + $(#[$doc:meta])* + $name:ident: $trait:ident::$method:ident($input:ty) + via $($axum:ident)::+ refusing with $rejection:ty; + )*) => {$( + $(#[$doc])* + struct $name(T); + + impl $trait for $name + where + $($axum)::+: $trait, + { + type Rejection = HttpError; + + async fn $method(input: $input, state: &S) -> Result { + let $($axum)::+(value) = <$($axum)::+>::$method(input, state).await?; + Ok(Self(value)) + } + } + + impl From<$rejection> for HttpError { + fn from(rejection: $rejection) -> Self { + Self::Rejected(rejection.status(), rejection.body_text()) + } + } + )*}; +} + +extractors! { + /// The request's path parameters. + Path: FromRequestParts::from_request_parts(&mut Parts) + via axum::extract::Path refusing with PathRejection; + /// The request's query. + Query: FromRequestParts::from_request_parts(&mut Parts) + via axum::extract::Query refusing with QueryRejection; + /// The request's JSON body; also a JSON response. + Json: FromRequest::from_request(Request) + via axum::Json refusing with JsonRejection; +} + +impl IntoResponse for Json { + fn into_response(self) -> Response { + axum::Json(self.0).into_response() + } +} + /// Runs a call on the service of repository `repo`, on the blocking thread /// pool: service calls do synchronous file system work, and event /// long-polls wait. @@ -133,6 +184,9 @@ pub enum HttpError { Pack(PackError), /// The caller's credentials are invalid. Unauthorized(InvalidToken), + /// axum refused the request's path, query or body, with this status: + /// a client error but for a route that doesn't match its handler. + Rejected(StatusCode, String), /// The service panicked. Panicked(String), } @@ -147,6 +201,11 @@ impl IntoResponse for HttpError { Self::Service(error) => (error.code(), error.to_string()), Self::Pack(error) => (ErrorCode::BadRequest, format!("invalid pack: {error}")), Self::Unauthorized(error) => (ErrorCode::Unauthorized, error.to_string()), + Self::Rejected(status, message) if status.is_server_error() => { + tracing::error!(%message, "request rejected"); + (ErrorCode::Internal, "internal server error".to_owned()) + } + Self::Rejected(_, message) => (ErrorCode::BadRequest, message), Self::Panicked(message) => { tracing::error!(%message, "request panicked"); (ErrorCode::Internal, "internal server error".to_owned()) diff --git a/apps/origin-src/tests/http.rs b/apps/origin-src/tests/http.rs index 018298e6..e5b59df7 100644 --- a/apps/origin-src/tests/http.rs +++ b/apps/origin-src/tests/http.rs @@ -8,9 +8,9 @@ use std::time::{Duration, Instant}; use origin_client::{Client, Error, Repo}; use origin_shared::api::{ - BrowseQuery, ErrorCode, EventsQuery, Expected, FetchRecords, FetchSnapshot, InventoryRequest, - LandRequest, List, LogQuery, NewTarget, PromoteRequest, PutQuery, RepoName, StatementsQuery, - TokenRequest, + ApiError, BrowseQuery, ErrorCode, EventsQuery, Expected, FetchRecords, FetchSnapshot, + InventoryRequest, LandRequest, List, LogQuery, NewTarget, PromoteRequest, PutQuery, RepoName, + StatementsQuery, TokenRequest, }; use origin_shared::event::EventKind; use origin_shared::landing::{Blocked, Landing, Proposal}; @@ -1135,6 +1135,26 @@ fn review(subject: RevisionId) -> EncodedObject { .encode() } +/// Requests axum's extractors refuse, for a malformed query or body, are +/// refused as an `ApiError`, as every other failure is. +#[tokio::test] +async fn refuses_malformed_requests_as_api_errors() { + let server = Server::start().await; + let http = reqwest::Client::new(); + let repo = format!("{}/api/v1/repos/demo", server.base); + for request in [ + http.get(format!("{repo}/events?wait=soon")), + http.post(format!("{repo}/changes/inventory")) + .header("content-type", "application/json") + .body("{"), + ] { + let response = request.send().await.unwrap(); + assert_eq!(response.status(), reqwest::StatusCode::BAD_REQUEST); + let error: ApiError = response.json().await.unwrap(); + assert_eq!(error.code, ErrorCode::BadRequest, "{error}"); + } +} + #[tokio::test] async fn serves_its_openapi_document() { let server = Server::start().await;