Skip to content

Instantly share code, notes, and snippets.

@samgiles
Last active March 22, 2025 03:22
Show Gist options
  • Save samgiles/eacdbc35dc5ff1d2ec4ce8d2aef54f67 to your computer and use it in GitHub Desktop.
Save samgiles/eacdbc35dc5ff1d2ec4ce8d2aef54f67 to your computer and use it in GitHub Desktop.
Merge headers according to RFC7230 as a Tower Layer. YMMV
/// License: MIT
/// Copyright 2025 Sam Giles
/// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
/// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
/// THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
use http::header::HeaderValue;
use http::{Request, Response};
use pin_project_lite::pin_project;
use smallvec::{SmallVec, ToSmallVec};
use std::future::Future;
use std::pin::Pin;
use std::task::{ready, Context, Poll};
use tower::{Layer, Service};
/// A layer that merges duplicate headers, with special handling for Set-Cookie
#[derive(Clone, Debug, Default)]
pub struct MergeHeadersLayer;
impl<S> Layer<S> for MergeHeadersLayer {
type Service = MergeHeadersService<S>;
fn layer(&self, service: S) -> Self::Service {
MergeHeadersService { inner: service }
}
}
/// A service that merges duplicate headers in the response
#[derive(Clone, Debug)]
pub struct MergeHeadersService<S> {
inner: S,
}
impl<ReqBody, ResBody, S> Service<Request<ReqBody>> for MergeHeadersService<S>
where
S: Service<Request<ReqBody>, Response = Response<ResBody>>,
{
type Response = S::Response;
type Error = S::Error;
type Future = ResponseFuture<S::Future>;
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.inner.poll_ready(cx)
}
fn call(&mut self, req: Request<ReqBody>) -> Self::Future {
let response = self.inner.call(req);
ResponseFuture { future: response }
}
}
pin_project! {
pub struct ResponseFuture<F> {
#[pin]
future: F,
}
}
impl<F, ResBody, E> Future for ResponseFuture<F>
where
F: Future<Output = Result<Response<ResBody>, E>>,
{
type Output = F::Output;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = self.project();
let mut res = ready!(this.future.poll(cx)?);
let headers = res.headers_mut();
let mut merged_headers = http::HeaderMap::new();
let mut current_header_name = None;
for (name, value) in headers.drain() {
if let Some(name) = name {
current_header_name = Some(name);
}
let current_name = current_header_name.as_ref().expect("invalid invariant");
if current_name == http::header::SET_COOKIE {
merged_headers.append(current_name, value);
} else if let Some(v) = merged_headers.get_mut(current_name) {
let mut new_val: SmallVec<[u8; 32]> = v.as_bytes().to_smallvec();
new_val.extend_from_slice(b", ");
new_val.extend_from_slice(value.as_bytes());
*v = HeaderValue::from_bytes(&new_val).unwrap();
} else {
merged_headers.insert(current_name, value);
}
}
*res.headers_mut() = merged_headers;
Poll::Ready(Ok(res))
}
}
#[cfg(test)]
mod tests {
use super::*;
use http::header::{HeaderValue, SET_COOKIE, VARY};
use http::{Response, StatusCode};
use std::convert::Infallible;
use tower::ServiceExt;
use tower_http::set_header::SetResponseHeaderLayer;
#[derive(Clone)]
struct TestService;
impl Service<http::Request<String>> for TestService {
type Response = Response<String>;
type Error = Infallible;
type Future = std::future::Ready<Result<Self::Response, Self::Error>>;
fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(()))
}
fn call(&mut self, req: http::Request<String>) -> Self::Future {
let response = Response::builder()
.header("vary", "accept-encoding")
.status(StatusCode::OK)
.body(req.into_body())
.unwrap();
std::future::ready(Ok(response))
}
}
#[tokio::test]
async fn test_merge_headers_layer() {
let mut service = tower::ServiceBuilder::new()
.layer(MergeHeadersLayer::default())
.layer(SetResponseHeaderLayer::appending(
VARY,
HeaderValue::from_static("accept-language"),
))
.service(TestService);
let request = http::Request::builder()
.method("POST")
.uri("/test")
.body("test request".to_string())
.unwrap();
let response = service.ready().await.unwrap().call(request).await.unwrap();
assert_eq!(response.status(), StatusCode::OK);
assert_eq!(response.body(), "test request");
assert_eq!(
response.headers().get(VARY).unwrap(),
"accept-encoding, accept-language"
);
}
#[tokio::test]
async fn test_set_cookie_headers_not_merged() {
let mut service = tower::ServiceBuilder::new()
.layer(MergeHeadersLayer::default())
.service(TestServiceWithCookies);
let request = http::Request::builder()
.method("POST")
.uri("/test")
.body("test request".to_string())
.unwrap();
let response = service.ready().await.unwrap().call(request).await.unwrap();
let cookies: Vec<_> = response.headers().get_all(SET_COOKIE).iter().collect();
assert_eq!(
cookies.len(),
2,
"Set-Cookie headers should remain separate"
);
assert_eq!(
cookies[0].to_str().unwrap(),
"session=abc123; Path=/; HttpOnly; Secure"
);
assert_eq!(
cookies[1].to_str().unwrap(),
"csrf=xyz789; Path=/; HttpOnly; Secure"
);
}
#[derive(Clone)]
struct TestServiceWithCookies;
impl Service<http::Request<String>> for TestServiceWithCookies {
type Response = Response<String>;
type Error = Infallible;
type Future = std::future::Ready<Result<Self::Response, Self::Error>>;
fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(()))
}
fn call(&mut self, req: http::Request<String>) -> Self::Future {
let response = Response::builder()
.header(SET_COOKIE, "session=abc123; Path=/; HttpOnly; Secure")
.header(SET_COOKIE, "csrf=xyz789; Path=/; HttpOnly; Secure")
.status(StatusCode::OK)
.body(req.into_body())
.unwrap();
std::future::ready(Ok(response))
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment