SetSensitiveHeadersLayer - Keeping Secrets Out of Logs in Axum
Learn how SetSensitiveHeadersLayer marks request and response headers as sensitive so logging middleware redacts them instead of printing secrets
Servers write logs. Those logs record what happened, which requests arrived, which responses went out, and how long each one took. The trouble is that a request often carries a secret in one of its headers, an Authorization token, a session cookie, or an API key. If the logger prints the headers as they are, the secret lands in a log file in plain text. Anyone who can read the logs can then use the token as if they were the user. SetSensitiveHeadersLayer is the tower-http middleware that stops that from happening. It marks chosen headers as sensitive, and a logger that respects the mark prints the word Sensitive instead of the value.
This page works through the layer from the ground up. You will see what a sensitive header is, what the layer does and does not do, the smallest working example, how to write the header names correctly, how to pair the layer with a logger so the redaction actually appears, and the ordering mistake that silently leaks secrets.
What a Sensitive Header Is
An HTTP header is a name and a value attached to a request or a response. The Authorization header, for example, carries a token that proves who the caller is. The Cookie header carries session data. These values are secrets, but to the HTTP library they are ordinary strings. Nothing about them says "do not print me".
The http crate, the crate Axum builds on, gives each header value a flag for exactly this. A HeaderValue has a method called set_sensitive, and when the flag is set, the value's debug output hides it. Debug output is the text Rust prints when a value is formatted with {:?}, which is what loggers and println! use when they show a header map. A sensitive value prints as the word Sensitive instead of its contents.
That flag is the whole mechanism of this page. SetSensitiveHeadersLayer sets the flag on the headers you name. A logger that prints header maps then shows Sensitive where the secret used to be. The flag travels with the value, so any code that prints the header map later sees the same redaction.
Think of the flag as a sticker on an envelope that says "do not read out loud". The letter inside is unchanged. Anyone who opens the envelope can still read it. The sticker only tells well-behaved readers not to announce the contents.
Marking is not hiding:
Setting the sensitive flag does not remove the header, change its value, or keep it from your handler. The handler still receives the real token and can use it normally. Only output that prints the header value through its debug form hides it. A println! of the raw string would still show the secret, because that bypasses the flag entirely.
What the Layer Does and Does Not Do
SetSensitiveHeadersLayer is a layer from the tower-http crate, in the sensitive_headers module. It marks headers on both the request and the response. When a request arrives, it marks the matching request headers before passing the request on. When the response comes back from the handler, it marks the matching response headers before the response leaves.
It does not do the redacting itself. The layer never prints anything. Redaction happens in the logger, most often TraceLayer, which checks the flag when it writes a log line. Without a logger that checks the flag, the layer changes nothing visible. The two pieces cooperate: one marks, the other respects the mark.
It also does not protect the secret on the network, in memory, or from code that reads the header directly. It is a log hygiene tool, not a security boundary. Secrets still need HTTPS in transit and careful handling in code. What it gives you is a single place to name the sensitive headers, instead of marking them by hand in every handler.
Your First Example With One Header
Start with the smallest setup: one route, one header, and a logger. The layer is only available when the sensitive-headers feature of tower-http is turned on, and the logger needs the trace feature.
[package]
name = "sensitive-headers-demo"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
tower-http = { version = "0.7", features = ["sensitive-headers", "trace"] }
tracing = "0.1"
tracing-subscriber = "0.3"
use axum::{routing::get, Router};
use tower_http::{sensitive_headers::SetSensitiveHeadersLayer, trace::TraceLayer};
#[tokio::main]
async fn main() {
tracing_subscriber::fmt().init();
let app = Router::new()
.route("/", get(|| async { "Hello, world!" }))
.layer(TraceLayer::new_for_http())
.layer(SetSensitiveHeadersLayer::new([
axum::http::header::AUTHORIZATION,
]));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Server running on http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
Two details in this program deserve attention, because both are easy to get backwards. First, the import path is tower_http::sensitive_headers::SetSensitiveHeadersLayer. There is a set_header module in tower-http, but it holds only the layers that set header values, and SetSensitiveHeadersLayer is not one of them. The wrong path does not compile.
Second, the order of the two .layer() calls matters. With repeated .layer() calls, the last call is the outermost layer, and the outermost layer sees the request first. Here TraceLayer is added first, so it ends up inside, and SetSensitiveHeadersLayer is added second, so it ends up outside. A request passes through the sensitive layer first, gets its authorization header marked, and only then reaches TraceLayer, which logs the request with the flag already set. Reverse the two calls and the logger sees the request before the marking happens. That ordering is the central fact of this page, and a later section shows the leaked log line that results from getting it wrong.
The handler returns a plain string and never touches the headers. That is the point. Nothing in the handler has to know about the marking. The layer does it for every request and every response on this router.
One thing to expect when you run this program is silence from the logger. TraceLayer logs at debug level by default, while the plain tracing_subscriber::fmt() subscriber above only shows info level and above, so no request lines appear yet. The section on making the redaction visible sets both sides to info level, and the lines appear from there on.
Add the sensitive layer after the logger:
With repeated .layer() calls, the layer added last runs first. To mark headers before TraceLayer logs them, add TraceLayer first and SetSensitiveHeadersLayer second. If you reverse them, the logger prints the live secret before the marking happens, and the layer cannot undo a log line that is already written.
Writing Header Names Correctly
SetSensitiveHeadersLayer::new takes an iterator of HeaderName values. A HeaderName is a type from the http crate that represents a validated header name. It is not a string. That distinction is the source of the most common compile error on this page.
For well-known headers, use the constants in axum::http::header, such as AUTHORIZATION, COOKIE, and SET_COOKIE. Axum re-exports the http crate, so axum::http::header::AUTHORIZATION works without adding the http crate to your Cargo.toml separately.
For a custom header, use HeaderName::from_static with a string literal.
use axum::{http::header::HeaderName, routing::get, Router};
use tower_http::sensitive_headers::SetSensitiveHeadersLayer;
let layer = SetSensitiveHeadersLayer::new([
axum::http::header::AUTHORIZATION,
axum::http::header::COOKIE,
HeaderName::from_static("x-api-key"),
]);
let _app: Router = Router::new()
.route("/", get(|| async { "Hello" }))
.layer(layer);
Header names are case-insensitive in HTTP, so authorization, Authorization, and AUTHORIZATION all name the same header. The constants are written in capitals by convention, and the string you pass to from_static is usually written in lowercase with hyphens, like "x-api-key".
Three things that look right but do not compile are worth naming plainly. Passing string literals, SetSensitiveHeadersLayer::new(["authorization"]), fails, because a &str does not convert into a HeaderName automatically. There is no .sensitive() builder method on the layer, so chaining one fails as well. And HeaderName does implement FromStr, which means a string can be parsed into one, but only with an explicit .parse(), as in "x-api-key".parse::<HeaderName>(). Rust will not do that conversion for you.
HeaderName::from_static panics if the name is not valid, so use it only with a literal you have checked. A name with a space in it, like "X API Key", is invalid. A name that arrives at runtime, from configuration or user input, should be parsed with .parse() so the error can be handled instead of panicking.
Marking Several Headers and Building the List
Most applications protect more than one header. A typical list is the authorization token, the session cookie, the Set-Cookie header on responses, and any custom API key header. Pass them all to new in one array.
use axum::{http::header::HeaderName, routing::get, Router};
use tower_http::sensitive_headers::SetSensitiveHeadersLayer;
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/", get(|| async { "Hello, world!" }))
.layer(SetSensitiveHeadersLayer::new([
axum::http::header::AUTHORIZATION,
axum::http::header::COOKIE,
axum::http::header::SET_COOKIE,
HeaderName::from_static("x-api-key"),
]));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
Because there is no builder method that adds one header at a time, build the collection first when the list depends on configuration, then hand it to new.
use axum::{http::header::HeaderName, routing::get, Router};
use tower_http::sensitive_headers::SetSensitiveHeadersLayer;
#[tokio::main]
async fn main() {
let mut headers = vec![
axum::http::header::AUTHORIZATION,
axum::http::header::COOKIE,
];
if std::env::var("API_KEY_HEADER").is_ok() {
headers.push(HeaderName::from_static("x-api-key"));
}
let sensitive = SetSensitiveHeadersLayer::new(headers);
let app = Router::new()
.route("/", get(|| async { "Hello, world!" }))
.layer(sensitive);
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
The layer also has a second constructor, from_shared, which takes an Arc<[HeaderName]>. It exists so the same list can be shared without copying it, for example when the request-marking half and the response-marking half of the layer use the same list, or when several routers share one list.
use std::sync::Arc;
use axum::http::header::HeaderName;
use tower_http::sensitive_headers::SetSensitiveHeadersLayer;
let headers: Arc<[HeaderName]> = Arc::from([
axum::http::header::AUTHORIZATION,
axum::http::header::COOKIE,
]);
let layer = SetSensitiveHeadersLayer::from_shared(headers);
Arc is a reference-counted pointer that lets several owners share the same data. You do not need from_shared in most programs. new is the normal choice, and from_shared is there for the cases where one list is genuinely shared.
There is no builder method:
The layer's API is new and from_shared only. If you are looking for a method that adds one header at a time, it does not exist. Collect the names first, then construct the layer once.
Making the Redaction Visible With TraceLayer
The layer alone produces no visible change. To see the redaction, you need a logger that prints headers, and TraceLayer does not print headers by default. Its span builder and its response handler both default to leaving headers out. A plain TraceLayer::new_for_http() will never print your token, redacted or otherwise, because there is nothing to redact. You have to opt in with .include_headers(true) on both the span builder and the response handler.
use axum::{routing::get, Router};
use tower_http::{
sensitive_headers::SetSensitiveHeadersLayer,
trace::{DefaultMakeSpan, DefaultOnRequest, DefaultOnResponse, TraceLayer},
};
use tracing::Level;
#[tokio::main]
async fn main() {
tracing_subscriber::fmt()
.with_max_level(Level::INFO)
.init();
let app = Router::new()
.route("/", get(|| async { "Hello, world!" }))
.layer(
TraceLayer::new_for_http()
.make_span_with(
DefaultMakeSpan::new()
.level(Level::INFO)
.include_headers(true),
)
.on_request(DefaultOnRequest::new().level(Level::INFO))
.on_response(
DefaultOnResponse::new()
.level(Level::INFO)
.include_headers(true),
),
)
.layer(SetSensitiveHeadersLayer::new([
axum::http::header::HeaderName::from_static("x-api-key"),
]));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Server running on http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
DefaultMakeSpan builds the span that wraps the whole request, and .include_headers(true) on it puts the request headers into that span. DefaultOnResponse writes the line when the response finishes, and .include_headers(true) on it puts the response headers into that line. Both calls are needed, because the request headers and the response headers are logged in different places. The .level(Level::INFO) calls matter too. TraceLayer logs at debug level by default, and a subscriber set to info level would never show those lines. Setting both sides to info makes the lines appear.
Run this server and send a request with the header.
curl -H "x-api-key: my-secret-key" http://127.0.0.1:3000/
The server console shows the request line with the value hidden.
INFO request{method=GET uri=/ version=HTTP/1.1 headers={"x-api-key": Sensitive}}: tower_http::trace::on_request: started processing request
The secret my-secret-key never appears. The word Sensitive sits in its place, which is the flag doing its job in the log output.
Now reverse the two .layer() calls, so the sensitive layer is added first and ends up inside TraceLayer. Send the same request again. This time the log line is different.
INFO request{method=GET uri=/ version=HTTP/1.1 headers={"x-api-key": "my-secret-key"}}: tower_http::trace::on_request: started processing request
The live key is printed in full. The logger ran before the marking happened, so there was nothing to redact yet. Both orders were run live while writing this page, and the two lines above are the actual output. The only change between the runs was the order of the two .layer() calls.
Seeing Sensitive in the log means the setup works:
If the request line shows Sensitive where the header value should be, the layer is outside the logger, header logging is on, and the marking is happening before anything is printed. If you see no headers at all, you forgot .include_headers(true). If you see the live value, the order is reversed.
No header gets redacted on its own:
The http crate prints a header value in full through its debug form unless the sensitive flag is set on it. That includes Authorization. A token in an Authorization header prints exactly as sent, with no part hidden, until this layer marks it. Do not rely on any built-in redaction to protect your secrets. Mark them with this layer, and check the result by looking at the actual log line.
Marking Only Requests or Only Responses
SetSensitiveHeadersLayer marks both directions at once, which is what most applications want. The module also provides the two halves separately, SetSensitiveRequestHeadersLayer and SetSensitiveResponseHeadersLayer, for the cases where the two directions need different treatment.
The halves matter because of ordering. A request header must be marked before the logger sees the request, so the request half belongs outside the logger. A response header is produced by the handler and only exists on the way out, so the response half must sit where it sees the response before the logger logs it. In a ServiceBuilder, where the first layer listed is the outermost and runs first, that arrangement looks like this. The example also needs the tower crate in Cargo.toml, since ServiceBuilder comes from there, and the trace feature on tower-http for TraceLayer.
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
tower = "0.5"
tower-http = { version = "0.7", features = ["sensitive-headers", "trace"] }
use axum::{http::header::HeaderName, routing::get, Router};
use std::sync::Arc;
use tower::ServiceBuilder;
use tower_http::{
sensitive_headers::{
SetSensitiveRequestHeadersLayer, SetSensitiveResponseHeadersLayer,
},
trace::TraceLayer,
};
#[tokio::main]
async fn main() {
let headers: Arc<[HeaderName]> = Arc::from([
axum::http::header::AUTHORIZATION,
axum::http::header::COOKIE,
]);
let app = Router::new()
.route("/", get(|| async { "Hello, world!" }))
.layer(
ServiceBuilder::new()
.layer(SetSensitiveRequestHeadersLayer::from_shared(
Arc::clone(&headers),
))
.layer(TraceLayer::new_for_http())
.layer(SetSensitiveResponseHeadersLayer::from_shared(headers)),
);
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
Read the builder from top to bottom, which is the order the layers run in. The request-marking layer is first, so it marks the request headers before TraceLayer logs them. The response-marking layer is last, so it sits closest to the handler and marks the response headers as they come back, before TraceLayer logs the response. The same Arc list is shared by both halves, so the two lists cannot drift apart.
You rarely need this split. The combined layer already arranges its two halves this way internally. Reach for the separate layers only when the request list and the response list are genuinely different, for example when a response header like Set-Cookie needs marking but no request header does.
Response Headers and Set-Cookie
The layer marks response headers too, which matters because handlers often add sensitive values to responses. A login handler that sets a session cookie writes a Set-Cookie header on the response. Without marking, a logger that prints response headers would show the session token. With the layer in place, the response half marks it on the way out, and the log shows Sensitive.
use axum::{
http::{header::SET_COOKIE, HeaderMap, HeaderValue},
routing::get,
Router,
};
use tower_http::sensitive_headers::SetSensitiveHeadersLayer;
async fn login() -> (HeaderMap, &'static str) {
let mut headers = HeaderMap::new();
headers.insert(
SET_COOKIE,
HeaderValue::from_static("session=abc123; HttpOnly; Path=/"),
);
(headers, "logged in")
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/login", get(login))
.layer(SetSensitiveHeadersLayer::new([
axum::http::header::SET_COOKIE,
]));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
The handler builds a HeaderMap, inserts a Set-Cookie header with a session value, and returns it together with the body. Axum sends those headers with the response. The layer sits outside the handler, so it sees the response after the handler produces it and marks the Set-Cookie value before anything else logs it. The client still receives the real cookie. Only the log output is redacted.
This works automatically for any response header your handler sets, as long as the header name is in the layer's list. You do not need to mark the header in the handler itself.
Applying the Layer Globally or Per Route
Like most layers, you can apply this one to a whole router or to a single route. The global form is the common one, and it is the form to use when redaction is the goal.
use axum::{routing::get, Router};
use tower_http::sensitive_headers::SetSensitiveHeadersLayer;
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/", get(|| async { "public endpoint" }))
.route("/private", get(|| async { "private endpoint" }))
.layer(SetSensitiveHeadersLayer::new([
axum::http::header::AUTHORIZATION,
]));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
Both routes are covered, because the .layer() call comes after both routes are added. A route added after the call would sit outside the layer and would not be marked.
A per-route form exists too. You can attach the layer to a single route's handler with the handler's own .layer() call.
use axum::{routing::get, Router};
use tower_http::sensitive_headers::SetSensitiveHeadersLayer;
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/", get(|| async { "public endpoint" }))
.route(
"/private",
get(|| async { "private endpoint" }).layer(
SetSensitiveHeadersLayer::new([axum::http::header::AUTHORIZATION]),
),
);
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
Only /private is marked here. That is fine when the goal is only to mark headers for that route's own processing. But if the goal is redaction in a global TraceLayer's logs, the per-route form does not reliably work. A route's own layer sits inside the router-level layers, so the global logger sees the request before the per-route layer has marked it, and the secret is logged before the marking happens. For log redaction, apply the sensitive layer globally and outside the logger, as in the earlier examples, rather than per route inside it.
Per-route marking happens too late for a global logger:
A layer attached to one route runs inside the router-level layers. A global TraceLayer therefore logs the request before the per-route sensitive layer marks it. If redaction in the logs is the goal, use the global form outside the logger. Use the per-route form only when the marking itself, not the logging, is what you need.
Common Mistakes
Forgetting the feature flag
SetSensitiveHeadersLayer is behind the sensitive-headers feature of tower-http. Without it, the module does not exist and the compiler reports that it cannot find sensitive_headers. The dependency line needs features = ["sensitive-headers"].
Passing strings instead of HeaderName
SetSensitiveHeadersLayer::new(["authorization"]) does not compile. The constructor takes HeaderName values, and Rust does not convert a string into one automatically. Use the constants, HeaderName::from_static for literals, or an explicit .parse() for strings that arrive at runtime.
Expecting the layer to redact on its own
The layer only sets a flag. If no logger checks the flag, nothing is hidden. A println! of the header value prints the secret, because printing a string does not consult the flag. The layer needs a cooperating logger, and TraceLayer with header logging enabled is the usual partner.
Expecting headers in the logs without opting in
TraceLayer logs no headers by default. If your logs show no headers at all, nothing is broken. Add .include_headers(true) to DefaultMakeSpan for the request line and to DefaultOnResponse for the response line. Only then does the sensitive flag have anything to redact.
Adding the layer on the wrong side of the logger
This is the mistake with real consequences, because the program compiles and runs, and the leak is silent. The sensitive layer must sit outside the logger. With repeated .layer() calls that means adding it after the logger. With a ServiceBuilder that means listing it before the logger. Either way, the marking must happen first.
Using an invalid header name
HeaderName::from_static panics on an invalid name. A name with a space or an uppercase letter in the wrong place will panic at startup. Names are lowercase words joined with hyphens, like "x-api-key". Parse runtime names with .parse() instead, so a bad name becomes an error you can handle.
This layer is not a security boundary:
Marking a header as sensitive does not remove it from memory, does not encrypt it, and does not stop anyone who can read the request from seeing it. It only keeps the value out of log output that respects the flag. Secrets still need HTTPS in transit, and credentials still need proper storage and handling. Treat this layer as log hygiene, and keep the rest of your security practices in place.
Where This Layer Fits in Real Applications
Any application that logs HTTP traffic and accepts credentials should use this layer. A login service marks authorization and cookie on requests and set-cookie on responses. An API gateway marks the API key header it accepts from clients. A service that forwards a token to another service marks the header on both sides, so the token never appears in either service's logs.
The list of headers belongs in one place, next to the layer, so a new header can be added in one edit. When a new endpoint starts accepting a new secret header, adding its name to the list is the whole change. That is the practical value of the layer. Without it, the same marking would be scattered across handlers, and one forgotten handler would leak.
Summary
The decision framework for this layer has three questions, and they are best asked in order. First, which headers carry secrets in your application. Name them in one list, and pass that list to SetSensitiveHeadersLayer::new with real HeaderName values, not strings. Second, which logger prints those headers, and does it have header logging turned on. TraceLayer needs .include_headers(true) before the flag has anything to redact. Third, does the marking happen before the logging. The sensitive layer must sit outside the logger, which means adding it after the logger with repeated .layer() calls, or listing it before the logger in a ServiceBuilder. Get those three answers right and your logs stay useful without carrying live credentials. Get the order wrong and the program still compiles, the server still runs, and the secret still lands in the log file, which is why the order is worth checking with a real request and a look at the actual log line.