diff --git a/Cargo.lock b/Cargo.lock index 7c6d0db..0d1a78c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1741,6 +1741,7 @@ dependencies = [ "tracing", "turso", "ulid", + "url", "zip", ] diff --git a/Cargo.toml b/Cargo.toml index 5871648..0a7f1b6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -45,6 +45,7 @@ tracing-subscriber = "0.3.23" # Without the default `fts` feature: no app uses full-text search, and it pulls in tantivy and zstd. turso = { version = "0.8.3", default-features = false, features = ["mimalloc"] } ulid = "3.0.0" +url = "2.5.8" quick-xml = "0.42.0" zip = { version = "9.1.3", default-features = false, features = ["deflate"] } diff --git a/README.md b/README.md index f55e3fd..743279c 100644 --- a/README.md +++ b/README.md @@ -35,14 +35,13 @@ Keys: | Key | Meaning | |---|---| -| `database` | SQLite database file. Its `-wal` and `-shm` files sit next to it. | +| `database` | SQLite database file. Its `-wal` and `-shm` files sit next to it, and they are created with mode `0600`. Keep it inside `data_dir`; boot logs a warning when it is not. | | `data_dir` | Directory for `iz.key`, the lock file, attachments and other local files. | | `listen` | HTTP listen address. Keep it on `127.0.0.1` behind the reverse proxy. | -| `base_url` | Public URL used in links and mail. `https://` or `http://`, no trailing slash. | -| `trusted_proxies` | Peers whose `X-Forwarded-For` is trusted for client IPs. IPs or CIDR networks. Behind Ferron on the same host, `["127.0.0.1/32"]`; left empty there, every visitor counts as the proxy. | +| `base_url` | Public URL used in links and mail. `https://`, or `http://` only for `localhost`, `127.0.0.1` or `::1`; no user name or password; no trailing slash. | | `[oidc]` | `issuer` (the `im` origin, no trailing slash; `https://` outside a local test), `client_id`, `client_secret_file`. Remove the section to run without sign-in. | | `[in_store]` | `enabled`. Stores attachments in the `in` Files service instead of local disk. Off by default. | -| `[backup]` | `dir` (backup sets go here), `interval_hours` (1 to 720, default 24), `keep` (1 to 365, default 14), `healthcheck_url` (optional, pinged after each good backup). Remove the section to turn scheduled backups off. | +| `[backup]` | `dir` (backup sets go here), `interval_hours` (1 to 168, default 24), `keep` (at least 1, default 14), `healthcheck_url` (optional, pinged after each good backup). Remove the section to turn scheduled backups off; boot then logs a warning that no backup sets are written. | Unknown keys are an error at boot, so a typo stops the start instead of being ignored. diff --git a/config/iz.example.toml b/config/iz.example.toml index 5d74d75..a28e9ce 100644 --- a/config/iz.example.toml +++ b/config/iz.example.toml @@ -7,11 +7,8 @@ database = "data/iz.db" data_dir = "data" # HTTP listen address. Keep it on loopback behind a reverse proxy. listen = "127.0.0.1:7654" -# Public base URL used in links and mail. No trailing slash. +# Public base URL used in links and mail. No trailing slash. https, or http on localhost, 127.0.0.1 or ::1. base_url = "http://127.0.0.1:7654" -# Peers whose X-Forwarded-For is trusted for client IPs. Addresses or CIDR networks. -# Behind Ferron on the same host, set ["127.0.0.1/32"]; left empty there, every visitor counts as 127.0.0.1. -trusted_proxies = [] # Identity provider (OpenID Connect). Uncomment to enable sign-in. # The client secret is read from client_secret_file at boot. That file must be mode 0600 or 0400. diff --git a/crates/iz-core/Cargo.toml b/crates/iz-core/Cargo.toml index 73984f0..f7b8f9f 100644 --- a/crates/iz-core/Cargo.toml +++ b/crates/iz-core/Cargo.toml @@ -32,6 +32,7 @@ toml.workspace = true tracing.workspace = true turso.workspace = true ulid.workspace = true +url.workspace = true zip.workspace = true [dev-dependencies] diff --git a/crates/iz-core/src/config.rs b/crates/iz-core/src/config.rs index 19212b1..6705700 100644 --- a/crates/iz-core/src/config.rs +++ b/crates/iz-core/src/config.rs @@ -2,11 +2,13 @@ //! password are entered in the admin UI and sealed in the database. Every struct denies unknown //! keys, so a misspelled option fails at boot instead of being silently ignored. -use std::net::{IpAddr, SocketAddr}; +use std::fmt; +use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; use std::path::{Path, PathBuf}; use ipnet::IpNet; use serde::{Deserialize, Deserializer}; +use url::Host; use crate::error::{Error, Result}; @@ -29,7 +31,8 @@ pub struct Config { /// Public base URL used in links and mail. No trailing slash. #[serde(default = "default_base_url")] pub base_url: String, - /// Peers whose `X-Forwarded-For` is trusted. Entries are CIDR networks or bare addresses. + /// Accepted so existing configs still load, but unused: iz does not read `X-Forwarded-For`. Boot warns + /// when it is set. Entries are CIDR networks or bare addresses. #[serde(default, deserialize_with = "deserialize_trusted_proxies")] pub trusted_proxies: Vec, /// OpenID Connect provider. Absent means sign-in is not configured. @@ -71,7 +74,7 @@ pub struct InStoreConfig { } /// Scheduled backup policy. -#[derive(Debug, Clone, Deserialize)] +#[derive(Clone, Deserialize)] #[serde(deny_unknown_fields)] pub struct BackupConfig { /// Directory that receives the backup sets. @@ -87,6 +90,21 @@ pub struct BackupConfig { pub healthcheck_url: Option, } +// Hand-written so that `Config` debug output never shows the healthcheck URL, which can carry a key. +impl fmt::Debug for BackupConfig { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("BackupConfig") + .field("dir", &self.dir) + .field("interval_hours", &self.interval_hours) + .field("keep", &self.keep) + .field( + "healthcheck_url", + &self.healthcheck_url.as_ref().map(|_| ""), + ) + .finish() + } +} + fn default_database() -> PathBuf { PathBuf::from("data/iz.db") } @@ -123,10 +141,10 @@ fn deserialize_trusted_proxies<'de, D: Deserializer<'de>>( if let Ok(net) = entry.parse::() { return Ok(net); } - entry - .parse::() - .map(IpNet::from) - .map_err(|_| serde::de::Error::custom(format!("invalid trusted proxy `{entry}`"))) + // The entry is left out of the message: a misplaced secret must not reach the log. + entry.parse::().map(IpNet::from).map_err(|_| { + serde::de::Error::custom("invalid trusted proxy: not an address or CIDR network") + }) }) .collect() } @@ -153,7 +171,8 @@ impl Config { /// Parses and validates config text. pub fn parse(text: &str) -> Result { - let config: Config = toml::from_str(text).map_err(|e| Error::Config(e.to_string()))?; + let config: Config = + toml::from_str(text).map_err(|e| Error::Config(parse_error(text, &e)))?; config.validate()?; Ok(config) } @@ -166,11 +185,7 @@ impl Config { if self.data_dir.as_os_str().is_empty() { return Err(Error::Config("data_dir must not be empty".into())); } - if !(self.base_url.starts_with("https://") || self.base_url.starts_with("http://")) { - return Err(Error::Config( - "base_url must start with https:// or http://".into(), - )); - } + require_secure_url("base_url", &self.base_url)?; if self.base_url.ends_with('/') { return Err(Error::Config("base_url must not end with /".into())); } @@ -222,14 +237,7 @@ fn validate_in_url(url: &str) -> Result<()> { if url.ends_with('/') { return Err(Error::Config("in_store.url must not end with /".into())); } - let loopback = url.starts_with("http://127.0.0.1") || url.starts_with("http://localhost"); - if url.starts_with("https://") || loopback { - Ok(()) - } else { - Err(Error::Config( - "in_store.url must be an https URL (http only for loopback)".into(), - )) - } + require_secure_url("in_store.url", url) } /// An issuer must be https. Plain http is allowed only for loopback, which is how a local @@ -239,13 +247,47 @@ fn validate_issuer(issuer: &str) -> Result<()> { if issuer.ends_with('/') { return Err(Error::Config("oidc.issuer must not end with /".into())); } - let loopback = issuer.starts_with("http://127.0.0.1") || issuer.starts_with("http://localhost"); - if issuer.starts_with("https://") || loopback { - Ok(()) - } else { - Err(Error::Config( - "oidc.issuer must be an https URL (http only for loopback)".into(), + require_secure_url("oidc.issuer", issuer) +} + +/// Checks that `value` is a URL iz may send secrets to. The URL is parsed, not prefix-matched, so that +/// `http://localhost.example.com` and `http://localhost@example.com` are refused. https is allowed for any +/// host. http is allowed only for the host `localhost`, `127.0.0.1` or `::1`, and only with no user name +/// or password in the URL. +fn require_secure_url(field: &str, value: &str) -> Result<()> { + let refused = || { + Error::Config(format!( + "{field} must be an https URL (http only for loopback, with no user name or password)" )) + }; + let url = url::Url::parse(value).map_err(|_| refused())?; + if !url.username().is_empty() || url.password().is_some() { + return Err(refused()); + } + let loopback = match url.host() { + Some(Host::Domain(name)) => name == "localhost", + Some(Host::Ipv4(ip)) => ip == Ipv4Addr::LOCALHOST, + Some(Host::Ipv6(ip)) => ip == Ipv6Addr::LOCALHOST, + None => false, + }; + match url.scheme() { + "https" => Ok(()), + "http" if loopback => Ok(()), + _ => Err(refused()), + } +} + +/// The message of a TOML error with its line and column. The source line itself is left out on purpose: +/// a secret that was put in the wrong file must not be written to the log. +fn parse_error(text: &str, error: &toml::de::Error) -> String { + match error.span() { + Some(span) => { + let before = text.get(..span.start).unwrap_or(""); + let line = before.matches('\n').count() + 1; + let column = before.rsplit('\n').next().map_or(0, |s| s.chars().count()) + 1; + format!("line {line}, column {column}: {}", error.message()) + } + None => error.message().to_owned(), } } @@ -279,6 +321,24 @@ mod tests { fn validation_rejects_bad_cross_field_values() { assert!(Config::parse("base_url = \"ftp://x\"\n").is_err()); assert!(Config::parse("base_url = \"https://x/\"\n").is_err()); + // Prefix and userinfo tricks must not pass as loopback. + for url in [ + "http://im.example.com", + "http://localhost.evil.example", + "http://localhost@evil.example", + "http://127.0.0.1.evil.example", + "http://127.0.0.2", + ] { + assert!( + Config::parse(&format!("base_url = \"{url}\"\n")).is_err(), + "{url}" + ); + } + assert!(Config::parse("base_url = \"http://[::1]:7654\"\n").is_ok()); + assert!( + Config::parse("[oidc]\nissuer = \"http://localhost.evil.example\"\nclient_id = \"iz\"\nclient_secret_file = \"s\"\n") + .is_err() + ); assert!( Config::parse("[oidc]\nissuer = \"http://im.example.com\"\nclient_id = \"iz\"\nclient_secret_file = \"s\"\n") .is_err() diff --git a/crates/iz-core/src/manifest.rs b/crates/iz-core/src/manifest.rs index e83333e..df08494 100644 --- a/crates/iz-core/src/manifest.rs +++ b/crates/iz-core/src/manifest.rs @@ -139,11 +139,21 @@ pub fn write_manifest( Ok(manifest) } -/// Writes `bytes` to `dir/name` through a temporary name, fsynced, then renamed into place. +/// Writes `bytes` to `dir/name` through a temporary name, fsynced, then renamed into place. The file is +/// created with mode 0600. A temporary file left by an interrupted write is overwritten. fn write_synced(dir: &Path, name: &str, bytes: &[u8]) -> Result<()> { + use std::io::Write; + use std::os::unix::fs::OpenOptionsExt; + let tmp = dir.join(format!("{name}.tmp")); - std::fs::write(&tmp, bytes)?; - File::open(&tmp)?.sync_all()?; + let mut file = std::fs::OpenOptions::new() + .write(true) + .create(true) + .truncate(true) + .mode(0o600) + .open(&tmp)?; + file.write_all(bytes)?; + file.sync_all()?; std::fs::rename(&tmp, dir.join(name))?; Ok(()) } diff --git a/crates/iz-core/src/sheet.rs b/crates/iz-core/src/sheet.rs index c2d829c..1aa0714 100644 --- a/crates/iz-core/src/sheet.rs +++ b/crates/iz-core/src/sheet.rs @@ -9,7 +9,9 @@ //! costs no more than the caps. An `.ods` is not previewed at all: calamine has no cell stream for it and reads //! its `content.xml` whole, and a tiny file can declare huge repeat counts that allocate gigabytes. The viewer //! shows such a file as refused, and it can still be downloaded. A CSV is read record by record and stops at -//! the row cap, so a long file costs no more than the cap. +//! the row cap, so a long file costs no more than the cap. An `.xlsb` is not previewed either: calamine reads its +//! sheet as a whole range, sized by the cells it finds rather than by the sheet's declared dimensions, so no cap +//! can be checked before the read. use std::collections::BTreeMap; use std::fs::File; @@ -59,9 +61,9 @@ fn data_ref_text(value: &DataRef<'_>) -> String { } } -/// Reads an `.xlsx` workbook (`.xls` and `.xlsb` too). Refused (as `Invalid`) when the zip checks fail, and -/// for an OpenDocument file: it is refused before calamine opens it, because calamine reads its `content.xml` -/// whole. +/// Reads an `.xlsx` workbook. It is a zip container, and it is refused (as `Invalid`) when the zip checks +/// fail. An `.xls` never gets this far, because it is not a zip. An OpenDocument file is refused before calamine +/// opens it, because calamine reads its `content.xml` whole. An `.xlsb` is refused too (see the module comment). pub fn read_workbook(path: &Path) -> Result { let mut zip = archive::open_checked(path, SHEET_INPUT_MAX_BYTES)?; if zip.by_name("content.xml").is_ok() { @@ -70,15 +72,15 @@ pub fn read_workbook(path: &Path) -> Result { } let mut workbook = open_workbook_auto(path).map_err(|_| Error::Invalid("bad_workbook".into()))?; - let names = workbook.sheet_names(); + let Sheets::Xlsx(xlsx) = &mut workbook else { + // Only `.xlsx` is streamed. An `.xlsb` is read whole by calamine, so it is refused. + return Err(Error::Invalid("xlsb_not_previewed".into())); + }; + let names = xlsx.sheet_names(); let sheet_count = names.len(); let mut sheets = Vec::new(); for name in names.into_iter().take(SHEETS_MAX) { - let sheet = match &mut workbook { - Sheets::Xlsx(xlsx) => read_xlsx_sheet(xlsx, &name)?, - _ => read_range_sheet(&mut workbook, &name)?, - }; - sheets.push(sheet); + sheets.push(read_xlsx_sheet(xlsx, &name)?); } Ok(Book { sheets, @@ -128,32 +130,6 @@ fn read_xlsx_sheet(xlsx: &mut Xlsx>, name: &str) -> Result>, name: &str) -> Result { - let range = workbook - .worksheet_range(name) - .map_err(|_| Error::Invalid("bad_workbook".into()))?; - let mut rows = Vec::new(); - let mut rows_cut = false; - for (index, row) in range.rows().enumerate() { - if index == SHEET_ROWS_MAX { - rows_cut = true; - break; - } - rows.push( - row.iter() - .take(SHEET_COLS_MAX) - .map(|cell: &Data| cell_text(&cell.to_string())) - .collect(), - ); - } - Ok(Sheet { - name: name.to_owned(), - rows, - rows_cut, - }) -} - /// Reads a CSV file as one sheet. Invalid UTF-8 is shown with replacement characters. pub fn read_csv(path: &Path, name: &str) -> Result { let len = std::fs::metadata(path)?.len(); diff --git a/crates/iz-core/src/store/mod.rs b/crates/iz-core/src/store/mod.rs index 4501c41..69ca2c7 100644 --- a/crates/iz-core/src/store/mod.rs +++ b/crates/iz-core/src/store/mod.rs @@ -71,6 +71,7 @@ impl Store { let path_str = path.to_str().ok_or_else(|| { Error::Config(format!("database path is not UTF-8: {}", path.display())) })?; + create_private_files(path)?; let db = Builder::new_local(path_str).build().await.map_err(db_err)?; let conn = db.connect().map_err(db_err)?; apply_pragmas(&conn).await; @@ -179,6 +180,31 @@ pub async fn finish(tx: turso::transaction::Transaction<'_>, outcome: Result< } } +/// Creates the database file and its `-wal` and `-shm` files with mode 0600 when they do not exist yet. +/// Turso would create them with the default umask. A file that already exists keeps its mode. +fn create_private_files(path: &Path) -> Result<()> { + use std::os::unix::fs::OpenOptionsExt; + + let with_suffix = |suffix: &str| { + let mut name = path.as_os_str().to_owned(); + name.push(suffix); + name + }; + for file in [with_suffix(""), with_suffix("-wal"), with_suffix("-shm")] { + let created = std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .mode(0o600) + .open(&file); + match created { + Ok(_) => {} + Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {} + Err(e) => return Err(e.into()), + } + } + Ok(()) +} + /// Makes a connection refuse writes. Turso takes `1`, not `ON`. Failure is fatal, because a reader /// that can write would break the pool's rule. async fn apply_query_only(conn: &Connection) -> Result<()> { @@ -385,6 +411,18 @@ mod tests { Ok(()) } + #[tokio::test] + async fn database_files_are_created_private() { + use std::os::unix::fs::PermissionsExt; + + let dir = tempfile::tempdir().expect("dir"); + Store::open(&dir.path().join("iz.db")).await.expect("store"); + for name in ["iz.db", "iz.db-wal", "iz.db-shm"] { + let meta = std::fs::metadata(dir.path().join(name)).expect("file"); + assert_eq!(meta.permissions().mode() & 0o777, 0o600, "{name}"); + } + } + #[tokio::test] async fn open_twice_is_idempotent_and_keeps_settings() { let dir = tempfile::tempdir().unwrap(); diff --git a/crates/iz-core/src/store/sessions.rs b/crates/iz-core/src/store/sessions.rs index 6cc7d25..525945f 100644 --- a/crates/iz-core/src/store/sessions.rs +++ b/crates/iz-core/src/store/sessions.rs @@ -5,6 +5,7 @@ //! `none`. Lookups repeat those checks in SQL, so disabling a member takes effect on the next request //! even if the back-channel message was lost. +use std::fmt; use std::time::Duration; use super::{col_opt_text, col_text, db_err, fetch_opt, new_id}; @@ -14,7 +15,7 @@ use crate::time::{now_stamp, stamp_after}; use crate::token::{generate_token, hash_token}; /// A session as the web layer needs it after a lookup. -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Clone, PartialEq, Eq)] pub struct SessionRecord { /// Session id (ULID). pub id: String, @@ -33,7 +34,7 @@ pub struct SessionRecord { } /// A freshly created session. `token` goes into the cookie and is never stored. -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Clone, PartialEq, Eq)] pub struct IssuedSession { /// Session id. pub id: String, @@ -43,6 +44,34 @@ pub struct IssuedSession { pub csrf_token: String, } +// Hand-written so that a debug print never shows a session's cookie, CSRF token or sealed ID token. +impl fmt::Debug for SessionRecord { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("SessionRecord") + .field("id", &self.id) + .field("sub", &self.sub) + .field("csrf_token", &"") + .field("sid", &self.sid) + .field( + "id_token_sealed", + &self.id_token_sealed.as_ref().map(|_| ""), + ) + .field("expires_at", &self.expires_at) + .field("last_seen", &self.last_seen) + .finish() + } +} + +impl fmt::Debug for IssuedSession { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("IssuedSession") + .field("id", &self.id) + .field("token", &"") + .field("csrf_token", &"") + .finish() + } +} + const SESSION_COLS: &str = "s.id, s.sub, s.csrf_token, s.sid, s.expires_at, s.last_seen, s.id_token_sealed"; diff --git a/crates/iz-web/src/auth.rs b/crates/iz-web/src/auth.rs index ed4dcd9..d236e6e 100644 --- a/crates/iz-web/src/auth.rs +++ b/crates/iz-web/src/auth.rs @@ -5,6 +5,7 @@ //! (`iz_core::store::sessions`). The sign-in flight (state, nonce, PKCE verifier, `next`) lives in //! `__Host-iz_flight`, sealed with the instance key under the `sign-in-flight` purpose, so the browser cannot change it. +use std::fmt; use std::time::Duration; use iz_core::authz::{Action, Actor, Denied, authorize}; @@ -78,7 +79,7 @@ impl CurrentMember { } /// The state of one sign-in, sealed into the flight cookie. -#[derive(Debug, Serialize, Deserialize)] +#[derive(Serialize, Deserialize)] pub struct SignInState { /// The `state` parameter sent to `im`. Compared with the one that comes back. pub state: String, @@ -92,6 +93,19 @@ pub struct SignInState { pub expires: u64, } +// Hand-written so that a debug print never shows the state, the nonce or the PKCE verifier. +impl fmt::Debug for SignInState { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("SignInState") + .field("state", &"") + .field("nonce", &"") + .field("verifier", &"") + .field("next", &self.next) + .field("expires", &self.expires) + .finish() + } +} + /// The cookie jar with the `__Host-` prefix, so the browser enforces `Secure`, `Path=/` and no domain. fn jar(cx: &Cx) -> impl Cookies + '_ { cookies(cx).override_prefix_host() diff --git a/crates/iz-web/src/boot.rs b/crates/iz-web/src/boot.rs index c7207c4..60dd8c9 100644 --- a/crates/iz-web/src/boot.rs +++ b/crates/iz-web/src/boot.rs @@ -5,7 +5,7 @@ //! the pragmas and the migrations), build the router, bind the listener, and serve until SIGTERM or //! Ctrl-C. Stored UI overrides are not layered on the file yet, because no page writes them. -use std::os::unix::fs::PermissionsExt; +use std::os::unix::fs::DirBuilderExt; use std::path::Path; use std::sync::Arc; @@ -36,10 +36,11 @@ const DEFAULT_KEY_PREFIX: &str = "IZ"; /// Runs the server until a stop signal arrives. Returns once every connection has finished. pub async fn serve(config_path: &Path) -> iz_core::Result<()> { let config = Config::load(config_path)?; + warn_about_config(&config); let listen = config.listen; // One server per data directory: the lock is held until this function returns, so a second `iz` // (or an operator command) refuses to touch the same files while this one runs. - std::fs::create_dir_all(&config.data_dir)?; + create_data_dir(&config.data_dir)?; let _lock = crate::cli::lock_data_dir(&config.data_dir).map_err(iz_core::Error::Config)?; let state = open_state(config).await?; @@ -78,12 +79,41 @@ pub async fn serve(config_path: &Path) -> iz_core::Result<()> { Ok(()) } -/// Creates the data directory and opens the key and the database. Everything the router needs -/// that touches the disk is ready when this returns. +/// Creates the data directory with mode 0700 when it is missing. The directory holds the instance key, so +/// only this user may enter it. An existing directory keeps its mode. +fn create_data_dir(path: &Path) -> std::io::Result<()> { + std::fs::DirBuilder::new() + .recursive(true) + .mode(0o700) + .create(path) +} + +/// Logs the settings that have no effect, and the ones that probably are not what the operator meant. Nothing +/// here stops the start. +fn warn_about_config(config: &Config) { + if config.backup.is_none() { + tracing::warn!("backups are not configured; no backup sets will be written"); + } + // Absolute paths compare the same whether the config wrote them relative or not. + if let (Ok(database), Ok(data_dir)) = ( + std::path::absolute(&config.database), + std::path::absolute(&config.data_dir), + ) && !database.starts_with(&data_dir) + { + tracing::warn!( + database = %config.database.display(), + data_dir = %config.data_dir.display(), + "database is outside data_dir" + ); + } + if !config.trusted_proxies.is_empty() { + tracing::warn!("trusted_proxies has no effect in iz"); + } +} + +/// Opens the key and the database. Everything the router needs that touches the disk is ready when this +/// returns. async fn open_state(config: Config) -> iz_core::Result { - std::fs::create_dir_all(&config.data_dir)?; - // The directory holds the instance key. Only this user may enter it. - std::fs::set_permissions(&config.data_dir, std::fs::Permissions::from_mode(0o700))?; let data_dir = config.data_dir.canonicalize()?; if let Some(parent) = config .database diff --git a/crates/iz-web/src/in_store.rs b/crates/iz-web/src/in_store.rs index 66cee21..c9ce195 100644 --- a/crates/iz-web/src/in_store.rs +++ b/crates/iz-web/src/in_store.rs @@ -222,9 +222,9 @@ fn clients(write: bool) -> iz_core::Result { .map_err(|error| iz_core::Error::Config(format!("cannot build the Files client: {error}"))) } -/// A connection-level failure as an [`InError`]. +/// A connection-level failure as an [`InError`]. The URL is left out of the text. fn transport(error: reqwest::Error) -> InError { - InError::Unavailable(error.to_string()) + InError::Unavailable(error.without_url().to_string()) } /// The file as a stream of frames, read in [`UPLOAD_FRAME`] pieces, so a large upload is never held whole. diff --git a/crates/iz-web/src/oidc.rs b/crates/iz-web/src/oidc.rs index 77bfb76..124670f 100644 --- a/crates/iz-web/src/oidc.rs +++ b/crates/iz-web/src/oidc.rs @@ -16,6 +16,7 @@ //! run without a network. use std::collections::HashMap; +use std::fmt; use std::path::Path; use std::sync::Arc; use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; @@ -97,7 +98,7 @@ pub struct Discovery { } /// The answer of the token endpoint. The refresh token is not read: iz discards it (contracts.md 2.4). -#[derive(Debug, Deserialize)] +#[derive(Deserialize)] pub struct TokenResponse { /// The ID token, for an authorization-code exchange. #[serde(default)] @@ -110,6 +111,20 @@ pub struct TokenResponse { pub expires_in: Option, } +// Hand-written so that a debug print never shows the ID token or the access token. +impl fmt::Debug for TokenResponse { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("TokenResponse") + .field("id_token", &self.id_token.as_ref().map(|_| "")) + .field( + "access_token", + &self.access_token.as_ref().map(|_| ""), + ) + .field("expires_in", &self.expires_in) + .finish() + } +} + /// The claims of an ID token that iz uses. `sid` is the `im` browser session. #[derive(Debug, Clone, Deserialize, PartialEq, Eq)] pub struct IdClaims { @@ -718,7 +733,7 @@ fn str_claim(claims: &Map, name: &str) -> Option { } fn unavailable(error: reqwest::Error) -> ImError { - ImError::Unavailable(error.to_string()) + ImError::Unavailable(error.without_url().to_string()) } /// Reads a response body, refusing one larger than `limit` bytes. The check runs while the body is diff --git a/crates/iz-web/src/pages/photo.rs b/crates/iz-web/src/pages/photo.rs index b60959a..dd74b7d 100644 --- a/crates/iz-web/src/pages/photo.rs +++ b/crates/iz-web/src/pages/photo.rs @@ -10,6 +10,7 @@ use std::path::{Path, PathBuf}; use http::header::{CACHE_CONTROL, CONTENT_TYPE, ETAG, IF_NONE_MATCH, X_CONTENT_TYPE_OPTIONS}; +use tokio::io::AsyncWriteExt; use topcoat::Result; use topcoat::context::{Cx, app_context}; use topcoat::router::error::not_found; @@ -148,7 +149,13 @@ async fn write_cache(dir: &Path, version: i64, mime: &str, bytes: &[u8]) -> std: data.extend_from_slice(mime.as_bytes()); data.push(b'\n'); data.extend_from_slice(bytes); - tokio::fs::write(&tmp, &data).await?; + let mut file = tokio::fs::OpenOptions::new() + .write(true) + .create_new(true) + .mode(0o600) + .open(&tmp) + .await?; + file.write_all(&data).await?; tokio::fs::rename(&tmp, dir.join(&name)).await?; let mut entries = tokio::fs::read_dir(dir).await?; while let Some(entry) = entries.next_entry().await? { diff --git a/crates/iz-web/src/pages/settings.rs b/crates/iz-web/src/pages/settings.rs index 62b3bc7..42f9a83 100644 --- a/crates/iz-web/src/pages/settings.rs +++ b/crates/iz-web/src/pages/settings.rs @@ -5,6 +5,8 @@ //! A refusal the admin can fix re-renders the page with the typed server values (never the password) and //! status `422`. A success redirects with a notice code in the query string. +use std::fmt; + use iz_core::mail_text::MailLang; use iz_core::secret; use iz_core::sender::{ @@ -46,7 +48,7 @@ use jiff::tz::TimeZone; use topcoat::router::path_param_segment; /// The sender form as posted. -#[derive(Debug, Default, Deserialize)] +#[derive(Default, Deserialize)] #[serde(default)] struct SenderSubmit { csrf: String, @@ -59,6 +61,22 @@ struct SenderSubmit { from_name: String, } +// Hand-written so that a debug print never shows the SMTP password. +impl fmt::Debug for SenderSubmit { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("SenderSubmit") + .field("csrf", &self.csrf) + .field("host", &self.host) + .field("port", &self.port) + .field("tls", &self.tls) + .field("username", &self.username) + .field("password", &"") + .field("from_address", &self.from_address) + .field("from_name", &self.from_name) + .finish() + } +} + /// The reminder form as posted. #[derive(Debug, Default, Deserialize)] #[serde(default)] diff --git a/crates/iz-web/src/pages/sign_in.rs b/crates/iz-web/src/pages/sign_in.rs index 6b2ccc0..5c5df6d 100644 --- a/crates/iz-web/src/pages/sign_in.rs +++ b/crates/iz-web/src/pages/sign_in.rs @@ -151,7 +151,7 @@ async fn callback(cx: &Cx) -> Result { if let Some(error) = query_param(cx, "error") { // The value comes from `im`. It is cut short and shown escaped, and never used for anything else. let shown: String = error.chars().take(64).collect(); - tracing::warn!(error = %shown, "sign-in: the identity provider refused the sign-in"); + tracing::warn!(error = ?shown, "sign-in: the identity provider refused the sign-in"); return message( cx, StatusCode::BAD_REQUEST, diff --git a/deploy/ferron.conf b/deploy/ferron.conf index 0dc32e3..38da441 100644 --- a/deploy/ferron.conf +++ b/deploy/ferron.conf @@ -2,9 +2,9 @@ # Replace iz.example.com with the public host name (base_url in /etc/iz/iz.toml must match it). # A bare host block gets automatic TLS. # -# The proxy sends X-Forwarded-For for the client. iz reads that header only from peers listed in -# trusted_proxies; with Ferron on the same machine the peer is 127.0.0.1, so set -# trusted_proxies = ["127.0.0.1/32"] in iz.toml. +# Ferron may send X-Forwarded-For, but iz does not read that header, so iz never sees the client +# address: every request reaches iz from 127.0.0.1. Leave trusted_proxies out of iz.toml; it has no +# effect, and boot logs a warning when it is set. # # Buffering is off because the live update streams (server-sent events) must reach the browser # as they are written. diff --git a/docs/architecture.md b/docs/architecture.md index 6910666..e32e09d 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -42,7 +42,7 @@ iz/ `clock.rs` (deadline + meeting time rules, inventory 2.4) - `rules/` (mail rule engine: triggers, audiences, decisions; pure where possible), `mail_text.rs` (subjects and bodies for every mail kind, both languages) -- `sniff.rs`, `sheet.rs` (`calamine`: xlsx, xls, xlsb; values only; `.ods` is refused, not previewed; paging 50 rows × 12 columns; correct offsets +- `sniff.rs`, `sheet.rs` (`calamine`: xlsx only; values only; `.ods` and `.xlsb` are refused, not previewed; paging 50 rows × 12 columns; correct offsets for ranges not starting at A1), `slides.rs` (pptx text outline via `zip` + `quick-xml`, size and entry limits against zip bombs) - `store/`: `members.rs`, `sessions.rs`, `board.rs`, `tasks.rs`, `deps.rs`, `comments.rs`, `attachments.rs`, @@ -128,7 +128,7 @@ the sweeper in batches of 500, one statement each, so the writer is never held f conventions. Settings: SMTP sender (password sealed), limits, batching window, reminder minutes (0–1440), allowed attachment types, attachment limit (1–500 MiB), attachment location (`local`|`in`), `default_role`, `key_prefix`, retention days for activity and mail ledger (default 365), -base URL, trusted proxies. +base URL. --- diff --git a/docs/conventions.md b/docs/conventions.md index 935efc1..1d31a3e 100644 --- a/docs/conventions.md +++ b/docs/conventions.md @@ -90,16 +90,14 @@ tokens, passwords, cookies, or secrets. ## 6. Auth primitives -- Passwords: argon2id (`Argon2::default()`), PHC strings, always on `spawn_blocking`. Unknown accounts verify - against a fixed dummy hash so timing does not reveal them. +- Passwords: iz holds none. People sign in at `im`, which owns passwords, second factors and their + throttles. - Tokens: 32 random bytes, base64url; stored as hex SHA-256; compared with `subtle`; shown once. -- Throttle (in memory, sliding window, bounded key count): failed logins per account and per IP, failed second - factors per user; checked before any lookup; `429` with `Retry-After`. - Secrets at rest: `seal`/`open` with XChaCha20-Poly1305, `v1:` + base64(nonce || ciphertext). The instance key is never used directly: every use gets its own key, HMAC-SHA256(instance key, " v1"), and each seal binds its purpose (a fixed label) as associated data, so a value sealed for one purpose cannot be opened as another. -- Client IP: the TCP peer unless it is in `trusted_proxies`; then `X-Forwarded-For` right to left. +- Client IP: none is read. iz ignores `X-Forwarded-For`; `trusted_proxies` is accepted, has no effect, and boot warns when it is set. ## 7. Authorization