feat(security): harden dashboard sessions, fix the login open redirect (#260) #306
No files matched your search
+7
-1
@@ -66,7 +66,8 @@ WERKBANK_RUNNER_TOKEN=
|
||||
# unauthenticated as the `dev` tenant. Required in staging/production:
|
||||
# KEYCLOAK_URL, KEYCLOAK_REALM, KEYCLOAK_AUDIENCE, CORS_ALLOWED_ORIGINS,
|
||||
# TENANT_REGISTRY_URL, TENANT_REGISTRY_CLIENT_ID/_SECRET,
|
||||
# PLATFORM_ALLOWED_CLIENTS, SECRETS_ENCRYPTION_KEY (+ MCP_PORT for compliance-mcp).
|
||||
# PLATFORM_ALLOWED_CLIENTS, SECRETS_ENCRYPTION_KEY (+ MCP_PORT for
|
||||
# compliance-mcp, DASHBOARD_SESSION_KEY for the dashboard).
|
||||
APP_ENV=dev
|
||||
# 64 hex characters (32 bytes) that seal tenant credentials (git and tracker
|
||||
# tokens, webhook secrets) at rest. Generate with `openssl rand -hex 32`. Without
|
||||
@@ -98,6 +99,11 @@ PLATFORM_ALLOWED_CLIENTS=
|
||||
# Dashboard
|
||||
DASHBOARD_PORT=8080
|
||||
AGENT_API_URL=http://localhost:3001
|
||||
# 128 hex characters (64 bytes): half signs the session cookie, half seals the
|
||||
# session records in Mongo (they hold the user's Keycloak tokens). Generate
|
||||
# with `openssl rand -hex 64`. Required in staging/production; unset in dev
|
||||
# means sessions end when the dashboard restarts.
|
||||
DASHBOARD_SESSION_KEY=
|
||||
|
||||
# MCP Server
|
||||
MCP_ENDPOINT_URL=http://localhost:8090
|
||||
|
||||
Generated
+2
-13
@@ -738,6 +738,7 @@ dependencies = [
|
||||
name = "compliance-dashboard"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"axum",
|
||||
"base64",
|
||||
"bson",
|
||||
@@ -750,6 +751,7 @@ dependencies = [
|
||||
"dioxus-logger 0.6.2",
|
||||
"dotenvy",
|
||||
"gloo-timers",
|
||||
"hex",
|
||||
"js-sys",
|
||||
"mongodb",
|
||||
"rand 0.9.2",
|
||||
@@ -6077,7 +6079,6 @@ dependencies = [
|
||||
"tower-layer",
|
||||
"tower-service",
|
||||
"tower-sessions-core",
|
||||
"tower-sessions-memory-store",
|
||||
"tracing",
|
||||
]
|
||||
|
||||
@@ -6102,18 +6103,6 @@ dependencies = [
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tower-sessions-memory-store"
|
||||
version = "0.15.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "713fabf882b6560a831e2bbed6204048b35bdd60e50bbb722902c74f8df33460"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"time",
|
||||
"tokio",
|
||||
"tower-sessions-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tracing"
|
||||
version = "0.1.44"
|
||||
|
||||
@@ -19,6 +19,7 @@ server = [
|
||||
"dioxus/fullstack",
|
||||
"compliance-core/mongodb",
|
||||
"compliance-core/telemetry",
|
||||
"compliance-core/secrets",
|
||||
"dep:axum",
|
||||
"dep:mongodb",
|
||||
"dep:reqwest",
|
||||
@@ -36,6 +37,8 @@ server = [
|
||||
"dep:base64",
|
||||
"dep:uuid",
|
||||
"dep:bson",
|
||||
"dep:hex",
|
||||
"dep:async-trait",
|
||||
]
|
||||
|
||||
[dependencies]
|
||||
@@ -65,7 +68,10 @@ dotenvy = { version = "0.15", optional = true }
|
||||
tokio = { workspace = true, optional = true }
|
||||
dioxus-cli-config = { version = "=0.7.3", optional = true }
|
||||
dioxus-fullstack = { version = "=0.7.3", optional = true }
|
||||
tower-sessions = { version = "0.15", default-features = false, features = ["axum-core", "memory-store", "signed"], optional = true }
|
||||
tower-sessions = { version = "0.15", default-features = false, features = ["axum-core", "signed"], optional = true }
|
||||
# Session store trait impls (`MongoSessionStore`).
|
||||
async-trait = { version = "0.1", optional = true }
|
||||
hex = { workspace = true, optional = true }
|
||||
time = { version = "0.3", default-features = false, optional = true }
|
||||
rand = { version = "0.9", optional = true }
|
||||
url = { version = "2", optional = true }
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
sync::{Arc, RwLock},
|
||||
collections::{HashMap, VecDeque},
|
||||
sync::{Arc, Mutex},
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
use axum::{
|
||||
@@ -20,31 +21,81 @@ use super::{
|
||||
|
||||
pub const LOGGED_IN_USER_SESS_KEY: &str = "logged-in-user";
|
||||
|
||||
/// How long a login may take between `/auth` and the Keycloak callback.
|
||||
const PENDING_LOGIN_TTL: Duration = Duration::from_secs(10 * 60);
|
||||
/// Most logins in flight at once. `/auth` is unauthenticated, so without a cap
|
||||
/// every request would grow this map for good; past it the oldest is dropped.
|
||||
const MAX_PENDING_LOGINS: usize = 10_000;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub(crate) struct PendingOAuthEntry {
|
||||
pub(crate) redirect_url: Option<String>,
|
||||
pub(crate) code_verifier: String,
|
||||
}
|
||||
|
||||
/// Logins started at `/auth` and not yet finished at the callback, by OAuth
|
||||
/// `state`. Entries expire after [`PENDING_LOGIN_TTL`] and the map holds at
|
||||
/// most [`MAX_PENDING_LOGINS`].
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct PendingOAuthStore(Arc<RwLock<HashMap<String, PendingOAuthEntry>>>);
|
||||
pub struct PendingOAuthStore(Arc<Mutex<PendingLogins>>);
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
struct PendingLogins {
|
||||
/// Each login with the time it started.
|
||||
by_state: HashMap<String, (Instant, PendingOAuthEntry)>,
|
||||
/// The same logins in start order, so expiry and eviction work from the
|
||||
/// front without scanning the map.
|
||||
started: VecDeque<(Instant, String)>,
|
||||
}
|
||||
|
||||
impl PendingOAuthStore {
|
||||
pub(crate) fn insert(&self, state: String, entry: PendingOAuthEntry) {
|
||||
self.insert_at(state, entry, Instant::now());
|
||||
}
|
||||
|
||||
fn insert_at(&self, state: String, entry: PendingOAuthEntry, now: Instant) {
|
||||
#[allow(clippy::expect_used)]
|
||||
self.0
|
||||
.write()
|
||||
.expect("pending oauth store lock poisoned")
|
||||
.insert(state, entry);
|
||||
let mut logins = self.0.lock().expect("pending oauth store lock poisoned");
|
||||
while let Some((started, _)) = logins.started.front() {
|
||||
let expired = now.duration_since(*started) >= PENDING_LOGIN_TTL;
|
||||
if !expired && logins.started.len() < MAX_PENDING_LOGINS {
|
||||
break;
|
||||
}
|
||||
if let Some((_, old)) = logins.started.pop_front() {
|
||||
logins.by_state.remove(&old);
|
||||
}
|
||||
}
|
||||
logins.started.push_back((now, state.clone()));
|
||||
logins.by_state.insert(state, (now, entry));
|
||||
}
|
||||
|
||||
pub(crate) fn take(&self, state: &str) -> Option<PendingOAuthEntry> {
|
||||
#[allow(clippy::expect_used)]
|
||||
self.0
|
||||
.write()
|
||||
.expect("pending oauth store lock poisoned")
|
||||
.remove(state)
|
||||
self.take_at(state, Instant::now())
|
||||
}
|
||||
|
||||
fn take_at(&self, state: &str, now: Instant) -> Option<PendingOAuthEntry> {
|
||||
#[allow(clippy::expect_used)]
|
||||
let mut logins = self.0.lock().expect("pending oauth store lock poisoned");
|
||||
// Its queue slot stays until it reaches the front. Expired entries are
|
||||
// only dropped on insert, so check the age here too.
|
||||
let (started, entry) = logins.by_state.remove(state)?;
|
||||
(now.duration_since(started) < PENDING_LOGIN_TTL).then_some(entry)
|
||||
}
|
||||
}
|
||||
|
||||
/// `raw` if it is a path on this site, else `None`.
|
||||
///
|
||||
/// The login flow sends the browser to `redirect_url` after Keycloak, so an
|
||||
/// unchecked value turns a genuine login link into a redirect to any site.
|
||||
/// Only a single leading `/` is accepted. `//host` and `/\host` are read by
|
||||
/// browsers as another host, and control characters are refused because
|
||||
/// browsers strip tabs and newlines, which can turn `/\t/host` into `//host`.
|
||||
fn same_origin_path(raw: &str) -> Option<&str> {
|
||||
let mut chars = raw.chars();
|
||||
let starts_with_single_slash =
|
||||
chars.next() == Some('/') && !matches!(chars.next(), Some('/' | '\\'));
|
||||
let clean = !raw.chars().any(|c| c == '\\' || c.is_control());
|
||||
(starts_with_single_slash && clean).then_some(raw)
|
||||
}
|
||||
|
||||
pub(crate) fn generate_state() -> String {
|
||||
@@ -82,7 +133,11 @@ pub async fn auth_login(
|
||||
let code_verifier = generate_code_verifier();
|
||||
let code_challenge = derive_code_challenge(&code_verifier);
|
||||
|
||||
let redirect_url = params.get("redirect_url").cloned();
|
||||
// Only same-site paths survive; anything else falls back to `/`.
|
||||
let redirect_url = params
|
||||
.get("redirect_url")
|
||||
.and_then(|u| same_origin_path(u))
|
||||
.map(str::to_string);
|
||||
pending.insert(
|
||||
csrf_state.clone(),
|
||||
PendingOAuthEntry {
|
||||
@@ -203,7 +258,7 @@ pub async fn auth_callback(
|
||||
|
||||
let target = entry
|
||||
.redirect_url
|
||||
.filter(|u| !u.is_empty())
|
||||
.filter(|u| same_origin_path(u).is_some())
|
||||
.unwrap_or_else(|| "/".into());
|
||||
|
||||
Ok(Redirect::temporary(&target))
|
||||
@@ -232,3 +287,60 @@ pub async fn logout(
|
||||
|
||||
Ok(Redirect::temporary(url.as_str()))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::expect_used)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn only_paths_on_this_site_are_followed_after_login() {
|
||||
for ok in ["/", "/targets", "/targets/abc?tab=scans#x", "/a//b"] {
|
||||
assert_eq!(same_origin_path(ok), Some(ok), "{ok}");
|
||||
}
|
||||
for evil in [
|
||||
"https://evil.example",
|
||||
"//evil.example",
|
||||
"/\\evil.example",
|
||||
"\\\\evil.example",
|
||||
"/\t/evil.example",
|
||||
"/\n/evil.example",
|
||||
"javascript:alert(1)",
|
||||
"evil.example",
|
||||
"",
|
||||
] {
|
||||
assert_eq!(same_origin_path(evil), None, "{evil:?}");
|
||||
}
|
||||
}
|
||||
|
||||
fn entry() -> PendingOAuthEntry {
|
||||
PendingOAuthEntry {
|
||||
redirect_url: None,
|
||||
code_verifier: "v".into(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pending_login_is_taken_once_and_expires() {
|
||||
let store = PendingOAuthStore::default();
|
||||
let t0 = Instant::now();
|
||||
store.insert_at("fresh".into(), entry(), t0);
|
||||
store.insert_at("stale".into(), entry(), t0);
|
||||
|
||||
assert!(store.take_at("fresh", t0).is_some());
|
||||
assert!(store.take_at("fresh", t0).is_none(), "one use only");
|
||||
assert!(store.take_at("stale", t0 + PENDING_LOGIN_TTL).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pending_logins_are_capped() {
|
||||
let store = PendingOAuthStore::default();
|
||||
let t0 = Instant::now();
|
||||
for i in 0..=MAX_PENDING_LOGINS {
|
||||
store.insert_at(format!("s{i}"), entry(), t0);
|
||||
}
|
||||
let logins = store.0.lock().expect("lock");
|
||||
assert_eq!(logins.by_state.len(), MAX_PENDING_LOGINS);
|
||||
assert!(!logins.by_state.contains_key("s0"), "oldest evicted");
|
||||
}
|
||||
}
|
||||
@@ -19,6 +19,11 @@ impl Database {
|
||||
Ok(Self { inner: db })
|
||||
}
|
||||
|
||||
/// The underlying database, for stores that manage their own collection.
|
||||
pub fn inner(&self) -> &mongodb::Database {
|
||||
&self.inner
|
||||
}
|
||||
|
||||
pub fn findings(&self) -> Collection<Finding> {
|
||||
self.inner.collection("findings")
|
||||
}
|
||||
|
||||
@@ -38,6 +38,8 @@ mod server;
|
||||
#[cfg(feature = "server")]
|
||||
pub mod server_state;
|
||||
#[cfg(feature = "server")]
|
||||
mod session_store;
|
||||
#[cfg(feature = "server")]
|
||||
mod user_state;
|
||||
|
||||
#[cfg(feature = "server")]
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
use axum::extract::DefaultBodyLimit;
|
||||
use axum::routing::{get, post};
|
||||
use axum::routing::get;
|
||||
use axum::{middleware, Extension};
|
||||
use dioxus::prelude::*;
|
||||
use time::Duration;
|
||||
use tower_sessions::{cookie::Key, MemoryStore, SessionManagerLayer};
|
||||
use tower_sessions::SessionManagerLayer;
|
||||
|
||||
use compliance_core::config::AppEnv;
|
||||
use compliance_core::models::{McpServerConfig, McpServerStatus, McpTransport};
|
||||
@@ -14,12 +13,9 @@ use super::database::Database;
|
||||
use super::error::DashboardError;
|
||||
use super::keycloak_config::KeycloakConfig;
|
||||
use super::server_state::{ServerState, ServerStateInner};
|
||||
use super::session_store::{load_session_key, MongoSessionStore};
|
||||
use super::{auth_callback, auth_login, logout, require_auth, PendingOAuthStore};
|
||||
|
||||
/// Largest webhook payload forwarded to the agent (GitHub caps push payloads at
|
||||
/// 25 MB). Every other route keeps axum's 2 MiB default.
|
||||
const WEBHOOK_MAX_BYTES: usize = 25 * 1024 * 1024;
|
||||
|
||||
pub fn server_start(app: fn() -> Element) -> Result<(), DashboardError> {
|
||||
tokio::runtime::Runtime::new()
|
||||
.map_err(|e| DashboardError::Other(e.to_string()))?
|
||||
@@ -61,6 +57,18 @@ pub fn server_start(app: fn() -> Element) -> Result<(), DashboardError> {
|
||||
.map(|v| v.trim().to_string())
|
||||
.filter(|v| !v.is_empty());
|
||||
|
||||
// Sessions survive a redeploy: signed with a key from the
|
||||
// environment, stored sealed in Mongo (#260).
|
||||
let key = load_session_key(app_env)?;
|
||||
let store = MongoSessionStore::new(db.inner(), &key).await?;
|
||||
let session = SessionManagerLayer::new(store)
|
||||
// HTTPS-only outside dev; a local dashboard is plain http.
|
||||
.with_secure(app_env.is_hardened())
|
||||
.with_http_only(true)
|
||||
.with_same_site(tower_sessions::cookie::SameSite::Lax)
|
||||
.with_expiry(tower_sessions::Expiry::OnInactivity(Duration::hours(24)))
|
||||
.with_signed(key);
|
||||
|
||||
let server_state: ServerState = ServerStateInner {
|
||||
agent_api_url: config.agent_api_url.clone(),
|
||||
db,
|
||||
@@ -70,15 +78,6 @@ pub fn server_start(app: fn() -> Element) -> Result<(), DashboardError> {
|
||||
}
|
||||
.into();
|
||||
|
||||
// Session layer
|
||||
let key = Key::generate();
|
||||
let store = MemoryStore::default();
|
||||
let session = SessionManagerLayer::new(store)
|
||||
.with_secure(false)
|
||||
.with_same_site(tower_sessions::cookie::SameSite::Lax)
|
||||
.with_expiry(tower_sessions::Expiry::OnInactivity(Duration::hours(24)))
|
||||
.with_signed(key);
|
||||
|
||||
let port = dioxus_cli_config::server_port().unwrap_or(8080);
|
||||
let addr = std::net::SocketAddr::from(([0, 0, 0, 0], port));
|
||||
let listener = tokio::net::TcpListener::bind(addr)
|
||||
@@ -91,12 +90,6 @@ pub fn server_start(app: fn() -> Element) -> Result<(), DashboardError> {
|
||||
.route("/auth", get(auth_login))
|
||||
.route("/auth/callback", get(auth_callback))
|
||||
.route("/logout", get(logout))
|
||||
// Webhook proxy: forward to agent (no auth required). Push
|
||||
// payloads can reach 25 MB (GitHub's cap), over the 2 MiB default.
|
||||
.route(
|
||||
"/webhook/{platform}/{repo_id}",
|
||||
post(webhook_proxy).layer(DefaultBodyLimit::max(WEBHOOK_MAX_BYTES)),
|
||||
)
|
||||
.serve_dioxus_application(ServeConfig::new(), app)
|
||||
// No raised body limit: uploads stream through `FileStream`, which
|
||||
// reads the raw body, so every other server function keeps axum's
|
||||
@@ -114,53 +107,6 @@ pub fn server_start(app: fn() -> Element) -> Result<(), DashboardError> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Forward incoming webhooks to the agent's webhook server.
|
||||
/// The dashboard acts as a public-facing proxy so the agent isn't exposed directly.
|
||||
async fn webhook_proxy(
|
||||
Extension(state): Extension<ServerState>,
|
||||
axum::extract::Path((platform, repo_id)): axum::extract::Path<(String, String)>,
|
||||
headers: axum::http::HeaderMap,
|
||||
body: axum::body::Bytes,
|
||||
) -> axum::http::StatusCode {
|
||||
// The agent_api_url typically looks like "http://agent:3001" or "http://localhost:3001"
|
||||
// Webhook routes are on the same server, so strip any trailing path
|
||||
let base = state.agent_api_url.trim_end_matches('/');
|
||||
// Remove /api/v1 suffix if present to get base URL
|
||||
let base = base
|
||||
.strip_suffix("/api/v1")
|
||||
.or_else(|| base.strip_suffix("/api"))
|
||||
.unwrap_or(base);
|
||||
let agent_url = format!("{base}/webhook/{platform}/{repo_id}");
|
||||
|
||||
// Forward all relevant headers
|
||||
let client = reqwest::Client::new();
|
||||
let mut req = client.post(&agent_url).body(body.to_vec());
|
||||
|
||||
for (name, value) in &headers {
|
||||
let name_str = name.as_str().to_lowercase();
|
||||
// Forward platform-specific headers
|
||||
if name_str.starts_with("x-gitea-")
|
||||
|| name_str.starts_with("x-github-")
|
||||
|| name_str.starts_with("x-hub-")
|
||||
|| name_str.starts_with("x-gitlab-")
|
||||
|| name_str == "content-type"
|
||||
{
|
||||
if let Ok(v) = value.to_str() {
|
||||
req = req.header(name.as_str(), v);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
match req.send().await {
|
||||
Ok(resp) => axum::http::StatusCode::from_u16(resp.status().as_u16())
|
||||
.unwrap_or(axum::http::StatusCode::BAD_GATEWAY),
|
||||
Err(e) => {
|
||||
tracing::error!("Webhook proxy failed: {e}");
|
||||
axum::http::StatusCode::BAD_GATEWAY
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Seed three default MCP server configs (Findings, SBOM, DAST) if they don't already exist.
|
||||
async fn seed_default_mcp_servers(db: &Database, mcp_endpoint_url: Option<&str>) {
|
||||
let endpoint = mcp_endpoint_url.unwrap_or("http://localhost:8090");
|
||||
|
||||
@@ -0,0 +1,313 @@
|
||||
//! Dashboard sessions in Mongo, sealed at rest (#260).
|
||||
//!
|
||||
//! Sessions used to live in process memory under a key generated at startup,
|
||||
//! so every redeploy logged everyone out. They now live in the
|
||||
//! `dashboard_sessions` collection, and the cookie is signed with
|
||||
//! `DASHBOARD_SESSION_KEY`, so both survive a restart. A session holds the
|
||||
//! user's Keycloak access and refresh tokens, so each record is sealed with
|
||||
//! the encryption half of the same key before it is written; a database dump
|
||||
//! reveals no token. Mongo's TTL index removes expired records.
|
||||
|
||||
use async_trait::async_trait;
|
||||
use mongodb::bson::{doc, DateTime as BsonDateTime, Document};
|
||||
use mongodb::error::{ErrorKind, WriteFailure};
|
||||
use mongodb::options::IndexOptions;
|
||||
use mongodb::{Collection, IndexModel};
|
||||
use tower_sessions::cookie::Key;
|
||||
use tower_sessions::session::{Id, Record};
|
||||
use tower_sessions::session_store::{self, SessionStore};
|
||||
|
||||
use compliance_core::config::AppEnv;
|
||||
use compliance_core::secret_box::SecretBox;
|
||||
|
||||
use super::error::DashboardError;
|
||||
|
||||
/// Mongo's code for a unique-index violation.
|
||||
const DUPLICATE_KEY: i32 = 11000;
|
||||
/// Hex digits in `DASHBOARD_SESSION_KEY` (a 64-byte cookie key: 32 bytes to
|
||||
/// sign the cookie, 32 to seal session records).
|
||||
const SESSION_KEY_HEX_LEN: usize = 128;
|
||||
|
||||
/// Load the session key from `DASHBOARD_SESSION_KEY`.
|
||||
///
|
||||
/// A hardened deployment must set it. In dev a missing key is generated, and
|
||||
/// sessions then end when the dashboard restarts.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// [`DashboardError::Config`] if the key is malformed, or missing in a
|
||||
/// hardened environment.
|
||||
pub fn load_session_key(app_env: AppEnv) -> Result<Key, DashboardError> {
|
||||
let raw = std::env::var("DASHBOARD_SESSION_KEY").unwrap_or_default();
|
||||
parse_session_key(raw.trim(), app_env)
|
||||
}
|
||||
|
||||
fn parse_session_key(raw: &str, app_env: AppEnv) -> Result<Key, DashboardError> {
|
||||
if raw.is_empty() {
|
||||
if app_env.is_hardened() {
|
||||
return Err(DashboardError::Config(format!(
|
||||
"DASHBOARD_SESSION_KEY is required in {}: without it every restart \
|
||||
logs everyone out and sessions cannot be sealed",
|
||||
app_env.as_str()
|
||||
)));
|
||||
}
|
||||
tracing::warn!("DASHBOARD_SESSION_KEY unset; sessions end when the dashboard restarts");
|
||||
return Ok(Key::generate());
|
||||
}
|
||||
let malformed = || {
|
||||
DashboardError::Config(format!(
|
||||
"DASHBOARD_SESSION_KEY must be {SESSION_KEY_HEX_LEN} hex characters \
|
||||
(generate one with `openssl rand -hex 64`)"
|
||||
))
|
||||
};
|
||||
if raw.len() != SESSION_KEY_HEX_LEN {
|
||||
return Err(malformed());
|
||||
}
|
||||
let bytes = hex::decode(raw).map_err(|_| malformed())?;
|
||||
Key::try_from(bytes.as_slice()).map_err(|_| malformed())
|
||||
}
|
||||
|
||||
/// A [`SessionStore`] over a Mongo collection, with every record sealed.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct MongoSessionStore {
|
||||
sessions: Collection<Document>,
|
||||
sealer: SecretBox,
|
||||
}
|
||||
|
||||
impl MongoSessionStore {
|
||||
/// Open the store in `db` and make sure expired sessions are removed.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns an error if the TTL index cannot be created.
|
||||
pub async fn new(db: &mongodb::Database, key: &Key) -> Result<Self, DashboardError> {
|
||||
let sessions = db.collection::<Document>("dashboard_sessions");
|
||||
// `expireAfterSeconds: 0` deletes a record once `expires_at` passes.
|
||||
let ttl = IndexModel::builder()
|
||||
.keys(doc! { "expires_at": 1 })
|
||||
.options(
|
||||
IndexOptions::builder()
|
||||
.expire_after(std::time::Duration::ZERO)
|
||||
.build(),
|
||||
)
|
||||
.build();
|
||||
sessions.create_index(ttl).await?;
|
||||
Ok(Self {
|
||||
sessions,
|
||||
sealer: sealer_for(key)?,
|
||||
})
|
||||
}
|
||||
|
||||
/// The stored form of a record: its id, the sealed record, and when it
|
||||
/// expires (for the TTL index and for load, since the TTL monitor runs
|
||||
/// only once a minute).
|
||||
fn to_document(&self, record: &Record) -> session_store::Result<Document> {
|
||||
let json = serde_json::to_string(record)
|
||||
.map_err(|e| session_store::Error::Encode(e.to_string()))?;
|
||||
let sealed = self
|
||||
.sealer
|
||||
.seal(&json)
|
||||
.map_err(|e| session_store::Error::Encode(e.to_string()))?;
|
||||
Ok(doc! {
|
||||
"_id": record.id.to_string(),
|
||||
"record": sealed,
|
||||
"expires_at": expiry(record),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The record-sealing box for a session key: the key's encryption half, so
|
||||
/// the half that signs cookies never seals anything.
|
||||
fn sealer_for(key: &Key) -> Result<SecretBox, DashboardError> {
|
||||
SecretBox::from_key(key.encryption()).map_err(|e| DashboardError::Config(e.to_string()))
|
||||
}
|
||||
|
||||
fn expiry(record: &Record) -> BsonDateTime {
|
||||
BsonDateTime::from_millis(
|
||||
i64::try_from(record.expiry_date.unix_timestamp_nanos() / 1_000_000).unwrap_or(i64::MAX),
|
||||
)
|
||||
}
|
||||
|
||||
fn backend(e: impl std::fmt::Display) -> session_store::Error {
|
||||
session_store::Error::Backend(e.to_string())
|
||||
}
|
||||
|
||||
fn is_duplicate_key(e: &mongodb::error::Error) -> bool {
|
||||
matches!(
|
||||
e.kind.as_ref(),
|
||||
ErrorKind::Write(WriteFailure::WriteError(w)) if w.code == DUPLICATE_KEY
|
||||
)
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl SessionStore for MongoSessionStore {
|
||||
async fn create(&self, record: &mut Record) -> session_store::Result<()> {
|
||||
// Session ids are random 128-bit values, so a collision is a
|
||||
// theoretical case; if it happens, draw a new id rather than
|
||||
// overwrite another user's session.
|
||||
loop {
|
||||
match self.sessions.insert_one(self.to_document(record)?).await {
|
||||
Ok(_) => return Ok(()),
|
||||
Err(e) if is_duplicate_key(&e) => record.id = Id::default(),
|
||||
Err(e) => return Err(backend(e)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn save(&self, record: &Record) -> session_store::Result<()> {
|
||||
self.sessions
|
||||
.replace_one(
|
||||
doc! { "_id": record.id.to_string() },
|
||||
self.to_document(record)?,
|
||||
)
|
||||
.upsert(true)
|
||||
.await
|
||||
.map_err(backend)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn load(&self, session_id: &Id) -> session_store::Result<Option<Record>> {
|
||||
let found = self
|
||||
.sessions
|
||||
.find_one(doc! {
|
||||
"_id": session_id.to_string(),
|
||||
"expires_at": { "$gt": BsonDateTime::now() },
|
||||
})
|
||||
.await
|
||||
.map_err(backend)?;
|
||||
let Some(stored) = found else {
|
||||
return Ok(None);
|
||||
};
|
||||
let sealed = stored
|
||||
.get_str("record")
|
||||
.map_err(|e| session_store::Error::Decode(e.to_string()))?;
|
||||
// A record sealed under another key (the key was changed) cannot be
|
||||
// opened; treat it as no session, so the user just logs in again.
|
||||
let Ok(json) = self.sealer.open(sealed) else {
|
||||
return Ok(None);
|
||||
};
|
||||
serde_json::from_str(&json)
|
||||
.map(Some)
|
||||
.map_err(|e| session_store::Error::Decode(e.to_string()))
|
||||
}
|
||||
|
||||
async fn delete(&self, session_id: &Id) -> session_store::Result<()> {
|
||||
self.sessions
|
||||
.delete_one(doc! { "_id": session_id.to_string() })
|
||||
.await
|
||||
.map_err(backend)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::expect_used, clippy::unwrap_used)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const KEY: &str = "00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff\
|
||||
ffeeddccbbaa99887766554433221100ffeeddccbbaa99887766554433221100";
|
||||
|
||||
#[test]
|
||||
fn a_hardened_dashboard_needs_the_session_key() {
|
||||
let err = parse_session_key("", AppEnv::Staging)
|
||||
.err()
|
||||
.expect("refused");
|
||||
assert!(err.to_string().contains("DASHBOARD_SESSION_KEY"));
|
||||
assert!(parse_session_key("", AppEnv::Dev).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_malformed_session_key_is_refused_everywhere() {
|
||||
for raw in ["abc", &KEY[..126], &format!("{}zz", &KEY[..126])] {
|
||||
assert!(parse_session_key(raw, AppEnv::Dev).is_err(), "{raw}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_same_key_always_gives_the_same_signing_and_sealing_keys() {
|
||||
let a = parse_session_key(KEY, AppEnv::Production).unwrap();
|
||||
let b = parse_session_key(KEY, AppEnv::Production).unwrap();
|
||||
assert_eq!(a.signing(), b.signing());
|
||||
// A record sealed before a restart opens after it.
|
||||
let sealed = sealer_for(&a).unwrap().seal("session").unwrap();
|
||||
assert_eq!(sealer_for(&b).unwrap().open(&sealed).unwrap(), "session");
|
||||
// The two halves differ, so signing never reuses the sealing key.
|
||||
assert_ne!(a.signing(), a.encryption());
|
||||
}
|
||||
|
||||
/// A store on a throwaway database, or `None` when no Mongo answers
|
||||
/// within two seconds (CI has none).
|
||||
async fn store_on_mongo(key: &Key) -> Option<(MongoSessionStore, mongodb::Database)> {
|
||||
let uri = std::env::var("TEST_MONGODB_URI")
|
||||
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
|
||||
let mut options = mongodb::options::ClientOptions::parse(&uri).await.ok()?;
|
||||
options.server_selection_timeout = Some(std::time::Duration::from_secs(2));
|
||||
let client = mongodb::Client::with_options(options).ok()?;
|
||||
if client
|
||||
.database("admin")
|
||||
.run_command(doc! { "ping": 1 })
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
eprintln!("SKIP session store: no MongoDB reachable at {uri}");
|
||||
return None;
|
||||
}
|
||||
let db = client.database(&format!("dsess_{}", uuid::Uuid::new_v4().simple()));
|
||||
let store = MongoSessionStore::new(&db, key).await.expect("store");
|
||||
Some((store, db))
|
||||
}
|
||||
|
||||
fn record(token: &str, expires_in: time::Duration) -> Record {
|
||||
Record {
|
||||
id: Id::default(),
|
||||
data: std::collections::HashMap::from([(
|
||||
"logged-in-user".to_string(),
|
||||
serde_json::json!({ "access_token": token }),
|
||||
)]),
|
||||
expiry_date: time::OffsetDateTime::now_utc() + expires_in,
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn sessions_survive_in_mongo_sealed_until_they_expire() {
|
||||
let key = parse_session_key(KEY, AppEnv::Production).unwrap();
|
||||
let Some((store, db)) = store_on_mongo(&key).await else {
|
||||
return;
|
||||
};
|
||||
|
||||
// A session written by one dashboard process loads in the next one.
|
||||
let mut live = record("tok-live-123", time::Duration::hours(1));
|
||||
store.create(&mut live).await.unwrap();
|
||||
let after_restart = MongoSessionStore::new(&db, &key).await.unwrap();
|
||||
assert_eq!(
|
||||
after_restart.load(&live.id).await.unwrap(),
|
||||
Some(live.clone())
|
||||
);
|
||||
|
||||
// Stored sealed: the token is not in the database.
|
||||
let stored = db
|
||||
.collection::<Document>("dashboard_sessions")
|
||||
.find_one(doc! { "_id": live.id.to_string() })
|
||||
.await
|
||||
.unwrap()
|
||||
.expect("stored");
|
||||
let sealed = stored.get_str("record").unwrap();
|
||||
assert!(SecretBox::is_sealed(sealed));
|
||||
assert!(!format!("{stored:?}").contains("tok-live-123"));
|
||||
|
||||
// Expired sessions do not load, even before the TTL monitor runs.
|
||||
let expired = record("tok-old", -time::Duration::minutes(1));
|
||||
store.save(&expired).await.unwrap();
|
||||
assert_eq!(store.load(&expired.id).await.unwrap(), None);
|
||||
|
||||
// A changed key means logging in again, not an error.
|
||||
let other = parse_session_key(&"ab".repeat(64), AppEnv::Production).unwrap();
|
||||
let other_store = MongoSessionStore::new(&db, &other).await.unwrap();
|
||||
assert_eq!(other_store.load(&live.id).await.unwrap(), None);
|
||||
|
||||
store.delete(&live.id).await.unwrap();
|
||||
assert_eq!(store.load(&live.id).await.unwrap(), None);
|
||||
db.drop().await.ok();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user