Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Gracefully handle missing headers #1810

Merged
merged 6 commits into from
Mar 3, 2023
Merged
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 31 additions & 13 deletions axum/src/typed_header.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,17 +61,19 @@ where
type Rejection = TypedHeaderRejection;

async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
match parts.headers.typed_try_get::<T>() {
Ok(Some(value)) => Ok(Self(value)),
Ok(None) => Err(TypedHeaderRejection {
let mut values = parts.headers.get_all(T::name()).iter();
let is_missing = values.size_hint() == (0, Some(0));
T::decode(&mut values)
.map(Self)
.map_err(|err| TypedHeaderRejection {
name: T::name(),
reason: TypedHeaderRejectionReason::Missing,
}),
Err(err) => Err(TypedHeaderRejection {
name: T::name(),
reason: TypedHeaderRejectionReason::Error(err),
}),
}
reason: if is_missing {
// Report a more precise rejection for the missing header case.
TypedHeaderRejectionReason::Missing
davidpdrsn marked this conversation as resolved.
Show resolved Hide resolved
} else {
TypedHeaderRejectionReason::Error(err)
},
})
}
}

Expand Down Expand Up @@ -174,19 +176,35 @@ mod tests {
async fn typed_header() {
async fn handle(
TypedHeader(user_agent): TypedHeader<headers::UserAgent>,
TypedHeader(cookies): TypedHeader<headers::Cookie>,
) -> impl IntoResponse {
user_agent.to_string()
let user_agent = user_agent.as_str();
let cookies = cookies.iter().collect::<Vec<_>>();
format!("User-Agent={user_agent:?}, Cookie={cookies:?}")
}

let app = Router::new().route("/", get(handle));

let client = TestClient::new(app);

let res = client
.get("/")
.header("user-agent", "foobar")
.header("cookie", "a=1; b=2")
.header("cookie", "c=3")
.send()
.await;
let body = res.text().await;
assert_eq!(
body,
r#"User-Agent="foobar", Cookie=[("a", "1"), ("b", "2"), ("c", "3")]"#
);

let res = client.get("/").header("user-agent", "foobar").send().await;
let body = res.text().await;
assert_eq!(body, "foobar");
assert_eq!(body, r#"User-Agent="foobar", Cookie=[]"#);

let res = client.get("/").send().await;
let res = client.get("/").header("cookie", "a=1").send().await;
let body = res.text().await;
assert_eq!(body, "Header of type `user-agent` was missing");
}
Expand Down