feat: snapshot Linux-first RMM MVP and pause handover
Rust development slice / linux (push) Failing after 1m10s
Rust development slice / linux (push) Failing after 1m10s
This commit is contained in:
@@ -0,0 +1,169 @@
|
||||
//! Configured OIDC wiring. No embedded identities, membership grants or production dev fallback.
|
||||
use anyhow::{Result, ensure};
|
||||
use rmm_oidc_auth::{Config, OidcAuth, Profile, SecretResolver, postgres::PostgresStateStore};
|
||||
use secrecy::{ExposeSecret, SecretString};
|
||||
use serde::Deserialize;
|
||||
use sqlx::{
|
||||
ConnectOptions,
|
||||
postgres::{PgConnectOptions, PgPoolOptions},
|
||||
};
|
||||
use std::{
|
||||
fs,
|
||||
os::unix::fs::{MetadataExt, PermissionsExt},
|
||||
path::Path,
|
||||
sync::Arc,
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
pub struct Provider {
|
||||
pub auth: OidcAuth,
|
||||
pub simulation: bool,
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct FileConfig {
|
||||
issuer: url::Url,
|
||||
browser_client_id: String,
|
||||
client_secret_ref: String,
|
||||
redirect_uri: url::Url,
|
||||
mcp_audience: String,
|
||||
mcp_client_ids: std::collections::BTreeSet<String>,
|
||||
auth_database_url_ref: String,
|
||||
state_key_ref: String,
|
||||
extra_ca_file: Option<String>,
|
||||
#[serde(default)]
|
||||
testsimulation: bool,
|
||||
}
|
||||
pub struct Files {
|
||||
owner: u32,
|
||||
}
|
||||
impl Files {
|
||||
fn read(&self, path: &str) -> Result<Vec<u8>> {
|
||||
let p = Path::new(path);
|
||||
ensure!(
|
||||
p.is_absolute(),
|
||||
"secret reference must be an absolute private file"
|
||||
);
|
||||
let m = fs::symlink_metadata(p)
|
||||
.map_err(|_| anyhow::anyhow!("private configuration unavailable"))?;
|
||||
let parent = fs::symlink_metadata(
|
||||
p.parent()
|
||||
.ok_or_else(|| anyhow::anyhow!("private parent missing"))?,
|
||||
)?;
|
||||
ensure!(
|
||||
m.is_file()
|
||||
&& m.uid() == self.owner
|
||||
&& m.permissions().mode() & 0o777 == 0o600
|
||||
&& m.len() <= 65536
|
||||
&& parent.is_dir()
|
||||
&& parent.uid() == self.owner
|
||||
&& parent.permissions().mode() & 0o022 == 0,
|
||||
"unsafe private configuration permissions"
|
||||
);
|
||||
fs::read(p).map_err(|_| anyhow::anyhow!("private configuration unavailable"))
|
||||
}
|
||||
}
|
||||
#[async_trait::async_trait]
|
||||
impl SecretResolver for Files {
|
||||
async fn resolve(&self, reference: &str) -> rmm_oidc_auth::Result<SecretString> {
|
||||
let bytes = self
|
||||
.read(reference)
|
||||
.map_err(|_| rmm_oidc_auth::Error::Secret)?;
|
||||
let value = String::from_utf8(bytes).map_err(|_| rmm_oidc_auth::Error::Secret)?;
|
||||
Ok(SecretString::from(value.trim_end_matches('\n').to_owned()))
|
||||
}
|
||||
}
|
||||
pub async fn configured(profile: &str, origin: &str) -> Result<Option<Provider>> {
|
||||
let Ok(path) = std::env::var("RMM_OIDC_CONFIG_FILE") else {
|
||||
return Ok(None);
|
||||
};
|
||||
let owner = fs::symlink_metadata(&path)
|
||||
.map_err(|_| anyhow::anyhow!("OIDC configuration unavailable"))?
|
||||
.uid();
|
||||
let files = Arc::new(Files { owner });
|
||||
let cfg: FileConfig = serde_json::from_slice(&files.read(&path)?)
|
||||
.map_err(|_| anyhow::anyhow!("invalid OIDC configuration"))?;
|
||||
ensure!(
|
||||
!cfg.testsimulation || profile == "development",
|
||||
"OIDC simulation is development-only"
|
||||
);
|
||||
ensure!(
|
||||
cfg.redirect_uri.as_str() == format!("{origin}/auth/oidc/callback"),
|
||||
"OIDC callback must match configured UI origin"
|
||||
);
|
||||
let database = files.resolve(&cfg.auth_database_url_ref).await?;
|
||||
let options: PgConnectOptions = database
|
||||
.expose_secret()
|
||||
.parse()
|
||||
.map_err(|_| anyhow::anyhow!("invalid auth database configuration"))?;
|
||||
let pool = PgPoolOptions::new()
|
||||
.max_connections(8)
|
||||
.acquire_timeout(Duration::from_secs(5))
|
||||
.connect_with(options.disable_statement_logging())
|
||||
.await
|
||||
.map_err(|_| anyhow::anyhow!("auth database connection failed"))?;
|
||||
let unsafe_role: bool = sqlx::query_scalar("SELECT rolsuper OR rolbypassrls OR EXISTS(SELECT 1 FROM pg_tables WHERE tableowner=current_user AND schemaname IN ('public','rmm_oidc_auth')) OR has_schema_privilege(current_user,'rmm_oidc_auth','CREATE') OR has_table_privilege(current_user,'public.memberships','SELECT') FROM pg_roles WHERE rolname=current_user")
|
||||
.fetch_one(&pool).await.map_err(|_|anyhow::anyhow!("auth database role check failed"))?;
|
||||
ensure!(
|
||||
!unsafe_role,
|
||||
"auth state pool must use a separate restricted nonowner identity"
|
||||
);
|
||||
let store =
|
||||
Arc::new(PostgresStateStore::new(pool, files.as_ref(), cfg.state_key_ref, 10000).await?);
|
||||
let roots = match cfg.extra_ca_file {
|
||||
None => vec![],
|
||||
Some(path) => vec![reqwest_certificate(&files.read(&path)?)?],
|
||||
};
|
||||
let auth = OidcAuth::discover(
|
||||
Config {
|
||||
issuer: cfg.issuer,
|
||||
browser_client_id: cfg.browser_client_id,
|
||||
client_secret_ref: cfg.client_secret_ref,
|
||||
redirect_uri: cfg.redirect_uri,
|
||||
mcp_audience: cfg.mcp_audience,
|
||||
mcp_client_ids: cfg.mcp_client_ids,
|
||||
},
|
||||
if profile == "production" {
|
||||
Profile::Production
|
||||
} else {
|
||||
Profile::DevTest
|
||||
},
|
||||
store.clone(),
|
||||
files,
|
||||
roots,
|
||||
)
|
||||
.await?;
|
||||
tokio::spawn(async move {
|
||||
loop {
|
||||
tokio::time::sleep(Duration::from_secs(30)).await;
|
||||
let _ = store.cleanup_expired(1000).await;
|
||||
}
|
||||
});
|
||||
Ok(Some(Provider {
|
||||
auth,
|
||||
simulation: cfg.testsimulation,
|
||||
}))
|
||||
}
|
||||
fn reqwest_certificate(bytes: &[u8]) -> Result<reqwest::Certificate> {
|
||||
reqwest::Certificate::from_pem(bytes)
|
||||
.map_err(|_| anyhow::anyhow!("invalid OIDC CA certificate"))
|
||||
}
|
||||
pub fn principal_id(issuer: &str, subject: &str) -> String {
|
||||
format!(
|
||||
"oidc:{}",
|
||||
rmm_domain::jobs::hash(&serde_json::to_vec(&(issuer, subject)).unwrap_or_default())
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn stable_identity_is_namespaced_and_not_concatenation_ambiguous() {
|
||||
let first = principal_id("https://issuer.example/", "subject");
|
||||
assert_eq!(first, principal_id("https://issuer.example/", "subject"));
|
||||
assert_ne!(first, principal_id("https://other.example/", "subject"));
|
||||
assert_ne!(principal_id("ab", "c"), principal_id("a", "bc"));
|
||||
assert_eq!(first.len(), 69);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user