Phase 1: app, Kanidm login, people, passports, addresses, audit log
visa.buildfor.life keeps the immigration records of the foreigners B4L looks after. This first phase is the base the deadlines and extension packs build on (docs/PLAN.md, phases 2 to 7). - One Rust binary (axum 0.8, minijinja, sqlx on PostgreSQL) with its templates, static files and migrations compiled in. - Login through Kanidm (OpenID Connect with PKCE and a nonce, ES256), client visa-web, group visa; sessions in PostgreSQL keyed by the SHA-256 of the cookie. VISA_INSECURE_NO_LOGIN=1 for loopback development only. - Same-site check and form token on every POST; a CSP without inline script or style; security headers. - People: list with filter, page, create, edit, archive, restore. - Passports from the machine-readable zone with check digits (ICAO 9303 TD3); expiry warnings at 12 and 6 months. - Addresses in Thailand in the order Thai forms use, with the house master and the TM.30 receipt. - Append-only audit log of every view and change, with the names of the changed fields but never their values (PDPA); the Activity page. - Invented demo people (visa seed-demo, refused when login is on). - 40 tests: unit tests, pages with demo data, the forms, the audit log and the whole login against a fake OpenID provider. - CI: gitleaks over the history, fmt, clippy and the tests against PostgreSQL 18; the pre-commit secret scan.
This commit is contained in:
commit
2e009700a9
56 files changed
+11193
No files matched your search
+225
@@ -0,0 +1,225 @@
|
||||
//! 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://visa.buildfor.life (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 |
|
||||
|
||||
use std::net::SocketAddr;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use anyhow::{Context, Result, bail, ensure};
|
||||
|
||||
#[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<String>,
|
||||
pub auth: Auth,
|
||||
}
|
||||
|
||||
#[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<Config> {
|
||||
Self::from_lookup(&|k| std::env::var(k).ok().filter(|v| !v.is_empty()))
|
||||
}
|
||||
|
||||
pub fn from_lookup(var: &dyn Fn(&str) -> Option<String>) -> Result<Config> {
|
||||
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"
|
||||
),
|
||||
};
|
||||
Ok(Config {
|
||||
listen,
|
||||
public_url,
|
||||
database_url,
|
||||
database_password,
|
||||
auth,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn redirect_uri(&self) -> String {
|
||||
format!("{}/auth/callback", self.public_url)
|
||||
}
|
||||
|
||||
pub fn login_enabled(&self) -> bool {
|
||||
matches!(self.auth, Auth::Oidc(_))
|
||||
}
|
||||
}
|
||||
|
||||
/// A systemd credential (`LoadCredential=`), when the unit passes one.
|
||||
fn credential(var: &dyn Fn(&str) -> Option<String>, name: &str) -> Result<Option<String>> {
|
||||
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<String> {
|
||||
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<Config> {
|
||||
let m: HashMap<String, String> = 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 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 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()),
|
||||
])
|
||||
.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}");
|
||||
std::fs::remove_dir_all(&dir).ok();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user