Api Key Exposure in Actix with Session Cookies
Api Key Exposure in Actix with Session Cookies — how this specific combination creates or exposes the vulnerability
In Actix web applications, storing or transmitting an API key within a session cookie can inadvertently expose the key to both client-side and network-level attackers. A session cookie is typically managed by the application server and intended to hold a session identifier, not long-lived secrets such as API keys. When an API key is placed into a session cookie, several risk scenarios emerge:
- Insecure cookie attributes: If the cookie is not marked
SecureandHttpOnly, it can be transmitted over unencrypted channels or exposed to JavaScript, enabling interception or cross-site scripting (XSS) based exfiltration. - Session fixation or hijacking: If session identifiers are predictable or improperly rotated, an attacker who obtains the session can also read the API key stored within it.
- Server-side leakage via logs or error messages: Actix code that inadvertently includes the session cookie (and thus the API key) in logs, URLs, or error pages can expose the key beyond intended boundaries.
- CSRF and unauthorized API use: Even if the API key is stored server-side in the session, exposing it to the client-side cookie scope may allow an attacker to leverage the key in unauthorized requests if CSRF protections are insufficient.
Because middleBrick tests unauthenticated attack surfaces, it can detect scenarios where API keys appear in cookies or are transmitted without adequate protections. For example, a scan might flag an endpoint that sets a cookie containing a key-like string and lacks Secure or HttpOnly, indicating insecure handling. Additionally, improper use of cookies for key material violates the principle of separation between session management and sensitive credentials, increasing the likelihood of accidental disclosure through client-side channels.
middleBrick’s checks include Data Exposure and Authentication analyses, which help surface these patterns. When an API key is stored in a session cookie, the scan can identify missing cookie security flags, lack of encryption in transit, and potential exposure pathways. This is especially important given that API keys often grant elevated access; their presence in session-scoped cookies expands the impact of any leakage.
Session Cookies-Specific Remediation in Actix — concrete code fixes
To remediate the risk of API key exposure when using session cookies in Actix, keep API keys server-side and avoid storing them in cookies. Use session cookies only for opaque session identifiers, and store sensitive values in server-side session storage. Apply strict cookie attributes and enforce secure transmission. Below are concrete code examples demonstrating secure session cookie practices in Actix.
1. Set secure session cookies without exposing API keys
Ensure cookies are marked Secure and HttpOnly, and prefer SameSite to mitigate CSRF. Never place API keys in these cookies.
use actix_web::{web, App, HttpResponse, HttpServer, Result};
use actix_session::{Session, SessionMiddleware, storage::CookieSessionStore};
use actix_web::cookie::Key;
async fn set_session(session: Session) -> Result<HttpResponse> {
// Store only an opaque session ID or user identifier, not the API key
session.insert("user_id", "user-123")?;
// Do NOT store API keys in the session cookie
Ok(HttpResponse::Ok().body("Session created"))
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
// Create a secure signing key for session cookies (use env vars in production)
let secret_key = Key::generate();
HttpServer::new(move || {
App::new()
.wrap(
SessionMiddleware::builder(CookieSessionStore::default(), secret_key.clone())
.cookie_name("session_id".to_string())
.cookie_secure(true) // Only sent over HTTPS
.cookie_http_only(true) // Prevent JavaScript access
.cookie_same_site(actix_web::cookie::SameSite::Lax)
.build(),
)
.route("/set-session", web::get().to(set_session))
})
.bind("127.0.0.1:8080")?
.run()
.await
}
2. Server-side session storage for sensitive data
Keep API keys in server-side storage (e.g., a secure cache or database) keyed by session ID. The cookie should contain only the session ID.
use actix_session::Session;
use actix_web::{web, HttpResponse};
async fn get_api_key(session: Session) -> HttpResponse {
// Retrieve opaque session identifier from cookie
if let Some(session_id) = session.get::
3. Rotate keys and invalidate sessions on logout
Implement logout to clear server-side session data and expire cookies, reducing the window for exposure.
use actix_session::Session;
use actix_web::HttpResponse;
async fn logout(session: Session) -> HttpResponse {
// Clear server-side session data associated with the session ID
session.purge();
// Expire the client-side cookie
actix_web::HttpResponse::Ok()
.cookie(
actix_web::cookie::Cookie::build(("session_id", "")).max_age(time::Duration::seconds(0)).finish()
)
.body("Logged out")
}
By following these practices, you reduce the likelihood of API key exposure through session cookies. middleBrick scans can validate that cookies include Secure, HttpOnly, and SameSite attributes and that API keys are not present in client-controlled storage.