forge
Explore
Log in

Don't you dare go Hollow

🛡️ ops: parsed loopback check, private files from creation, quiet config errors, redacted Debug, URL-free errors, no xlsb preview

Browse files at this commit

9c1ef0f3504271801ba268360e69d66b41cd672bAhmet Kaan GümüşParent: dbbbc05
Cargo.lockmodified+1 -0
@@ -1741,6 +1741,7 @@ dependencies = [
1741 "tracing",1741 "tracing",
1742 "turso",1742 "turso",
1743 "ulid",1743 "ulid",
1744+ "url",
1744 "zip",1745 "zip",
1745 ]1746 ]
1746 1747
Cargo.tomlmodified+1 -0
@@ -45,6 +45,7 @@ tracing-subscriber = "0.3.23"
45 # Without the default `fts` feature: no app uses full-text search, and it pulls in tantivy and zstd.45 # Without the default `fts` feature: no app uses full-text search, and it pulls in tantivy and zstd.
46 turso = { version = "0.8.3", default-features = false, features = ["mimalloc"] }46 turso = { version = "0.8.3", default-features = false, features = ["mimalloc"] }
47 ulid = "3.0.0"47 ulid = "3.0.0"
48+url = "2.5.8"
48 quick-xml = "0.42.0"49 quick-xml = "0.42.0"
49 zip = { version = "9.1.3", default-features = false, features = ["deflate"] }50 zip = { version = "9.1.3", default-features = false, features = ["deflate"] }
50 51
README.mdmodified+3 -4
@@ -35,14 +35,13 @@ Keys:
35 35
36 | Key | Meaning |36 | Key | Meaning |
37 |---|---|37 |---|---|
38-| `database` | SQLite database file. Its `-wal` and `-shm` files sit next to it. |38+| `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. |
39 | `data_dir` | Directory for `iz.key`, the lock file, attachments and other local files. |39 | `data_dir` | Directory for `iz.key`, the lock file, attachments and other local files. |
40 | `listen` | HTTP listen address. Keep it on `127.0.0.1` behind the reverse proxy. |40 | `listen` | HTTP listen address. Keep it on `127.0.0.1` behind the reverse proxy. |
41-| `base_url` | Public URL used in links and mail. `https://` or `http://`, no trailing slash. |41+| `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. |
42-| `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. |
43 | `[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. |42 | `[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. |
44 | `[in_store]` | `enabled`. Stores attachments in the `in` Files service instead of local disk. Off by default. |43 | `[in_store]` | `enabled`. Stores attachments in the `in` Files service instead of local disk. Off by default. |
45-| `[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. |44+| `[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. |
46 45
47 Unknown keys are an error at boot, so a typo stops the start instead of being ignored.46 Unknown keys are an error at boot, so a typo stops the start instead of being ignored.
48 47
config/iz.example.tomlmodified+1 -4
@@ -7,11 +7,8 @@ database = "data/iz.db"
7 data_dir = "data"7 data_dir = "data"
8 # HTTP listen address. Keep it on loopback behind a reverse proxy.8 # HTTP listen address. Keep it on loopback behind a reverse proxy.
9 listen = "127.0.0.1:7654"9 listen = "127.0.0.1:7654"
10-# Public base URL used in links and mail. No trailing slash.10+# Public base URL used in links and mail. No trailing slash. https, or http on localhost, 127.0.0.1 or ::1.
11 base_url = "http://127.0.0.1:7654"11 base_url = "http://127.0.0.1:7654"
12-# Peers whose X-Forwarded-For is trusted for client IPs. Addresses or CIDR networks.
13-# Behind Ferron on the same host, set ["127.0.0.1/32"]; left empty there, every visitor counts as 127.0.0.1.
14-trusted_proxies = []
15 12
16 # Identity provider (OpenID Connect). Uncomment to enable sign-in.13 # Identity provider (OpenID Connect). Uncomment to enable sign-in.
17 # The client secret is read from client_secret_file at boot. That file must be mode 0600 or 0400.14 # The client secret is read from client_secret_file at boot. That file must be mode 0600 or 0400.
crates/iz-core/Cargo.tomlmodified+1 -0
@@ -32,6 +32,7 @@ toml.workspace = true
32 tracing.workspace = true32 tracing.workspace = true
33 turso.workspace = true33 turso.workspace = true
34 ulid.workspace = true34 ulid.workspace = true
35+url.workspace = true
35 zip.workspace = true36 zip.workspace = true
36 37
37 [dev-dependencies]38 [dev-dependencies]
crates/iz-core/src/config.rsmodified+87 -27
@@ -2,11 +2,13 @@
2 //! password are entered in the admin UI and sealed in the database. Every struct denies unknown2 //! password are entered in the admin UI and sealed in the database. Every struct denies unknown
3 //! keys, so a misspelled option fails at boot instead of being silently ignored.3 //! keys, so a misspelled option fails at boot instead of being silently ignored.
4 4
5-use std::net::{IpAddr, SocketAddr};5+use std::fmt;
6+use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
6 use std::path::{Path, PathBuf};7 use std::path::{Path, PathBuf};
7 8
8 use ipnet::IpNet;9 use ipnet::IpNet;
9 use serde::{Deserialize, Deserializer};10 use serde::{Deserialize, Deserializer};
11+use url::Host;
10 12
11 use crate::error::{Error, Result};13 use crate::error::{Error, Result};
12 14
@@ -29,7 +31,8 @@ pub struct Config {
29 /// Public base URL used in links and mail. No trailing slash.31 /// Public base URL used in links and mail. No trailing slash.
30 #[serde(default = "default_base_url")]32 #[serde(default = "default_base_url")]
31 pub base_url: String,33 pub base_url: String,
32- /// Peers whose `X-Forwarded-For` is trusted. Entries are CIDR networks or bare addresses.34+ /// Accepted so existing configs still load, but unused: iz does not read `X-Forwarded-For`. Boot warns
35+ /// when it is set. Entries are CIDR networks or bare addresses.
33 #[serde(default, deserialize_with = "deserialize_trusted_proxies")]36 #[serde(default, deserialize_with = "deserialize_trusted_proxies")]
34 pub trusted_proxies: Vec<IpNet>,37 pub trusted_proxies: Vec<IpNet>,
35 /// OpenID Connect provider. Absent means sign-in is not configured.38 /// OpenID Connect provider. Absent means sign-in is not configured.
@@ -71,7 +74,7 @@ pub struct InStoreConfig {
71 }74 }
72 75
73 /// Scheduled backup policy.76 /// Scheduled backup policy.
74-#[derive(Debug, Clone, Deserialize)]77+#[derive(Clone, Deserialize)]
75 #[serde(deny_unknown_fields)]78 #[serde(deny_unknown_fields)]
76 pub struct BackupConfig {79 pub struct BackupConfig {
77 /// Directory that receives the backup sets.80 /// Directory that receives the backup sets.
@@ -87,6 +90,21 @@ pub struct BackupConfig {
87 pub healthcheck_url: Option<String>,90 pub healthcheck_url: Option<String>,
88 }91 }
89 92
93+// Hand-written so that `Config` debug output never shows the healthcheck URL, which can carry a key.
94+impl fmt::Debug for BackupConfig {
95+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
96+ f.debug_struct("BackupConfig")
97+ .field("dir", &self.dir)
98+ .field("interval_hours", &self.interval_hours)
99+ .field("keep", &self.keep)
100+ .field(
101+ "healthcheck_url",
102+ &self.healthcheck_url.as_ref().map(|_| "<redacted>"),
103+ )
104+ .finish()
105+ }
106+}
107+
90 fn default_database() -> PathBuf {108 fn default_database() -> PathBuf {
91 PathBuf::from("data/iz.db")109 PathBuf::from("data/iz.db")
92 }110 }
@@ -123,10 +141,10 @@ fn deserialize_trusted_proxies<'de, D: Deserializer<'de>>(
123 if let Ok(net) = entry.parse::<IpNet>() {141 if let Ok(net) = entry.parse::<IpNet>() {
124 return Ok(net);142 return Ok(net);
125 }143 }
126- entry144+ // The entry is left out of the message: a misplaced secret must not reach the log.
127- .parse::<IpAddr>()145+ entry.parse::<IpAddr>().map(IpNet::from).map_err(|_| {
128- .map(IpNet::from)146+ serde::de::Error::custom("invalid trusted proxy: not an address or CIDR network")
129- .map_err(|_| serde::de::Error::custom(format!("invalid trusted proxy `{entry}`")))147+ })
130 })148 })
131 .collect()149 .collect()
132 }150 }
@@ -153,7 +171,8 @@ impl Config {
153 171
154 /// Parses and validates config text.172 /// Parses and validates config text.
155 pub fn parse(text: &str) -> Result<Config> {173 pub fn parse(text: &str) -> Result<Config> {
156- let config: Config = toml::from_str(text).map_err(|e| Error::Config(e.to_string()))?;174+ let config: Config =
175+ toml::from_str(text).map_err(|e| Error::Config(parse_error(text, &e)))?;
157 config.validate()?;176 config.validate()?;
158 Ok(config)177 Ok(config)
159 }178 }
@@ -166,11 +185,7 @@ impl Config {
166 if self.data_dir.as_os_str().is_empty() {185 if self.data_dir.as_os_str().is_empty() {
167 return Err(Error::Config("data_dir must not be empty".into()));186 return Err(Error::Config("data_dir must not be empty".into()));
168 }187 }
169- if !(self.base_url.starts_with("https://") || self.base_url.starts_with("http://")) {188+ require_secure_url("base_url", &self.base_url)?;
170- return Err(Error::Config(
171- "base_url must start with https:// or http://".into(),
172- ));
173- }
174 if self.base_url.ends_with('/') {189 if self.base_url.ends_with('/') {
175 return Err(Error::Config("base_url must not end with /".into()));190 return Err(Error::Config("base_url must not end with /".into()));
176 }191 }
@@ -222,14 +237,7 @@ fn validate_in_url(url: &str) -> Result<()> {
222 if url.ends_with('/') {237 if url.ends_with('/') {
223 return Err(Error::Config("in_store.url must not end with /".into()));238 return Err(Error::Config("in_store.url must not end with /".into()));
224 }239 }
225- let loopback = url.starts_with("http://127.0.0.1") || url.starts_with("http://localhost");240+ require_secure_url("in_store.url", url)
226- if url.starts_with("https://") || loopback {
227- Ok(())
228- } else {
229- Err(Error::Config(
230- "in_store.url must be an https URL (http only for loopback)".into(),
231- ))
232- }
233 }241 }
234 242
235 /// An issuer must be https. Plain http is allowed only for loopback, which is how a local243 /// 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<()> {
239 if issuer.ends_with('/') {247 if issuer.ends_with('/') {
240 return Err(Error::Config("oidc.issuer must not end with /".into()));248 return Err(Error::Config("oidc.issuer must not end with /".into()));
241 }249 }
242- let loopback = issuer.starts_with("http://127.0.0.1") || issuer.starts_with("http://localhost");250+ require_secure_url("oidc.issuer", issuer)
243- if issuer.starts_with("https://") || loopback {251+}
244- Ok(())252+
245- } else {253+/// Checks that `value` is a URL iz may send secrets to. The URL is parsed, not prefix-matched, so that
246- Err(Error::Config(254+/// `http://localhost.example.com` and `http://localhost@example.com` are refused. https is allowed for any
247- "oidc.issuer must be an https URL (http only for loopback)".into(),255+/// host. http is allowed only for the host `localhost`, `127.0.0.1` or `::1`, and only with no user name
256+/// or password in the URL.
257+fn require_secure_url(field: &str, value: &str) -> Result<()> {
258+ let refused = || {
259+ Error::Config(format!(
260+ "{field} must be an https URL (http only for loopback, with no user name or password)"
248 ))261 ))
262+ };
263+ let url = url::Url::parse(value).map_err(|_| refused())?;
264+ if !url.username().is_empty() || url.password().is_some() {
265+ return Err(refused());
266+ }
267+ let loopback = match url.host() {
268+ Some(Host::Domain(name)) => name == "localhost",
269+ Some(Host::Ipv4(ip)) => ip == Ipv4Addr::LOCALHOST,
270+ Some(Host::Ipv6(ip)) => ip == Ipv6Addr::LOCALHOST,
271+ None => false,
272+ };
273+ match url.scheme() {
274+ "https" => Ok(()),
275+ "http" if loopback => Ok(()),
276+ _ => Err(refused()),
277+ }
278+}
279+
280+/// The message of a TOML error with its line and column. The source line itself is left out on purpose:
281+/// a secret that was put in the wrong file must not be written to the log.
282+fn parse_error(text: &str, error: &toml::de::Error) -> String {
283+ match error.span() {
284+ Some(span) => {
285+ let before = text.get(..span.start).unwrap_or("");
286+ let line = before.matches('\n').count() + 1;
287+ let column = before.rsplit('\n').next().map_or(0, |s| s.chars().count()) + 1;
288+ format!("line {line}, column {column}: {}", error.message())
289+ }
290+ None => error.message().to_owned(),
249 }291 }
250 }292 }
251 293
@@ -279,6 +321,24 @@ mod tests {
279 fn validation_rejects_bad_cross_field_values() {321 fn validation_rejects_bad_cross_field_values() {
280 assert!(Config::parse("base_url = \"ftp://x\"\n").is_err());322 assert!(Config::parse("base_url = \"ftp://x\"\n").is_err());
281 assert!(Config::parse("base_url = \"https://x/\"\n").is_err());323 assert!(Config::parse("base_url = \"https://x/\"\n").is_err());
324+ // Prefix and userinfo tricks must not pass as loopback.
325+ for url in [
326+ "http://im.example.com",
327+ "http://localhost.evil.example",
328+ "http://localhost@evil.example",
329+ "http://127.0.0.1.evil.example",
330+ "http://127.0.0.2",
331+ ] {
332+ assert!(
333+ Config::parse(&format!("base_url = \"{url}\"\n")).is_err(),
334+ "{url}"
335+ );
336+ }
337+ assert!(Config::parse("base_url = \"http://[::1]:7654\"\n").is_ok());
338+ assert!(
339+ Config::parse("[oidc]\nissuer = \"http://localhost.evil.example\"\nclient_id = \"iz\"\nclient_secret_file = \"s\"\n")
340+ .is_err()
341+ );
282 assert!(342 assert!(
283 Config::parse("[oidc]\nissuer = \"http://im.example.com\"\nclient_id = \"iz\"\nclient_secret_file = \"s\"\n")343 Config::parse("[oidc]\nissuer = \"http://im.example.com\"\nclient_id = \"iz\"\nclient_secret_file = \"s\"\n")
284 .is_err()344 .is_err()
crates/iz-core/src/manifest.rsmodified+13 -3
@@ -139,11 +139,21 @@ pub fn write_manifest(
139 Ok(manifest)139 Ok(manifest)
140 }140 }
141 141
142-/// Writes `bytes` to `dir/name` through a temporary name, fsynced, then renamed into place.142+/// Writes `bytes` to `dir/name` through a temporary name, fsynced, then renamed into place. The file is
143+/// created with mode 0600. A temporary file left by an interrupted write is overwritten.
143 fn write_synced(dir: &Path, name: &str, bytes: &[u8]) -> Result<()> {144 fn write_synced(dir: &Path, name: &str, bytes: &[u8]) -> Result<()> {
145+ use std::io::Write;
146+ use std::os::unix::fs::OpenOptionsExt;
147+
144 let tmp = dir.join(format!("{name}.tmp"));148 let tmp = dir.join(format!("{name}.tmp"));
145- std::fs::write(&tmp, bytes)?;149+ let mut file = std::fs::OpenOptions::new()
146- File::open(&tmp)?.sync_all()?;150+ .write(true)
151+ .create(true)
152+ .truncate(true)
153+ .mode(0o600)
154+ .open(&tmp)?;
155+ file.write_all(bytes)?;
156+ file.sync_all()?;
147 std::fs::rename(&tmp, dir.join(name))?;157 std::fs::rename(&tmp, dir.join(name))?;
148 Ok(())158 Ok(())
149 }159 }
crates/iz-core/src/sheet.rsmodified+12 -36
@@ -9,7 +9,9 @@
9 //! costs no more than the caps. An `.ods` is not previewed at all: calamine has no cell stream for it and reads9 //! costs no more than the caps. An `.ods` is not previewed at all: calamine has no cell stream for it and reads
10 //! its `content.xml` whole, and a tiny file can declare huge repeat counts that allocate gigabytes. The viewer10 //! its `content.xml` whole, and a tiny file can declare huge repeat counts that allocate gigabytes. The viewer
11 //! shows such a file as refused, and it can still be downloaded. A CSV is read record by record and stops at11 //! shows such a file as refused, and it can still be downloaded. A CSV is read record by record and stops at
12-//! the row cap, so a long file costs no more than the cap.12+//! the row cap, so a long file costs no more than the cap. An `.xlsb` is not previewed either: calamine reads its
13+//! sheet as a whole range, sized by the cells it finds rather than by the sheet's declared dimensions, so no cap
14+//! can be checked before the read.
13 15
14 use std::collections::BTreeMap;16 use std::collections::BTreeMap;
15 use std::fs::File;17 use std::fs::File;
@@ -59,9 +61,9 @@ fn data_ref_text(value: &DataRef<'_>) -> String {
59 }61 }
60 }62 }
61 63
62-/// Reads an `.xlsx` workbook (`.xls` and `.xlsb` too). Refused (as `Invalid`) when the zip checks fail, and64+/// Reads an `.xlsx` workbook. It is a zip container, and it is refused (as `Invalid`) when the zip checks
63-/// for an OpenDocument file: it is refused before calamine opens it, because calamine reads its `content.xml`65+/// fail. An `.xls` never gets this far, because it is not a zip. An OpenDocument file is refused before calamine
64-/// whole.66+/// opens it, because calamine reads its `content.xml` whole. An `.xlsb` is refused too (see the module comment).
65 pub fn read_workbook(path: &Path) -> Result<Book> {67 pub fn read_workbook(path: &Path) -> Result<Book> {
66 let mut zip = archive::open_checked(path, SHEET_INPUT_MAX_BYTES)?;68 let mut zip = archive::open_checked(path, SHEET_INPUT_MAX_BYTES)?;
67 if zip.by_name("content.xml").is_ok() {69 if zip.by_name("content.xml").is_ok() {
@@ -70,15 +72,15 @@ pub fn read_workbook(path: &Path) -> Result<Book> {
70 }72 }
71 let mut workbook =73 let mut workbook =
72 open_workbook_auto(path).map_err(|_| Error::Invalid("bad_workbook".into()))?;74 open_workbook_auto(path).map_err(|_| Error::Invalid("bad_workbook".into()))?;
73- let names = workbook.sheet_names();75+ let Sheets::Xlsx(xlsx) = &mut workbook else {
76+ // Only `.xlsx` is streamed. An `.xlsb` is read whole by calamine, so it is refused.
77+ return Err(Error::Invalid("xlsb_not_previewed".into()));
78+ };
79+ let names = xlsx.sheet_names();
74 let sheet_count = names.len();80 let sheet_count = names.len();
75 let mut sheets = Vec::new();81 let mut sheets = Vec::new();
76 for name in names.into_iter().take(SHEETS_MAX) {82 for name in names.into_iter().take(SHEETS_MAX) {
77- let sheet = match &mut workbook {83+ sheets.push(read_xlsx_sheet(xlsx, &name)?);
78- Sheets::Xlsx(xlsx) => read_xlsx_sheet(xlsx, &name)?,
79- _ => read_range_sheet(&mut workbook, &name)?,
80- };
81- sheets.push(sheet);
82 }84 }
83 Ok(Book {85 Ok(Book {
84 sheets,86 sheets,
@@ -128,32 +130,6 @@ fn read_xlsx_sheet(xlsx: &mut Xlsx<BufReader<File>>, name: &str) -> Result<Sheet
128 })130 })
129 }131 }
130 132
131-/// Reads one sheet of a workbook that is not streamed (`.xls`, `.xlsb`) as a whole range.
132-fn read_range_sheet(workbook: &mut Sheets<BufReader<File>>, name: &str) -> Result<Sheet> {
133- let range = workbook
134- .worksheet_range(name)
135- .map_err(|_| Error::Invalid("bad_workbook".into()))?;
136- let mut rows = Vec::new();
137- let mut rows_cut = false;
138- for (index, row) in range.rows().enumerate() {
139- if index == SHEET_ROWS_MAX {
140- rows_cut = true;
141- break;
142- }
143- rows.push(
144- row.iter()
145- .take(SHEET_COLS_MAX)
146- .map(|cell: &Data| cell_text(&cell.to_string()))
147- .collect(),
148- );
149- }
150- Ok(Sheet {
151- name: name.to_owned(),
152- rows,
153- rows_cut,
154- })
155-}
156-
157 /// Reads a CSV file as one sheet. Invalid UTF-8 is shown with replacement characters.133 /// Reads a CSV file as one sheet. Invalid UTF-8 is shown with replacement characters.
158 pub fn read_csv(path: &Path, name: &str) -> Result<Book> {134 pub fn read_csv(path: &Path, name: &str) -> Result<Book> {
159 let len = std::fs::metadata(path)?.len();135 let len = std::fs::metadata(path)?.len();
crates/iz-core/src/store/mod.rsmodified+38 -0
@@ -71,6 +71,7 @@ impl Store {
71 let path_str = path.to_str().ok_or_else(|| {71 let path_str = path.to_str().ok_or_else(|| {
72 Error::Config(format!("database path is not UTF-8: {}", path.display()))72 Error::Config(format!("database path is not UTF-8: {}", path.display()))
73 })?;73 })?;
74+ create_private_files(path)?;
74 let db = Builder::new_local(path_str).build().await.map_err(db_err)?;75 let db = Builder::new_local(path_str).build().await.map_err(db_err)?;
75 let conn = db.connect().map_err(db_err)?;76 let conn = db.connect().map_err(db_err)?;
76 apply_pragmas(&conn).await;77 apply_pragmas(&conn).await;
@@ -179,6 +180,31 @@ pub async fn finish<T>(tx: turso::transaction::Transaction<'_>, outcome: Result<
179 }180 }
180 }181 }
181 182
183+/// Creates the database file and its `-wal` and `-shm` files with mode 0600 when they do not exist yet.
184+/// Turso would create them with the default umask. A file that already exists keeps its mode.
185+fn create_private_files(path: &Path) -> Result<()> {
186+ use std::os::unix::fs::OpenOptionsExt;
187+
188+ let with_suffix = |suffix: &str| {
189+ let mut name = path.as_os_str().to_owned();
190+ name.push(suffix);
191+ name
192+ };
193+ for file in [with_suffix(""), with_suffix("-wal"), with_suffix("-shm")] {
194+ let created = std::fs::OpenOptions::new()
195+ .write(true)
196+ .create_new(true)
197+ .mode(0o600)
198+ .open(&file);
199+ match created {
200+ Ok(_) => {}
201+ Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {}
202+ Err(e) => return Err(e.into()),
203+ }
204+ }
205+ Ok(())
206+}
207+
182 /// Makes a connection refuse writes. Turso takes `1`, not `ON`. Failure is fatal, because a reader208 /// Makes a connection refuse writes. Turso takes `1`, not `ON`. Failure is fatal, because a reader
183 /// that can write would break the pool's rule.209 /// that can write would break the pool's rule.
184 async fn apply_query_only(conn: &Connection) -> Result<()> {210 async fn apply_query_only(conn: &Connection) -> Result<()> {
@@ -385,6 +411,18 @@ mod tests {
385 Ok(())411 Ok(())
386 }412 }
387 413
414+ #[tokio::test]
415+ async fn database_files_are_created_private() {
416+ use std::os::unix::fs::PermissionsExt;
417+
418+ let dir = tempfile::tempdir().expect("dir");
419+ Store::open(&dir.path().join("iz.db")).await.expect("store");
420+ for name in ["iz.db", "iz.db-wal", "iz.db-shm"] {
421+ let meta = std::fs::metadata(dir.path().join(name)).expect("file");
422+ assert_eq!(meta.permissions().mode() & 0o777, 0o600, "{name}");
423+ }
424+ }
425+
388 #[tokio::test]426 #[tokio::test]
389 async fn open_twice_is_idempotent_and_keeps_settings() {427 async fn open_twice_is_idempotent_and_keeps_settings() {
390 let dir = tempfile::tempdir().unwrap();428 let dir = tempfile::tempdir().unwrap();
crates/iz-core/src/store/sessions.rsmodified+31 -2
@@ -5,6 +5,7 @@
5 //! `none`. Lookups repeat those checks in SQL, so disabling a member takes effect on the next request5 //! `none`. Lookups repeat those checks in SQL, so disabling a member takes effect on the next request
6 //! even if the back-channel message was lost.6 //! even if the back-channel message was lost.
7 7
8+use std::fmt;
8 use std::time::Duration;9 use std::time::Duration;
9 10
10 use super::{col_opt_text, col_text, db_err, fetch_opt, new_id};11 use super::{col_opt_text, col_text, db_err, fetch_opt, new_id};
@@ -14,7 +15,7 @@ use crate::time::{now_stamp, stamp_after};
14 use crate::token::{generate_token, hash_token};15 use crate::token::{generate_token, hash_token};
15 16
16 /// A session as the web layer needs it after a lookup.17 /// A session as the web layer needs it after a lookup.
17-#[derive(Debug, Clone, PartialEq, Eq)]18+#[derive(Clone, PartialEq, Eq)]
18 pub struct SessionRecord {19 pub struct SessionRecord {
19 /// Session id (ULID).20 /// Session id (ULID).
20 pub id: String,21 pub id: String,
@@ -33,7 +34,7 @@ pub struct SessionRecord {
33 }34 }
34 35
35 /// A freshly created session. `token` goes into the cookie and is never stored.36 /// A freshly created session. `token` goes into the cookie and is never stored.
36-#[derive(Debug, Clone, PartialEq, Eq)]37+#[derive(Clone, PartialEq, Eq)]
37 pub struct IssuedSession {38 pub struct IssuedSession {
38 /// Session id.39 /// Session id.
39 pub id: String,40 pub id: String,
@@ -43,6 +44,34 @@ pub struct IssuedSession {
43 pub csrf_token: String,44 pub csrf_token: String,
44 }45 }
45 46
47+// Hand-written so that a debug print never shows a session's cookie, CSRF token or sealed ID token.
48+impl fmt::Debug for SessionRecord {
49+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
50+ f.debug_struct("SessionRecord")
51+ .field("id", &self.id)
52+ .field("sub", &self.sub)
53+ .field("csrf_token", &"<redacted>")
54+ .field("sid", &self.sid)
55+ .field(
56+ "id_token_sealed",
57+ &self.id_token_sealed.as_ref().map(|_| "<redacted>"),
58+ )
59+ .field("expires_at", &self.expires_at)
60+ .field("last_seen", &self.last_seen)
61+ .finish()
62+ }
63+}
64+
65+impl fmt::Debug for IssuedSession {
66+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
67+ f.debug_struct("IssuedSession")
68+ .field("id", &self.id)
69+ .field("token", &"<redacted>")
70+ .field("csrf_token", &"<redacted>")
71+ .finish()
72+ }
73+}
74+
46 const SESSION_COLS: &str =75 const SESSION_COLS: &str =
47 "s.id, s.sub, s.csrf_token, s.sid, s.expires_at, s.last_seen, s.id_token_sealed";76 "s.id, s.sub, s.csrf_token, s.sid, s.expires_at, s.last_seen, s.id_token_sealed";
48 77
crates/iz-web/src/auth.rsmodified+15 -1
@@ -5,6 +5,7 @@
5 //! (`iz_core::store::sessions`). The sign-in flight (state, nonce, PKCE verifier, `next`) lives in5 //! (`iz_core::store::sessions`). The sign-in flight (state, nonce, PKCE verifier, `next`) lives in
6 //! `__Host-iz_flight`, sealed with the instance key under the `sign-in-flight` purpose, so the browser cannot change it.6 //! `__Host-iz_flight`, sealed with the instance key under the `sign-in-flight` purpose, so the browser cannot change it.
7 7
8+use std::fmt;
8 use std::time::Duration;9 use std::time::Duration;
9 10
10 use iz_core::authz::{Action, Actor, Denied, authorize};11 use iz_core::authz::{Action, Actor, Denied, authorize};
@@ -78,7 +79,7 @@ impl CurrentMember {
78 }79 }
79 80
80 /// The state of one sign-in, sealed into the flight cookie.81 /// The state of one sign-in, sealed into the flight cookie.
81-#[derive(Debug, Serialize, Deserialize)]82+#[derive(Serialize, Deserialize)]
82 pub struct SignInState {83 pub struct SignInState {
83 /// The `state` parameter sent to `im`. Compared with the one that comes back.84 /// The `state` parameter sent to `im`. Compared with the one that comes back.
84 pub state: String,85 pub state: String,
@@ -92,6 +93,19 @@ pub struct SignInState {
92 pub expires: u64,93 pub expires: u64,
93 }94 }
94 95
96+// Hand-written so that a debug print never shows the state, the nonce or the PKCE verifier.
97+impl fmt::Debug for SignInState {
98+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
99+ f.debug_struct("SignInState")
100+ .field("state", &"<redacted>")
101+ .field("nonce", &"<redacted>")
102+ .field("verifier", &"<redacted>")
103+ .field("next", &self.next)
104+ .field("expires", &self.expires)
105+ .finish()
106+ }
107+}
108+
95 /// The cookie jar with the `__Host-` prefix, so the browser enforces `Secure`, `Path=/` and no domain.109 /// The cookie jar with the `__Host-` prefix, so the browser enforces `Secure`, `Path=/` and no domain.
96 fn jar(cx: &Cx) -> impl Cookies + '_ {110 fn jar(cx: &Cx) -> impl Cookies + '_ {
97 cookies(cx).override_prefix_host()111 cookies(cx).override_prefix_host()
crates/iz-web/src/boot.rsmodified+37 -7
@@ -5,7 +5,7 @@
5 //! the pragmas and the migrations), build the router, bind the listener, and serve until SIGTERM or5 //! the pragmas and the migrations), build the router, bind the listener, and serve until SIGTERM or
6 //! Ctrl-C. Stored UI overrides are not layered on the file yet, because no page writes them.6 //! Ctrl-C. Stored UI overrides are not layered on the file yet, because no page writes them.
7 7
8-use std::os::unix::fs::PermissionsExt;8+use std::os::unix::fs::DirBuilderExt;
9 use std::path::Path;9 use std::path::Path;
10 use std::sync::Arc;10 use std::sync::Arc;
11 11
@@ -36,10 +36,11 @@ const DEFAULT_KEY_PREFIX: &str = "IZ";
36 /// Runs the server until a stop signal arrives. Returns once every connection has finished.36 /// Runs the server until a stop signal arrives. Returns once every connection has finished.
37 pub async fn serve(config_path: &Path) -> iz_core::Result<()> {37 pub async fn serve(config_path: &Path) -> iz_core::Result<()> {
38 let config = Config::load(config_path)?;38 let config = Config::load(config_path)?;
39+ warn_about_config(&config);
39 let listen = config.listen;40 let listen = config.listen;
40 // One server per data directory: the lock is held until this function returns, so a second `iz`41 // One server per data directory: the lock is held until this function returns, so a second `iz`
41 // (or an operator command) refuses to touch the same files while this one runs.42 // (or an operator command) refuses to touch the same files while this one runs.
42- std::fs::create_dir_all(&config.data_dir)?;43+ create_data_dir(&config.data_dir)?;
43 let _lock = crate::cli::lock_data_dir(&config.data_dir).map_err(iz_core::Error::Config)?;44 let _lock = crate::cli::lock_data_dir(&config.data_dir).map_err(iz_core::Error::Config)?;
44 let state = open_state(config).await?;45 let state = open_state(config).await?;
45 46
@@ -78,12 +79,41 @@ pub async fn serve(config_path: &Path) -> iz_core::Result<()> {
78 Ok(())79 Ok(())
79 }80 }
80 81
81-/// Creates the data directory and opens the key and the database. Everything the router needs82+/// Creates the data directory with mode 0700 when it is missing. The directory holds the instance key, so
82-/// that touches the disk is ready when this returns.83+/// only this user may enter it. An existing directory keeps its mode.
84+fn create_data_dir(path: &Path) -> std::io::Result<()> {
85+ std::fs::DirBuilder::new()
86+ .recursive(true)
87+ .mode(0o700)
88+ .create(path)
89+}
90+
91+/// Logs the settings that have no effect, and the ones that probably are not what the operator meant. Nothing
92+/// here stops the start.
93+fn warn_about_config(config: &Config) {
94+ if config.backup.is_none() {
95+ tracing::warn!("backups are not configured; no backup sets will be written");
96+ }
97+ // Absolute paths compare the same whether the config wrote them relative or not.
98+ if let (Ok(database), Ok(data_dir)) = (
99+ std::path::absolute(&config.database),
100+ std::path::absolute(&config.data_dir),
101+ ) && !database.starts_with(&data_dir)
102+ {
103+ tracing::warn!(
104+ database = %config.database.display(),
105+ data_dir = %config.data_dir.display(),
106+ "database is outside data_dir"
107+ );
108+ }
109+ if !config.trusted_proxies.is_empty() {
110+ tracing::warn!("trusted_proxies has no effect in iz");
111+ }
112+}
113+
114+/// Opens the key and the database. Everything the router needs that touches the disk is ready when this
115+/// returns.
83 async fn open_state(config: Config) -> iz_core::Result<AppState> {116 async fn open_state(config: Config) -> iz_core::Result<AppState> {
84- std::fs::create_dir_all(&config.data_dir)?;
85- // The directory holds the instance key. Only this user may enter it.
86- std::fs::set_permissions(&config.data_dir, std::fs::Permissions::from_mode(0o700))?;
87 let data_dir = config.data_dir.canonicalize()?;117 let data_dir = config.data_dir.canonicalize()?;
88 if let Some(parent) = config118 if let Some(parent) = config
89 .database119 .database
crates/iz-web/src/in_store.rsmodified+2 -2
@@ -222,9 +222,9 @@ fn clients(write: bool) -> iz_core::Result<reqwest::Client> {
222 .map_err(|error| iz_core::Error::Config(format!("cannot build the Files client: {error}")))222 .map_err(|error| iz_core::Error::Config(format!("cannot build the Files client: {error}")))
223 }223 }
224 224
225-/// A connection-level failure as an [`InError`].225+/// A connection-level failure as an [`InError`]. The URL is left out of the text.
226 fn transport(error: reqwest::Error) -> InError {226 fn transport(error: reqwest::Error) -> InError {
227- InError::Unavailable(error.to_string())227+ InError::Unavailable(error.without_url().to_string())
228 }228 }
229 229
230 /// The file as a stream of frames, read in [`UPLOAD_FRAME`] pieces, so a large upload is never held whole.230 /// The file as a stream of frames, read in [`UPLOAD_FRAME`] pieces, so a large upload is never held whole.
crates/iz-web/src/oidc.rsmodified+17 -2
@@ -16,6 +16,7 @@
16 //! run without a network.16 //! run without a network.
17 17
18 use std::collections::HashMap;18 use std::collections::HashMap;
19+use std::fmt;
19 use std::path::Path;20 use std::path::Path;
20 use std::sync::Arc;21 use std::sync::Arc;
21 use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};22 use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
@@ -97,7 +98,7 @@ pub struct Discovery {
97 }98 }
98 99
99 /// The answer of the token endpoint. The refresh token is not read: iz discards it (contracts.md 2.4).100 /// The answer of the token endpoint. The refresh token is not read: iz discards it (contracts.md 2.4).
100-#[derive(Debug, Deserialize)]101+#[derive(Deserialize)]
101 pub struct TokenResponse {102 pub struct TokenResponse {
102 /// The ID token, for an authorization-code exchange.103 /// The ID token, for an authorization-code exchange.
103 #[serde(default)]104 #[serde(default)]
@@ -110,6 +111,20 @@ pub struct TokenResponse {
110 pub expires_in: Option<u64>,111 pub expires_in: Option<u64>,
111 }112 }
112 113
114+// Hand-written so that a debug print never shows the ID token or the access token.
115+impl fmt::Debug for TokenResponse {
116+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
117+ f.debug_struct("TokenResponse")
118+ .field("id_token", &self.id_token.as_ref().map(|_| "<redacted>"))
119+ .field(
120+ "access_token",
121+ &self.access_token.as_ref().map(|_| "<redacted>"),
122+ )
123+ .field("expires_in", &self.expires_in)
124+ .finish()
125+ }
126+}
127+
113 /// The claims of an ID token that iz uses. `sid` is the `im` browser session.128 /// The claims of an ID token that iz uses. `sid` is the `im` browser session.
114 #[derive(Debug, Clone, Deserialize, PartialEq, Eq)]129 #[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
115 pub struct IdClaims {130 pub struct IdClaims {
@@ -718,7 +733,7 @@ fn str_claim(claims: &Map<String, Value>, name: &str) -> Option<String> {
718 }733 }
719 734
720 fn unavailable(error: reqwest::Error) -> ImError {735 fn unavailable(error: reqwest::Error) -> ImError {
721- ImError::Unavailable(error.to_string())736+ ImError::Unavailable(error.without_url().to_string())
722 }737 }
723 738
724 /// Reads a response body, refusing one larger than `limit` bytes. The check runs while the body is739 /// Reads a response body, refusing one larger than `limit` bytes. The check runs while the body is
crates/iz-web/src/pages/photo.rsmodified+8 -1
@@ -10,6 +10,7 @@
10 use std::path::{Path, PathBuf};10 use std::path::{Path, PathBuf};
11 11
12 use http::header::{CACHE_CONTROL, CONTENT_TYPE, ETAG, IF_NONE_MATCH, X_CONTENT_TYPE_OPTIONS};12 use http::header::{CACHE_CONTROL, CONTENT_TYPE, ETAG, IF_NONE_MATCH, X_CONTENT_TYPE_OPTIONS};
13+use tokio::io::AsyncWriteExt;
13 use topcoat::Result;14 use topcoat::Result;
14 use topcoat::context::{Cx, app_context};15 use topcoat::context::{Cx, app_context};
15 use topcoat::router::error::not_found;16 use topcoat::router::error::not_found;
@@ -148,7 +149,13 @@ async fn write_cache(dir: &Path, version: i64, mime: &str, bytes: &[u8]) -> std:
148 data.extend_from_slice(mime.as_bytes());149 data.extend_from_slice(mime.as_bytes());
149 data.push(b'\n');150 data.push(b'\n');
150 data.extend_from_slice(bytes);151 data.extend_from_slice(bytes);
151- tokio::fs::write(&tmp, &data).await?;152+ let mut file = tokio::fs::OpenOptions::new()
153+ .write(true)
154+ .create_new(true)
155+ .mode(0o600)
156+ .open(&tmp)
157+ .await?;
158+ file.write_all(&data).await?;
152 tokio::fs::rename(&tmp, dir.join(&name)).await?;159 tokio::fs::rename(&tmp, dir.join(&name)).await?;
153 let mut entries = tokio::fs::read_dir(dir).await?;160 let mut entries = tokio::fs::read_dir(dir).await?;
154 while let Some(entry) = entries.next_entry().await? {161 while let Some(entry) = entries.next_entry().await? {
crates/iz-web/src/pages/settings.rsmodified+19 -1
@@ -5,6 +5,8 @@
5 //! A refusal the admin can fix re-renders the page with the typed server values (never the password) and5 //! A refusal the admin can fix re-renders the page with the typed server values (never the password) and
6 //! status `422`. A success redirects with a notice code in the query string.6 //! status `422`. A success redirects with a notice code in the query string.
7 7
8+use std::fmt;
9+
8 use iz_core::mail_text::MailLang;10 use iz_core::mail_text::MailLang;
9 use iz_core::secret;11 use iz_core::secret;
10 use iz_core::sender::{12 use iz_core::sender::{
@@ -46,7 +48,7 @@ use jiff::tz::TimeZone;
46 use topcoat::router::path_param_segment;48 use topcoat::router::path_param_segment;
47 49
48 /// The sender form as posted.50 /// The sender form as posted.
49-#[derive(Debug, Default, Deserialize)]51+#[derive(Default, Deserialize)]
50 #[serde(default)]52 #[serde(default)]
51 struct SenderSubmit {53 struct SenderSubmit {
52 csrf: String,54 csrf: String,
@@ -59,6 +61,22 @@ struct SenderSubmit {
59 from_name: String,61 from_name: String,
60 }62 }
61 63
64+// Hand-written so that a debug print never shows the SMTP password.
65+impl fmt::Debug for SenderSubmit {
66+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
67+ f.debug_struct("SenderSubmit")
68+ .field("csrf", &self.csrf)
69+ .field("host", &self.host)
70+ .field("port", &self.port)
71+ .field("tls", &self.tls)
72+ .field("username", &self.username)
73+ .field("password", &"<redacted>")
74+ .field("from_address", &self.from_address)
75+ .field("from_name", &self.from_name)
76+ .finish()
77+ }
78+}
79+
62 /// The reminder form as posted.80 /// The reminder form as posted.
63 #[derive(Debug, Default, Deserialize)]81 #[derive(Debug, Default, Deserialize)]
64 #[serde(default)]82 #[serde(default)]
crates/iz-web/src/pages/sign_in.rsmodified+1 -1
@@ -151,7 +151,7 @@ async fn callback(cx: &Cx) -> Result<impl View> {
151 if let Some(error) = query_param(cx, "error") {151 if let Some(error) = query_param(cx, "error") {
152 // The value comes from `im`. It is cut short and shown escaped, and never used for anything else.152 // The value comes from `im`. It is cut short and shown escaped, and never used for anything else.
153 let shown: String = error.chars().take(64).collect();153 let shown: String = error.chars().take(64).collect();
154- tracing::warn!(error = %shown, "sign-in: the identity provider refused the sign-in");154+ tracing::warn!(error = ?shown, "sign-in: the identity provider refused the sign-in");
155 return message(155 return message(
156 cx,156 cx,
157 StatusCode::BAD_REQUEST,157 StatusCode::BAD_REQUEST,
deploy/ferron.confmodified+3 -3
@@ -2,9 +2,9 @@
2 # Replace iz.example.com with the public host name (base_url in /etc/iz/iz.toml must match it).2 # Replace iz.example.com with the public host name (base_url in /etc/iz/iz.toml must match it).
3 # A bare host block gets automatic TLS.3 # A bare host block gets automatic TLS.
4 #4 #
5-# The proxy sends X-Forwarded-For for the client. iz reads that header only from peers listed in5+# Ferron may send X-Forwarded-For, but iz does not read that header, so iz never sees the client
6-# trusted_proxies; with Ferron on the same machine the peer is 127.0.0.1, so set6+# address: every request reaches iz from 127.0.0.1. Leave trusted_proxies out of iz.toml; it has no
7-# trusted_proxies = ["127.0.0.1/32"] in iz.toml.7+# effect, and boot logs a warning when it is set.
8 #8 #
9 # Buffering is off because the live update streams (server-sent events) must reach the browser9 # Buffering is off because the live update streams (server-sent events) must reach the browser
10 # as they are written.10 # as they are written.
docs/architecture.mdmodified+2 -2
@@ -42,7 +42,7 @@ iz/
42 `clock.rs` (deadline + meeting time rules, inventory 2.4)42 `clock.rs` (deadline + meeting time rules, inventory 2.4)
43 - `rules/` (mail rule engine: triggers, audiences, decisions; pure where possible), `mail_text.rs` (subjects and43 - `rules/` (mail rule engine: triggers, audiences, decisions; pure where possible), `mail_text.rs` (subjects and
44 bodies for every mail kind, both languages)44 bodies for every mail kind, both languages)
45-- `sniff.rs`, `sheet.rs` (`calamine`: xlsx, xls, xlsb; values only; `.ods` is refused, not previewed; paging 50 rows × 12 columns; correct offsets45+- `sniff.rs`, `sheet.rs` (`calamine`: xlsx only; values only; `.ods` and `.xlsb` are refused, not previewed; paging 50 rows × 12 columns; correct offsets
46 for ranges not starting at A1), `slides.rs` (pptx text outline via `zip` + `quick-xml`, size and entry limits46 for ranges not starting at A1), `slides.rs` (pptx text outline via `zip` + `quick-xml`, size and entry limits
47 against zip bombs)47 against zip bombs)
48 - `store/`: `members.rs`, `sessions.rs`, `board.rs`, `tasks.rs`, `deps.rs`, `comments.rs`, `attachments.rs`,48 - `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
128 conventions. Settings: SMTP sender (password sealed), limits, batching window,128 conventions. Settings: SMTP sender (password sealed), limits, batching window,
129 reminder minutes (0–1440), allowed attachment types, attachment limit (1–500 MiB), attachment location129 reminder minutes (0–1440), allowed attachment types, attachment limit (1–500 MiB), attachment location
130 (`local`|`in`), `default_role`, `key_prefix`, retention days for activity and mail ledger (default 365),130 (`local`|`in`), `default_role`, `key_prefix`, retention days for activity and mail ledger (default 365),
131-base URL, trusted proxies.131+base URL.
132 132
133 ---133 ---
134 134
docs/conventions.mdmodified+3 -5
@@ -90,16 +90,14 @@ tokens, passwords, cookies, or secrets.
90 90
91 ## 6. Auth primitives91 ## 6. Auth primitives
92 92
93-- Passwords: argon2id (`Argon2::default()`), PHC strings, always on `spawn_blocking`. Unknown accounts verify93+- Passwords: iz holds none. People sign in at `im`, which owns passwords, second factors and their
94- against a fixed dummy hash so timing does not reveal them.94+ throttles.
95 - Tokens: 32 random bytes, base64url; stored as hex SHA-256; compared with `subtle`; shown once.95 - Tokens: 32 random bytes, base64url; stored as hex SHA-256; compared with `subtle`; shown once.
96-- Throttle (in memory, sliding window, bounded key count): failed logins per account and per IP, failed second
97- factors per user; checked before any lookup; `429` with `Retry-After`.
98 - Secrets at rest: `seal`/`open` with XChaCha20-Poly1305, `v1:` + base64(nonce || ciphertext). The instance96 - Secrets at rest: `seal`/`open` with XChaCha20-Poly1305, `v1:` + base64(nonce || ciphertext). The instance
99 key is never used directly: every use gets its own key, HMAC-SHA256(instance key, "<app> <use> v1"), and97 key is never used directly: every use gets its own key, HMAC-SHA256(instance key, "<app> <use> v1"), and
100 each seal binds its purpose (a fixed label) as associated data, so a value sealed for one purpose cannot98 each seal binds its purpose (a fixed label) as associated data, so a value sealed for one purpose cannot
101 be opened as another.99 be opened as another.
102-- Client IP: the TCP peer unless it is in `trusted_proxies`; then `X-Forwarded-For` right to left.100+- Client IP: none is read. iz ignores `X-Forwarded-For`; `trusted_proxies` is accepted, has no effect, and boot warns when it is set.
103 101
104 ## 7. Authorization102 ## 7. Authorization
105 103