//! Settings from the environment. The NixOS module sets them; secrets come as //! files or systemd credentials, never as values in the environment. //! //! | Variable | Meaning | //! | -------------------------------- | ------------------------------------------------ | //! | `VISA_LISTEN` | address to listen on, default 127.0.0.1:8040 | //! | `VISA_PUBLIC_URL` | https://app.lannadesk.com (login redirects) | //! | `VISA_DATABASE_URL` | postgres://user@host/db | //! | `VISA_DATABASE_PASSWORD_FILE` | the role's password (else credential `db-password`) | //! | `VISA_OIDC_ISSUER` | https://id.cnx.network/oauth2/openid/visa-web | //! | `VISA_OIDC_CLIENT_ID` | default `visa-web` | //! | `VISA_OIDC_CLIENT_SECRET_FILE` | else credential `oidc-client-secret` | //! | `VISA_OIDC_GROUP` | default `visa` | //! | `VISA_INSECURE_NO_LOGIN` | `1`: no login, loopback addresses only | //! | `VISA_S3_BUCKET` | the bucket the encrypted documents lie in | //! | `VISA_S3_ENDPOINT` | the S3 server, `http://127.0.0.1:3900` (Garage) | //! | `VISA_S3_REGION` | default `garage` | //! | `VISA_S3_ACCESS_KEY_ID` | the bucket key's id | //! | `VISA_S3_SECRET_ACCESS_KEY_FILE` | its secret (else credential `s3-secret`) | //! | `VISA_FILES_DIR` | a directory for them instead (development) | //! | `VISA_FILES_KEY_FILE` | the file key (else credential `files-key`) | //! | `VISA_SMTP_HOST` | the mail server, `mail.lannadesk.com`: mail on | //! | `VISA_SMTP_PORT` | default 465 | //! | `VISA_SMTP_SECURITY` | `tls` (default), `starttls`, `none` (loopback) | //! | `VISA_SMTP_USER` | the mailbox, `reminders@lannadesk.com` | //! | `VISA_SMTP_PASSWORD_FILE` | its password (else credential `smtp-password`) | //! | `VISA_MAIL_FROM` | default `Lanna Desk ` | //! | `VISA_MAIL_REPLY_TO` | where replies go, such as contact@lannadesk.com | //! //! With the login on, documents are required: a place for them (the bucket, //! or a directory) and the file key. Local development may go without them; //! uploads are then off. use std::net::SocketAddr; use std::path::PathBuf; use anyhow::{Context, Result, bail, ensure}; use crate::files::FileKey; use crate::s3::S3Config; #[derive(Clone, Debug)] pub struct Config { pub listen: SocketAddr, /// Without a trailing slash. pub public_url: String, pub database_url: String, pub database_password: Option, pub auth: Auth, /// Documents: off in local development without a place for them. pub files: Option, /// Mail: off without `VISA_SMTP_HOST`. pub mail: Option, } /// How the connection to the mail server is protected. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum MailSecurity { /// TLS from the first byte: mx1's submission port 465. Tls, /// A plain start that must turn into TLS (port 587 elsewhere). StartTls, /// No TLS: a test server on this machine only. None, } #[derive(Clone)] pub struct MailConfig { pub host: String, pub port: u16, pub security: MailSecurity, /// The mailbox's login; empty for a server without one (tests). pub user: String, pub password: Option, /// "Lanna Desk " pub from: String, pub reply_to: Option, } // The password stays out of logs and panics. impl std::fmt::Debug for MailConfig { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("MailConfig") .field("host", &self.host) .field("port", &self.port) .field("security", &self.security) .field("user", &self.user) .field( "password", &format_args!("<{} bytes>", self.password.as_ref().map_or(0, String::len)), ) .field("from", &self.from) .field("reply_to", &self.reply_to) .finish() } } /// The mail settings that only mean something with `VISA_SMTP_HOST`. const MAIL_VARS: [&str; 6] = [ "VISA_SMTP_PORT", "VISA_SMTP_SECURITY", "VISA_SMTP_USER", "VISA_SMTP_PASSWORD_FILE", "VISA_MAIL_FROM", "VISA_MAIL_REPLY_TO", ]; #[derive(Clone, Debug)] pub struct FilesConfig { pub place: FilesPlace, pub key: FileKey, } /// Where the encrypted files lie. #[derive(Clone, Debug)] pub enum FilesPlace { /// A bucket of an S3 store: the fleet's Garage. Bucket(S3Config), /// A directory: local development and the tests. Dir(PathBuf), } /// The S3 settings that only mean something with `VISA_S3_BUCKET`. const S3_VARS: [&str; 4] = [ "VISA_S3_ENDPOINT", "VISA_S3_REGION", "VISA_S3_ACCESS_KEY_ID", "VISA_S3_SECRET_ACCESS_KEY_FILE", ]; #[derive(Clone, Debug)] pub enum Auth { Oidc(OidcConfig), /// Local development: everyone is "local"; loopback addresses only. Disabled, } #[derive(Clone)] pub struct OidcConfig { pub issuer: String, pub client_id: String, pub client_secret: String, pub group: String, } // The secret stays out of logs and panics. impl std::fmt::Debug for OidcConfig { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("OidcConfig") .field("issuer", &self.issuer) .field("client_id", &self.client_id) .field( "client_secret", &format_args!("<{} bytes>", self.client_secret.len()), ) .field("group", &self.group) .finish() } } impl Config { pub fn from_env() -> Result { Self::from_lookup(&|k| std::env::var(k).ok().filter(|v| !v.is_empty())) } pub fn from_lookup(var: &dyn Fn(&str) -> Option) -> Result { let listen: SocketAddr = var("VISA_LISTEN") .unwrap_or_else(|| "127.0.0.1:8040".into()) .parse() .context("VISA_LISTEN is not an address:port")?; let public_url = var("VISA_PUBLIC_URL") .unwrap_or_else(|| format!("http://{listen}")) .trim_end_matches('/') .to_string(); let database_url = var("VISA_DATABASE_URL").context("VISA_DATABASE_URL is not set")?; let database_password = match var("VISA_DATABASE_PASSWORD_FILE") { Some(path) => Some(read_file(&PathBuf::from(path), "the database password")?), None => credential(var, "db-password")?, }; let auth = match var("VISA_OIDC_ISSUER") { Some(issuer) => { ensure!( public_url.starts_with("https://"), "VISA_PUBLIC_URL must be https:// when the login is on (the session cookie is Secure)" ); let client_secret = match var("VISA_OIDC_CLIENT_SECRET_FILE") { Some(path) => read_file(&PathBuf::from(path), "the OIDC client secret")?, None => credential(var, "oidc-client-secret")?.context( "no OIDC client secret: set VISA_OIDC_CLIENT_SECRET_FILE or pass the \ credential oidc-client-secret", )?, }; Auth::Oidc(OidcConfig { issuer: issuer.trim_end_matches('/').to_string(), client_id: var("VISA_OIDC_CLIENT_ID").unwrap_or_else(|| "visa-web".into()), client_secret, group: var("VISA_OIDC_GROUP").unwrap_or_else(|| "visa".into()), }) } None if var("VISA_INSECURE_NO_LOGIN").as_deref() == Some("1") => { if !listen.ip().is_loopback() { bail!("VISA_INSECURE_NO_LOGIN=1 works only with a loopback VISA_LISTEN"); } Auth::Disabled } None => bail!( "no login configured: set VISA_OIDC_ISSUER and the client settings, or \ VISA_INSECURE_NO_LOGIN=1 for local development on a loopback address" ), }; let key = match var("VISA_FILES_KEY_FILE") { Some(path) => Some(read_file(&PathBuf::from(path), "the file key")?), None => credential(var, "files-key")?, }; let place = match (var("VISA_S3_BUCKET"), var("VISA_FILES_DIR")) { (Some(_), Some(_)) => bail!( "VISA_S3_BUCKET and VISA_FILES_DIR are both set: the documents lie in one place, \ the bucket or the directory" ), (Some(bucket), None) => Some(FilesPlace::Bucket(s3_config(var, bucket)?)), (None, dir) => { if let Some(v) = S3_VARS.iter().find(|v| var(v).is_some()) { bail!("{v} is set but VISA_S3_BUCKET is not"); } dir.map(|d| FilesPlace::Dir(PathBuf::from(d))) } }; let files = match (place, key) { (Some(place), Some(key)) => Some(FilesConfig { place, key: FileKey::from_hex(&key).context("reading the file key")?, }), (None, None) => None, (Some(_), None) => bail!( "the documents have a place but there is no file key: set VISA_FILES_KEY_FILE or \ pass the credential files-key" ), (None, Some(_)) => bail!( "there is a file key but no place for the documents: set VISA_S3_BUCKET with the \ S3 settings, or VISA_FILES_DIR" ), }; if matches!(auth, Auth::Oidc(_)) && files.is_none() { bail!( "documents are not set up: with the login on, set VISA_S3_BUCKET with the S3 \ settings (or VISA_FILES_DIR) and the file key (VISA_FILES_KEY_FILE or the \ credential files-key)" ); } let mail = match var("VISA_SMTP_HOST") { Some(host) => Some(mail_config(var, host)?), None => { if let Some(v) = MAIL_VARS.iter().find(|v| var(v).is_some()) { bail!("{v} is set but VISA_SMTP_HOST is not"); } None } }; Ok(Config { listen, public_url, database_url, database_password, auth, files, mail, }) } pub fn redirect_uri(&self) -> String { format!("{}/auth/callback", self.public_url) } pub fn login_enabled(&self) -> bool { matches!(self.auth, Auth::Oidc(_)) } } /// The bucket's settings; the secret from its file or the credential /// `s3-secret`. fn s3_config(var: &dyn Fn(&str) -> Option, bucket: String) -> Result { let need = |name: &str| var(name).with_context(|| format!("VISA_S3_BUCKET is set but {name} is not")); let secret_access_key = match var("VISA_S3_SECRET_ACCESS_KEY_FILE") { Some(path) => read_file(&PathBuf::from(path), "the S3 secret key")?, None => credential(var, "s3-secret")?.context( "VISA_S3_BUCKET is set but there is no S3 secret key: set \ VISA_S3_SECRET_ACCESS_KEY_FILE or pass the credential s3-secret", )?, }; let cfg = S3Config { endpoint: need("VISA_S3_ENDPOINT")?, bucket, region: var("VISA_S3_REGION").unwrap_or_else(|| "garage".into()), access_key_id: need("VISA_S3_ACCESS_KEY_ID")?, secret_access_key, }; // the endpoint and the name are checked now, not at the first upload crate::s3::Bucket::new(&cfg)?; Ok(cfg) } /// The mail server's settings; the password from its file or the /// credential `smtp-password`. fn mail_config(var: &dyn Fn(&str) -> Option, host: String) -> Result { let security = match var("VISA_SMTP_SECURITY").as_deref() { None | Some("tls") => MailSecurity::Tls, Some("starttls") => MailSecurity::StartTls, Some("none") => MailSecurity::None, Some(other) => bail!("VISA_SMTP_SECURITY is {other:?}: use tls, starttls or none"), }; if security == MailSecurity::None && !matches!(host.as_str(), "127.0.0.1" | "::1" | "localhost") { bail!("VISA_SMTP_SECURITY=none works only with a mail server on this machine"); } let port = match var("VISA_SMTP_PORT") { Some(p) => p.parse().context("VISA_SMTP_PORT is not a port")?, None => 465, }; let user = var("VISA_SMTP_USER").unwrap_or_default(); let password = match var("VISA_SMTP_PASSWORD_FILE") { Some(path) => Some(read_file(&PathBuf::from(path), "the mail password")?), None => credential(var, "smtp-password")?, }; if !user.is_empty() && password.is_none() { bail!( "VISA_SMTP_USER is set but there is no password: set VISA_SMTP_PASSWORD_FILE or \ pass the credential smtp-password" ); } let from = match var("VISA_MAIL_FROM") { Some(f) => f, None if user.contains('@') => format!("Lanna Desk <{user}>"), None => bail!("VISA_SMTP_HOST is set but there is no sender: set VISA_MAIL_FROM"), }; let cfg = MailConfig { host, port, security, user, password, from, reply_to: var("VISA_MAIL_REPLY_TO"), }; // the addresses are checked now, not at the first mail crate::mail::check_addresses(&cfg)?; Ok(cfg) } /// A systemd credential (`LoadCredential=`), when the unit passes one. fn credential(var: &dyn Fn(&str) -> Option, name: &str) -> Result> { let Some(dir) = var("CREDENTIALS_DIRECTORY") else { return Ok(None); }; let path = PathBuf::from(dir).join(name); if !path.exists() { return Ok(None); } read_file(&path, name).map(Some) } fn read_file(path: &PathBuf, what: &str) -> Result { let text = std::fs::read_to_string(path) .with_context(|| format!("reading {what} from {}", path.display()))?; let value = text.trim().to_string(); ensure!(!value.is_empty(), "{} is empty", path.display()); Ok(value) } #[cfg(test)] mod tests { use super::*; use std::collections::HashMap; fn cfg(pairs: &[(&str, &str)]) -> Result { let m: HashMap = pairs .iter() .map(|(k, v)| (k.to_string(), v.to_string())) .collect(); Config::from_lookup(&|k| m.get(k).cloned()) } #[test] fn refuses_to_start_without_a_login() { let e = cfg(&[("VISA_DATABASE_URL", "postgres://x/y")]).unwrap_err(); assert!(e.to_string().contains("no login configured"), "{e}"); } #[test] fn no_login_only_on_loopback() { let ok = cfg(&[ ("VISA_DATABASE_URL", "postgres://x/y"), ("VISA_INSECURE_NO_LOGIN", "1"), ]) .unwrap(); assert!(matches!(ok.auth, Auth::Disabled)); assert_eq!(ok.public_url, "http://127.0.0.1:8040"); let e = cfg(&[ ("VISA_DATABASE_URL", "postgres://x/y"), ("VISA_INSECURE_NO_LOGIN", "1"), ("VISA_LISTEN", "0.0.0.0:8040"), ]) .unwrap_err(); assert!(e.to_string().contains("loopback"), "{e}"); } #[test] fn mail_needs_its_server_and_its_password() { let base = [ ("VISA_DATABASE_URL", "postgres://x/y"), ("VISA_INSECURE_NO_LOGIN", "1"), ]; let with = |extra: &[(&str, &str)]| { let mut v = base.to_vec(); v.extend_from_slice(extra); cfg(&v) }; assert!(with(&[]).unwrap().mail.is_none(), "mail is off by default"); let e = with(&[("VISA_SMTP_USER", "reminders@lannadesk.com")]).unwrap_err(); assert!(e.to_string().contains("VISA_SMTP_HOST is not"), "{e}"); let e = with(&[ ("VISA_SMTP_HOST", "mail.lannadesk.com"), ("VISA_SMTP_USER", "reminders@lannadesk.com"), ]) .unwrap_err(); assert!(e.to_string().contains("no password"), "{e}"); let e = with(&[ ("VISA_SMTP_HOST", "mail.lannadesk.com"), ("VISA_SMTP_SECURITY", "none"), ("VISA_MAIL_FROM", "x@lannadesk.com"), ]) .unwrap_err(); assert!(e.to_string().contains("on this machine"), "{e}"); let dir = std::env::temp_dir().join(format!("visa-mail-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); let pw = dir.join("smtp"); std::fs::write(&pw, "otter-lantern-cobalt-driftwood-42\n").unwrap(); let c = with(&[ ("VISA_SMTP_HOST", "mail.lannadesk.com"), ("VISA_SMTP_USER", "reminders@lannadesk.com"), ("VISA_SMTP_PASSWORD_FILE", pw.to_str().unwrap()), ("VISA_MAIL_REPLY_TO", "contact@lannadesk.com"), ]) .unwrap(); let m = c.mail.unwrap(); assert_eq!((m.port, m.security), (465, MailSecurity::Tls)); assert_eq!(m.from, "Lanna Desk "); assert_eq!( m.password.as_deref(), Some("otter-lantern-cobalt-driftwood-42") ); assert!( !format!("{m:?}").contains("otter"), "the password stays out of logs" ); let e = with(&[ ("VISA_SMTP_HOST", "mail.lannadesk.com"), ("VISA_MAIL_FROM", "not an address"), ]) .unwrap_err(); assert!(format!("{e:#}").contains("VISA_MAIL_FROM"), "{e:#}"); std::fs::remove_dir_all(&dir).ok(); } #[test] fn oidc_reads_the_secret_from_a_file() { let dir = std::env::temp_dir().join(format!("visa-cfg-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); let f = dir.join("secret"); std::fs::write(&f, "s3cret\n").unwrap(); let key = dir.join("files.key"); std::fs::write(&key, format!("{}\n", "ab".repeat(32))).unwrap(); let files_dir = dir.join("files"); let c = cfg(&[ ("VISA_DATABASE_URL", "postgres://x/y"), ("VISA_PUBLIC_URL", "https://visa.example/"), ( "VISA_OIDC_ISSUER", "https://id.example/oauth2/openid/visa-web/", ), ("VISA_OIDC_CLIENT_SECRET_FILE", f.to_str().unwrap()), ("VISA_FILES_DIR", files_dir.to_str().unwrap()), ("VISA_FILES_KEY_FILE", key.to_str().unwrap()), ]) .unwrap(); let Auth::Oidc(o) = &c.auth else { panic!("login expected") }; assert_eq!(o.client_secret, "s3cret"); assert_eq!(o.client_id, "visa-web"); assert_eq!(o.group, "visa"); assert_eq!(o.issuer, "https://id.example/oauth2/openid/visa-web"); assert_eq!(c.redirect_uri(), "https://visa.example/auth/callback"); assert!(!format!("{o:?}").contains("s3cret")); // a plain-http public URL cannot carry the Secure cookie let e = cfg(&[ ("VISA_DATABASE_URL", "postgres://x/y"), ("VISA_PUBLIC_URL", "http://visa.example"), ( "VISA_OIDC_ISSUER", "https://id.example/oauth2/openid/visa-web", ), ("VISA_OIDC_CLIENT_SECRET_FILE", f.to_str().unwrap()), ]) .unwrap_err(); assert!(e.to_string().contains("https"), "{e}"); // with the login on, documents must be set up let e = cfg(&[ ("VISA_DATABASE_URL", "postgres://x/y"), ("VISA_PUBLIC_URL", "https://visa.example"), ( "VISA_OIDC_ISSUER", "https://id.example/oauth2/openid/visa-web", ), ("VISA_OIDC_CLIENT_SECRET_FILE", f.to_str().unwrap()), ]) .unwrap_err(); assert!(e.to_string().contains("documents are not set up"), "{e}"); let files = c.files.unwrap(); assert!(matches!(&files.place, FilesPlace::Dir(d) if *d == files_dir)); assert!(!format!("{files:?}").contains("abab")); std::fs::remove_dir_all(&dir).ok(); } #[test] fn documents_need_both_the_directory_and_the_key() { let dir = std::env::temp_dir().join(format!("visa-cfg-files-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); let key = dir.join("files.key"); let base = [ ("VISA_DATABASE_URL", "postgres://x/y"), ("VISA_INSECURE_NO_LOGIN", "1"), ]; // local development may go without documents assert!(cfg(&base).unwrap().files.is_none()); let with = |extra: &[(&str, &str)]| { let mut all = base.to_vec(); all.extend_from_slice(extra); cfg(&all) }; let e = with(&[("VISA_FILES_DIR", "/srv/files")]).unwrap_err(); assert!(e.to_string().contains("no file key"), "{e}"); std::fs::write(&key, "not hex").unwrap(); let e = with(&[ ("VISA_FILES_DIR", "/srv/files"), ("VISA_FILES_KEY_FILE", key.to_str().unwrap()), ]) .unwrap_err(); assert!(format!("{e:#}").contains("64 hex digits"), "{e:#}"); // the systemd credential std::fs::write(dir.join("files-key"), "cd".repeat(32)).unwrap(); let c = with(&[ ("VISA_FILES_DIR", "/srv/files"), ("CREDENTIALS_DIRECTORY", dir.to_str().unwrap()), ]) .unwrap(); assert!(c.files.is_some()); let e = with(&[("CREDENTIALS_DIRECTORY", dir.to_str().unwrap())]).unwrap_err(); assert!(e.to_string().contains("no place for the documents"), "{e}"); std::fs::remove_dir_all(&dir).ok(); } #[test] fn documents_in_a_bucket_take_its_settings_and_the_secret_from_a_credential() { let dir = std::env::temp_dir().join(format!("visa-cfg-s3-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); std::fs::write(dir.join("files-key"), "cd".repeat(32)).unwrap(); std::fs::write(dir.join("s3-secret"), "s3-secret-value\n").unwrap(); let creds = dir.to_str().unwrap(); let base = [ ("VISA_DATABASE_URL", "postgres://x/y"), ("VISA_INSECURE_NO_LOGIN", "1"), ("CREDENTIALS_DIRECTORY", creds), ]; let with = |extra: &[(&str, &str)]| { let mut all = base.to_vec(); all.extend_from_slice(extra); cfg(&all) }; let bucket = [ ("VISA_S3_BUCKET", "visa-documents"), ("VISA_S3_ENDPOINT", "http://127.0.0.1:3900"), ("VISA_S3_ACCESS_KEY_ID", "GK00112233"), ]; let c = with(&bucket).unwrap(); let Some(FilesConfig { place: FilesPlace::Bucket(b), .. }) = &c.files else { panic!("a bucket expected: {:?}", c.files) }; assert_eq!(b.bucket, "visa-documents"); assert_eq!(b.region, "garage"); assert_eq!(b.secret_access_key, "s3-secret-value"); assert!(!format!("{c:?}").contains("s3-secret-value")); // every part is needed, and one place only for missing in ["VISA_S3_ENDPOINT", "VISA_S3_ACCESS_KEY_ID"] { let some: Vec<_> = bucket .iter() .copied() .filter(|(k, _)| *k != missing) .collect(); let e = with(&some).unwrap_err(); assert!(e.to_string().contains(missing), "{e}"); } let mut both = bucket.to_vec(); both.push(("VISA_FILES_DIR", "/srv/files")); let e = with(&both).unwrap_err(); assert!(e.to_string().contains("both set"), "{e}"); let e = with(&[("VISA_S3_ENDPOINT", "http://127.0.0.1:3900")]).unwrap_err(); assert!(e.to_string().contains("VISA_S3_BUCKET is not"), "{e}"); let mut bad = bucket.to_vec(); bad[1] = ("VISA_S3_ENDPOINT", "127.0.0.1:3900"); assert!(with(&bad).is_err()); // without the credential, the secret's file must be named std::fs::remove_file(dir.join("s3-secret")).unwrap(); let e = with(&bucket).unwrap_err(); assert!(e.to_string().contains("no S3 secret key"), "{e}"); let f = dir.join("secret-file"); std::fs::write(&f, "from-a-file").unwrap(); let mut named = bucket.to_vec(); named.push(("VISA_S3_SECRET_ACCESS_KEY_FILE", f.to_str().unwrap())); assert!(with(&named).is_ok()); std::fs::remove_dir_all(&dir).ok(); } }