use std::path::{Path, PathBuf}; use serde::Deserialize; use url::Url; use crate::clients::{ Admission, ClientError, ClientId, ClientPolicy, ClientRegistry, ClientSecret, EmailPolicy, RedirectUri, RegisteredClient, UnknownEmailPolicy, }; use crate::keys::{SigningAlgorithm, UnknownSigningAlgorithm}; #[derive(Deserialize)] #[serde(deny_unknown_fields)] struct FileConfig { issuer: String, listen: String, client_name: String, #[serde(default)] trust_proxy_headers: bool, #[serde(default)] allow_private_fetch: bool, #[serde(default)] rate_limit: RateLimit, #[serde(default)] webfinger_domains: Vec, #[serde(default = "default_session_days")] session_days: u64, #[serde(default)] extra_css: Option, #[serde(default)] clients: Vec, } fn default_session_days() -> u64 { 30 } #[derive(Clone, Copy, Debug, Eq, PartialEq, Deserialize)] #[serde(deny_unknown_fields, default)] pub struct RateLimit { pub burst: u32, pub period_seconds: u64, } impl Default for RateLimit { fn default() -> Self { Self { burst: 30, period_seconds: 1, } } } #[derive(Deserialize)] #[serde(deny_unknown_fields)] struct FileClient { id: String, secret: Option, secret_file: Option, redirect_uris: Vec, email: Option, signing_algorithm: Option, allow: Option>, #[serde(default)] deny: Vec, #[serde(default)] insecure_redirects: bool, } fn read_secret( id: &ClientId, secret: Option, secret_file: Option, ) -> Result, ConfigError> { match (secret, secret_file) { (Some(secret), None) => Ok(secret.into_bytes()), (None, Some(path)) => Ok(std::fs::read(&path) .map_err(|error| ConfigError::SecretFile { client: id.clone(), path: path.display().to_string(), reason: error.to_string(), })? .into_iter() .rev() .skip_while(u8::is_ascii_whitespace) .collect::>() .into_iter() .rev() .collect()), _ => Err(ConfigError::SecretChoice(id.clone())), } } impl FileClient { fn into_registered(self) -> Result { let id = ClientId::new(self.id); let secret = read_secret(&id, self.secret, self.secret_file)?; let secret = ClientSecret::new(secret)?; let redirect_uris = self .redirect_uris .iter() .map(|raw| RedirectUri::parse(raw)) .collect::, ClientError>>()?; let email = match self.email.as_deref() { None => EmailPolicy::None, Some(value) => value.parse().map_err(|source| ConfigError::EmailPolicy { client: id.clone(), source, })?, }; let signing = match self.signing_algorithm.as_deref() { None => SigningAlgorithm::Es256, Some(value) => value .parse() .map_err(|source| ConfigError::SigningAlgorithm { client: id.clone(), source, })?, }; let policy = ClientPolicy { email, signing, admission: Admission::parse(self.allow.as_deref(), &self.deny)?, insecure_redirects: self.insecure_redirects, }; Ok(RegisteredClient::new(id, secret, redirect_uris, policy)?) } } #[derive(Clone, Debug)] pub struct ServerConfig { issuer: String, pub listen: String, pub state_dir: PathBuf, pub client_name: String, pub clients: ClientRegistry, pub trust_proxy_headers: bool, pub allow_private_fetch: bool, pub rate_limit: RateLimit, pub webfinger_domains: Vec, pub session_days: u64, pub extra_css: Option, } impl ServerConfig { pub fn new( issuer: &str, listen: impl Into, state_dir: impl Into, client_name: impl Into, clients: ClientRegistry, ) -> Result { let issuer = parse_issuer(issuer)?; let listen = listen.into(); let state_dir = state_dir.into(); let client_name = client_name.into(); if listen.trim().is_empty() { return Err(ConfigError::EmptyListen); } if state_dir.as_os_str().is_empty() { return Err(ConfigError::EmptyStateDir); } if client_name.trim().is_empty() { return Err(ConfigError::EmptyClientName); } if clients.is_empty() { return Err(ConfigError::NoClients); } Ok(Self { issuer, listen, state_dir, client_name, clients, trust_proxy_headers: false, allow_private_fetch: false, rate_limit: RateLimit::default(), webfinger_domains: Vec::new(), session_days: 30, extra_css: None, }) } pub fn load(path: &Path, state_dir: PathBuf) -> Result { let text = std::fs::read_to_string(path).map_err(|error| ConfigError::Read { path: path.display().to_string(), reason: error.to_string(), })?; let file: FileConfig = toml::from_str(&text).map_err(|error| ConfigError::Parse { path: path.display().to_string(), reason: error.to_string(), })?; let clients = file .clients .into_iter() .map(FileClient::into_registered) .collect::, ConfigError>>()?; if file.rate_limit.burst == 0 || file.rate_limit.period_seconds == 0 { return Err(ConfigError::RateLimit); } let mut config = Self::new( &file.issuer, file.listen, state_dir, file.client_name, ClientRegistry::new(clients)?, )?; config.trust_proxy_headers = file.trust_proxy_headers; config.allow_private_fetch = file.allow_private_fetch; if file.session_days > 365 { return Err(ConfigError::SessionDays); } config.rate_limit = file.rate_limit; config.session_days = file.session_days; config.webfinger_domains = file .webfinger_domains .into_iter() .map(|domain| domain.trim().trim_end_matches('.').to_ascii_lowercase()) .filter(|domain| !domain.is_empty()) .collect(); config.extra_css = file.extra_css; Ok(config) } pub fn issuer(&self) -> &str { &self.issuer } pub fn endpoint(&self, path: &str) -> String { format!("{}{path}", self.issuer) } } fn parse_issuer(raw: &str) -> Result { if raw.trim().is_empty() { return Err(ConfigError::Issuer( "issuer must be configured explicitly".to_owned(), )); } parse_origin(raw).map_err(ConfigError::Issuer) } fn parse_origin(raw: &str) -> Result { let url = Url::parse(raw.trim()).map_err(|error| error.to_string())?; let is_origin = url.scheme() == "https" && url.host_str().is_some() && url.username().is_empty() && url.password().is_none() && url.path() == "/" && url.query().is_none() && url.fragment().is_none(); if !is_origin { return Err(format!( "{raw:?} must be an explicit HTTPS origin without path, query, or fragment" )); } Ok(url.origin().ascii_serialization()) } #[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)] pub enum ConfigError { #[error("invalid issuer: {0}")] Issuer(String), #[error("listen address must not be empty")] EmptyListen, #[error("state directory must not be empty")] EmptyStateDir, #[error("client name must not be empty")] EmptyClientName, #[error("at least one client must be registered")] NoClients, #[error("rate_limit burst and period_seconds must both be positive")] RateLimit, #[error("session_days must be at most 365; 0 disables remembered sign-in")] SessionDays, #[error("client {client}: {source}")] EmailPolicy { client: ClientId, source: UnknownEmailPolicy, }, #[error("client {client}: {source}")] SigningAlgorithm { client: ClientId, source: UnknownSigningAlgorithm, }, #[error(transparent)] Client(#[from] ClientError), #[error("cannot read config {path}: {reason}")] Read { path: String, reason: String }, #[error("cannot parse config {path}: {reason}")] Parse { path: String, reason: String }, #[error("client {0} needs exactly one of secret or secret_file")] SecretChoice(ClientId), #[error("client {client}: cannot read secret_file {path}: {reason}")] SecretFile { client: ClientId, path: String, reason: String, }, } #[cfg(test)] mod tests { use super::*; fn load(top: &str, clients: &str) -> Result { let dir = tempfile::tempdir().expect("tempdir"); let path = dir.path().join("config.toml"); let secret_file = dir.path().join("client.secret"); std::fs::write(&secret_file, format!("{}\n", "s".repeat(40))).expect("secret"); let issuer = if top.contains("issuer =") { "" } else { "issuer = \"https://ratlogin.test\"\n" }; let text = format!( "{issuer}listen = \"127.0.0.1:9411\"\nclient_name = \"Test\"\n{top}\n{clients}" ) .replace("SECRET_FILE", &secret_file.display().to_string()) .replace("SECRET", &"i".repeat(32)); std::fs::write(&path, text).expect("config"); ServerConfig::load(&path, dir.path().to_path_buf()) } const APP: &str = r#" [[clients]] id = "app" secret = "SECRET" "#; #[test] fn loads_settings_and_clients_with_inline_and_file_secrets() { let config = load( r#" trust_proxy_headers = true allow_private_fetch = true webfinger_domains = ["ShatteredSky.net."] session_days = 7 extra_css = "body { background: #000; }" [rate_limit] burst = 10 "#, r#" [[clients]] id = "headscale" secret_file = "SECRET_FILE" redirect_uris = ["https://headscale.test/oidc/callback"] [[clients]] id = "inline" secret = "SECRET" redirect_uris = ["https://app.test/cb"] "#, ) .expect("load"); assert_eq!(config.issuer(), "https://ratlogin.test"); assert!(config.trust_proxy_headers); assert!(config.allow_private_fetch); assert_eq!(config.webfinger_domains, ["shatteredsky.net"]); assert_eq!(config.session_days, 7); assert_eq!( config.extra_css.as_deref(), Some("body { background: #000; }") ); assert_eq!( config.rate_limit, RateLimit { burst: 10, period_seconds: 1 } ); let client = |id: &str| config.clients.get(&ClientId::new(id)).expect("client"); assert!(client("headscale").authenticate("s".repeat(40).as_bytes())); assert!(!client("headscale").authenticate(format!("{}\n", "s".repeat(40)).as_bytes())); assert!(client("inline").authenticate("i".repeat(32).as_bytes())); assert_eq!(client("inline").policy(), &ClientPolicy::default()); } #[test] fn per_client_policy_is_read_from_the_client_table() { let config = load( "", &format!( r#"{APP} redirect_uris = ["app.immich:///oauth-callback", "http://immich.internal/cb"] email = "required" signing_algorithm = "rs256" allow = ["*.example.com"] deny = ["bob.example.com"] insecure_redirects = true "# ), ) .expect("load"); let app = config.clients.get(&ClientId::new("app")).expect("app"); let deny = ["bob.example.com".to_owned()]; assert_eq!( app.policy(), &ClientPolicy { email: EmailPolicy::Required, signing: SigningAlgorithm::Rs256, admission: Admission::parse(Some(&["*.example.com".to_owned()]), &deny) .expect("admission"), insecure_redirects: true, } ); assert_eq!( app.plaintext_redirect_uris(), vec!["app.immich:///oauth-callback", "http://immich.internal/cb"] ); } #[test] fn rejects_invalid_client_tables_and_unknown_fields() { let https = r#"redirect_uris = ["https://app.test/cb"]"#; let cases = [ ( format!(r#"{APP}redirect_uris = ["http://immich.internal/cb"]"#), "client app has an invalid redirect: http://immich.internal/cb", ), ( format!("{APP}{https}\nallow = [\"a.*\"]"), "\"a.*\" is not a DID, a handle, or a *.suffix pattern", ), ( format!("{APP}{https}\nemail = \"sometimes\""), "client app: email policy must be none, optional, or required, not \"sometimes\"", ), ( format!("{APP}{https}\nsigning_algorithm = \"HS256\""), "client app: signing algorithm must be RS256 or ES256, not \"HS256\"", ), ( format!("{APP}{https}\nsecret_file = \"/nonexistent\""), "client app needs exactly one of secret or secret_file", ), ( format!("[[clients]]\nid = \"app\"\n{https}\nsecret_file = \"/nonexistent\""), "client app: cannot read secret_file /nonexistent: No such file or directory (os error 2)", ), ( format!("{APP}{https}\n{APP}{https}"), "client app is registered twice", ), ]; for (clients, expected) in cases { let error = load("", &clients).expect_err(expected); assert_eq!(error.to_string(), expected); } for (top, expected) in [ ("session_days = 366", ConfigError::SessionDays), ( "issuer = \"http://ratlogin.test\"", ConfigError::Issuer( "\"http://ratlogin.test\" must be an explicit HTTPS origin without path, query, or fragment" .to_owned(), ), ), ("[rate_limit]\nburst = 0", ConfigError::RateLimit), ("[rate_limit]\nperiod_seconds = 0", ConfigError::RateLimit), ] { assert_eq!(load(top, &format!("{APP}{https}")).err(), Some(expected)); } assert!(matches!( ServerConfig::load(Path::new("/nonexistent/config.toml"), PathBuf::new()), Err(ConfigError::Read { .. }) )); for (top, extra) in [ ("master_key = \"legacy\"", ""), ("", "\nmaster_key = \"legacy\""), ] { assert!(matches!( load(top, &format!("{APP}{https}{extra}")), Err(ConfigError::Parse { .. }) )); } } #[test] fn issuer_must_be_a_bare_https_origin_and_clients_must_exist() { let registry = || { ClientRegistry::new([RegisteredClient::new( ClientId::new("client"), ClientSecret::new(vec![b's'; 32]).expect("long enough"), vec![RedirectUri::parse("https://client.example/cb").expect("valid uri")], ClientPolicy::default(), ) .expect("valid client")]) .expect("registry") }; assert!( ServerConfig::new( "https://issuer.example", "127.0.0.1:0", "state", "Test", registry() ) .is_ok() ); for issuer in ["", "http://issuer.example", "https://issuer.example/path"] { let error = ServerConfig::new(issuer, "127.0.0.1:0", "state", "Test", registry()).err(); assert!( matches!(error, Some(ConfigError::Issuer(_))), "{issuer}: {error:?}" ); } let issuer = "https://issuer.example"; for (listen, state_dir, name, clients, expected) in [ (" ", "state", "Test", registry(), ConfigError::EmptyListen), ( "127.0.0.1:0", "", "Test", registry(), ConfigError::EmptyStateDir, ), ( "127.0.0.1:0", "state", " ", registry(), ConfigError::EmptyClientName, ), ( "127.0.0.1:0", "state", "Test", ClientRegistry::default(), ConfigError::NoClients, ), ] { let error = ServerConfig::new(issuer, listen, state_dir, name, clients).err(); assert_eq!(error, Some(expected)); } } }