Missing Tls in Actix with Api Keys
Missing Tls in Actix with Api Keys — how this specific combination creates or exposes the vulnerability
Transport Layer Security (TLS) ensures confidentiality and integrity between clients and servers. When an Actix web service that uses API keys does not enforce TLS, keys can be captured in transit. middleBrick flags this pattern under Data Exposure and Authentication checks, noting that unencrypted channels allow on-path attackers to observe or modify traffic.
In an Actix application, API keys are often passed via HTTP headers (e.g., x-api-key). Without TLS, these headers are sent in plaintext. An attacker on the same network or through a compromised router can sniff packets and harvest keys. Even if the application validates keys correctly, transmitting them without encryption violates secure transport principles and can lead to unauthorized access across services that trust the key.
middleBrick also checks whether API keys are passed in URLs as query parameters. URLs are more likely to be logged in server access logs, browser history, and proxy caches. If TLS is missing, these logs further expose keys in cleartext. The scanner cross-references OpenAPI specs to detect whether security schemes declare scheme: https; if not, and keys are used, the finding is surfaced with severity Medium to High depending on context.
The combination of missing TLS and API keys exemplifies a failure in transport-layer security, increasing risk of credential theft and downstream impersonation. This aligns with OWASP API Top 10 A05:2023 Security Misconfiguration and A02:2023 Broken Authentication. middleBrick tests unauthenticated endpoints and, where applicable, checks whether responses contain indicators (e.g., WWW-Authenticate) that might inadvertently leak information about the authentication scheme.
Api Keys-Specific Remediation in Actix — concrete code fixes
Remediation involves two parts: enforcing TLS at the server or load balancer and ensuring API keys are handled securely within Actix. Below are concrete Actix examples that assume TLS termination at the edge or via Rust TLS configuration.
1) Require HTTPS for all routes and reject cleartext HTTP. Use middleware to inspect the request and enforce secure connections before processing API keys.
use actix_web::{web, App, HttpServer, middleware::Logger, dev::ServiceRequest, Error};
use actix_web::http::header::HeaderValue;
use actix_web::Either;
use std::future::{ready, Ready};
async fn validate_tls(req: ServiceRequest) -> Result, Error> {
let head = req.head();
if head.secure() {
Ok(Either::Left(req))
} else {
// Reject cleartext requests before API key validation
Ok(Either::Right((req, "HTTPS required")))
}
}
async fn handler_api_key(
req: ServiceRequest,
web::Query(params): web::Query>,
) -> Result {
let keys = req.headers().get("x-api-key")
.ok_or_else(|| actix_web::error::ErrorUnauthorized("Missing key"))?;
// Validate key against a secure store
if keys != "expected_key" {
return Err(actix_web::error::ErrorForbidden("Invalid key"));
}
Ok(web::Json("OK"))
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| {
App::new()
.wrap(Logger::default())
.wrap_fn(|req, srv| {
validate_tls(req).and_then(|res| match res {
Either::Left(req) => srv.call(req),
Either::Right((_, msg)) => {
futures::future::ok(req.into_response(
actix_web::HttpResponse::build(actix_web::http::StatusCode::FORBIDDEN)
.body(msg.to_string())
))
}
})
})
.service(web::resource("/data").route(web::get().to(handler_api_key)))
})
.bind_rustls("0.0.0.0:8443", rustls::ServerConfig::new())? // TLS enforced here
.unwrap()
.run()
.await
}
2) When using reverse proxies or load balancers, ensure they terminate TLS and forward only to Actix over HTTPS. Set headers like X-Forwarded-Proto and validate them in Actix to prevent downgrade attacks.
async fn handler_with_forwarded(
req: ServiceRequest,
) -> Result {
let proto = req.headers().get("x-forwarded-proto")
.and_then(|v| v.to_str().ok())
.unwrap_or("http");
if proto != "https" {
return Err(actix_web::error::ErrorBadRequest("TLS required"));
}
let keys = req.headers().get("x-api-key")
.ok_or_else(|| actix_web::error::ErrorUnauthorized("Missing key"))?;
// key validation logic
Ok(web::Json("secure"))
}
3) Store API keys securely and avoid logging them. Configure Actix to filter sensitive headers from logs and error responses.
use actix_web::http::header::HeaderMap;
fn sanitize_headers(mut headers: HeaderMap) -> HeaderMap {
if let Some(key) = headers.get("x-api-key") {
// Replace key value in logs with a placeholder
headers.insert("x-api-key", HeaderValue::from_static("**filtered**"));
}
headers
}
These examples illustrate how to integrate TLS enforcement and secure key handling within Actix. middleBrick’s scans verify that endpoints requiring keys are served over HTTPS and that security headers are present, reducing the risk of key exposure.
Related CWEs: encryption
| CWE ID | Name | Severity |
|---|---|---|
| CWE-319 | Cleartext Transmission of Sensitive Information | HIGH |
| CWE-295 | Improper Certificate Validation | HIGH |
| CWE-326 | Inadequate Encryption Strength | HIGH |
| CWE-327 | Use of a Broken or Risky Cryptographic Algorithm | HIGH |
| CWE-328 | Use of Weak Hash | HIGH |
| CWE-330 | Use of Insufficiently Random Values | HIGH |
| CWE-338 | Use of Cryptographically Weak PRNG | MEDIUM |
| CWE-693 | Protection Mechanism Failure | MEDIUM |
| CWE-757 | Selection of Less-Secure Algorithm During Negotiation | HIGH |
| CWE-261 | Weak Encoding for Password | HIGH |