forge
Explore
Log in

Don't you dare go Hollow

The admin sets the address mail links point at

Browse files at this commit

1497e100795cc2b7d00ce3946bfa5cba69890fabAhmet Kaan GümüşParent: 8b504c3
  • feat
    • the admin sets the address mail links point at
Show full message
✨ feat(settings): the admin sets the address mail links point at

A box behind a proxy answers on localhost and is reached on a public name,
so every mailed link carried the wrong origin. The outgoing mail panel now
takes a link address, stored on the workspace and used by both the sign-in
mail and every rule mail; empty falls back to config/izlek.toml's base_url,
which the field shows as its placeholder. A trailing slash is trimmed and
anything that is not an http:// or https:// origin is refused.

Also fits the sheet viewer inside its panel: the viewer body is a row flex,
so without a min-width the sheet's automatic minimum size was the whole
table's width and a wide book pushed the panel off the screen instead of
panning inside it.
crates/izlek-core/migrations/0002_public_url.sqladded+6 -0
@@ -0,0 +1,6 @@
1+-- The address mail points at, when it is not the one the process was
2+-- configured with. A box behind a proxy answers on localhost and is reached
3+-- on a public name, and only an admin knows which — so this is workspace
4+-- content, edited in Settings, and `config/izlek.toml`'s `base_url` is what
5+-- it falls back to.
6+ALTER TABLE workspace ADD COLUMN public_url TEXT;
crates/izlek-core/src/accounts.rsmodified+20 -1
@@ -195,6 +195,25 @@ impl Accounts {
195 Ok(())195 Ok(())
196 }196 }
197 197
198+ /// The address the process was configured with — what a link falls back
199+ /// to when no admin has set one.
200+ pub fn configured_url(&self) -> &str {
201+ &self.base_url
202+ }
203+
204+ /// 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 a
206+ /// proxy answers on localhost and is reached on a public name, and only
207+ /// the admin knows which — so the stored one wins whenever it is there.
208+ async fn base(&self) -> Result<String> {
209+ Ok(self
210+ .store
211+ .workspace()
212+ .await?
213+ .and_then(|workspace| workspace.public_url)
214+ .unwrap_or_else(|| self.base_url.clone()))
215+ }
216+
198 async fn mint_link(&self, actor: &User, user: &User) -> Result<Invitation> {217 async fn mint_link(&self, actor: &User, user: &User) -> Result<Invitation> {
199 let token = Token::mint();218 let token = Token::mint();
200 let expires_at = OffsetDateTime::now_utc() + SIGNIN_LINK_LIFETIME;219 let expires_at = OffsetDateTime::now_utc() + SIGNIN_LINK_LIFETIME;
@@ -205,7 +224,7 @@ impl Accounts {
205 let body = format!(224 let body = format!(
206 "{actor} added you to Izlek.\n\n{base}/join/{token}\n\nThe link works once and expires in 7 days.\n",225 "{actor} added you to Izlek.\n\n{base}/join/{token}\n\nThe link works once and expires in 7 days.\n",
207 actor = actor.display_name,226 actor = actor.display_name,
208- base = self.base_url,227+ base = self.base().await?,
209 token = token.expose(),228 token = token.expose(),
210 );229 );
211 self.store230 self.store
crates/izlek-core/src/mail.rsmodified+9 -1
@@ -719,12 +719,20 @@ impl Engine {
719 | ActivityKind::Other(_) => format!("{} touched it.", actor),719 | ActivityKind::Other(_) => format!("{} touched it.", actor),
720 },720 },
721 };721 };
722+ // The address an admin set in Settings wins over the configured one:
723+ // a box behind a proxy answers on localhost and is reached on a
724+ // public name, and a mail nobody can click is a mail not sent.
725+ let base = self
726+ .store
727+ .workspace()
728+ .await?
729+ .and_then(|workspace| workspace.public_url)
730+ .unwrap_or_else(|| self.base_url.clone());
722 let mut body = format!(731 let mut body = format!(
723 "{key} — {title}\n\n{happened}\n\n{when}\n\n{base}/?task={id}\n",732 "{key} — {title}\n\n{happened}\n\n{when}\n\n{base}/?task={id}\n",
724 key = facts.row.task_key,733 key = facts.row.task_key,
725 title = facts.row.title,734 title = facts.row.title,
726 when = day_and_time(event.at()),735 when = day_and_time(event.at()),
727- base = self.base_url,
728 id = facts.row.id,736 id = facts.row.id,
729 );737 );
730 if rule.include_task_details {738 if rule.include_task_details {
crates/izlek-core/src/store/mod.rsmodified+9 -0
@@ -71,6 +71,11 @@ pub struct Workspace {
71 pub attachment_limit_bytes: u64,71 pub attachment_limit_bytes: u64,
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`
75+ /// means the address the process was configured with — a box behind a
76+ /// proxy answers on localhost and is reached on a public name, and only
77+ /// an admin knows which.
78+ pub public_url: Option<String>,
74 }79 }
75 80
76 /// One file hung off a task, as a screen lists it: a name, a type, a size and81 /// One file hung off a task, as a screen lists it: a name, a type, a size and
@@ -618,6 +623,10 @@ pub trait Store: BoardReads + DetailReads + 'static {
618 /// returns reaches a response body.623 /// returns reaches a response body.
619 async fn smtp_password(&self, workspace_id: &str) -> Result<Option<String>>;624 async fn smtp_password(&self, workspace_id: &str) -> Result<Option<String>>;
620 625
626+ /// Writes the address mail links point at. `None` clears it, and the
627+ /// configured `base_url` is what a cleared one falls back to.
628+ async fn set_public_url(&self, workspace_id: &str, public_url: Option<&str>) -> Result<()>;
629+
621 async fn set_limits(630 async fn set_limits(
622 &self,631 &self,
623 workspace_id: &str,632 workspace_id: &str,
crates/izlek-core/src/store/turso_store.rsmodified+15 -1
@@ -33,6 +33,7 @@ use time::macros::format_description;
33 /// Every migration, in order. Adding one means appending a file and a line.33 /// Every migration, in order. Adding one means appending a file and a line.
34 const MIGRATIONS: &[(i64, &str)] = &[34 const MIGRATIONS: &[(i64, &str)] = &[
35 (1, include_str!("../../migrations/0001_init.sql")),35 (1, include_str!("../../migrations/0001_init.sql")),
36+ (2, include_str!("../../migrations/0002_public_url.sql")),
36 ];37 ];
37 38
38 /// The board a fresh workspace gets, and its columns. `Done` is the column39 /// The board a fresh workspace gets, and its columns. `Done` is the column
@@ -562,6 +563,7 @@ fn workspace_from(row: &Row) -> Result<Workspace> {
562 }),563 }),
563 None => None,564 None => None,
564 },565 },
566+ public_url: opt_text(row, 15)?,
565 })567 })
566 }568 }
567 569
@@ -572,7 +574,7 @@ const WORKSPACE_COLUMNS: &str = "id, name, created_at, attachment_limit_bytes, \
572 allowed_file_types, photo_limit_bytes, smtp_host, smtp_port, smtp_username, \574 allowed_file_types, photo_limit_bytes, smtp_host, smtp_port, smtp_username, \
573 smtp_from_name, smtp_from_address, \575 smtp_from_name, smtp_from_address, \
574 (smtp_password IS NOT NULL AND smtp_password <> ''), \576 (smtp_password IS NOT NULL AND smtp_password <> ''), \
575- smtp_test_at, smtp_test_ms, smtp_test_error";577+ smtp_test_at, smtp_test_ms, smtp_test_error, public_url";
576 578
577 fn user_from(row: &Row) -> Result<User> {579 fn user_from(row: &Row) -> Result<User> {
578 Ok(User {580 Ok(User {
@@ -820,6 +822,18 @@ impl Store for TursoStore {
820 Ok(sealed.as_deref().and_then(|s| secret::open(&self.key, s)))822 Ok(sealed.as_deref().and_then(|s| secret::open(&self.key, s)))
821 }823 }
822 824
825+ async fn set_public_url(&self, workspace_id: &str, public_url: Option<&str>) -> Result<()> {
826+ let conn = self.conn.lock().await;
827+ conn
828+ .execute(
829+ "UPDATE workspace SET public_url = ?1 WHERE id = ?2",
830+ params![public_url, workspace_id],
831+ )
832+ .await
833+ .map_err(backend)?;
834+ Ok(())
835+ }
836+
823 async fn set_limits(837 async fn set_limits(
824 &self,838 &self,
825 workspace_id: &str,839 workspace_id: &str,
crates/izlek-core/tests/store.rsmodified+47 -2
@@ -101,14 +101,14 @@ async fn migrations_apply_once_and_survive_reopen() {
101 let path = dir.join("izlek.db").to_string_lossy().into_owned();101 let path = dir.join("izlek.db").to_string_lossy().into_owned();
102 102
103 let first = TursoStore::open(&path).await.unwrap();103 let first = TursoStore::open(&path).await.unwrap();
104- assert_eq!(first.schema_version().await.unwrap(), 1);104+ assert_eq!(first.schema_version().await.unwrap(), 2);
105 claim(&first).await;105 claim(&first).await;
106 drop(first);106 drop(first);
107 107
108 // Re-opening must not re-run 0001 (which would fail on CREATE TABLE) and108 // Re-opening must not re-run 0001 (which would fail on CREATE TABLE) and
109 // must not lose what the first open wrote.109 // must not lose what the first open wrote.
110 let second = TursoStore::open(&path).await.unwrap();110 let second = TursoStore::open(&path).await.unwrap();
111- assert_eq!(second.schema_version().await.unwrap(), 1);111+ assert_eq!(second.schema_version().await.unwrap(), 2);
112 assert_eq!(second.workspace().await.unwrap().unwrap().name, "Izlek");112 assert_eq!(second.workspace().await.unwrap().unwrap().name, "Izlek");
113 drop(second);113 drop(second);
114 let _ = std::fs::remove_dir_all(&dir);114 let _ = std::fs::remove_dir_all(&dir);
@@ -5654,3 +5654,48 @@ async fn an_every_column_rule_survives_the_round_trip() {
5654 let _ = admin;5654 let _ = admin;
5655 let _ = std::fs::remove_dir_all(&dir);5655 let _ = std::fs::remove_dir_all(&dir);
5656 }5656 }
5657+
5658+/// A box behind a proxy answers on one address and is reached on another, so
5659+/// an admin can set the origin mail links point at. What is stored wins over
5660+/// what the process was configured with.
5661+#[tokio::test]
5662+async fn a_stored_address_is_the_one_mail_links_point_at() {
5663+ let (dir, store, workspace, admin) = shared().await;
5664+ let mate = member(&store, &workspace, "emre@izlek.sh", "Emre").await;
5665+ let task = add_task(&store, &workspace, "Backlog", "Ship it", None, &admin).await;
5666+ store.assign_task(&task, &mate).await.unwrap();
5667+ a_rule(&store, &workspace, "Done", "Task completed").await;
5668+ store
5669+ .set_public_url(&workspace, Some("https://board.example"))
5670+ .await
5671+ .unwrap();
5672+
5673+ let mailer = Remembering::taking_everything();
5674+ let engine = Engine::new(store.clone(), mailer.clone(), "http://127.0.0.1:3000");
5675+ let moved = moved_to(&store, &workspace, &task, "Backlog", "Done", &admin).await;
5676+ engine.on_transition(&moved).await.unwrap();
5677+
5678+ let sent = mailer.sent();
5679+ assert!(
5680+ sent[0].body.contains("https://board.example/?task="),
5681+ "the mail did not use the stored address: {}",
5682+ sent[0].body
5683+ );
5684+
5685+ // Cleared, the configured address is what is left.
5686+ store.set_public_url(&workspace, None).await.unwrap();
5687+ let back = add_task(&store, &workspace, "Backlog", "Ship it too", None, &admin).await;
5688+ store.assign_task(&back, &mate).await.unwrap();
5689+ let moved = moved_to(&store, &workspace, &back, "Backlog", "Done", &admin).await;
5690+ engine.on_transition(&moved).await.unwrap();
5691+ let sent = mailer.sent();
5692+ assert!(
5693+ sent.last()
5694+ .unwrap()
5695+ .body
5696+ .contains("http://127.0.0.1:3000/?task="),
5697+ "a cleared address did not fall back: {}",
5698+ sent.last().unwrap().body
5699+ );
5700+ let _ = std::fs::remove_dir_all(&dir);
5701+}
crates/izlek-web/src/i18n.rsmodified+6 -0
@@ -161,6 +161,8 @@ pub enum Key {
161 SmtpUsernameRequired,161 SmtpUsernameRequired,
162 PasswordNeededFirstTime,162 PasswordNeededFirstTime,
163 NotFromAddress,163 NotFromAddress,
164+ NotAnOrigin,
165+ LinkAddressLabel,
164 SenderNotConfiguredYet,166 SenderNotConfiguredYet,
165 167
166 // pages.rs168 // pages.rs
@@ -598,6 +600,10 @@ pub fn t(lang: Lang, key: Key) -> &'static str {
598 (PasswordNeededFirstTime, Tr) => "İlk seferde bir parola gerekir.",600 (PasswordNeededFirstTime, Tr) => "İlk seferde bir parola gerekir.",
599 (NotFromAddress, En) => "That is not a from-address.",601 (NotFromAddress, En) => "That is not a from-address.",
600 (NotFromAddress, Tr) => "Bu bir gönderen adresi değil.",602 (NotFromAddress, Tr) => "Bu bir gönderen adresi değil.",
603+ (NotAnOrigin, En) => "Not an http:// or https:// address.",
604+ (NotAnOrigin, Tr) => "http:// veya https:// adresi değil.",
605+ (LinkAddressLabel, En) => "Link address",
606+ (LinkAddressLabel, Tr) => "Bağlantı adresi",
601 (SenderNotConfiguredYet, En) => "No sender to test.",607 (SenderNotConfiguredYet, En) => "No sender to test.",
602 (SenderNotConfiguredYet, Tr) => "Test edilecek gönderen yok.",608 (SenderNotConfiguredYet, Tr) => "Test edilecek gönderen yok.",
603 609
crates/izlek-web/src/settings.rsmodified+57 -2
@@ -342,6 +342,10 @@ struct SaveSenderForm {
342 password: String,342 password: String,
343 from_name: String,343 from_name: String,
344 from_address: String,344 from_address: String,
345+ /// The origin mailed links point at. Empty falls back to the address the
346+ /// process was configured with.
347+ #[serde(default)]
348+ public_url: String,
345 }349 }
346 350
347 /// Writes the workspace's sender. Admin-only, checked here.351 /// Writes the workspace's sender. Admin-only, checked here.
@@ -370,6 +374,9 @@ async fn save_sender(
370 let username = input.username.trim().to_string();374 let username = input.username.trim().to_string();
371 let from_name = input.from_name.trim().to_string();375 let from_name = input.from_name.trim().to_string();
372 let from_address = input.from_address.trim().to_string();376 let from_address = input.from_address.trim().to_string();
377+ // Trailing slashes go: every link built from this appends its own path,
378+ // and `https://izlek.sh//?task=X` is a link that works by luck.
379+ let public_url = input.public_url.trim().trim_end_matches('/').to_string();
373 // Not typed is not the same as blanked. Nothing here can clear a stored380 // Not typed is not the same as blanked. Nothing here can clear a stored
374 // password; replacing it means typing a new one.381 // password; replacing it means typing a new one.
375 let password = (!input.password.is_empty()).then_some(input.password);382 let password = (!input.password.is_empty()).then_some(input.password);
@@ -393,6 +400,8 @@ async fn save_sender(
393 Some(Key::PasswordNeededFirstTime)400 Some(Key::PasswordNeededFirstTime)
394 } else if !is_address(&from_address) {401 } else if !is_address(&from_address) {
395 Some(Key::NotFromAddress)402 Some(Key::NotFromAddress)
403+ } else if !public_url.is_empty() && !is_origin(&public_url) {
404+ Some(Key::NotAnOrigin)
396 } else {405 } else {
397 None406 None
398 };407 };
@@ -403,7 +412,7 @@ async fn save_sender(
403 ));412 ));
404 }413 }
405 414
406- let outcome = store415+ let outcome = match store
407 .set_sender(416 .set_sender(
408 &admin.workspace_id,417 &admin.workspace_id,
409 NewSender {418 NewSender {
@@ -415,7 +424,18 @@ async fn save_sender(
415 from_address,424 from_address,
416 },425 },
417 )426 )
418- .await;427+ .await
428+ {
429+ Ok(()) => {
430+ store
431+ .set_public_url(
432+ &admin.workspace_id,
433+ (!public_url.is_empty()).then_some(public_url.as_str()),
434+ )
435+ .await
436+ }
437+ Err(problem) => Err(problem),
438+ };
419 let refusal = match outcome {439 let refusal = match outcome {
420 Ok(()) => {440 Ok(()) => {
421 let _ = store441 let _ = store
@@ -855,6 +875,9 @@ struct Sender {
855 from_address: String,875 from_address: String,
856 password_set: bool,876 password_set: bool,
857 test: Option<TestResult>,877 test: Option<TestResult>,
878+ /// The origin mailed links point at, empty when the configured one is
879+ /// still in use.
880+ public_url: String,
858 }881 }
859 882
860 impl Sender {883 impl Sender {
@@ -877,6 +900,7 @@ async fn sender_now(cx: &Cx, zone: time::UtcOffset) -> Result<Sender> {
877 from_address: String::new(),900 from_address: String::new(),
878 password_set: false,901 password_set: false,
879 test: None,902 test: None,
903+ public_url: String::new(),
880 },904 },
881 Some(workspace) => Sender {905 Some(workspace) => Sender {
882 host: workspace.smtp_host.unwrap_or_default(),906 host: workspace.smtp_host.unwrap_or_default(),
@@ -893,10 +917,28 @@ async fn sender_now(cx: &Cx, zone: time::UtcOffset) -> Result<Sender> {
893 took: test.error.is_none().then(|| took_label(test.took_ms)),917 took: test.error.is_none().then(|| took_label(test.took_ms)),
894 error: test.error,918 error: test.error,
895 }),919 }),
920+ public_url: workspace.public_url.unwrap_or_default(),
896 },921 },
897 })922 })
898 }923 }
899 924
925+/// Whether a typed address is an origin a link can be built on: an http or
926+/// https scheme, a host after it, and no whitespace anywhere. A path is
927+/// allowed — Izlek behind `example.com/izlek` is a real deployment — but a
928+/// bare host or a mail address is not.
929+fn is_origin(value: &str) -> bool {
930+ let Some(rest) = value
931+ .strip_prefix("https://")
932+ .or_else(|| value.strip_prefix("http://"))
933+ else {
934+ return false;
935+ };
936+ let host = rest.split('/').next().unwrap_or_default();
937+ !host.is_empty()
938+ && !host.contains('@')
939+ && !value.chars().any(char::is_whitespace)
940+}
941+
900 /// The refusal that landed on this call's redirect, if any, and this call's942 /// The refusal that landed on this call's redirect, if any, and this call's
901 /// own `saved=<call>` flag.943 /// own `saved=<call>` flag.
902 fn call_state<'q>(query: &'q str, call: &str) -> (Option<Refusal>, bool) {944 fn call_state<'q>(query: &'q str, call: &str) -> (Option<Refusal>, bool) {
@@ -989,6 +1031,9 @@ async fn settings_page(cx: &Cx) -> Result {
989 };1031 };
990 1032
991 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 placeholder
1035+ // shows it rather than an invented example.
1036+ let configured_url = accounts(cx).configured_url().to_string();
992 let sender = if administers {1037 let sender = if administers {
993 Some(sender_now(cx, zone).await?)1038 Some(sender_now(cx, zone).await?)
994 } else {1039 } else {
@@ -1227,6 +1272,16 @@ async fn settings_page(cx: &Cx) -> Result {
1227 >1272 >
1228 </label>1273 </label>
1229 </div>1274 </div>
1275+ <label class="field">
1276+ <span class="field-label">(t(lang, Key::LinkAddressLabel))</span>
1277+ <input
1278+ class="field-input"
1279+ type="text"
1280+ name="public_url"
1281+ value=(sender.public_url.clone())
1282+ placeholder=(configured_url.clone())
1283+ >
1284+ </label>
1230 </form>1285 </form>
1231 <div class="panel-foot panel-foot-split">1286 <div class="panel-foot panel-foot-split">
1232 <div class="foot-side">1287 <div class="foot-side">
crates/izlek-web/tests/http.rsmodified+71 -0
@@ -6423,3 +6423,74 @@ async fn the_queue_says_when_the_next_try_fires() {
6423 logs.body6423 logs.body
6424 );6424 );
6425 }6425 }
6426+
6427+/// An admin can set the address mail links point at — the box answers on
6428+/// localhost and is reached through a proxy on a public name. A trailing
6429+/// slash is trimmed, something that is not an origin is refused, and an empty
6430+/// field puts the configured address back.
6431+#[tokio::test]
6432+async fn an_admin_sets_the_address_mail_links_point_at() {
6433+ let app = App::open().await;
6434+ let admin_cookie = admin(&app).await;
6435+
6436+ async fn sender_with(app: &App, admin: &str, public_url: &str) -> Answer {
6437+ app.post(
6438+ "/api/save_sender",
6439+ Some(admin),
6440+ &[
6441+ ("host", "smtp.fastmail.com"),
6442+ ("port", "465"),
6443+ ("username", "izlek"),
6444+ ("password", SENDER_PASSWORD),
6445+ ("from_name", "Izlek"),
6446+ ("from_address", "izlek@izlek.sh"),
6447+ ("public_url", public_url),
6448+ ],
6449+ )
6450+ .await
6451+ }
6452+
6453+ let answer = sender_with(&app, &admin_cookie, "https://board.example/").await;
6454+ assert!(
6455+ answer
6456+ .location
6457+ .as_deref()
6458+ .is_some_and(|location| !location.contains("refusal=")),
6459+ "the address was refused: {:?}",
6460+ answer.location
6461+ );
6462+ assert_eq!(
6463+ app.store.workspace().await.unwrap().unwrap().public_url,
6464+ Some("https://board.example".to_string()),
6465+ "the trailing slash was kept"
6466+ );
6467+
6468+ // The field shows what is stored, so a reload does not blank it.
6469+ let page = app
6470+ .get("/settings?section=outgoing", Some(&admin_cookie))
6471+ .await;
6472+ let html = String::from_utf8_lossy(&page.bytes);
6473+ assert!(html.contains("https://board.example"), "{html}");
6474+
6475+ let refused = sender_with(&app, &admin_cookie, "board.example").await;
6476+ assert!(
6477+ refused
6478+ .location
6479+ .as_deref()
6480+ .is_some_and(|location| location.contains("refusal=")),
6481+ "a bare host was taken as an origin: {:?}",
6482+ refused.location
6483+ );
6484+ assert_eq!(
6485+ app.store.workspace().await.unwrap().unwrap().public_url,
6486+ Some("https://board.example".to_string()),
6487+ "the refused save wrote anyway"
6488+ );
6489+
6490+ sender_with(&app, &admin_cookie, "").await;
6491+ assert_eq!(
6492+ app.store.workspace().await.unwrap().unwrap().public_url,
6493+ None,
6494+ "an empty field did not clear the stored address"
6495+ );
6496+}
style/main.scssmodified+5 -0
@@ -1237,6 +1237,10 @@ img.avatar {
1237 flex-direction: column;1237 flex-direction: column;
1238 gap: 10px;1238 gap: 10px;
1239 width: min(86vw, 900px);1239 width: min(86vw, 900px);
1240+ // The viewer body is a row flex, so without this the sheet's automatic
1241+ // minimum size is the whole table's width and a wide book pushes the panel
1242+ // off the screen instead of panning inside it.
1243+ min-width: 0;
1240 }1244 }
1241 1245
1242 .sheet-tabs {1246 .sheet-tabs {
@@ -1265,6 +1269,7 @@ img.avatar {
1265 1269
1266 .sheet-grid {1270 .sheet-grid {
1267 max-height: 70vh;1271 max-height: 70vh;
1272+ min-width: 0;
1268 overflow: auto;1273 overflow: auto;
1269 scrollbar-width: none;1274 scrollbar-width: none;
1270 border: 1px solid var(--border);1275 border: 1px solid var(--border);