#![cfg(feature = "postgres-state")] use async_trait::async_trait; use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD}; use rmm_oidc_auth::{ Error, PendingLogin, Result, SecretResolver, StateStore, postgres::{MIGRATION_SQL, PostgresStateStore}, }; use secrecy::{ExposeSecret, SecretString}; use sha2::{Digest, Sha256}; use sqlx::{ ConnectOptions, Row, postgres::{PgConnectOptions, PgPoolOptions}, }; use std::{ sync::Arc, time::{SystemTime, UNIX_EPOCH}, }; fn must(result: std::result::Result, message: &str) -> T { result.unwrap_or_else(|_| panic!("{message}")) } fn time() -> u64 { SystemTime::now() .duration_since(UNIX_EPOCH) .unwrap() .as_secs() } fn random() -> String { URL_SAFE_NO_PAD.encode(rand::random::<[u8; 32]>()) } fn handle() -> String { URL_SAFE_NO_PAD.encode(Sha256::digest(random().as_bytes())) } fn pending(binding: &str) -> PendingLogin { PendingLogin { binding_hash: binding.into(), nonce: random(), pkce_verifier: random(), expires_at: time() + 300, } } struct Key(SecretString); #[async_trait] impl SecretResolver for Key { async fn resolve(&self, reference: &str) -> Result { if reference != "test-oidc-state-key-v1" && reference != "test-oidc-state-key-v2" { return Err(Error::Secret); } Ok(SecretString::from(self.0.expose_secret().to_owned())) } } /// Explicit opt-in; the supplied owner identity must belong to a disposable database. /// The package runner creates a new dedicated container and never uses the server DB. #[tokio::test] #[ignore = "requires isolated PostgreSQL owner test identity; use tests/run_postgres.py"] async fn real_postgres_encrypted_state_nonowner_atomicity_and_limits() { assert_eq!( std::env::var("RMM_OIDC_TEST_ALLOW_OWNER_DDL") .ok() .as_deref(), Some("isolated"), "owner DDL must be explicitly permitted for isolated tests" ); let url = must( std::env::var("RMM_OIDC_TEST_DATABASE_URL"), "isolated PostgreSQL URL missing", ); let options: PgConnectOptions = must(url.parse(), "invalid isolated PostgreSQL configuration"); let options = options.disable_statement_logging(); let owner = must( PgPoolOptions::new() .max_connections(2) .connect_with(options.clone()) .await, "owner connection failed", ); must( sqlx::raw_sql(MIGRATION_SQL).execute(&owner).await, "isolated migration fixture failed", ); let role = format!("oidc_auth_test_{:016x}", rand::random::()); let password = format!( "{:032x}{:032x}", rand::random::(), rand::random::() ); // Both interpolated values are locally generated ASCII hex/identifier characters, // never caller/config input. Runtime adapter queries contain only bind parameters. must(sqlx::raw_sql(&format!( "CREATE ROLE {role} LOGIN PASSWORD '{password}' NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT NOBYPASSRLS; \ GRANT USAGE ON SCHEMA rmm_oidc_auth TO {role}; \ GRANT SELECT, INSERT, DELETE ON rmm_oidc_auth.login_states TO {role};" )).execute(&owner).await, "isolated nonowner runtime role fixture failed"); let runtime = must( PgPoolOptions::new() .max_connections(16) .acquire_timeout(std::time::Duration::from_secs(10)) .connect_with(options.username(&role).password(&password)) .await, "nonowner runtime connection failed", ); let privileges = must( sqlx::query( "SELECT r.rolsuper, r.rolbypassrls, \ has_schema_privilege(current_user, 'rmm_oidc_auth', 'CREATE') AS can_create, \ c.relowner <> r.oid AS nonowner \ FROM pg_roles r CROSS JOIN pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace \ WHERE r.rolname=current_user AND n.nspname='rmm_oidc_auth' AND c.relname='login_states'", ) .fetch_one(&runtime) .await, "runtime privilege check failed", ); assert!(!privileges.get::("rolsuper")); assert!(!privileges.get::("rolbypassrls")); assert!(!privileges.get::("can_create")); assert!(privileges.get::("nonowner")); assert!( sqlx::query("CREATE TABLE rmm_oidc_auth.forbidden_runtime_ddl (id int)") .execute(&runtime) .await .is_err(), "runtime must not create tables" ); let resolver = Key(SecretString::from(random())); let store = Arc::new(must( PostgresStateStore::new( runtime.clone(), &resolver, "test-oidc-state-key-v1".into(), 100, ) .await, "state adapter setup failed", )); assert!(store.is_persistent()); assert!(matches!( PostgresStateStore::new( runtime.clone(), &Key(SecretString::from("invalid-key")), "test-oidc-state-key-v1".into(), 100 ) .await, Err(Error::Configuration) )); assert!( sqlx::query("UPDATE rmm_oidc_auth.login_states SET expires_at=expires_at WHERE false") .execute(&runtime) .await .is_err(), "runtime must not update state" ); let state = handle(); let binding = handle(); let login = pending(&binding); let nonce = login.nonce.clone(); let verifier = login.pkce_verifier.clone(); must( store.insert(state.clone(), login).await, "nonowner insert failed", ); let other_version = must( PostgresStateStore::new( runtime.clone(), &resolver, "test-oidc-state-key-v2".into(), 100, ) .await, "key-version test setup failed", ); assert!( matches!( other_version.consume(&state, &binding, time()).await, Err(Error::State) ), "a different configured key version must not consume this state" ); let saved = must( sqlx::query("SELECT state_hash, binding_hash, ciphertext FROM rmm_oidc_auth.login_states") .fetch_one(&owner) .await, "encrypted fixture inspection failed", ); assert_eq!(saved.get::, _>("state_hash").len(), 32); assert_eq!(saved.get::, _>("binding_hash").len(), 32); let ciphertext: Vec = saved.get("ciphertext"); assert!( !ciphertext .windows(nonce.len()) .any(|w| w == nonce.as_bytes()) ); assert!( !ciphertext .windows(verifier.len()) .any(|w| w == verifier.as_bytes()) ); assert!( matches!( store.consume(&state, &handle(), time()).await, Err(Error::State) ), "wrong binding must fail" ); assert!( matches!( store.consume(&state, &binding, time() + 600).await, Err(Error::State) ), "caller expiry must fail without burning valid state" ); assert!( store .insert(state.clone(), pending(&binding)) .await .is_err(), "duplicate handle must not overwrite" ); let mut tasks = vec![]; for _ in 0..16 { let store = store.clone(); let state = state.clone(); let binding = binding.clone(); tasks.push(tokio::spawn(async move { store.consume(&state, &binding, time()).await })); } let mut winners = 0; for task in tasks { match must(task.await, "concurrent callback task failed") { Ok(login) => { winners += 1; assert!(login.nonce == nonce); assert!(login.pkce_verifier == verifier); } Err(error) => assert_eq!(error, Error::State), } } assert_eq!(winners, 1, "exactly one callback may consume state"); assert!( matches!( store.consume(&state, &binding, time()).await, Err(Error::State) ), "replay must fail" ); let expired = handle(); must( store.insert(expired.clone(), pending(&binding)).await, "expiry fixture insert failed", ); must( sqlx::query("UPDATE rmm_oidc_auth.login_states SET created_at=$1, expires_at=$2") .bind(i64::try_from(time() - 600).unwrap()) .bind(i64::try_from(time() - 1).unwrap()) .execute(&owner) .await, "owner expiry fixture failed", ); assert!( matches!( store.consume(&expired, &binding, 0).await, Err(Error::State) ), "database clock must prevent revival with an old caller clock" ); assert_eq!( must(store.cleanup_expired(1).await, "expiry cleanup failed"), 1 ); assert!(matches!( store.cleanup_expired(1001).await, Err(Error::Configuration) )); let tampered = handle(); must( store.insert(tampered.clone(), pending(&binding)).await, "tamper fixture insert failed", ); must( sqlx::query("UPDATE rmm_oidc_auth.login_states SET ciphertext=$1") .bind(vec![0u8; 32]) .execute(&owner) .await, "owner tamper fixture failed", ); assert!( matches!( store.consume(&tampered, &binding, time()).await, Err(Error::Store) ), "tampering must fail authenticated decryption" ); assert!( matches!( store.consume(&tampered, &binding, time()).await, Err(Error::State) ), "decrypt failure must not restore consumed state" ); let small = Arc::new(must( PostgresStateStore::new( runtime.clone(), &resolver, "test-oidc-state-key-v1".into(), 2, ) .await, "capacity adapter setup failed", )); let mut tasks = vec![]; for _ in 0..8 { let small = small.clone(); let binding = binding.clone(); tasks.push(tokio::spawn(async move { small.insert(handle(), pending(&binding)).await })); } let mut admitted = 0; for task in tasks { admitted += usize::from(must(task.await, "admission task failed").is_ok()); } assert_eq!( admitted, 2, "capacity check must serialize concurrent inserts" ); must( sqlx::query("UPDATE rmm_oidc_auth.login_states SET created_at=$1, expires_at=$2") .bind(i64::try_from(time() - 600).unwrap()) .bind(i64::try_from(time() - 1).unwrap()) .execute(&owner) .await, "cleanup fixtures failed", ); assert_eq!( must(store.cleanup_expired(1).await, "bounded cleanup failed"), 1 ); assert_eq!( must(store.cleanup_expired(1).await, "bounded cleanup failed"), 1 ); assert_eq!( must(store.cleanup_expired(1).await, "bounded cleanup failed"), 0 ); assert!(matches!( store .insert("not-a-hashed-state".into(), pending(&binding)) .await, Err(Error::State) )); let mut too_long = pending(&binding); too_long.expires_at = time() + 3600; assert!(matches!( store.insert(handle(), too_long).await, Err(Error::State) )); runtime.close().await; must( sqlx::raw_sql(&format!("DROP OWNED BY {role}; DROP ROLE {role};")) .execute(&owner) .await, "isolated role cleanup failed", ); owner.close().await; println!( "PostgreSQL: nonowner role verified; concurrent consume winners=1/16; capacity admitted=2/8; encrypted storage, wrong binding, expiry, replay, tampering and bounded cleanup checked" ); }