HIGH header injectionactixapi keys

Header Injection in Actix with Api Keys

Header Injection in Actix with Api Keys — how this specific combination creates or exposes the vulnerability

Header Injection in Actix when using API keys occurs when user-controlled input is reflected into HTTP response headers without validation or sanitization. In Actix-web, headers are commonly set via HttpResponse::build() or by using the .insert_header((HeaderName, HeaderValue)) pattern. If an API key or any header value is derived from request parameters, query strings, or JSON bodies and is passed directly into these header-setting APIs, an attacker can inject additional header lines such as Location, Set-Cookie, or X-Forwarded-For.

For example, consider an Actix handler that copies an API key from a request header into a custom response header. If the API key is user-supplied and not validated, an attacker can provide a value like mykey\r\nX-Injected: malicious. When the server constructs a header using this value, the CRLF sequence (\r\n) can terminate the intended header and begin a new one. This can enable cross-site scripting via Set-Cookie injection, open redirects via Location injection, or cache poisoning via X-Forwarded-For manipulation.

Even when using API keys for authentication, improper handling can expose sensitive information or change routing behavior. For instance, if an API key is passed as a query parameter and then reflected in a X-API-Key response header without sanitization, an attacker can craft requests that inject newline sequences to reveal other headers or influence downstream proxies. The risk is compounded when the Actix service trusts header values to determine authorization or routing, as seen in misconfigured reverse proxy integrations.

Actix does not automatically sanitize header values, so developers must treat all external inputs as untrusted. The framework provides tools like HeaderMap::insert and typed extractors, but these require explicit use. Attack patterns such as CRLF injection map to OWASP API Top 10 A05:2023 (Security Misconfiguration) and can lead to security bypasses, information disclosure, or request smuggling when API keys are involved.

In the context of middleBrick’s 12 security checks, Header Injection is identified as part of Input Validation and Data Exposure. The scanner tests whether user-controlled data can escape header contexts by injecting sequences like \r\nX-Injected: 1 and observing whether the response contains the injected line. For services using API keys in headers, this becomes a critical vector because keys are often high-value targets for leakage or manipulation.

Real-world examples include APIs that concatenate headers using string formatting without proper encoding:

let api_key = req.headers().get("X-API-Key").unwrap().to_str().unwrap();
let custom_header = format!("Key-{}-End", api_key);
resp.headers_mut().insert("X-Custom", custom_header.parse().unwrap());

If api_key contains \r\nX-Tampered: true, the resulting header will inject an additional header. middleBrick’s active testing for this class of issue includes sending newline sequences in API key positions and verifying that they are not reflected verbatim in responses.

Api Keys-Specific Remediation in Actix — concrete code fixes

To remediate Header Injection in Actix when using API keys, ensure that any user-controlled data included in headers is strictly validated and encoded. Use Actix’s typed header APIs rather than string-based insertion wherever possible, and avoid reflecting raw input into headers.

Instead of directly inserting user input into headers, validate the API key against a known set or pattern, and use a server-side identifier for logging or routing. If you must echo a key-related value, encode it or use a mapping to a non-user-controlled representation.

The following example demonstrates a vulnerable pattern and its secure counterpart.

Vulnerable code

use actix_web::{web, HttpResponse, Result};

async fn handler(req: web::HttpRequest) -> Result {
    let api_key = req.headers().get("X-API-Key").unwrap().to_str().unwrap();
    // Vulnerable: directly using user-controlled value in another header
    let response = HttpResponse::Ok()
        .insert_header(("X-API-Key", api_key))
        .body("OK");
    Ok(response)
}

If api_key contains CRLF sequences, this can lead to header injection.

Remediation: validate and avoid reflection

use actix_web::{web, HttpResponse, Result, http::header::HeaderValue};
use regex::Regex;

async fn handler(req: web::HttpRequest) -> Result {
    let api_key = req.headers().get("X-API-Key")
        .and_then(|v| v.to_str().ok())
        .filter(|s| !s.contains("\r") && !s.contains("\n"))
        .ok_or_else(|| actix_web::error::ErrorBadRequest("Invalid API key"))?;

    // Use a server-side identifier instead of reflecting the raw key
    let safe_value = HeaderValue::from_static("redacted");
    let response = HttpResponse::Ok()
        .insert_header(("X-API-Key", safe_value))
        .body("OK");
    Ok(response)
}

In this fix, the API key is checked for newline characters before use, and a constant, safe value is placed in the response header. For authentication, prefer validating the key against a database or cache and using a session or token mechanism rather than echoing it back.

When constructing custom headers from multiple sources, always use HeaderValue::from_str which returns a Result, and handle errors explicitly:

use actix_web::http::header::HeaderValue;

let user_value = "some-value";
match HeaderValue::from_str(user_value) {
    Ok(safe) => { resp.headers_mut().insert("X-Custom", safe); }
    Err(_) => { return Err(actix_web::error::ErrorBadRequest("Invalid header value")); }
}

Additionally, apply strict input validation on query parameters and JSON bodies that influence headers. For API keys, use middleware to authenticate and set request extensions rather than injecting them into response headers. middleBrick’s CLI can verify that your endpoints do not reflect untrusted data into headers by scanning with active CRLF injection probes.

For continuous protection, use the middleBrick GitHub Action to fail builds if header injection risks are detected during CI/CD, and enable the Pro plan’s continuous monitoring to catch regressions. The MCP Server can also flag vulnerable header handling patterns directly in supported IDEs.

Frequently Asked Questions

Can header injection bypass authentication when API keys are used in Actix?
Yes. If an API key is reflected into response headers without validation, an attacker can inject additional headers such as Set-Cookie or Location, potentially bypassing intended routing or stealing session-like identifiers. Always validate and avoid echoing raw keys into headers.
How does middleBrick detect header injection in Actix APIs?
middleBrick sends carefully crafted newline sequences in API key positions and checks whether these sequences are reflected verbatim in response headers. This tests for improper input sanitization in header construction, mapping findings to OWASP API Top 10 and providing remediation guidance.