forge
Explore
Log in

Don't you dare go Hollow

the switcher takes the family from im instead of the file: an app-level setting store arrives (0005, the same shape in already uses), the directory beat also mirrors GET /family into it every five minutes and the topbar renders that copy — absent, unparseable or empty keeps the chrome bare — while [[services]] leaves the config for good; Settings grows a Server rail whose public-address field says where a sign-out from here returns, resolved per walk as the saved address, then the config's base_url, then the bound one

Browse files at this commit

ec39aa394dbd8b2f10717bfa2f8e37239f9d44cbAhmet Kaan GümüşParent: 5af77e4
crates/iz-client/src/lib.rsmodified+73 -7
@@ -13,6 +13,9 @@
1313 //! against im; when im has revoked the central session, the rotation is
1414 //! refused and the app sees a signed-out user.
1515
16+use std::pin::Pin;
17+use std::sync::Arc;
18+
1619 use base64::Engine;
1720 use base64::engine::general_purpose::URL_SAFE_NO_PAD as b64url;
1821 use chacha20poly1305::aead::Aead;
@@ -42,9 +45,12 @@ pub struct Config {
4245 pub client_secret: String,
4346 /// Must exactly match one of the URIs registered with im.
4447 pub redirect_uri: String,
45- /// Where im sends the browser when a sign-out that started here
46- /// finishes: this app's own public address, slash-terminated. Offered
47- /// to im's `/logout` as its `back`, so the browser comes home.
48+ /// Fallback for where im sends the browser when a sign-out that
49+ /// started here finishes: this app's public address. Offered to im's
50+ /// `/logout` as its `back`, so the browser comes home. An app whose
51+ /// public address is a stored setting — a live fact, not a boot-time
52+ /// one — registers a [`LogoutBack`] resolver, and this is what answers
53+ /// when that resolver is absent or has no opinion.
4854 pub logout_back: String,
4955 /// The app's session cookie name, e.g. `iz_session`.
5056 pub cookie_name: String,
@@ -52,6 +58,18 @@ pub struct Config {
5258 pub cookie_key: [u8; 32],
5359 }
5460
61+/// The answer a [`LogoutBack`] resolver returns for one request: where the
62+/// browser comes home to, or `None` to say the app has no opinion this
63+/// time and [`Config::logout_back`] should answer.
64+pub type BackAnswer<'a> = Pin<Box<dyn Future<Output = Option<String>> + Send + 'a>>;
65+
66+/// A per-request resolver for where im sends the browser when a sign-out
67+/// that started here finishes. An app whose public address is a stored
68+/// setting registers one as an app context; `/auth/logout` asks it first
69+/// and falls back to [`Config::logout_back`] when it is absent or answers
70+/// `None`.
71+pub struct LogoutBack(pub Arc<dyn for<'a> Fn(&'a Cx) -> BackAnswer<'a> + Send + Sync>);
72+
5573 /// The registered state: the config, one HTTP client, and the JWKS cache.
5674 pub struct IzClient {
5775 config: Config,
@@ -165,6 +183,17 @@ pub struct DirectoryMember {
165183 pub admin: bool,
166184 }
167185
186+/// One entry of im's family list: the wordmark key, the human name, and
187+/// where the app lives — exactly what the topbar switcher renders.
188+/// `Serialize` because the app that fetched it mirrors it into its own
189+/// store as the same JSON array im served.
190+#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
191+pub struct FamilyService {
192+ pub key: String,
193+ pub name: String,
194+ pub url: String,
195+}
196+
168197 impl IzClient {
169198 /// The family phonebook: every non-disabled user im knows, fetched as
170199 /// the app (`Authorization: Basic` with the client pair, the same
@@ -185,6 +214,27 @@ impl IzClient {
185214 }
186215 reply.json().await.ok()
187216 }
217+
218+ /// The family list: every app im's admin panel serves, fetched as the
219+ /// app (`Authorization: Basic` with the client pair, the same
220+ /// credentials the directory takes). `None` on anything that is not a
221+ /// readable list — a refused pair, a dropped connection, a body that
222+ /// is not the array — because a missed beat must never look like an
223+ /// empty family: the caller keeps the list it has and asks again next
224+ /// beat.
225+ pub async fn family(&self) -> Option<Vec<FamilyService>> {
226+ let reply = self
227+ .http
228+ .get(format!("{}/family", self.config.issuer))
229+ .basic_auth(&self.config.client_id, Some(&self.config.client_secret))
230+ .send()
231+ .await
232+ .ok()?;
233+ if !reply.status().is_success() {
234+ return None;
235+ }
236+ reply.json().await.ok()
237+ }
188238 }
189239
190240 /// Path of im's RFC 7662 introspection endpoint, relative to the issuer.
@@ -546,16 +596,32 @@ async fn iz_callback(cx: &Cx) -> Result<Response, topcoat::Error> {
546596 /// cleared, and the browser is sent on to im's `/logout` with `back`
547597 /// pointed back here. Ending the central session is im's half of the
548598 /// handoff — which is why a sign-out anywhere is a sign-out everywhere.
599+///
600+/// Where "here" is resolves per request: a registered [`LogoutBack`] is
601+/// asked first — a public address stored as a setting is a live fact, not
602+/// a boot-time one — and [`Config::logout_back`] answers when it is
603+/// absent or has no opinion. Either way the value goes out
604+/// slash-terminated: im redirects onto it, and a back without its slash
605+/// would make the next path segment join it by luck.
549606 #[route(GET "/auth/logout")]
550607 async fn iz_logout(cx: &Cx) -> Result<Response, topcoat::Error> {
551- let config = &client(cx).config;
552- clear_cookie(cx, &config.cookie_name);
608+ let state = client(cx);
609+ clear_cookie(cx, &state.config.cookie_name);
610+ let asked = match try_app_context::<LogoutBack>(cx) {
611+ Some(resolver) => (resolver.0)(cx).await,
612+ None => None,
613+ };
614+ let back = format!(
615+ "{}/",
616+ asked.unwrap_or_else(|| state.config.logout_back.clone())
617+ .trim_end_matches('/')
618+ );
553619 see(
554620 cx,
555621 &format!(
556622 "{}/logout?back={}",
557- config.issuer,
558- urlencoded(&config.logout_back)
623+ state.config.issuer,
624+ urlencoded(&back)
559625 ),
560626 )
561627 }
crates/iz-core/migrations/0005_settings.sqladded+16 -0
@@ -0,0 +1,16 @@
1+-- App-level settings, one row per key.
2+--
3+-- The workspace row carries what members share; a key here is the
4+-- deployment's own and has no workspace to hang off. Two things live here
5+-- today, both written by the app itself rather than typed into a file: the
6+-- family list mirrored from im's `/family` (the topbar switcher renders
7+-- from it), and the public address a sign-out that started here sends the
8+-- browser back to.
9+--
10+-- A fresh table, so an old database simply gains it empty on rebuild;
11+-- `iz reconcile` maps it and copies nothing, because an older database
12+-- has no rows to give.
13+CREATE TABLE setting (
14+ key TEXT PRIMARY KEY,
15+ value TEXT NOT NULL
16+);
crates/iz-core/src/config.rsmodified+9 -158
@@ -63,27 +63,6 @@ base_url = ""
6363 # revoked sign-in stops receiving within this long.
6464 live_seconds = 300
6565
66-# The dizey family, as the topbar's wordmark switcher shows it: one
67-# [[services]] table per app, with key ("in"|"im"|"iz"), a human name, and
68-# the url, absolute, no trailing slash. An empty list keeps the switcher
69-# off. Production serves the family at https://<key>.dizey.sh, written in
70-# the deploy's own config; this file carries only the development
71-# addresses.
72-[[services]]
73-key = "in"
74-name = "Files"
75-url = "http://127.0.0.1:7655"
76-
77-[[services]]
78-key = "im"
79-name = "Account"
80-url = "http://127.0.0.1:7650"
81-
82-[[services]]
83-key = "iz"
84-name = "Board"
85-url = "http://127.0.0.1:7654"
86-
8766 [oidc]
8867 # The provider that signs people in. Required: no default is guessed.
8968 issuer = ""
@@ -150,17 +129,6 @@ const OPTIONAL_KEYS: &[(&str, &str)] = &[
150129 "base_url = \"\"\n"
151130 ),
152131 ),
153- (
154- "services",
155- concat!(
156- "# The dizey family, as the topbar's wordmark switcher shows it: one\n",
157- "# [[services]] table per app, with key (\"in\"|\"im\"|\"iz\"), a human\n",
158- "# name, and the url, absolute, no trailing slash. An empty list keeps\n",
159- "# the switcher off. Production serves the family at\n",
160- "# https://<key>.dizey.sh, written in the deploy's own config.\n",
161- "services = []\n"
162- ),
163- ),
164132 ];
165133
166134 /// The `[oidc]` table of `config/iz.toml`, before the values are checked.
@@ -176,15 +144,6 @@ struct OidcToml {
176144 other: std::collections::BTreeMap<String, toml::Value>,
177145 }
178146
179-/// One `[[services]]` entry of `config/iz.toml`, before the values are
180-/// checked.
181-#[derive(Deserialize)]
182-struct ServiceToml {
183- key: String,
184- name: String,
185- url: String,
186-}
187-
188147 /// The shape of `config/iz.toml`, before the values are checked. Anything
189148 /// else the file says lands in `other`, which is read for its key names only
190149 /// — enough for the report to say a key was seen and not obeyed.
@@ -195,7 +154,6 @@ struct Toml {
195154 listen: Option<String>,
196155 live_seconds: Option<u64>,
197156 base_url: Option<String>,
198- services: Option<Vec<ServiceToml>>,
199157 oidc: Option<OidcToml>,
200158 #[serde(flatten)]
201159 other: std::collections::BTreeMap<String, toml::Value>,
@@ -215,18 +173,6 @@ pub struct OidcConfig {
215173 pub redirect_uri: String,
216174 }
217175
218-/// One of the apps the topbar's wordmark switcher links to.
219-#[derive(Clone, Debug, PartialEq, Eq)]
220-pub struct ServiceConfig {
221- /// The wordmark, lowercase — and how the app recognises itself in the
222- /// list (`"iz"` here).
223- pub key: String,
224- /// The human name, offered as the link's title: "Files", "Account".
225- pub name: String,
226- /// Where the app lives: absolute, no trailing slash.
227- pub url: String,
228-}
229-
230176 /// What the process needs to know before it opens a socket.
231177 #[derive(Clone, Debug, PartialEq, Eq)]
232178 pub struct Config {
@@ -251,9 +197,6 @@ pub struct Config {
251197 /// `redirect_uri` has. It is where the family sends the browser back
252198 /// to after a sign-out that started here.
253199 pub base_url: String,
254- /// The apps of the family, as the topbar's wordmark switcher links
255- /// them. Empty: no switcher, and everything else stays as it was.
256- pub services: Vec<ServiceConfig>,
257200 /// The OIDC provider İz trusts.
258201 pub oidc: OidcConfig,
259202 /// Whether `config/iz.toml` did not exist and was just written with the
@@ -370,25 +313,6 @@ impl Config {
370313 // everyone else follows `listen` for free.
371314 let base_url = value(toml.base_url).unwrap_or_default();
372315
373- // An entry that cannot be shown — no wordmark, no name, no
374- // destination — is refused rather than rendered half of itself.
375- let mut services = Vec::new();
376- for service in toml.services.unwrap_or_default() {
377- if service.key.trim().is_empty()
378- || service.name.trim().is_empty()
379- || service.url.trim().is_empty()
380- {
381- return Err(ConfigError::Invalid {
382- key: "services",
383- why: "every [[services]] needs a non-empty key, name and url".to_string(),
384- });
385- }
386- services.push(ServiceConfig {
387- key: service.key,
388- name: service.name,
389- url: service.url,
390- });
391- }
392316 // Zero would mean a stream that ends the moment it opens, which is a
393317 // reconnect loop rather than a live feed; the key is refused rather
394318 // than quietly corrected, because a deployment that meant to say
@@ -419,7 +343,6 @@ impl Config {
419343 storage,
420344 listen,
421345 base_url,
422- services,
423346 live_seconds,
424347 oidc: OidcConfig {
425348 issuer,
@@ -583,17 +506,13 @@ fn complete(path: &Path, text: &str, base: &Path) {
583506 }
584507 }
585508
586-/// Whether the file sets this key — a line whose first word it is, or an
587-/// array-of-tables header naming it (`[[services]]`), which is how a list
588-/// of tables says the same thing. A key named inside a comment or a value
589-/// does not count.
509+/// Whether the file sets this key — a line whose first word it is. A key
510+/// named inside a comment or a value does not count.
590511 fn mentions(text: &str, key: &str) -> bool {
591- let header = format!("[[{key}]]");
592512 text.lines().any(|line| {
593- let line = line.trim_start();
594- line.strip_prefix(key)
513+ line.trim_start()
514+ .strip_prefix(key)
595515 .is_some_and(|rest| rest.trim_start().starts_with('='))
596- || line.starts_with(&header)
597516 })
598517 }
599518
@@ -718,7 +637,7 @@ mod tests {
718637 std::fs::create_dir_all(dir.join("config")).unwrap();
719638 let mine = &format!(
720639 "database = \"iz.db\"\nstorage = \"files\"\nlisten = \"0.0.0.0:8080\"\n\
721- live_seconds = 30\nbase_url = \"\"\nservices = []\n{OIDC}"
640+ live_seconds = 30\nbase_url = \"\"\n{OIDC}"
722641 );
723642 std::fs::write(dir.join(FILE_NAME), mine).unwrap();
724643 let config = Config::load_from(&dir).unwrap();
@@ -960,40 +879,17 @@ mod tests {
960879 );
961880 }
962881
963- /// The family list parses into the switcher's entries, in the order the
964- /// file gives them — the order the wordmarks show.
965- #[test]
966- fn services_parse_into_the_switcher_list() {
967- let config = Config::parse(
968- &format!(
969- "database = \"iz.db\"\n\
970- [[services]]\nkey = \"in\"\nname = \"Files\"\nurl = \"http://127.0.0.1:7655\"\n\
971- [[services]]\nkey = \"iz\"\nname = \"Board\"\nurl = \"http://127.0.0.1:7654\"\n\
972- [[services]]\nkey = \"im\"\nname = \"Account\"\nurl = \"http://127.0.0.1:7650\"\n\
973- {OIDC}"
974- ),
975- Path::new("."),
976- false,
977- )
978- .unwrap();
979- let keys: Vec<&str> = config.services.iter().map(|s| s.key.as_str()).collect();
980- assert_eq!(keys, vec!["in", "iz", "im"]);
981- assert_eq!(config.services[1].name, "Board");
982- assert_eq!(config.services[0].url, "http://127.0.0.1:7655");
983- }
984-
985- /// A file silent about the family keeps the switcher off, and the
986- /// address the family returns the browser to falls back to the address
987- /// bound — the same fallback `redirect_uri` has.
882+ /// A file silent about a `base_url` keeps the address the family
883+ /// returns the browser to derived from the address bound — the same
884+ /// fallback `redirect_uri` has.
988885 #[test]
989- fn without_services_or_base_url_the_switcher_is_off_and_the_address_is_derived() {
886+ fn without_a_base_url_the_address_is_derived() {
990887 let config = Config::parse(
991888 &format!("database = \"iz.db\"\nlisten = \"0.0.0.0:9000\"\n{OIDC}"),
992889 Path::new("."),
993890 false,
994891 )
995892 .unwrap();
996- assert!(config.services.is_empty());
997893 assert_eq!(config.public_url(), "http://127.0.0.1:9000");
998894 }
999895
@@ -1013,27 +909,6 @@ mod tests {
1013909 assert_eq!(config.public_url(), "https://iz.dizey.sh");
1014910 }
1015911
1016- /// An entry that could not be shown — a wordmark, a name or a
1017- /// destination missing — stops the boot naming the key, rather than
1018- /// rendering half a link.
1019- #[test]
1020- fn a_service_missing_a_field_stops_the_boot_naming_the_key() {
1021- let problem = Config::parse(
1022- &format!(
1023- "database = \"iz.db\"\n\
1024- [[services]]\nkey = \"in\"\nname = \"\"\nurl = \"http://127.0.0.1:7655\"\n\
1025- {OIDC}"
1026- ),
1027- Path::new("."),
1028- false,
1029- )
1030- .unwrap_err();
1031- assert!(
1032- matches!(problem, ConfigError::Invalid { key: "services", .. }),
1033- "{problem:?}"
1034- );
1035- }
1036-
1037912 #[test]
1038913 fn a_key_inside_oidc_nothing_reads_is_named_with_its_table() {
1039914 let config = Config::parse(
@@ -1067,28 +942,4 @@ mod tests {
1067942 let _ = std::fs::remove_dir_all(&dir);
1068943 }
1069944
1070- /// A file that already carries `[[services]]` tables is not completed
1071- /// with the empty list: the header is how a list of tables says the
1072- /// key is set, and an appended `services = []` beside it would read as
1073- /// a phantom, empty extra entry.
1074- #[test]
1075- fn completion_does_not_add_services_beside_tables_already_there() {
1076- let dir = scratch();
1077- std::fs::create_dir_all(dir.join("config")).unwrap();
1078- let mine = &format!(
1079- "database = \"iz.db\"\n\
1080- [[services]]\nkey = \"in\"\nname = \"Files\"\nurl = \"http://127.0.0.1:7655\"\n{OIDC}"
1081- );
1082- std::fs::write(dir.join(FILE_NAME), mine).unwrap();
1083- Config::load_from(&dir).unwrap();
1084- let written = std::fs::read_to_string(dir.join(FILE_NAME)).unwrap();
1085- assert_eq!(written.matches("[[services]]").count(), 1, "{written}");
1086- assert!(!written.contains("services = []"), "{written}");
1087- // What was there is untouched: the sole family entry survives, and
1088- // a re-parse reads it back as exactly one service.
1089- assert!(written.contains("key = \"in\""), "{written}");
1090- let reparsed: toml::Value = toml::from_str(&written).unwrap();
1091- assert_eq!(reparsed["services"].as_array().map(Vec::len), Some(1));
1092- let _ = std::fs::remove_dir_all(&dir);
1093- }
1094945 }
crates/iz-core/src/store/mod.rsmodified+17 -0
@@ -720,6 +720,23 @@ pub trait Store: BoardReads + DetailReads + 'static {
720720 reminder_minutes: u32,
721721 ) -> Result<()>;
722722
723+ // -- app settings ------------------------------------------------------
724+
725+ /// One app-level setting, by key. `None` when the key was never set —
726+ /// the caller owns the default, not the row.
727+ ///
728+ /// App-level on purpose: the workspace row carries what members share,
729+ /// while a key here belongs to the deployment itself — the family list
730+ /// mirrored from im, the public address a sign-out lands on. No
731+ /// workspace column, because there is no workspace to name.
732+ async fn get_setting(&self, key: &str) -> Result<Option<String>>;
733+
734+ /// Writes one app-level setting, creating or replacing the row.
735+ /// Quiet by design: a background mirror rewrites its key every beat,
736+ /// and an announcement it cannot help is one nobody asked for. What a
737+ /// settings save owes the screen it lands on, the redirect carries.
738+ async fn set_setting(&self, key: &str, value: &str) -> Result<()>;
739+
723740 // -- users -------------------------------------------------------------
724741
725742 /// Upserts the account for a person who just proved who they are to im.
crates/iz-core/src/store/reconcile.rsmodified+12 -0
@@ -554,6 +554,10 @@ fn build_maps(
554554 "created_at",
555555 ]),
556556 });
557+ maps.push(TableMap {
558+ name: "setting",
559+ columns: old_cols(&["key", "value"]),
560+ });
557561
558562 maps
559563 }
@@ -742,6 +746,7 @@ async fn copy_data(old_conn: &Connection, new_conn: &Connection, path: &str) ->
742746 let has_clock = old_has_column(old_conn, "task", "clock_at").await?;
743747 let has_reminder = old_has_column(old_conn, "workspace", "reminder_minutes").await?;
744748 let has_tag = old_has_column(old_conn, "tag", "id").await?;
749+ let has_setting = old_has_column(old_conn, "setting", "key").await?;
745750 let maps = build_maps(
746751 has_smtp_check,
747752 has_batch_window,
@@ -759,6 +764,13 @@ async fn copy_data(old_conn: &Connection, new_conn: &Connection, path: &str) ->
759764 if map.name == "tag" && !has_tag {
760765 continue;
761766 }
767+ // A database from before app-level settings has no `setting` table:
768+ // nothing to copy — the rebuilt table starts empty, and the first
769+ // boot's family mirror refills it. The map itself still exists, so
770+ // `validate_maps` sees the declared table covered either way.
771+ if map.name == "setting" && !has_setting {
772+ continue;
773+ }
762774 // The default tags are seeded just before `task`: the old tags are
763775 // already in, so seeding only tops up the boards the copy left
764776 // without a default — it can therefore never violate
crates/iz-core/src/store/schema.rsmodified+1 -0
@@ -18,6 +18,7 @@ pub(crate) const MIGRATIONS: &[&str] = &[
1818 include_str!("../../migrations/0002_security_knobs.sql"),
1919 include_str!("../../migrations/0003_sso.sql"),
2020 include_str!("../../migrations/0004_no_photo_limit.sql"),
21+ include_str!("../../migrations/0005_settings.sql"),
2122 ];
2223
2324 /// The whole declared schema — every migration applied in order — as one
crates/iz-core/src/store/turso_store.rsmodified+22 -0
@@ -1707,6 +1707,28 @@ impl Store for TursoStore {
17071707 Ok(())
17081708 }
17091709
1710+ async fn get_setting(&self, key: &str) -> Result<Option<String>> {
1711+ match self
1712+ .one_row("SELECT value FROM setting WHERE key = ?1", params![key])
1713+ .await?
1714+ {
1715+ Some(row) => Ok(Some(text(&row, 0)?)),
1716+ None => Ok(None),
1717+ }
1718+ }
1719+
1720+ async fn set_setting(&self, key: &str, value: &str) -> Result<()> {
1721+ let conn = self.conn.lock().await;
1722+ conn.execute(
1723+ "INSERT INTO setting (key, value) VALUES (?1, ?2) \
1724+ ON CONFLICT (key) DO UPDATE SET value = excluded.value",
1725+ params![key, value],
1726+ )
1727+ .await
1728+ .map_err(backend)?;
1729+ Ok(())
1730+ }
1731+
17101732 async fn set_limits(
17111733 &self,
17121734 workspace_id: &str,
crates/iz-core/tests/store.rsmodified+50 -1
@@ -5568,7 +5568,14 @@ fn every_writing_method_announces_or_is_named_here() {
55685568 // announce for themselves when they commit. Announcing the lease as
55695569 // well would wake every connected client on every sweep for a screen
55705570 // that would look identical.
5571- const SILENT_ON_PURPOSE: &[&str] = &["claim_sends_owed"];
5571+ //
5572+ // `set_setting` serves two keys: the public address a sign-out hands
5573+ // the browser to, and the family list the background beat rewrites
5574+ // every five minutes from im. Neither renders on a live screen — the
5575+ // logout handoff is resolved per request, the switcher is served with
5576+ // the page — and an announcement the mirror cannot help would wake
5577+ // every open client, every beat, for nothing.
5578+ const SILENT_ON_PURPOSE: &[&str] = &["claim_sends_owed", "set_setting"];
55725579
55735580 let source = include_str!("../src/store/turso_store.rs");
55745581 let start = source
@@ -8432,3 +8439,45 @@ async fn a_sync_without_a_workspace_skips_and_writes_nothing() {
84328439 assert_eq!(sync, iz_core::store::MemberSync::Skipped);
84338440 assert!(scratch.store.workspace().await.unwrap().is_none());
84348441 }
8442+
8443+/// The app-level setting drawer: a key never set reads as absent, one set
8444+/// reads back, and setting it again replaces rather than duplicates — the
8445+/// family mirror rewrites its key every beat, and two rows for one key
8446+/// would make "which one renders" a coin flip.
8447+#[tokio::test]
8448+async fn app_settings_round_trip_through_one_row_per_key() {
8449+ let scratch = Scratch::open().await;
8450+
8451+ assert_eq!(scratch.store.get_setting("family").await.unwrap(), None);
8452+
8453+ scratch
8454+ .store
8455+ .set_setting("family", r#"[{"key":"in"}]"#)
8456+ .await
8457+ .unwrap();
8458+ assert_eq!(
8459+ scratch.store.get_setting("family").await.unwrap(),
8460+ Some(r#"[{"key":"in"}]"#.to_string())
8461+ );
8462+
8463+ scratch.store.set_setting("family", "[]").await.unwrap();
8464+ assert_eq!(
8465+ scratch.store.get_setting("family").await.unwrap(),
8466+ Some("[]".to_string())
8467+ );
8468+
8469+ // Keys are independent drawers: rewriting one leaves the other alone.
8470+ scratch
8471+ .store
8472+ .set_setting("public_url", "https://iz.example")
8473+ .await
8474+ .unwrap();
8475+ assert_eq!(
8476+ scratch.store.get_setting("family").await.unwrap(),
8477+ Some("[]".to_string())
8478+ );
8479+ assert_eq!(
8480+ scratch.store.get_setting("public_url").await.unwrap(),
8481+ Some("https://iz.example".to_string())
8482+ );
8483+}
crates/iz-web/src/i18n.rsmodified+16 -0
@@ -185,6 +185,9 @@ pub enum Key {
185185 NotFromAddress,
186186 NotAnOrigin,
187187 LinkAddressLabel,
188+ Server,
189+ PublicAddressLabel,
190+ PublicAddressNote,
188191 SenderNotConfiguredYet,
189192
190193 // pages.rs
@@ -662,6 +665,19 @@ pub fn t(lang: Lang, key: Key) -> &'static str {
662665 (NotAnOrigin, Tr) => "http:// veya https:// adresi değil.",
663666 (LinkAddressLabel, En) => "Link address",
664667 (LinkAddressLabel, Tr) => "Bağlantı adresi",
668+ (Server, En) => "Server",
669+ (Server, Tr) => "Sunucu",
670+ (PublicAddressLabel, En) => "Public address",
671+ (PublicAddressLabel, Tr) => "Genel adres",
672+ (PublicAddressNote, En) => {
673+ "Where the family sends the browser after a sign-out that started \
674+ here. Empty: the configured address, then the one this server binds."
675+ }
676+ (PublicAddressNote, Tr) => {
677+ "Aile, burada başlayan bir oturum kapanışından sonra tarayıcıyı \
678+ buraya gönderir. Boş: yapılandırılmış adres, sonra bu sunucunun \
679+ bağlandığı adres."
680+ }
665681 (SenderNotConfiguredYet, En) => "No sender to test.",
666682 (SenderNotConfiguredYet, Tr) => "Test edilecek gönderen yok.",
667683
crates/iz-web/src/layout.rsmodified+25 -11
@@ -14,7 +14,7 @@ use topcoat::{
1414 };
1515
1616 use crate::i18n::{Key, Lang, t};
17-use crate::server::current_user;
17+use crate::server::{FAMILY_KEY, current_user, store};
1818
1919 /// The İz monogram again, as the tab icon: the same drawing as `wordmark`,
2020 /// inlined because it must carry its own colours — a data URI has no page to
@@ -228,21 +228,35 @@ pub async fn topbar_nav(cx: &Cx, active: NavPage, role: iz_core::Role, lang: Lan
228228 }
229229 }
230230
231-/// The family's wordmark trio — `in im iz` — as the topbar's switcher
232-/// between the apps of dizey.sh. The current app is held in ink and marked
233-/// `aria-current`; the others are plain doors out, titled with the human
234-/// name the config gives them. Rendered only when config/iz.toml lists
235-/// services, so a deployment standing alone shows a chrome without the
236-/// trio. The links leave this origin, so they carry `data-hard`, like the
237-/// issuer link in the user menu.
231+/// The family list as the switcher shows it, read from the app's own
232+/// `setting` store — the mirror im's admin panel feeds through the
233+/// background beat in `main.rs`. Absent, empty, unparseable or a store
234+/// that will not answer all read the same: an empty list, which renders
235+/// no switcher. A page must not fail for the want of a wordmark.
236+async fn family_of(cx: &Cx) -> Vec<iz_client::FamilyService> {
237+ match store(cx).get_setting(FAMILY_KEY).await {
238+ Ok(Some(raw)) => serde_json::from_str(&raw).unwrap_or_default(),
239+ _ => Vec::new(),
240+ }
241+}
242+
243+/// The family's wordmark switcher — `in im iz` — as the topbar's way
244+/// between the apps of dizey.sh. The current app is held in ink and
245+/// marked `aria-current`; the others are plain doors out, titled with the
246+/// human name im's admin panel gives them. The list is the app's own
247+/// mirror of im's `/family` ([`family_of`]), so the panel decides the
248+/// trio without a deploy here, and a mirror that has not arrived yet —
249+/// or a deployment standing alone — shows a chrome without the trio. The
250+/// links leave this origin, so they carry `data-hard`, like the issuer
251+/// link in the user menu.
238252 async fn service_switcher(cx: &Cx) -> Result {
239253 const SELF: &str = "iz";
240- let services = crate::server::config(cx).services;
254+ let family = family_of(cx).await;
241255 view! {
242256 cx =>
243- if !services.is_empty() {
257+ if !family.is_empty() {
244258 <nav class="service-switcher">
245- for service in services {
259+ for service in family {
246260 if service.key == SELF {
247261 <span
248262 class="service-mark service-mark-on"
crates/iz-web/src/main.rsmodified+28 -8
@@ -123,10 +123,11 @@ async fn main() {
123123 client_id: config.oidc.client_id.clone(),
124124 client_secret: config.oidc.client_secret.clone(),
125125 redirect_uri: config.oidc.redirect_uri.clone(),
126- // Where im's /logout sends the browser when a sign-out that
127- // started here finishes: this app's public address, derived from
128- // `listen` unless the file says a `base_url`.
129- logout_back: format!("{}/", config.public_url().trim_end_matches('/')),
126+ // Fallback for where im's /logout sends the browser when a
127+ // sign-out that started here finishes: this app's configured
128+ // public address. The stored one answers first — the
129+ // `LogoutBack` context below is asked before this is.
130+ logout_back: config.public_url(),
130131 cookie_name: "iz_session".to_string(),
131132 cookie_key,
132133 };
@@ -165,6 +166,7 @@ async fn main() {
165166 oidc,
166167 )
167168 .app_context(store.clone())
169+ .app_context(iz_client::LogoutBack(Arc::new(iz_web::server::logout_back)))
168170 .app_context(config.clone())
169171 .app_context(iz_web::live::LiveWindow(std::time::Duration::from_secs(
170172 config.live_seconds,
@@ -313,10 +315,11 @@ async fn sweep(engine: std::sync::Arc<iz_core::MailEngine>, store: Arc<dyn iz_co
313315 /// long enough that the two services are not talking about it constantly.
314316 const DIRECTORY_SECONDS: u64 = 300;
315317
316-/// Keeps the member list a mirror of im's directory, first pass at boot and
317-/// then on the beat. Every pass is a full read of a short list, so the
318-/// store hears one entry at a time and announces only what changed. An im
319-/// that does not answer — down, restarting, mid-deploy — costs one log line
318+/// Keeps the member list a mirror of im's directory, and the switcher's
319+/// family list a mirror of im's admin panel, first pass at boot and then
320+/// on the beat. Every pass is a full read of a short list, so the store
321+/// hears one entry at a time and announces only what changed. An im that
322+/// does not answer — down, restarting, mid-deploy — costs one log line
320323 /// and nothing else: the rows stay, and the next beat asks again.
321324 async fn directory_sync(store: Arc<dyn iz_core::store::Store>, client: iz_client::IzClient) {
322325 loop {
@@ -333,6 +336,23 @@ async fn directory_sync(store: Arc<dyn iz_core::store::Store>, client: iz_client
333336 }
334337 None => eprintln!("directory sync: im did not answer; keeping the rows there are"),
335338 }
339+ // The family rides the same beat: one JSON array in one setting
340+ // row, the same shape im's `/family` served this pass. `family`
341+ // refuses a body it cannot read whole rather than storing half a
342+ // switcher, so what lands in the row is always renderable.
343+ match client.family().await {
344+ Some(family) => match serde_json::to_string(&family) {
345+ Ok(json) => {
346+ if let Err(problem) =
347+ store.set_setting(iz_web::server::FAMILY_KEY, &json).await
348+ {
349+ eprintln!("family sync: {problem}");
350+ }
351+ }
352+ Err(problem) => eprintln!("family sync: {problem}"),
353+ },
354+ None => eprintln!("family sync: im did not answer; keeping the list there is"),
355+ }
336356 tokio::time::sleep(std::time::Duration::from_secs(DIRECTORY_SECONDS)).await;
337357 }
338358 }
crates/iz-web/src/server.rsmodified+33 -0
@@ -32,6 +32,33 @@ pub fn config(cx: &Cx) -> iz_core::Config {
3232 app_context::<iz_core::Config>(cx).clone()
3333 }
3434
35+/// The app-level `setting` key the background beat in `main.rs` stores
36+/// im's family list under, and `layout.rs`'s switcher renders from. The
37+/// value is a JSON array of `{key, name, url}` — exactly what im's
38+/// `/family` served.
39+pub const FAMILY_KEY: &str = "family";
40+
41+/// The app-level `setting` key the public-address field on Settings
42+/// writes: where a sign-out that started here sends the browser. Saving
43+/// empty clears the row rather than storing an empty string, so what the
44+/// fallback chain sits under is always either a usable address or nothing.
45+pub const PUBLIC_URL_KEY: &str = "public_url";
46+
47+/// Resolves where a sign-out that started here sends the browser, per
48+/// request: the public address an admin stored wins; a missing or
49+/// unreadable one is no opinion, and iz-client falls back to the
50+/// configured chain — `base_url`, else the address bound. Registered as
51+/// an app context in `main.rs`; this function is the shape that
52+/// registration wants.
53+pub fn logout_back(cx: &Cx) -> iz_client::BackAnswer<'_> {
54+ Box::pin(async move {
55+ match store(cx).get_setting(PUBLIC_URL_KEY).await {
56+ Ok(Some(value)) if !value.trim().is_empty() => Some(value),
57+ _ => None,
58+ }
59+ })
60+}
61+
3562 /// The mail engine, or the fact that there is nobody to hand a crossing to.
3663 ///
3764 /// The running server always has an engine: the sender is workspace settings
@@ -333,6 +360,8 @@ pub enum Refusal {
333360 BadEmail,
334361 /// Something in the allowed-types list is not a file extension.
335362 BadFileType,
363+ /// A public address that is not an http:// or https:// origin.
364+ BadOrigin,
336365 /// The sender panel was saved with a field it cannot work without, or with
337366 /// one that is not what it claims to be. The message names the field: this
338367 /// is a form somebody is filling in, not an attacker probing, and "that did
@@ -405,6 +434,7 @@ impl Refusal {
405434 Refusal::BadFileType => {
406435 "File types are extensions — png, pdf, zip — separated by commas.".to_string()
407436 }
437+ Refusal::BadOrigin => "Not an http:// or https:// address.".to_string(),
408438 Refusal::BadSender(problem) => problem.clone(),
409439 Refusal::EmptyComment => "Write something first.".to_string(),
410440 Refusal::NoFile => "Choose a file first.".to_string(),
@@ -472,6 +502,7 @@ impl Refusal {
472502 Refusal::BadFileType => {
473503 "Dosya türleri virgülle ayrılmış uzantılardır — png, pdf, zip.".to_string()
474504 }
505+ Refusal::BadOrigin => "http:// veya https:// adresi değil.".to_string(),
475506 // `BadSender`'s sentence is built where the complaint is
476507 // decided (`settings.rs`), already in the caller's language —
477508 // this is only reached for a request with no admin to read a
@@ -502,6 +533,7 @@ impl Refusal {
502533 "bad-language" => Refusal::BadLanguage,
503534 "bad-email" => Refusal::BadEmail,
504535 "bad-file-type" => Refusal::BadFileType,
536+ "bad-origin" => Refusal::BadOrigin,
505537 // The specific complaint (which field, and why) lives only in the
506538 // response the save itself returned; a code that survived a round
507539 // trip through the address bar carries no more than this.
@@ -549,6 +581,7 @@ impl Refusal {
549581 Refusal::BadLanguage => "bad-language",
550582 Refusal::BadEmail => "bad-email",
551583 Refusal::BadFileType => "bad-file-type",
584+ Refusal::BadOrigin => "bad-origin",
552585 Refusal::BadSender(_) => "bad-sender",
553586 Refusal::EmptyComment => "empty-comment",
554587 Refusal::NoFile => "no-file",
crates/iz-web/src/settings.rsmodified+90 -1
@@ -24,7 +24,7 @@ use iz_core::detail::ActivityKind;
2424 use iz_core::store::{NewSender, SenderCheck, SenderTest, Store, StoreError, User};
2525
2626 use crate::i18n::{Key, Lang, t};
27-use crate::server::{Refusal, config, mail, require_admin, require_user, store};
27+use crate::server::{PUBLIC_URL_KEY, Refusal, config, mail, require_admin, require_user, store};
2828
2929 /// The widest the limit may be set to. A ceiling of any size is a promise
3030 /// the disk has to keep, and a limit typed with one extra zero is a mistake
@@ -143,6 +143,7 @@ fn section_of_call(call: &str) -> &'static str {
143143 match call {
144144 "save_sender" | "send_test_mail" | "check_sender" => "outgoing",
145145 "save_limits" => "limits",
146+ "save_public_url" => "server",
146147 "set_role" | "set_disabled" | "add_member" => "members",
147148 "send_message" => "message",
148149 _ => "profile",
@@ -502,6 +503,48 @@ fn probe_sender(
502503 });
503504 }
504505
506+#[derive(serde::Deserialize)]
507+struct SavePublicUrlForm {
508+ #[serde(default)]
509+ public_url: String,
510+}
511+
512+/// Writes the app-level public address: where a sign-out that started here
513+/// sends the browser once im is done with it. Admin-only, checked here.
514+///
515+/// The workspace's own link address lives on the sender row — that one is
516+/// about mailed links. This one is about the family's handoff, so it is a
517+/// setting of the app itself, and the logout route reads it per request:
518+/// a save takes effect on the very next sign-out, no restart.
519+///
520+/// A value the boot would not take is refused here for the same reason
521+/// [`is_origin`] refuses one on the sender panel, and the stored setting
522+/// is left untouched. Saving empty clears the row; the config chain —
523+/// `base_url`, else the address bound — answers instead.
524+#[route(POST "/api/save_public_url")]
525+async fn save_public_url(
526+ cx: &Cx,
527+ Form(input): Form<SavePublicUrlForm>,
528+) -> Result<(StatusCode, HeaderMap, Vec<u8>)> {
529+ if let Err(refusal) = require_admin(cx).await {
530+ return Ok(saved_or_refused("save_public_url", Some(refusal)));
531+ }
532+ // Trailing slashes go: every consumer appends its own path, and a
533+ // stored `https://iz.sh//` is a handoff that works by luck.
534+ let public_url = input.public_url.trim().trim_end_matches('/').to_string();
535+ if !public_url.is_empty() && !is_origin(&public_url) {
536+ return Ok(saved_or_refused("save_public_url", Some(Refusal::BadOrigin)));
537+ }
538+ let refusal = match store(cx).set_setting(PUBLIC_URL_KEY, &public_url).await {
539+ Ok(()) => None,
540+ Err(problem) => {
541+ eprintln!("store error: {problem}");
542+ Some(Refusal::Unavailable)
543+ }
544+ };
545+ Ok(saved_or_refused("save_public_url", refusal))
546+}
547+
505548 /// Dials the mail server without sending anything, on an admin's say-so.
506549 #[route(POST "/api/check_sender")]
507550 async fn check_sender(cx: &Cx) -> Result<(StatusCode, HeaderMap, Vec<u8>)> {
@@ -1118,6 +1161,7 @@ enum Section {
11181161 Profile,
11191162 Outgoing,
11201163 Limits,
1164+ Server,
11211165 Members,
11221166 Message,
11231167 }
@@ -1154,6 +1198,7 @@ async fn settings_page(cx: &Cx) -> Result {
11541198 let section = match query_value(query, "section") {
11551199 Some("outgoing") if administers => Section::Outgoing,
11561200 Some("limits") if administers => Section::Limits,
1201+ Some("server") if administers => Section::Server,
11571202 Some("members") if administers => Section::Members,
11581203 Some("message") if administers => Section::Message,
11591204 _ => Section::Profile,
@@ -1180,11 +1225,20 @@ async fn settings_page(cx: &Cx) -> Result {
11801225 } else {
11811226 None
11821227 };
1228+ // What the public-address field shows: the stored app-level address,
1229+ // or nothing — the placeholder then shows what the fallback chain
1230+ // would use, the same way the sender panel's does.
1231+ let stored_public_url = if administers {
1232+ store(cx).get_setting(PUBLIC_URL_KEY).await.ok().flatten()
1233+ } else {
1234+ None
1235+ };
11831236
11841237 let (profile_refusal, profile_saved) = call_state(query, "save_profile");
11851238 let (sender_refusal, sender_saved) = call_state(query, "save_sender");
11861239 let (test_refusal, _) = call_state(query, "send_test_mail");
11871240 let (limits_refusal, limits_saved) = call_state(query, "save_limits");
1241+ let (server_refusal, server_saved) = call_state(query, "save_public_url");
11881242 let (role_refusal, _) = call_state(query, "set_role");
11891243 let (disabled_refusal, _) = call_state(query, "set_disabled");
11901244 let (add_refusal, add_saved) = call_state(query, "add_member");
@@ -1206,6 +1260,7 @@ async fn settings_page(cx: &Cx) -> Result {
12061260 if administers {
12071261 <a class=(rail_class(section, Section::Outgoing)) href="/settings?section=outgoing">(t(lang, Key::OutgoingMail))</a>
12081262 <a class=(rail_class(section, Section::Limits)) href="/settings?section=limits">(t(lang, Key::WorkspaceLimits))</a>
1263+ <a class=(rail_class(section, Section::Server)) href="/settings?section=server">(t(lang, Key::Server))</a>
12091264 <a class=(rail_class(section, Section::Message)) href="/settings?section=message">(t(lang, Key::Message))</a>
12101265 }
12111266 </nav>
@@ -1481,6 +1536,40 @@ async fn settings_page(cx: &Cx) -> Result {
14811536 </section>
14821537 }
14831538
1539+ if section == Section::Server {
1540+ <section class="panel" id="server">
1541+ <div class="panel-head">
1542+ <h2 class="panel-title">(t(lang, Key::Server))</h2>
1543+ <span class="chip chip-admin">(t(lang, Key::AdminOnly))</span>
1544+ </div>
1545+ <form method="post" action="/api/save_public_url" class="panel-body" id="public-address">
1546+ <label class="field">
1547+ <span class="field-label">(t(lang, Key::PublicAddressLabel))</span>
1548+ <input
1549+ class="field-input"
1550+ type="text"
1551+ name="public_url"
1552+ value=(stored_public_url.clone().unwrap_or_default())
1553+ placeholder=(configured_url.clone())
1554+ >
1555+ </label>
1556+ <p class="panel-lede">(t(lang, Key::PublicAddressNote))</p>
1557+ </form>
1558+ <div class="panel-foot panel-foot-split">
1559+ <div class="foot-side"></div>
1560+ <div class="foot-side">
1561+ if let Some(refusal) = &server_refusal {
1562+ <span class="field-error">(refusal.message_in(lang))</span>
1563+ }
1564+ if server_saved {
1565+ <span class="field-note">(t(lang, Key::Saved))</span>
1566+ }
1567+ <button class="primary" type="submit" form="public-address">(t(lang, Key::Save))</button>
1568+ </div>
1569+ </div>
1570+ </section>
1571+ }
1572+
14841573 if section == Section::Members && let Some(members) = &members {
14851574 <section class="panel" id="members">
14861575 <div class="panel-head">
crates/iz-web/tests/http.rsmodified+101 -53
@@ -280,12 +280,15 @@ struct App {
280280
281281 impl App {
282282 async fn build(mail: Mail) -> Self {
283- Self::build_with(mail, Vec::new()).await
283+ Self::build_with(mail, None, "").await
284284 }
285285
286- /// Like `build`, but with a `[[services]]` list, so a test can see the
287- /// family switcher a configured deployment shows.
288- async fn build_with(mail: Mail, services: Vec<iz_core::config::ServiceConfig>) -> Self {
286+ /// Like `build`, but with the knobs a configured deployment has: the
287+ /// family list mirrored from im — passed as the raw JSON the `setting`
288+ /// row holds, so a test can also feed it a body that will not parse —
289+ /// and the configured `base_url`. Building them in is what lets the
290+ /// switcher and the sign-out handoff be asserted over real HTTP.
291+ async fn build_with(mail: Mail, family: Option<String>, base_url: &str) -> Self {
289292 let dir = std::env::temp_dir().join(format!("iz-http-{}", Ulid::new()));
290293 std::fs::create_dir_all(&dir).unwrap();
291294 let db = dir.join("iz.db");
@@ -295,23 +298,21 @@ impl App {
295298 .await
296299 .unwrap(),
297300 );
301+ // The family list is a mirror, not a config: the test plays the
302+ // part of the background beat that stores what im served.
303+ if let Some(family) = &family {
304+ store
305+ .set_setting(iz_web::server::FAMILY_KEY, family)
306+ .await
307+ .unwrap();
308+ }
298309 let fake = FakeIm::spawn().await;
299- let client = iz_client::Config {
300- issuer: fake.url(),
301- client_id: "iz-test".to_string(),
302- client_secret: "s3cr3t".to_string(),
303- redirect_uri: "http://127.0.0.1:7655/auth/callback".to_string(),
304- logout_back: "http://127.0.0.1:7655/".to_string(),
305- cookie_name: "iz_session".to_string(),
306- cookie_key: [7u8; 32],
307- };
308310 let config = iz_core::Config {
309311 database: db,
310312 storage,
311313 listen: "127.0.0.1:7655".parse().unwrap(),
312314 live_seconds: 300,
313- base_url: String::new(),
314- services,
315+ base_url: base_url.to_string(),
315316 oidc: iz_core::config::OidcConfig {
316317 issuer: fake.url(),
317318 client_id: "iz-test".to_string(),
@@ -321,6 +322,17 @@ impl App {
321322 ignored: Vec::new(),
322323 defaulted: false,
323324 };
325+ // The fallback half of the chain, built exactly as `main.rs` builds
326+ // it: the configured public address, else the address bound.
327+ let client = iz_client::Config {
328+ issuer: fake.url(),
329+ client_id: "iz-test".to_string(),
330+ client_secret: "s3cr3t".to_string(),
331+ redirect_uri: "http://127.0.0.1:7655/auth/callback".to_string(),
332+ logout_back: config.public_url(),
333+ cookie_name: "iz_session".to_string(),
334+ cookie_key: [7u8; 32],
335+ };
324336 let (stop, stopping) = tokio::sync::watch::channel(false);
325337 let router = iz_client::mount(
326338 Router::builder()
@@ -337,6 +349,9 @@ impl App {
337349 client.clone(),
338350 )
339351 .app_context(store.clone())
352+ .app_context(iz_client::LogoutBack(Arc::new(
353+ iz_web::server::logout_back,
354+ )))
340355 .app_context(config.clone())
341356 .app_context(TEST_LIVE_WINDOW)
342357 .app_context(iz_web::live::Shutdown(stopping))
@@ -375,21 +390,11 @@ impl App {
375390 "https://iz.sh",
376391 ));
377392 let fake = FakeIm::spawn().await;
378- let client = iz_client::Config {
379- issuer: fake.url(),
380- client_id: "iz-test".to_string(),
381- client_secret: "s3cr3t".to_string(),
382- redirect_uri: "http://127.0.0.1:7655/auth/callback".to_string(),
383- logout_back: "http://127.0.0.1:7655/".to_string(),
384- cookie_name: "iz_session".to_string(),
385- cookie_key: [7u8; 32],
386- };
387393 let config = iz_core::Config {
388394 database: db,
389395 storage,
390396 listen: "127.0.0.1:7655".parse().unwrap(),
391397 base_url: String::new(),
392- services: Vec::new(),
393398 live_seconds: 300,
394399 oidc: iz_core::config::OidcConfig {
395400 issuer: fake.url(),
@@ -400,6 +405,17 @@ impl App {
400405 ignored: Vec::new(),
401406 defaulted: false,
402407 };
408+ // The fallback half of the chain, built exactly as `main.rs` builds
409+ // it: the configured public address, else the address bound.
410+ let client = iz_client::Config {
411+ issuer: fake.url(),
412+ client_id: "iz-test".to_string(),
413+ client_secret: "s3cr3t".to_string(),
414+ redirect_uri: "http://127.0.0.1:7655/auth/callback".to_string(),
415+ logout_back: config.public_url(),
416+ cookie_name: "iz_session".to_string(),
417+ cookie_key: [7u8; 32],
418+ };
403419 let (stop, stopping) = tokio::sync::watch::channel(false);
404420 let router = iz_client::mount(
405421 Router::builder()
@@ -416,6 +432,9 @@ impl App {
416432 client.clone(),
417433 )
418434 .app_context(store.clone())
435+ .app_context(iz_client::LogoutBack(Arc::new(
436+ iz_web::server::logout_back,
437+ )))
419438 .app_context(config.clone())
420439 .app_context(TEST_LIVE_WINDOW)
421440 .app_context(iz_web::live::Shutdown(stopping))
@@ -9580,9 +9599,12 @@ fn the_stylesheet_guard_refuses_a_foreign_bundle() {
95809599
95819600 /// Sign-out leaves through the family's front door: the local cookie is
95829601 /// cleared, and the browser is handed to im's `/logout` with `back` pointed
9583-/// at this app, so the central session ends with the local one.
9602+/// at this app. Where "here" is resolves per request — the stored public
9603+/// address wins, the configured `base_url` is the fallback, and the
9604+/// address the server binds is the last resort.
95849605 #[tokio::test]
95859606 async fn a_sign_out_hands_the_browser_to_the_providers_logout_pointed_home() {
9607+ // No stored address, no configured one: the bind address answers.
95869608 let app = App::open().await;
95879609 let admin = admin(&app).await;
95889610 let raw = app.get("/auth/logout", Some(&admin)).await;
@@ -9593,49 +9615,75 @@ async fn a_sign_out_hands_the_browser_to_the_providers_logout_pointed_home() {
95939615 encode("http://127.0.0.1:7655/")
95949616 );
95959617 assert_eq!(raw.location.as_deref(), Some(expected.as_str()));
9618+
9619+ // A configured `base_url` is what the fallback says when nothing is
9620+ // stored — a deployment behind a proxy says its name once, in the file.
9621+ let configured = App::build_with(Mail::silent(), None, "https://board.example").await;
9622+ let raw = configured.get("/auth/logout", None).await;
9623+ let expected = format!(
9624+ "{}/logout?back={}",
9625+ configured.client.issuer,
9626+ encode("https://board.example/")
9627+ );
9628+ assert_eq!(raw.location.as_deref(), Some(expected.as_str()));
9629+
9630+ // A stored public address wins over the configured chain, and it reads
9631+ // per request: no restart between the save and the next sign-out.
9632+ let stored = App::build_with(Mail::silent(), None, "https://stale.example").await;
9633+ stored
9634+ .store
9635+ .set_setting(iz_web::server::PUBLIC_URL_KEY, "https://stored.example")
9636+ .await
9637+ .unwrap();
9638+ let raw = stored.get("/auth/logout", None).await;
9639+ let expected = format!(
9640+ "{}/logout?back={}",
9641+ stored.client.issuer,
9642+ encode("https://stored.example/")
9643+ );
9644+ assert_eq!(raw.location.as_deref(), Some(expected.as_str()));
95969645 }
95979646
9598-/// The signed-in chrome carries the family's wordmark trio when the config
9599-/// lists services: one mark per `[[services]]` row in the file's order, the
9600-/// current app held in ink with `aria-current`, the others plain links out.
9601-/// A deployment that lists none shows no switcher at all.
9647+/// The switcher renders the family list the app mirrors from im — the
9648+/// stored JSON, in stored order, with the current app held in ink with
9649+/// `aria-current`, the others plain links out. A list that is absent,
9650+/// empty, or will not parse shows no switcher at all.
96029651 #[tokio::test]
96039652 async fn the_topbar_shows_the_family_switcher_and_marks_this_app_only_when_configured() {
9604- let services = vec![
9605- iz_core::config::ServiceConfig {
9606- key: "in".to_string(),
9607- name: "Files".to_string(),
9608- url: "http://127.0.0.1:7655".to_string(),
9609- },
9610- iz_core::config::ServiceConfig {
9611- key: "iz".to_string(),
9612- name: "Board".to_string(),
9613- url: "http://127.0.0.1:7654".to_string(),
9614- },
9615- iz_core::config::ServiceConfig {
9616- key: "im".to_string(),
9617- name: "Account".to_string(),
9618- url: "http://127.0.0.1:7650".to_string(),
9619- },
9620- ];
9621- let app = App::build_with(Mail::silent(), services).await;
9653+ let family = "\
9654+ [{\"key\":\"in\",\"name\":\"Files\",\"url\":\"http://127.0.0.1:7655\"},\
9655+ {\"key\":\"iz\",\"name\":\"Board\",\"url\":\"http://127.0.0.1:7654\"},\
9656+ {\"key\":\"im\",\"name\":\"Account\",\"url\":\"http://127.0.0.1:7650\"}]"
9657+ .to_string();
9658+ let app = App::build_with(Mail::silent(), Some(family), "").await;
96229659 let board_admin = admin(&app).await;
96239660 let html = String::from_utf8_lossy(&app.get("/", Some(&board_admin)).await.bytes).to_string();
96249661 assert!(html.contains("service-switcher"), "{html}");
96259662 assert!(html.contains("service-mark-on"), "{html}");
96269663 assert!(html.contains("aria-current=\"page\""), "{html}");
9627- // The trio reads in the order the config gave, with the current app
9664+ // The mirror reads in the order im served it, with the current app
96289665 // between its neighbours, not pushed to an end.
96299666 let in_at = html.find("href=\"http://127.0.0.1:7655\"").unwrap();
96309667 let iz_at = html.find("service-mark-on").unwrap();
96319668 let im_at = html.find("href=\"http://127.0.0.1:7650\"").unwrap();
96329669 assert!(in_at < iz_at && iz_at < im_at, "marks out of order: {html}");
96339670
9634- let alone = App::open().await;
9635- let alone_admin = admin(&alone).await;
9636- let plain = String::from_utf8_lossy(&alone.get("/", Some(&alone_admin)).await.bytes).to_string();
9671+ // A list that will not parse hides the switcher rather than rendering
9672+ // half of it — and so does an empty one, and a mirror that never
9673+ // arrived.
9674+ for broken in ["[".to_string(), "[]".to_string()] {
9675+ let app = App::build_with(Mail::silent(), Some(broken), "").await;
9676+ let board_admin = admin(&app).await;
9677+ let html =
9678+ String::from_utf8_lossy(&app.get("/", Some(&board_admin)).await.bytes).to_string();
9679+ assert!(!html.contains("service-switcher"), "{html}");
9680+ }
9681+ let plain = App::open().await;
9682+ let alone_admin = admin(&plain).await;
9683+ let plain =
9684+ String::from_utf8_lossy(&plain.get("/", Some(&alone_admin)).await.bytes).to_string();
96379685 assert!(
96389686 !plain.contains("service-switcher"),
9639- "no services, no switcher: {plain}"
9687+ "no mirror, no switcher: {plain}"
96409688 );
96419689 }