forge
Explore
Log in

Don't you dare go Hollow

The address mail uses is the address the server binds

Browse files at this commit

304b2a9bdb307c35f25716952ded12ec11cca11bAhmet Kaan GümüşParent: abdae7a
  • refactor
    • the address mail uses is the address the server binds
Show full message
🔥 refactor(config): the address mail uses is the address the server binds

`base_url` is gone. It said a second time what `listen` already says, and
the two could disagree — a config claiming izlek.sh while the process
answered on 3000 mailed links nobody could click. Mail now falls back to the
address bound, and an admin's Link address in Settings still wins over it.
A bind that names no interface (0.0.0.0, ::) is reachable by no name, so the
loopback stands in.

The file is also kept complete now: a key it does not mention is appended on
boot, with its comment and the default already in force, so what can be
changed is learnt by reading the file rather than by reading the source —
`listen` had been silently defaulted in a file that never mentioned it. A
key nothing reads is named in the startup report instead of being obeyed or
refused, so a typo is visible without being a boot failure.
config/izlek.tomlmodified+4 -2
@@ -1,4 +1,6 @@
1 # Where the one database file lives. One process holds it.1 # Where the one database file lives. One process holds it.
2 database = "izlek.db"2 database = "izlek.db"
3-# The origin sign-in links in mail point at.3+# The address the server listens on. Environment variables are ignored —
4-base_url = "http://127.0.0.1:3000"4+# this is the only thing that decides where Izlek binds. It is also the
5+# address mail links fall back to, until an admin sets one in Settings.
6+listen = "127.0.0.1:3000"
crates/izlek-core/src/accounts.rsmodified+13 -11
@@ -86,14 +86,16 @@ pub struct Accounts {
86 store: Arc<dyn Store>,86 store: Arc<dyn Store>,
87 /// The origin the sign-in link in an invite mail points at, with no87 /// The origin the sign-in link in an invite mail points at, with no
88 /// trailing slash.88 /// trailing slash.
89- base_url: String,89+ /// The address a mailed link carries when no admin has set one: the
90+ /// address the process binds, from `config/izlek.toml`.
91+ fallback_url: String,
90 }92 }
91 93
92 impl Accounts {94 impl Accounts {
93- pub fn new(store: Arc<dyn Store>, base_url: impl Into<String>) -> Self {95+ pub fn new(store: Arc<dyn Store>, fallback_url: impl Into<String>) -> Self {
94 Self {96 Self {
95 store,97 store,
96- base_url: base_url.into(),98+ fallback_url: fallback_url.into(),
97 }99 }
98 }100 }
99 101
@@ -195,23 +197,23 @@ impl Accounts {
195 Ok(())197 Ok(())
196 }198 }
197 199
198- /// The address the process was configured with — what a link falls back200+ /// What a link falls back to when no admin has set an address: where the
199- /// to when no admin has set one.201+ /// process listens.
200- pub fn configured_url(&self) -> &str {202+ pub fn fallback_url(&self) -> &str {
201- &self.base_url203+ &self.fallback_url
202 }204 }
203 205
204 /// The origin a mailed link points at: the address an admin set in206 /// The origin a mailed link points at: the address an admin set in
205- /// Settings, or the one the process was configured with. A box behind a207+ /// Settings, or the one the process listens on. A box behind a proxy
206- /// proxy answers on localhost and is reached on a public name, and only208+ /// answers on localhost and is reached on a public name, and only the
207- /// the admin knows which — so the stored one wins whenever it is there.209+ /// admin knows which — so the stored one wins whenever it is there.
208 async fn base(&self) -> Result<String> {210 async fn base(&self) -> Result<String> {
209 Ok(self211 Ok(self
210 .store212 .store
211 .workspace()213 .workspace()
212 .await?214 .await?
213 .and_then(|workspace| workspace.public_url)215 .and_then(|workspace| workspace.public_url)
214- .unwrap_or_else(|| self.base_url.clone()))216+ .unwrap_or_else(|| self.fallback_url.clone()))
215 }217 }
216 218
217 async fn mint_link(&self, actor: &User, user: &User) -> Result<Invitation> {219 async fn mint_link(&self, actor: &User, user: &User) -> Result<Invitation> {
crates/izlek-core/src/config.rsmodified+207 -88
@@ -6,8 +6,7 @@
6 //! `database` does not mean "no data", it means a second Izlek quietly6 //! `database` does not mean "no data", it means a second Izlek quietly
7 //! writing a different file while everyone believes they are looking at the7 //! writing a different file while everyone believes they are looking at the
8 //! same board — and Turso is single-writer, so the two are not even8 //! same board — and Turso is single-writer, so the two are not even
9-//! reconcilable afterwards. A wrong `base_url` mails people a sign-in link9+//! reconcilable afterwards.
10-//! pointing at a host that is not us.
11 //!10 //!
12 //! Development still needs to be one command, so the *absence* of11 //! Development still needs to be one command, so the *absence* of
13 //! `config/izlek.toml` is the opt-in that takes the development defaults: the12 //! `config/izlek.toml` is the opt-in that takes the development defaults: the
@@ -19,8 +18,16 @@
19 //! choices, because it only writes when the file is not there at all.18 //! choices, because it only writes when the file is not there at all.
20 //!19 //!
21 //! Whatever is finally resolved is printed once at startup — the database20 //! Whatever is finally resolved is printed once at startup — the database
22-//! path absolute, the base URL as it will appear in mail — so "which file21+//! path absolute, the address bound, the address mail will fall back to — so
23-//! are we on" is answered by the log rather than by someone's memory.22+//! "which file are we on" is answered by the log rather than by someone's
23+//! memory.
24+//!
25+//! The file is kept complete: a key it does not mention is appended, with its
26+//! comment and the default already in effect, so reading the file is the way
27+//! to learn what can be changed. A key nobody here knows is named in the
28+//! startup report rather than obeyed or refused — a typo should be visible
29+//! without being a boot failure, and a key this file has stopped honouring
30+//! must never half-configure anything.
24 //!31 //!
25 //! The sender is not here. Host, port, username, password and from-address32 //! The sender is not here. Host, port, username, password and from-address
26 //! are workspace settings an admin writes on the Settings screen, so that33 //! are workspace settings an admin writes on the Settings screen, so that
@@ -40,24 +47,38 @@ const FILE_NAME: &str = "config/izlek.toml";
40 /// defaults, so that a plain `izlek` in an empty directory is one command.47 /// defaults, so that a plain `izlek` in an empty directory is one command.
41 const DEVELOPMENT_DEFAULTS: &str = r#"# Where the one database file lives. One process holds it.48 const DEVELOPMENT_DEFAULTS: &str = r#"# Where the one database file lives. One process holds it.
42 database = "izlek.db"49 database = "izlek.db"
43-# The origin sign-in links in mail point at.
44-base_url = "http://127.0.0.1:3000"
45 # The address the server listens on. Environment variables are ignored —50 # The address the server listens on. Environment variables are ignored —
46-# this is the only thing that decides where Izlek binds.51+# this is the only thing that decides where Izlek binds. It is also the
52+# address mail links fall back to, until an admin sets one in Settings.
47 listen = "127.0.0.1:3000"53 listen = "127.0.0.1:3000"
48 "#;54 "#;
49 55
50-/// The default `listen` when the file is silent about it — an existing56+/// The default `listen` when the file is silent about it. A file missing this
51-/// deployment's `config/izlek.toml` from before this key existed still57+/// key is completed with it on the next boot, so the silence lasts one run.
52-/// loads, and still listens where it always did.
53 const DEFAULT_LISTEN: &str = "127.0.0.1:3000";58 const DEFAULT_LISTEN: &str = "127.0.0.1:3000";
54 59
55-/// The shape of `config/izlek.toml`, before the values are checked.60+/// Every optional key, with the comment and default a file missing it is
61+/// completed with. `database` is not here: it has no default worth guessing,
62+/// so its absence stops the boot instead.
63+const OPTIONAL_KEYS: &[(&str, &str)] = &[(
64+ "listen",
65+ concat!(
66+ "# The address the server listens on. Environment variables are ignored —\n",
67+ "# this is the only thing that decides where Izlek binds. It is also the\n",
68+ "# address mail links fall back to, until an admin sets one in Settings.\n",
69+ "listen = \"127.0.0.1:3000\"\n"
70+ ),
71+)];
72+
73+/// The shape of `config/izlek.toml`, before the values are checked. Anything
74+/// else the file says lands in `other`, which is read for its key names only
75+/// — enough for the report to say a key was seen and not obeyed.
56 #[derive(Deserialize)]76 #[derive(Deserialize)]
57 struct Toml {77 struct Toml {
58 database: Option<String>,78 database: Option<String>,
59- base_url: Option<String>,
60 listen: Option<String>,79 listen: Option<String>,
80+ #[serde(flatten)]
81+ other: std::collections::BTreeMap<String, toml::Value>,
61 }82 }
62 83
63 /// What the process needs to know before it opens a socket.84 /// What the process needs to know before it opens a socket.
@@ -65,11 +86,12 @@ struct Toml {
65 pub struct Config {86 pub struct Config {
66 /// The database file, absolute. One process holds it.87 /// The database file, absolute. One process holds it.
67 pub database: PathBuf,88 pub database: PathBuf,
68- /// The origin links in mail point at, with no trailing slash.
69- pub base_url: String,
70 /// The address the server binds. The only source for this — `HOST` and89 /// The address the server binds. The only source for this — `HOST` and
71 /// `PORT` environment variables are never read.90 /// `PORT` environment variables are never read.
72 pub listen: SocketAddr,91 pub listen: SocketAddr,
92+ /// Keys the file sets that nothing here reads, in the order the file
93+ /// gives them. Named at startup so a typo is visible.
94+ pub ignored: Vec<String>,
73 /// Whether `config/izlek.toml` did not exist and was just written with the95 /// Whether `config/izlek.toml` did not exist and was just written with the
74 /// development defaults this boot.96 /// development defaults this boot.
75 pub defaulted: bool,97 pub defaulted: bool,
@@ -127,7 +149,11 @@ impl Config {
127 pub fn load_from(dir: &Path) -> Result<Config, ConfigError> {149 pub fn load_from(dir: &Path) -> Result<Config, ConfigError> {
128 let path = dir.join(FILE_NAME);150 let path = dir.join(FILE_NAME);
129 match std::fs::read_to_string(&path) {151 match std::fs::read_to_string(&path) {
130- Ok(text) => Config::parse(&text, dir, false),152+ Ok(text) => {
153+ let config = Config::parse(&text, dir, false)?;
154+ complete(&path, &text);
155+ Ok(config)
156+ }
131 Err(err) if err.kind() == std::io::ErrorKind::NotFound => {157 Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
132 if let Some(parent) = path.parent() {158 if let Some(parent) = path.parent() {
133 std::fs::create_dir_all(parent).map_err(|err| {159 std::fs::create_dir_all(parent).map_err(|err| {
@@ -158,15 +184,6 @@ impl Config {
158 let value = |raw: Option<String>| raw.filter(|value| !value.trim().is_empty());184 let value = |raw: Option<String>| raw.filter(|value| !value.trim().is_empty());
159 185
160 let database = value(toml.database).ok_or(ConfigError::Missing("database"))?;186 let database = value(toml.database).ok_or(ConfigError::Missing("database"))?;
161- let base_url = value(toml.base_url).ok_or(ConfigError::Missing("base_url"))?;
162-
163- if !(base_url.starts_with("http://") || base_url.starts_with("https://")) {
164- return Err(ConfigError::Invalid {
165- key: "base_url",
166- why: format!("{base_url:?} is not an http:// or https:// origin"),
167- });
168- }
169- let base_url = base_url.trim_end_matches('/').to_string();
170 187
171 let listen = value(toml.listen).unwrap_or_else(|| DEFAULT_LISTEN.to_string());188 let listen = value(toml.listen).unwrap_or_else(|| DEFAULT_LISTEN.to_string());
172 let listen: SocketAddr = listen.parse().map_err(|err| ConfigError::Invalid {189 let listen: SocketAddr = listen.parse().map_err(|err| ConfigError::Invalid {
@@ -176,20 +193,49 @@ impl Config {
176 193
177 Ok(Config {194 Ok(Config {
178 database: absolute(dir, Path::new(&database)),195 database: absolute(dir, Path::new(&database)),
179- base_url,
180 listen,196 listen,
197+ ignored: toml.other.into_keys().collect(),
181 defaulted,198 defaulted,
182 })199 })
183 }200 }
184 201
202+ /// The address a mailed link points at until an admin sets one in
203+ /// Settings: the address the server binds, as a URL.
204+ ///
205+ /// A bind that names no interface — `0.0.0.0`, `::` — answers everywhere
206+ /// and is reachable at none of it by name, so the loopback stands in: a
207+ /// link somebody on the box can click beats a link nobody can. Whoever
208+ /// puts Izlek behind a proxy sets the real address in Settings, which is
209+ /// the only thing this defers to.
210+ pub fn listen_url(&self) -> String {
211+ let ip = self.listen.ip();
212+ let host = if ip.is_unspecified() {
213+ "127.0.0.1".to_string()
214+ } else if self.listen.is_ipv6() {
215+ format!("[{ip}]")
216+ } else {
217+ ip.to_string()
218+ };
219+ match self.listen.port() {
220+ 80 => format!("http://{host}"),
221+ port => format!("http://{host}:{port}"),
222+ }
223+ }
224+
185 /// The lines to print once at startup. Nothing secret is among them.225 /// The lines to print once at startup. Nothing secret is among them.
186 pub fn report(&self) -> Vec<String> {226 pub fn report(&self) -> Vec<String> {
187 let mut lines = vec![227 let mut lines = vec![
188 format!("database {}", self.database.display()),228 format!("database {}", self.database.display()),
189- format!("base url {}", self.base_url),
190 format!("listen {}", self.listen),229 format!("listen {}", self.listen),
230+ format!("mail url {} until an admin sets one", self.listen_url()),
191 ];231 ];
192 lines.push("mail the sender is in Settings, not here".to_string());232 lines.push("mail the sender is in Settings, not here".to_string());
233+ if !self.ignored.is_empty() {
234+ lines.push(format!(
235+ "ignored {FILE_NAME} sets {}, which nothing reads",
236+ self.ignored.join(", ")
237+ ));
238+ }
193 if self.defaulted {239 if self.defaulted {
194 lines.push(format!(240 lines.push(format!(
195 "dev {FILE_NAME} did not exist, development defaults written and taken"241 "dev {FILE_NAME} did not exist, development defaults written and taken"
@@ -199,6 +245,54 @@ impl Config {
199 }245 }
200 }246 }
201 247
248+/// Appends the keys the file does not mention, each with its own comment and
249+/// the default already in effect. The file is how a reader learns what can be
250+/// changed, so a key that is silently defaulted is a key nobody discovers.
251+///
252+/// Only ever adds, never rewrites: whatever else the file says — comments,
253+/// ordering, a value somebody chose — is theirs. A file that cannot be
254+/// written is not a reason not to start; the defaults it is missing are the
255+/// ones already in force, so the run is correct either way and the note says
256+/// what could not be done.
257+fn complete(path: &Path, text: &str) {
258+ let missing: Vec<&str> = OPTIONAL_KEYS
259+ .iter()
260+ .filter(|(key, _)| !mentions(text, key))
261+ .map(|(_, block)| *block)
262+ .collect();
263+ if missing.is_empty() {
264+ return;
265+ }
266+ let mut completed = text.to_string();
267+ if !completed.is_empty() && !completed.ends_with('\n') {
268+ completed.push('\n');
269+ }
270+ completed.push('\n');
271+ completed.push_str(&missing.join("\n"));
272+ match std::fs::write(path, completed) {
273+ Ok(()) => println!(
274+ "izlek added {} to {FILE_NAME}, at the default already in use",
275+ OPTIONAL_KEYS
276+ .iter()
277+ .filter(|(key, _)| !mentions(text, key))
278+ .map(|(key, _)| *key)
279+ .collect::<Vec<_>>()
280+ .join(", ")
281+ ),
282+ Err(err) => println!("izlek could not complete {FILE_NAME}: {err}"),
283+ }
284+}
285+
286+/// Whether the file sets this key — a line whose first word it is. A key
287+/// named inside a comment or a value does not count.
288+fn mentions(text: &str, key: &str) -> bool {
289+ text.lines().any(|line| {
290+ line.trim_start()
291+ .strip_prefix(key)
292+ .is_some_and(|rest| rest.trim_start().starts_with('='))
293+ })
294+}
295+
202 /// An absolute path for a file that may not exist yet: the directory is296 /// An absolute path for a file that may not exist yet: the directory is
203 /// resolved against `base` (the directory `config/izlek.toml` was read297 /// resolved against `base` (the directory `config/izlek.toml` was read
204 /// from), the file name is kept as written.298 /// from), the file name is kept as written.
@@ -248,8 +342,8 @@ mod tests {
248 assert!(config.defaulted);342 assert!(config.defaulted);
249 assert!(config.database.is_absolute(), "{:?}", config.database);343 assert!(config.database.is_absolute(), "{:?}", config.database);
250 assert!(config.database.ends_with("izlek.db"));344 assert!(config.database.ends_with("izlek.db"));
251- assert_eq!(config.base_url, "http://127.0.0.1:3000");
252 assert_eq!(config.listen, "127.0.0.1:3000".parse().unwrap());345 assert_eq!(config.listen, "127.0.0.1:3000".parse().unwrap());
346+ assert_eq!(config.listen_url(), "http://127.0.0.1:3000");
253 347
254 let written = std::fs::read_to_string(dir.join(FILE_NAME)).unwrap();348 let written = std::fs::read_to_string(dir.join(FILE_NAME)).unwrap();
255 assert_eq!(written, DEVELOPMENT_DEFAULTS);349 assert_eq!(written, DEVELOPMENT_DEFAULTS);
@@ -258,23 +352,59 @@ mod tests {
258 let again = Config::load_from(&dir).unwrap();352 let again = Config::load_from(&dir).unwrap();
259 assert!(!again.defaulted);353 assert!(!again.defaulted);
260 assert_eq!(again, Config { defaulted: false, ..config });354 assert_eq!(again, Config { defaulted: false, ..config });
355+ let _ = std::fs::remove_dir_all(&dir);
261 }356 }
262 357
358+ /// Every key the file can carry is written into a file that was made
359+ /// without it, so what can be changed is learnt by reading the file
360+ /// rather than by reading the source.
263 #[test]361 #[test]
264- fn an_empty_string_is_not_a_value() {362+ fn a_file_missing_a_key_is_completed_with_it() {
265- let problem = Config::parse(363+ let dir = scratch();
266- "database = \" \"\nbase_url = \"https://izlek.sh\"\n",364+ std::fs::create_dir_all(dir.join("config")).unwrap();
267- Path::new("."),365+ std::fs::write(
268- false,366+ dir.join(FILE_NAME),
367+ "# mine\ndatabase = \"state/izlek.db\"\n",
269 )368 )
270- .unwrap_err();369+ .unwrap();
370+
371+ let config = Config::load_from(&dir).unwrap();
372+ assert_eq!(config.listen, "127.0.0.1:3000".parse().unwrap());
373+
374+ let written = std::fs::read_to_string(dir.join(FILE_NAME)).unwrap();
375+ assert!(written.contains("listen = \"127.0.0.1:3000\""), "{written}");
376+ // What was there is untouched, comment and all.
377+ assert!(written.starts_with("# mine\ndatabase = \"state/izlek.db\"\n"), "{written}");
378+
379+ // Completing is not rewriting: a second load leaves the file alone.
380+ Config::load_from(&dir).unwrap();
381+ assert_eq!(std::fs::read_to_string(dir.join(FILE_NAME)).unwrap(), written);
382+ let _ = std::fs::remove_dir_all(&dir);
383+ }
384+
385+ /// A key that is already set is not touched, whatever its value.
386+ #[test]
387+ fn completion_leaves_a_key_that_is_already_there() {
388+ let dir = scratch();
389+ std::fs::create_dir_all(dir.join("config")).unwrap();
390+ let mine = "database = \"izlek.db\"\nlisten = \"0.0.0.0:8080\"\n";
391+ std::fs::write(dir.join(FILE_NAME), mine).unwrap();
392+ let config = Config::load_from(&dir).unwrap();
393+ assert_eq!(config.listen, "0.0.0.0:8080".parse().unwrap());
394+ assert_eq!(std::fs::read_to_string(dir.join(FILE_NAME)).unwrap(), mine);
395+ let _ = std::fs::remove_dir_all(&dir);
396+ }
397+
398+ #[test]
399+ fn an_empty_string_is_not_a_value() {
400+ let problem = Config::parse("database = \" \"\n", Path::new("."), false).unwrap_err();
271 assert_eq!(problem, ConfigError::Missing("database"));401 assert_eq!(problem, ConfigError::Missing("database"));
272 }402 }
273 403
274 #[test]404 #[test]
275 fn a_missing_key_names_itself_rather_than_guessing() {405 fn a_missing_key_names_itself_rather_than_guessing() {
276- let problem = Config::parse("base_url = \"https://izlek.sh\"\n", Path::new("."), false)406+ let problem =
277- .unwrap_err();407+ Config::parse("listen = \"127.0.0.1:3000\"\n", Path::new("."), false).unwrap_err();
278 assert_eq!(problem, ConfigError::Missing("database"));408 assert_eq!(problem, ConfigError::Missing("database"));
279 let said = problem.to_string();409 let said = problem.to_string();
280 assert!(said.contains("database"), "{said}");410 assert!(said.contains("database"), "{said}");
@@ -283,8 +413,8 @@ mod tests {
283 413
284 #[test]414 #[test]
285 fn unparseable_toml_names_the_file_not_a_stack_trace() {415 fn unparseable_toml_names_the_file_not_a_stack_trace() {
286- let problem = Config::parse("this is not toml at all {{{", Path::new("."), false)416+ let problem =
287- .unwrap_err();417+ Config::parse("this is not toml at all {{{", Path::new("."), false).unwrap_err();
288 assert!(418 assert!(
289 matches!(problem, ConfigError::Unparseable { .. }),419 matches!(problem, ConfigError::Unparseable { .. }),
290 "{problem:?}"420 "{problem:?}"
@@ -295,12 +425,7 @@ mod tests {
295 #[test]425 #[test]
296 fn a_relative_database_is_reported_absolute() {426 fn a_relative_database_is_reported_absolute() {
297 let dir = scratch();427 let dir = scratch();
298- let config = Config::parse(428+ let config = Config::parse("database = \"state/izlek.db\"\n", &dir, false).unwrap();
299- "database = \"state/izlek.db\"\nbase_url = \"https://izlek.sh\"\n",
300- &dir,
301- false,
302- )
303- .unwrap();
304 assert!(config.database.is_absolute(), "{:?}", config.database);429 assert!(config.database.is_absolute(), "{:?}", config.database);
305 assert!(config.database.ends_with("izlek.db"));430 assert!(config.database.ends_with("izlek.db"));
306 let report = config.report().join("\n");431 let report = config.report().join("\n");
@@ -308,45 +433,21 @@ mod tests {
308 report.contains(&config.database.display().to_string()),433 report.contains(&config.database.display().to_string()),
309 "{report}"434 "{report}"
310 );435 );
436+ let _ = std::fs::remove_dir_all(&dir);
311 }437 }
312 438
313- #[test]439+ /// A file written before `listen` existed still loads, and still binds
314- fn a_base_url_that_is_not_an_origin_stops_the_boot() {440+ /// where it always did.
315- let problem = Config::parse(
316- "database = \"/srv/izlek.db\"\nbase_url = \"izlek.sh\"\n",
317- Path::new("."),
318- false,
319- )
320- .unwrap_err();
321- assert!(
322- matches!(
323- problem,
324- ConfigError::Invalid {
325- key: "base_url",
326- ..
327- }
328- ),
329- "{problem:?}"
330- );
331- }
332-
333- /// A `config/izlek.toml` written before `listen` existed must still load,
334- /// and must still bind where it always did.
335 #[test]441 #[test]
336 fn a_file_without_listen_falls_back_to_the_old_default() {442 fn a_file_without_listen_falls_back_to_the_old_default() {
337- let config = Config::parse(443+ let config = Config::parse("database = \"/srv/izlek.db\"\n", Path::new("."), false).unwrap();
338- "database = \"/srv/izlek.db\"\nbase_url = \"https://izlek.sh\"\n",
339- Path::new("."),
340- false,
341- )
342- .unwrap();
343 assert_eq!(config.listen, "127.0.0.1:3000".parse().unwrap());444 assert_eq!(config.listen, "127.0.0.1:3000".parse().unwrap());
344 }445 }
345 446
346 #[test]447 #[test]
347 fn an_unparseable_listen_stops_the_boot_naming_the_key() {448 fn an_unparseable_listen_stops_the_boot_naming_the_key() {
348 let problem = Config::parse(449 let problem = Config::parse(
349- "database = \"/srv/izlek.db\"\nbase_url = \"https://izlek.sh\"\nlisten = \"not an address\"\n",450+ "database = \"/srv/izlek.db\"\nlisten = \"not an address\"\n",
350 Path::new("."),451 Path::new("."),
351 false,452 false,
352 )453 )
@@ -357,36 +458,54 @@ mod tests {
357 );458 );
358 }459 }
359 460
461+ /// The address mail falls back to is the address the server answers on —
462+ /// there is no second key to keep in step with the first.
360 #[test]463 #[test]
361- fn the_base_url_keeps_no_trailing_slash_so_links_are_built_once() {464+ fn the_mail_fallback_is_the_address_the_server_binds() {
362- let config = Config::parse(465+ let url = |listen: &str| {
363- "database = \"/srv/izlek.db\"\nbase_url = \"https://izlek.sh/\"\n",466+ Config::parse(
364- Path::new("."),467+ &format!("database = \"/srv/izlek.db\"\nlisten = \"{listen}\"\n"),
365- false,468+ Path::new("."),
366- )469+ false,
367- .unwrap();470+ )
368- assert_eq!(config.base_url, "https://izlek.sh");471+ .unwrap()
472+ .listen_url()
473+ };
474+ assert_eq!(url("127.0.0.1:3000"), "http://127.0.0.1:3000");
475+ assert_eq!(url("192.168.1.20:8080"), "http://192.168.1.20:8080");
476+ // Port 80 is the one a URL does not say.
477+ assert_eq!(url("10.0.0.4:80"), "http://10.0.0.4");
478+ // A bind that names no interface is reachable by no name, so the
479+ // loopback stands in: a link somebody on the box can click beats a
480+ // link nobody can.
481+ assert_eq!(url("0.0.0.0:3000"), "http://127.0.0.1:3000");
482+ assert_eq!(url("[::]:3000"), "http://127.0.0.1:3000");
483+ assert_eq!(url("[::1]:3000"), "http://[::1]:3000");
369 }484 }
370 485
371- /// The sender used to be environment variables read directly. It is486+ /// The sender used to be environment variables read directly, and the
372- /// workspace settings now, so unrelated keys left in the file must do487+ /// base URL used to be a key of its own. Both are gone, so a file that
373- /// nothing at all — not half-configure a sender, not stop the boot, and488+ /// still carries them must do nothing at all — not half-configure a
374- /// above all not quietly send through an account the Settings screen489+ /// sender, not stop the boot, and above all not quietly send through an
375- /// does not show.490+ /// account the Settings screen does not show. The report says they were
491+ /// seen, so a typo is visible too.
376 #[test]492 #[test]
377- fn unrelated_keys_are_ignored_entirely() {493+ fn keys_nothing_reads_are_named_rather_than_obeyed() {
378 let config = Config::parse(494 let config = Config::parse(
379- "database = \"/srv/izlek.db\"\nbase_url = \"https://izlek.sh\"\nsmtp_password = \"hunter2-and-then-some\"\n",495+ "database = \"/srv/izlek.db\"\nbase_url = \"https://izlek.sh\"\n\
496+ smtp_password = \"hunter2-and-then-some\"\n",
380 Path::new("."),497 Path::new("."),
381 false,498 false,
382 )499 )
383- .expect("an unrelated key in the file is not an error");500+ .expect("a key the file no longer honours is not an error");
384 501
502+ assert_eq!(config.ignored, vec!["base_url", "smtp_password"]);
385 let report = config.report().join("\n");503 let report = config.report().join("\n");
386 assert!(504 assert!(
387 !report.contains("hunter2-and-then-some"),505 !report.contains("hunter2-and-then-some"),
388 "the report read a key it no longer honours: {report}"506 "the report read a key it no longer honours: {report}"
389 );507 );
508+ assert!(report.contains("base_url"), "{report}");
390 assert!(509 assert!(
391 report.contains("the sender is in Settings"),510 report.contains("the sender is in Settings"),
392 "the report should say where the sender lives: {report}"511 "the report should say where the sender lives: {report}"
crates/izlek-core/src/mail.rsmodified+10 -7
@@ -130,19 +130,21 @@ pub struct Engine {
130 store: Arc<dyn Store>,130 store: Arc<dyn Store>,
131 mailer: Arc<dyn Mailer>,131 mailer: Arc<dyn Mailer>,
132 /// The origin links in mail point at, with no trailing slash.132 /// The origin links in mail point at, with no trailing slash.
133- base_url: String,133+ /// Where a mailed link points when no admin has set an address: the
134+ /// address the process listens on.
135+ fallback_url: String,
134 }136 }
135 137
136 impl Engine {138 impl Engine {
137 pub fn new(139 pub fn new(
138 store: Arc<dyn Store>,140 store: Arc<dyn Store>,
139 mailer: Arc<dyn Mailer>,141 mailer: Arc<dyn Mailer>,
140- base_url: impl Into<String>,142+ fallback_url: impl Into<String>,
141 ) -> Self {143 ) -> Self {
142 Self {144 Self {
143 store,145 store,
144 mailer,146 mailer,
145- base_url: base_url.into(),147+ fallback_url: fallback_url.into(),
146 }148 }
147 }149 }
148 150
@@ -719,15 +721,16 @@ impl Engine {
719 | ActivityKind::Other(_) => format!("{} touched it.", actor),721 | ActivityKind::Other(_) => format!("{} touched it.", actor),
720 },722 },
721 };723 };
722- // The address an admin set in Settings wins over the configured one:724+ // The address an admin set in Settings wins over the one the process
723- // a box behind a proxy answers on localhost and is reached on a725+ // listens on: a box behind a proxy answers on localhost and is
724- // public name, and a mail nobody can click is a mail not sent.726+ // reached on a public name, and a mail nobody can click is a mail
727+ // not sent.
725 let base = self728 let base = self
726 .store729 .store
727 .workspace()730 .workspace()
728 .await?731 .await?
729 .and_then(|workspace| workspace.public_url)732 .and_then(|workspace| workspace.public_url)
730- .unwrap_or_else(|| self.base_url.clone());733+ .unwrap_or_else(|| self.fallback_url.clone());
731 let mut body = format!(734 let mut body = format!(
732 "{key} — {title}\n\n{happened}\n\n{when}\n\n{base}/?task={id}\n",735 "{key} — {title}\n\n{happened}\n\n{when}\n\n{base}/?task={id}\n",
733 key = facts.row.task_key,736 key = facts.row.task_key,
crates/izlek-core/src/store/mod.rsmodified+4 -4
@@ -72,9 +72,9 @@ pub struct Workspace {
72 pub photo_limit_bytes: u64,72 pub photo_limit_bytes: u64,
73 pub allowed_file_types: Vec<String>,73 pub allowed_file_types: Vec<String>,
74 /// The origin mail links point at, when an admin has set one. `None`74 /// The origin mail links point at, when an admin has set one. `None`
75- /// means the address the process was configured with — a box behind a75+ /// means the address the process listens on — a box behind a proxy
76- /// proxy answers on localhost and is reached on a public name, and only76+ /// answers on localhost and is reached on a public name, and only an
77- /// an admin knows which.77+ /// admin knows which.
78 pub public_url: Option<String>,78 pub public_url: Option<String>,
79 }79 }
80 80
@@ -624,7 +624,7 @@ pub trait Store: BoardReads + DetailReads + 'static {
624 async fn smtp_password(&self, workspace_id: &str) -> Result<Option<String>>;624 async fn smtp_password(&self, workspace_id: &str) -> Result<Option<String>>;
625 625
626 /// Writes the address mail links point at. `None` clears it, and the626 /// Writes the address mail links point at. `None` clears it, and the
627- /// configured `base_url` is what a cleared one falls back to.627+ /// address the process listens on is what a cleared one falls back to.
628 async fn set_public_url(&self, workspace_id: &str, public_url: Option<&str>) -> Result<()>;628 async fn set_public_url(&self, workspace_id: &str, public_url: Option<&str>) -> Result<()>;
629 629
630 async fn set_limits(630 async fn set_limits(
crates/izlek-web/src/main.rsmodified+3 -2
@@ -38,7 +38,8 @@ async fn main() {
38 .await38 .await
39 .expect("failed to open the database");39 .expect("failed to open the database");
40 let store: Arc<dyn izlek_core::store::Store> = Arc::new(store);40 let store: Arc<dyn izlek_core::store::Store> = Arc::new(store);
41- let accounts = Accounts::new(store.clone(), config.base_url.clone());41+ // The address mail links carry when no admin has set one in Settings.
42+ let accounts = Accounts::new(store.clone(), config.listen_url());
42 43
43 // The engine is always built, because a sender can appear at any moment:44 // The engine is always built, because a sender can appear at any moment:
44 // an admin fills the panel in and the next sweep sends what was held. It45 // an admin fills the panel in and the next sweep sends what was held. It
@@ -47,7 +48,7 @@ async fn main() {
47 let engine = Arc::new(izlek_core::MailEngine::new(48 let engine = Arc::new(izlek_core::MailEngine::new(
48 store.clone(),49 store.clone(),
49 Arc::new(izlek_web::smtp::WorkspaceSmtp::new(store.clone())),50 Arc::new(izlek_web::smtp::WorkspaceSmtp::new(store.clone())),
50- config.base_url.clone(),51+ config.listen_url(),
51 ));52 ));
52 tokio::spawn(sweep(engine.clone()));53 tokio::spawn(sweep(engine.clone()));
53 54
crates/izlek-web/src/settings.rsmodified+1 -1
@@ -1033,7 +1033,7 @@ async fn settings_page(cx: &Cx) -> Result {
1033 let zone = izlek_core::detail::parse_zone(&user.timezone);1033 let zone = izlek_core::detail::parse_zone(&user.timezone);
1034 // What a link falls back to when the field is empty — the placeholder1034 // What a link falls back to when the field is empty — the placeholder
1035 // shows it rather than an invented example.1035 // shows it rather than an invented example.
1036- let configured_url = accounts(cx).configured_url().to_string();1036+ let configured_url = accounts(cx).fallback_url().to_string();
1037 let sender = if administers {1037 let sender = if administers {
1038 Some(sender_now(cx, zone).await?)1038 Some(sender_now(cx, zone).await?)
1039 } else {1039 } else {