227 lines
8.9 KiB
Rust
227 lines
8.9 KiB
Rust
//! Encrypted, global pre-auth state. No runtime DDL or tenant access.
|
|
use crate::{Error, PendingLogin, Result, SecretResolver, StateStore, now};
|
|
use aes_gcm::{
|
|
Aes256Gcm, KeyInit, Nonce,
|
|
aead::{Aead, Payload},
|
|
};
|
|
use async_trait::async_trait;
|
|
use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
|
|
use secrecy::ExposeSecret;
|
|
use sqlx::{PgPool, Row};
|
|
use zeroize::Zeroizing;
|
|
|
|
pub const MIGRATION_SQL: &str = include_str!("../sql/001_oidc_login_states.sql");
|
|
pub const MAX_LOGIN_TTL_SECONDS: u64 = 300;
|
|
pub const MAX_CLEANUP_BATCH: u32 = 1000;
|
|
// App-specific, database-local insertion admission lock; never an authorization bypass.
|
|
const ADMISSION_LOCK: i64 = 0x524d4d4f49444301;
|
|
|
|
/// No Debug: neither pool configuration nor cryptographic material should enter logs.
|
|
pub struct PostgresStateStore {
|
|
pool: PgPool,
|
|
cipher: Aes256Gcm,
|
|
key_ref: String,
|
|
capacity: i64,
|
|
}
|
|
|
|
impl PostgresStateStore {
|
|
/// `key_ref` must be an immutable/versioned secret reference. Its value is exactly
|
|
/// 32 random bytes encoded as unpadded base64url. Resolve it from outside the DB.
|
|
/// This constructor does NOT create tables, grant privileges or verify migrations.
|
|
pub async fn new(
|
|
pool: PgPool,
|
|
resolver: &dyn SecretResolver,
|
|
key_ref: String,
|
|
capacity: u32,
|
|
) -> Result<Self> {
|
|
if key_ref.is_empty() || key_ref.len() > 256 || !(1..=100_000).contains(&capacity) {
|
|
return Err(Error::Configuration);
|
|
}
|
|
let secret = resolver.resolve(&key_ref).await?;
|
|
let bytes = Zeroizing::new(
|
|
URL_SAFE_NO_PAD
|
|
.decode(secret.expose_secret())
|
|
.map_err(|_| Error::Configuration)?,
|
|
);
|
|
let cipher = Aes256Gcm::new_from_slice(&bytes).map_err(|_| Error::Configuration)?;
|
|
Ok(Self {
|
|
pool,
|
|
cipher,
|
|
key_ref,
|
|
capacity: i64::from(capacity),
|
|
})
|
|
}
|
|
|
|
/// Bounded, concurrent-safe TTL cleanup. Invoke periodically from the global auth
|
|
/// service; expired rows also count toward admission capacity until removed.
|
|
pub async fn cleanup_expired(&self, batch: u32) -> Result<u64> {
|
|
if batch == 0 || batch > MAX_CLEANUP_BATCH {
|
|
return Err(Error::Configuration);
|
|
}
|
|
let mut tx = self.pool.begin().await.map_err(|_| Error::Store)?;
|
|
limits(&mut tx).await?;
|
|
let result = sqlx::query(
|
|
"WITH expired AS (SELECT state_hash FROM rmm_oidc_auth.login_states \
|
|
WHERE expires_at <= floor(extract(epoch FROM clock_timestamp()))::bigint \
|
|
ORDER BY expires_at, state_hash LIMIT $1) \
|
|
DELETE FROM rmm_oidc_auth.login_states AS states USING expired \
|
|
WHERE states.state_hash = expired.state_hash",
|
|
)
|
|
.bind(i64::from(batch))
|
|
.execute(&mut *tx)
|
|
.await
|
|
.map_err(|_| Error::Store)?;
|
|
tx.commit().await.map_err(|_| Error::Store)?;
|
|
Ok(result.rows_affected())
|
|
}
|
|
|
|
fn aad(&self, state: &[u8], binding: &[u8], expiry: i64) -> Vec<u8> {
|
|
let mut aad = b"rmm-oidc-preauth-v1\0".to_vec();
|
|
aad.extend_from_slice(state);
|
|
aad.extend_from_slice(binding);
|
|
aad.extend_from_slice(&expiry.to_be_bytes());
|
|
aad.extend_from_slice(self.key_ref.as_bytes());
|
|
aad
|
|
}
|
|
}
|
|
|
|
async fn limits(tx: &mut sqlx::Transaction<'_, sqlx::Postgres>) -> Result<()> {
|
|
// Admission must see a fresh snapshot after waiting for the advisory lock,
|
|
// even if the caller's pool changes the connection's default isolation level.
|
|
sqlx::query("SET TRANSACTION ISOLATION LEVEL READ COMMITTED")
|
|
.execute(&mut **tx)
|
|
.await
|
|
.map_err(|_| Error::Store)?;
|
|
sqlx::query("SET LOCAL statement_timeout = '5s'")
|
|
.execute(&mut **tx)
|
|
.await
|
|
.map_err(|_| Error::Store)?;
|
|
sqlx::query("SET LOCAL lock_timeout = '2s'")
|
|
.execute(&mut **tx)
|
|
.await
|
|
.map_err(|_| Error::Store)?;
|
|
Ok(())
|
|
}
|
|
|
|
fn digest(value: &str) -> Result<Vec<u8>> {
|
|
let bytes = URL_SAFE_NO_PAD.decode(value).map_err(|_| Error::State)?;
|
|
if bytes.len() != 32 || URL_SAFE_NO_PAD.encode(&bytes) != value {
|
|
return Err(Error::State);
|
|
}
|
|
Ok(bytes)
|
|
}
|
|
|
|
#[async_trait]
|
|
impl StateStore for PostgresStateStore {
|
|
fn is_persistent(&self) -> bool {
|
|
true
|
|
}
|
|
|
|
async fn insert(&self, state_hash: String, login: PendingLogin) -> Result<()> {
|
|
let state = digest(&state_hash)?;
|
|
let binding = digest(&login.binding_hash)?;
|
|
let time = now();
|
|
if login.expires_at <= time
|
|
|| login.expires_at > time.saturating_add(MAX_LOGIN_TTL_SECONDS)
|
|
|| digest(&login.nonce).is_err()
|
|
|| digest(&login.pkce_verifier).is_err()
|
|
{
|
|
return Err(Error::State);
|
|
}
|
|
let expiry = i64::try_from(login.expires_at).map_err(|_| Error::State)?;
|
|
let plaintext = Zeroizing::new(serde_json::to_vec(&login).map_err(|_| Error::Store)?);
|
|
let nonce = rand::random::<[u8; 12]>();
|
|
let aad = self.aad(&state, &binding, expiry);
|
|
let ciphertext = self
|
|
.cipher
|
|
.encrypt(
|
|
&Nonce::from(nonce),
|
|
Payload {
|
|
msg: &plaintext,
|
|
aad: &aad,
|
|
},
|
|
)
|
|
.map_err(|_| Error::Store)?;
|
|
let mut tx = self.pool.begin().await.map_err(|_| Error::Store)?;
|
|
limits(&mut tx).await?;
|
|
// All adapter instances share this lock; concurrent capacity checks cannot race.
|
|
sqlx::query("SELECT pg_advisory_xact_lock($1)")
|
|
.bind(ADMISSION_LOCK)
|
|
.execute(&mut *tx)
|
|
.await
|
|
.map_err(|_| Error::Store)?;
|
|
let result = sqlx::query(
|
|
"INSERT INTO rmm_oidc_auth.login_states \
|
|
(state_hash, binding_hash, expires_at, encryption_key_ref, encryption_nonce, ciphertext) \
|
|
SELECT $1, $2, $3, $4, $5, $6 \
|
|
WHERE (SELECT count(*) FROM rmm_oidc_auth.login_states) < $7 \
|
|
AND $3 > floor(extract(epoch FROM clock_timestamp()))::bigint"
|
|
).bind(&state).bind(&binding).bind(expiry).bind(&self.key_ref).bind(nonce.as_slice()).bind(ciphertext).bind(self.capacity)
|
|
.execute(&mut *tx).await.map_err(|_| Error::Store)?;
|
|
if result.rows_affected() != 1 {
|
|
return Err(Error::Store);
|
|
}
|
|
tx.commit().await.map_err(|_| Error::Store)?;
|
|
Ok(())
|
|
}
|
|
|
|
async fn consume(
|
|
&self,
|
|
state_hash: &str,
|
|
binding_hash: &str,
|
|
time: u64,
|
|
) -> Result<PendingLogin> {
|
|
let state = digest(state_hash)?;
|
|
let binding = digest(binding_hash)?;
|
|
let time = i64::try_from(time).map_err(|_| Error::State)?;
|
|
let mut tx = self.pool.begin().await.map_err(|_| Error::Store)?;
|
|
limits(&mut tx).await?;
|
|
// The binding predicate is inside DELETE: a wrong-cookie attack cannot burn state.
|
|
// Server time is authoritative even when a caller supplies an earlier time.
|
|
let row = sqlx::query(
|
|
"DELETE FROM rmm_oidc_auth.login_states \
|
|
WHERE state_hash = $1 AND binding_hash = $2 AND encryption_key_ref = $3 \
|
|
AND expires_at > GREATEST($4, floor(extract(epoch FROM clock_timestamp()))::bigint) \
|
|
RETURNING expires_at, encryption_nonce, ciphertext",
|
|
)
|
|
.bind(&state)
|
|
.bind(&binding)
|
|
.bind(&self.key_ref)
|
|
.bind(time)
|
|
.fetch_optional(&mut *tx)
|
|
.await
|
|
.map_err(|_| Error::Store)?;
|
|
// Commit consumption BEFORE decrypt/parse: never restore after invalid data or callback failure.
|
|
tx.commit().await.map_err(|_| Error::Store)?;
|
|
let row = row.ok_or(Error::State)?;
|
|
let expiry: i64 = row.try_get("expires_at").map_err(|_| Error::Store)?;
|
|
let nonce: Vec<u8> = row.try_get("encryption_nonce").map_err(|_| Error::Store)?;
|
|
let ciphertext: Vec<u8> = row.try_get("ciphertext").map_err(|_| Error::Store)?;
|
|
if nonce.len() != 12 || ciphertext.len() > 4096 {
|
|
return Err(Error::Store);
|
|
}
|
|
let nonce: [u8; 12] = nonce.try_into().map_err(|_| Error::Store)?;
|
|
let aad = self.aad(&state, &binding, expiry);
|
|
let plaintext = Zeroizing::new(
|
|
self.cipher
|
|
.decrypt(
|
|
&Nonce::from(nonce),
|
|
Payload {
|
|
msg: &ciphertext,
|
|
aad: &aad,
|
|
},
|
|
)
|
|
.map_err(|_| Error::Store)?,
|
|
);
|
|
let login: PendingLogin = serde_json::from_slice(&plaintext).map_err(|_| Error::Store)?;
|
|
if login.binding_hash != binding_hash
|
|
|| i64::try_from(login.expires_at).ok() != Some(expiry)
|
|
|| digest(&login.nonce).is_err()
|
|
|| digest(&login.pkce_verifier).is_err()
|
|
{
|
|
return Err(Error::Store);
|
|
}
|
|
Ok(login)
|
|
}
|
|
}
|