diff --git a/crates/iz-client/src/lib.rs b/crates/iz-client/src/lib.rs index fcf7393..00e46ba 100644 --- a/crates/iz-client/src/lib.rs +++ b/crates/iz-client/src/lib.rs @@ -13,6 +13,9 @@ //! against im; when im has revoked the central session, the rotation is //! refused and the app sees a signed-out user. +use std::pin::Pin; +use std::sync::Arc; + use base64::Engine; use base64::engine::general_purpose::URL_SAFE_NO_PAD as b64url; use chacha20poly1305::aead::Aead; @@ -42,9 +45,12 @@ pub struct Config { pub client_secret: String, /// Must exactly match one of the URIs registered with im. pub redirect_uri: String, - /// Where im sends the browser when a sign-out that started here - /// finishes: this app's own public address, slash-terminated. Offered - /// to im's `/logout` as its `back`, so the browser comes home. + /// Fallback for where im sends the browser when a sign-out that + /// started here finishes: this app's public address. Offered to im's + /// `/logout` as its `back`, so the browser comes home. An app whose + /// public address is a stored setting — a live fact, not a boot-time + /// one — registers a [`LogoutBack`] resolver, and this is what answers + /// when that resolver is absent or has no opinion. pub logout_back: String, /// The app's session cookie name, e.g. `iz_session`. pub cookie_name: String, @@ -52,6 +58,18 @@ pub struct Config { pub cookie_key: [u8; 32], } +/// The answer a [`LogoutBack`] resolver returns for one request: where the +/// browser comes home to, or `None` to say the app has no opinion this +/// time and [`Config::logout_back`] should answer. +pub type BackAnswer<'a> = Pin> + Send + 'a>>; + +/// A per-request resolver for where im sends the browser when a sign-out +/// that started here finishes. An app whose public address is a stored +/// setting registers one as an app context; `/auth/logout` asks it first +/// and falls back to [`Config::logout_back`] when it is absent or answers +/// `None`. +pub struct LogoutBack(pub Arc Fn(&'a Cx) -> BackAnswer<'a> + Send + Sync>); + /// The registered state: the config, one HTTP client, and the JWKS cache. pub struct IzClient { config: Config, @@ -165,6 +183,17 @@ pub struct DirectoryMember { pub admin: bool, } +/// One entry of im's family list: the wordmark key, the human name, and +/// where the app lives — exactly what the topbar switcher renders. +/// `Serialize` because the app that fetched it mirrors it into its own +/// store as the same JSON array im served. +#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] +pub struct FamilyService { + pub key: String, + pub name: String, + pub url: String, +} + impl IzClient { /// The family phonebook: every non-disabled user im knows, fetched as /// the app (`Authorization: Basic` with the client pair, the same @@ -185,6 +214,27 @@ impl IzClient { } reply.json().await.ok() } + + /// The family list: every app im's admin panel serves, fetched as the + /// app (`Authorization: Basic` with the client pair, the same + /// credentials the directory takes). `None` on anything that is not a + /// readable list — a refused pair, a dropped connection, a body that + /// is not the array — because a missed beat must never look like an + /// empty family: the caller keeps the list it has and asks again next + /// beat. + pub async fn family(&self) -> Option> { + let reply = self + .http + .get(format!("{}/family", self.config.issuer)) + .basic_auth(&self.config.client_id, Some(&self.config.client_secret)) + .send() + .await + .ok()?; + if !reply.status().is_success() { + return None; + } + reply.json().await.ok() + } } /// Path of im's RFC 7662 introspection endpoint, relative to the issuer. @@ -546,16 +596,32 @@ async fn iz_callback(cx: &Cx) -> Result { /// cleared, and the browser is sent on to im's `/logout` with `back` /// pointed back here. Ending the central session is im's half of the /// handoff — which is why a sign-out anywhere is a sign-out everywhere. +/// +/// Where "here" is resolves per request: a registered [`LogoutBack`] is +/// asked first — a public address stored as a setting is a live fact, not +/// a boot-time one — and [`Config::logout_back`] answers when it is +/// absent or has no opinion. Either way the value goes out +/// slash-terminated: im redirects onto it, and a back without its slash +/// would make the next path segment join it by luck. #[route(GET "/auth/logout")] async fn iz_logout(cx: &Cx) -> Result { - let config = &client(cx).config; - clear_cookie(cx, &config.cookie_name); + let state = client(cx); + clear_cookie(cx, &state.config.cookie_name); + let asked = match try_app_context::(cx) { + Some(resolver) => (resolver.0)(cx).await, + None => None, + }; + let back = format!( + "{}/", + asked.unwrap_or_else(|| state.config.logout_back.clone()) + .trim_end_matches('/') + ); see( cx, &format!( "{}/logout?back={}", - config.issuer, - urlencoded(&config.logout_back) + state.config.issuer, + urlencoded(&back) ), ) } diff --git a/crates/iz-core/migrations/0005_settings.sql b/crates/iz-core/migrations/0005_settings.sql new file mode 100644 index 0000000..2288229 --- /dev/null +++ b/crates/iz-core/migrations/0005_settings.sql @@ -0,0 +1,16 @@ +-- App-level settings, one row per key. +-- +-- The workspace row carries what members share; a key here is the +-- deployment's own and has no workspace to hang off. Two things live here +-- today, both written by the app itself rather than typed into a file: the +-- family list mirrored from im's `/family` (the topbar switcher renders +-- from it), and the public address a sign-out that started here sends the +-- browser back to. +-- +-- A fresh table, so an old database simply gains it empty on rebuild; +-- `iz reconcile` maps it and copies nothing, because an older database +-- has no rows to give. +CREATE TABLE setting ( + key TEXT PRIMARY KEY, + value TEXT NOT NULL +); diff --git a/crates/iz-core/src/config.rs b/crates/iz-core/src/config.rs index 93f8448..1b759e2 100644 --- a/crates/iz-core/src/config.rs +++ b/crates/iz-core/src/config.rs @@ -63,27 +63,6 @@ base_url = "" # revoked sign-in stops receiving within this long. live_seconds = 300 -# The dizey family, as the topbar's wordmark switcher shows it: one -# [[services]] table per app, with key ("in"|"im"|"iz"), a human name, and -# the url, absolute, no trailing slash. An empty list keeps the switcher -# off. Production serves the family at https://.dizey.sh, written in -# the deploy's own config; this file carries only the development -# addresses. -[[services]] -key = "in" -name = "Files" -url = "http://127.0.0.1:7655" - -[[services]] -key = "im" -name = "Account" -url = "http://127.0.0.1:7650" - -[[services]] -key = "iz" -name = "Board" -url = "http://127.0.0.1:7654" - [oidc] # The provider that signs people in. Required: no default is guessed. issuer = "" @@ -150,17 +129,6 @@ const OPTIONAL_KEYS: &[(&str, &str)] = &[ "base_url = \"\"\n" ), ), - ( - "services", - concat!( - "# The dizey family, as the topbar's wordmark switcher shows it: one\n", - "# [[services]] table per app, with key (\"in\"|\"im\"|\"iz\"), a human\n", - "# name, and the url, absolute, no trailing slash. An empty list keeps\n", - "# the switcher off. Production serves the family at\n", - "# https://.dizey.sh, written in the deploy's own config.\n", - "services = []\n" - ), - ), ]; /// The `[oidc]` table of `config/iz.toml`, before the values are checked. @@ -176,15 +144,6 @@ struct OidcToml { other: std::collections::BTreeMap, } -/// One `[[services]]` entry of `config/iz.toml`, before the values are -/// checked. -#[derive(Deserialize)] -struct ServiceToml { - key: String, - name: String, - url: String, -} - /// The shape of `config/iz.toml`, before the values are checked. Anything /// else the file says lands in `other`, which is read for its key names only /// — enough for the report to say a key was seen and not obeyed. @@ -195,7 +154,6 @@ struct Toml { listen: Option, live_seconds: Option, base_url: Option, - services: Option>, oidc: Option, #[serde(flatten)] other: std::collections::BTreeMap, @@ -215,18 +173,6 @@ pub struct OidcConfig { pub redirect_uri: String, } -/// One of the apps the topbar's wordmark switcher links to. -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct ServiceConfig { - /// The wordmark, lowercase — and how the app recognises itself in the - /// list (`"iz"` here). - pub key: String, - /// The human name, offered as the link's title: "Files", "Account". - pub name: String, - /// Where the app lives: absolute, no trailing slash. - pub url: String, -} - /// What the process needs to know before it opens a socket. #[derive(Clone, Debug, PartialEq, Eq)] pub struct Config { @@ -251,9 +197,6 @@ pub struct Config { /// `redirect_uri` has. It is where the family sends the browser back /// to after a sign-out that started here. pub base_url: String, - /// The apps of the family, as the topbar's wordmark switcher links - /// them. Empty: no switcher, and everything else stays as it was. - pub services: Vec, /// The OIDC provider İz trusts. pub oidc: OidcConfig, /// Whether `config/iz.toml` did not exist and was just written with the @@ -370,25 +313,6 @@ impl Config { // everyone else follows `listen` for free. let base_url = value(toml.base_url).unwrap_or_default(); - // An entry that cannot be shown — no wordmark, no name, no - // destination — is refused rather than rendered half of itself. - let mut services = Vec::new(); - for service in toml.services.unwrap_or_default() { - if service.key.trim().is_empty() - || service.name.trim().is_empty() - || service.url.trim().is_empty() - { - return Err(ConfigError::Invalid { - key: "services", - why: "every [[services]] needs a non-empty key, name and url".to_string(), - }); - } - services.push(ServiceConfig { - key: service.key, - name: service.name, - url: service.url, - }); - } // Zero would mean a stream that ends the moment it opens, which is a // reconnect loop rather than a live feed; the key is refused rather // than quietly corrected, because a deployment that meant to say @@ -419,7 +343,6 @@ impl Config { storage, listen, base_url, - services, live_seconds, oidc: OidcConfig { issuer, @@ -583,17 +506,13 @@ fn complete(path: &Path, text: &str, base: &Path) { } } -/// Whether the file sets this key — a line whose first word it is, or an -/// array-of-tables header naming it (`[[services]]`), which is how a list -/// of tables says the same thing. A key named inside a comment or a value -/// does not count. +/// Whether the file sets this key — a line whose first word it is. A key +/// named inside a comment or a value does not count. fn mentions(text: &str, key: &str) -> bool { - let header = format!("[[{key}]]"); text.lines().any(|line| { - let line = line.trim_start(); - line.strip_prefix(key) + line.trim_start() + .strip_prefix(key) .is_some_and(|rest| rest.trim_start().starts_with('=')) - || line.starts_with(&header) }) } @@ -718,7 +637,7 @@ mod tests { std::fs::create_dir_all(dir.join("config")).unwrap(); let mine = &format!( "database = \"iz.db\"\nstorage = \"files\"\nlisten = \"0.0.0.0:8080\"\n\ - live_seconds = 30\nbase_url = \"\"\nservices = []\n{OIDC}" + live_seconds = 30\nbase_url = \"\"\n{OIDC}" ); std::fs::write(dir.join(FILE_NAME), mine).unwrap(); let config = Config::load_from(&dir).unwrap(); @@ -960,40 +879,17 @@ mod tests { ); } - /// The family list parses into the switcher's entries, in the order the - /// file gives them — the order the wordmarks show. - #[test] - fn services_parse_into_the_switcher_list() { - let config = Config::parse( - &format!( - "database = \"iz.db\"\n\ - [[services]]\nkey = \"in\"\nname = \"Files\"\nurl = \"http://127.0.0.1:7655\"\n\ - [[services]]\nkey = \"iz\"\nname = \"Board\"\nurl = \"http://127.0.0.1:7654\"\n\ - [[services]]\nkey = \"im\"\nname = \"Account\"\nurl = \"http://127.0.0.1:7650\"\n\ - {OIDC}" - ), - Path::new("."), - false, - ) - .unwrap(); - let keys: Vec<&str> = config.services.iter().map(|s| s.key.as_str()).collect(); - assert_eq!(keys, vec!["in", "iz", "im"]); - assert_eq!(config.services[1].name, "Board"); - assert_eq!(config.services[0].url, "http://127.0.0.1:7655"); - } - - /// A file silent about the family keeps the switcher off, and the - /// address the family returns the browser to falls back to the address - /// bound — the same fallback `redirect_uri` has. + /// A file silent about a `base_url` keeps the address the family + /// returns the browser to derived from the address bound — the same + /// fallback `redirect_uri` has. #[test] - fn without_services_or_base_url_the_switcher_is_off_and_the_address_is_derived() { + fn without_a_base_url_the_address_is_derived() { let config = Config::parse( &format!("database = \"iz.db\"\nlisten = \"0.0.0.0:9000\"\n{OIDC}"), Path::new("."), false, ) .unwrap(); - assert!(config.services.is_empty()); assert_eq!(config.public_url(), "http://127.0.0.1:9000"); } @@ -1013,27 +909,6 @@ mod tests { assert_eq!(config.public_url(), "https://iz.dizey.sh"); } - /// An entry that could not be shown — a wordmark, a name or a - /// destination missing — stops the boot naming the key, rather than - /// rendering half a link. - #[test] - fn a_service_missing_a_field_stops_the_boot_naming_the_key() { - let problem = Config::parse( - &format!( - "database = \"iz.db\"\n\ - [[services]]\nkey = \"in\"\nname = \"\"\nurl = \"http://127.0.0.1:7655\"\n\ - {OIDC}" - ), - Path::new("."), - false, - ) - .unwrap_err(); - assert!( - matches!(problem, ConfigError::Invalid { key: "services", .. }), - "{problem:?}" - ); - } - #[test] fn a_key_inside_oidc_nothing_reads_is_named_with_its_table() { let config = Config::parse( @@ -1067,28 +942,4 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } - /// A file that already carries `[[services]]` tables is not completed - /// with the empty list: the header is how a list of tables says the - /// key is set, and an appended `services = []` beside it would read as - /// a phantom, empty extra entry. - #[test] - fn completion_does_not_add_services_beside_tables_already_there() { - let dir = scratch(); - std::fs::create_dir_all(dir.join("config")).unwrap(); - let mine = &format!( - "database = \"iz.db\"\n\ - [[services]]\nkey = \"in\"\nname = \"Files\"\nurl = \"http://127.0.0.1:7655\"\n{OIDC}" - ); - std::fs::write(dir.join(FILE_NAME), mine).unwrap(); - Config::load_from(&dir).unwrap(); - let written = std::fs::read_to_string(dir.join(FILE_NAME)).unwrap(); - assert_eq!(written.matches("[[services]]").count(), 1, "{written}"); - assert!(!written.contains("services = []"), "{written}"); - // What was there is untouched: the sole family entry survives, and - // a re-parse reads it back as exactly one service. - assert!(written.contains("key = \"in\""), "{written}"); - let reparsed: toml::Value = toml::from_str(&written).unwrap(); - assert_eq!(reparsed["services"].as_array().map(Vec::len), Some(1)); - let _ = std::fs::remove_dir_all(&dir); - } } diff --git a/crates/iz-core/src/store/mod.rs b/crates/iz-core/src/store/mod.rs index afe9517..9c385d7 100644 --- a/crates/iz-core/src/store/mod.rs +++ b/crates/iz-core/src/store/mod.rs @@ -720,6 +720,23 @@ pub trait Store: BoardReads + DetailReads + 'static { reminder_minutes: u32, ) -> Result<()>; + // -- app settings ------------------------------------------------------ + + /// One app-level setting, by key. `None` when the key was never set — + /// the caller owns the default, not the row. + /// + /// App-level on purpose: the workspace row carries what members share, + /// while a key here belongs to the deployment itself — the family list + /// mirrored from im, the public address a sign-out lands on. No + /// workspace column, because there is no workspace to name. + async fn get_setting(&self, key: &str) -> Result>; + + /// Writes one app-level setting, creating or replacing the row. + /// Quiet by design: a background mirror rewrites its key every beat, + /// and an announcement it cannot help is one nobody asked for. What a + /// settings save owes the screen it lands on, the redirect carries. + async fn set_setting(&self, key: &str, value: &str) -> Result<()>; + // -- users ------------------------------------------------------------- /// Upserts the account for a person who just proved who they are to im. diff --git a/crates/iz-core/src/store/reconcile.rs b/crates/iz-core/src/store/reconcile.rs index c78691a..7c337f9 100644 --- a/crates/iz-core/src/store/reconcile.rs +++ b/crates/iz-core/src/store/reconcile.rs @@ -554,6 +554,10 @@ fn build_maps( "created_at", ]), }); + maps.push(TableMap { + name: "setting", + columns: old_cols(&["key", "value"]), + }); maps } @@ -742,6 +746,7 @@ async fn copy_data(old_conn: &Connection, new_conn: &Connection, path: &str) -> let has_clock = old_has_column(old_conn, "task", "clock_at").await?; let has_reminder = old_has_column(old_conn, "workspace", "reminder_minutes").await?; let has_tag = old_has_column(old_conn, "tag", "id").await?; + let has_setting = old_has_column(old_conn, "setting", "key").await?; let maps = build_maps( has_smtp_check, has_batch_window, @@ -759,6 +764,13 @@ async fn copy_data(old_conn: &Connection, new_conn: &Connection, path: &str) -> if map.name == "tag" && !has_tag { continue; } + // A database from before app-level settings has no `setting` table: + // nothing to copy — the rebuilt table starts empty, and the first + // boot's family mirror refills it. The map itself still exists, so + // `validate_maps` sees the declared table covered either way. + if map.name == "setting" && !has_setting { + continue; + } // The default tags are seeded just before `task`: the old tags are // already in, so seeding only tops up the boards the copy left // without a default — it can therefore never violate diff --git a/crates/iz-core/src/store/schema.rs b/crates/iz-core/src/store/schema.rs index 2a9af5c..53cac8c 100644 --- a/crates/iz-core/src/store/schema.rs +++ b/crates/iz-core/src/store/schema.rs @@ -18,6 +18,7 @@ pub(crate) const MIGRATIONS: &[&str] = &[ include_str!("../../migrations/0002_security_knobs.sql"), include_str!("../../migrations/0003_sso.sql"), include_str!("../../migrations/0004_no_photo_limit.sql"), + include_str!("../../migrations/0005_settings.sql"), ]; /// The whole declared schema — every migration applied in order — as one diff --git a/crates/iz-core/src/store/turso_store.rs b/crates/iz-core/src/store/turso_store.rs index d46cf04..639f7df 100644 --- a/crates/iz-core/src/store/turso_store.rs +++ b/crates/iz-core/src/store/turso_store.rs @@ -1707,6 +1707,28 @@ impl Store for TursoStore { Ok(()) } + async fn get_setting(&self, key: &str) -> Result> { + match self + .one_row("SELECT value FROM setting WHERE key = ?1", params![key]) + .await? + { + Some(row) => Ok(Some(text(&row, 0)?)), + None => Ok(None), + } + } + + async fn set_setting(&self, key: &str, value: &str) -> Result<()> { + let conn = self.conn.lock().await; + conn.execute( + "INSERT INTO setting (key, value) VALUES (?1, ?2) \ + ON CONFLICT (key) DO UPDATE SET value = excluded.value", + params![key, value], + ) + .await + .map_err(backend)?; + Ok(()) + } + async fn set_limits( &self, workspace_id: &str, diff --git a/crates/iz-core/tests/store.rs b/crates/iz-core/tests/store.rs index 17bf65f..2888f59 100644 --- a/crates/iz-core/tests/store.rs +++ b/crates/iz-core/tests/store.rs @@ -5568,7 +5568,14 @@ fn every_writing_method_announces_or_is_named_here() { // announce for themselves when they commit. Announcing the lease as // well would wake every connected client on every sweep for a screen // that would look identical. - const SILENT_ON_PURPOSE: &[&str] = &["claim_sends_owed"]; + // + // `set_setting` serves two keys: the public address a sign-out hands + // the browser to, and the family list the background beat rewrites + // every five minutes from im. Neither renders on a live screen — the + // logout handoff is resolved per request, the switcher is served with + // the page — and an announcement the mirror cannot help would wake + // every open client, every beat, for nothing. + const SILENT_ON_PURPOSE: &[&str] = &["claim_sends_owed", "set_setting"]; let source = include_str!("../src/store/turso_store.rs"); let start = source @@ -8432,3 +8439,45 @@ async fn a_sync_without_a_workspace_skips_and_writes_nothing() { assert_eq!(sync, iz_core::store::MemberSync::Skipped); assert!(scratch.store.workspace().await.unwrap().is_none()); } + +/// The app-level setting drawer: a key never set reads as absent, one set +/// reads back, and setting it again replaces rather than duplicates — the +/// family mirror rewrites its key every beat, and two rows for one key +/// would make "which one renders" a coin flip. +#[tokio::test] +async fn app_settings_round_trip_through_one_row_per_key() { + let scratch = Scratch::open().await; + + assert_eq!(scratch.store.get_setting("family").await.unwrap(), None); + + scratch + .store + .set_setting("family", r#"[{"key":"in"}]"#) + .await + .unwrap(); + assert_eq!( + scratch.store.get_setting("family").await.unwrap(), + Some(r#"[{"key":"in"}]"#.to_string()) + ); + + scratch.store.set_setting("family", "[]").await.unwrap(); + assert_eq!( + scratch.store.get_setting("family").await.unwrap(), + Some("[]".to_string()) + ); + + // Keys are independent drawers: rewriting one leaves the other alone. + scratch + .store + .set_setting("public_url", "https://iz.example") + .await + .unwrap(); + assert_eq!( + scratch.store.get_setting("family").await.unwrap(), + Some("[]".to_string()) + ); + assert_eq!( + scratch.store.get_setting("public_url").await.unwrap(), + Some("https://iz.example".to_string()) + ); +} diff --git a/crates/iz-web/src/i18n.rs b/crates/iz-web/src/i18n.rs index 9f2a341..fd7bdad 100644 --- a/crates/iz-web/src/i18n.rs +++ b/crates/iz-web/src/i18n.rs @@ -185,6 +185,9 @@ pub enum Key { NotFromAddress, NotAnOrigin, LinkAddressLabel, + Server, + PublicAddressLabel, + PublicAddressNote, SenderNotConfiguredYet, // pages.rs @@ -662,6 +665,19 @@ pub fn t(lang: Lang, key: Key) -> &'static str { (NotAnOrigin, Tr) => "http:// veya https:// adresi değil.", (LinkAddressLabel, En) => "Link address", (LinkAddressLabel, Tr) => "Bağlantı adresi", + (Server, En) => "Server", + (Server, Tr) => "Sunucu", + (PublicAddressLabel, En) => "Public address", + (PublicAddressLabel, Tr) => "Genel adres", + (PublicAddressNote, En) => { + "Where the family sends the browser after a sign-out that started \ + here. Empty: the configured address, then the one this server binds." + } + (PublicAddressNote, Tr) => { + "Aile, burada başlayan bir oturum kapanışından sonra tarayıcıyı \ + buraya gönderir. Boş: yapılandırılmış adres, sonra bu sunucunun \ + bağlandığı adres." + } (SenderNotConfiguredYet, En) => "No sender to test.", (SenderNotConfiguredYet, Tr) => "Test edilecek gönderen yok.", diff --git a/crates/iz-web/src/layout.rs b/crates/iz-web/src/layout.rs index da8817a..0869ae0 100644 --- a/crates/iz-web/src/layout.rs +++ b/crates/iz-web/src/layout.rs @@ -14,7 +14,7 @@ use topcoat::{ }; use crate::i18n::{Key, Lang, t}; -use crate::server::current_user; +use crate::server::{FAMILY_KEY, current_user, store}; /// The İz monogram again, as the tab icon: the same drawing as `wordmark`, /// 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 } } -/// The family's wordmark trio — `in im iz` — as the topbar's switcher -/// between the apps of dizey.sh. The current app is held in ink and marked -/// `aria-current`; the others are plain doors out, titled with the human -/// name the config gives them. Rendered only when config/iz.toml lists -/// services, so a deployment standing alone shows a chrome without the -/// trio. The links leave this origin, so they carry `data-hard`, like the -/// issuer link in the user menu. +/// The family list as the switcher shows it, read from the app's own +/// `setting` store — the mirror im's admin panel feeds through the +/// background beat in `main.rs`. Absent, empty, unparseable or a store +/// that will not answer all read the same: an empty list, which renders +/// no switcher. A page must not fail for the want of a wordmark. +async fn family_of(cx: &Cx) -> Vec { + match store(cx).get_setting(FAMILY_KEY).await { + Ok(Some(raw)) => serde_json::from_str(&raw).unwrap_or_default(), + _ => Vec::new(), + } +} + +/// The family's wordmark switcher — `in im iz` — as the topbar's way +/// between the apps of dizey.sh. The current app is held in ink and +/// marked `aria-current`; the others are plain doors out, titled with the +/// human name im's admin panel gives them. The list is the app's own +/// mirror of im's `/family` ([`family_of`]), so the panel decides the +/// trio without a deploy here, and a mirror that has not arrived yet — +/// or a deployment standing alone — shows a chrome without the trio. The +/// links leave this origin, so they carry `data-hard`, like the issuer +/// link in the user menu. async fn service_switcher(cx: &Cx) -> Result { const SELF: &str = "iz"; - let services = crate::server::config(cx).services; + let family = family_of(cx).await; view! { cx => - if !services.is_empty() { + if !family.is_empty() { @@ -1481,6 +1536,40 @@ async fn settings_page(cx: &Cx) -> Result { } + if section == Section::Server { +
+
+

(t(lang, Key::Server))

+ (t(lang, Key::AdminOnly)) +
+
+ +

(t(lang, Key::PublicAddressNote))

+
+
+
+
+ if let Some(refusal) = &server_refusal { + (refusal.message_in(lang)) + } + if server_saved { + (t(lang, Key::Saved)) + } + +
+
+
+ } + if section == Section::Members && let Some(members) = &members {
diff --git a/crates/iz-web/tests/http.rs b/crates/iz-web/tests/http.rs index 0d7d5d7..e5d3b24 100644 --- a/crates/iz-web/tests/http.rs +++ b/crates/iz-web/tests/http.rs @@ -280,12 +280,15 @@ struct App { impl App { async fn build(mail: Mail) -> Self { - Self::build_with(mail, Vec::new()).await + Self::build_with(mail, None, "").await } - /// Like `build`, but with a `[[services]]` list, so a test can see the - /// family switcher a configured deployment shows. - async fn build_with(mail: Mail, services: Vec) -> Self { + /// Like `build`, but with the knobs a configured deployment has: the + /// family list mirrored from im — passed as the raw JSON the `setting` + /// row holds, so a test can also feed it a body that will not parse — + /// and the configured `base_url`. Building them in is what lets the + /// switcher and the sign-out handoff be asserted over real HTTP. + async fn build_with(mail: Mail, family: Option, base_url: &str) -> Self { let dir = std::env::temp_dir().join(format!("iz-http-{}", Ulid::new())); std::fs::create_dir_all(&dir).unwrap(); let db = dir.join("iz.db"); @@ -295,23 +298,21 @@ impl App { .await .unwrap(), ); + // The family list is a mirror, not a config: the test plays the + // part of the background beat that stores what im served. + if let Some(family) = &family { + store + .set_setting(iz_web::server::FAMILY_KEY, family) + .await + .unwrap(); + } let fake = FakeIm::spawn().await; - let client = iz_client::Config { - issuer: fake.url(), - client_id: "iz-test".to_string(), - client_secret: "s3cr3t".to_string(), - redirect_uri: "http://127.0.0.1:7655/auth/callback".to_string(), - logout_back: "http://127.0.0.1:7655/".to_string(), - cookie_name: "iz_session".to_string(), - cookie_key: [7u8; 32], - }; let config = iz_core::Config { database: db, storage, listen: "127.0.0.1:7655".parse().unwrap(), live_seconds: 300, - base_url: String::new(), - services, + base_url: base_url.to_string(), oidc: iz_core::config::OidcConfig { issuer: fake.url(), client_id: "iz-test".to_string(), @@ -321,6 +322,17 @@ impl App { ignored: Vec::new(), defaulted: false, }; + // The fallback half of the chain, built exactly as `main.rs` builds + // it: the configured public address, else the address bound. + let client = iz_client::Config { + issuer: fake.url(), + client_id: "iz-test".to_string(), + client_secret: "s3cr3t".to_string(), + redirect_uri: "http://127.0.0.1:7655/auth/callback".to_string(), + logout_back: config.public_url(), + cookie_name: "iz_session".to_string(), + cookie_key: [7u8; 32], + }; let (stop, stopping) = tokio::sync::watch::channel(false); let router = iz_client::mount( Router::builder() @@ -337,6 +349,9 @@ impl App { client.clone(), ) .app_context(store.clone()) + .app_context(iz_client::LogoutBack(Arc::new( + iz_web::server::logout_back, + ))) .app_context(config.clone()) .app_context(TEST_LIVE_WINDOW) .app_context(iz_web::live::Shutdown(stopping)) @@ -375,21 +390,11 @@ impl App { "https://iz.sh", )); let fake = FakeIm::spawn().await; - let client = iz_client::Config { - issuer: fake.url(), - client_id: "iz-test".to_string(), - client_secret: "s3cr3t".to_string(), - redirect_uri: "http://127.0.0.1:7655/auth/callback".to_string(), - logout_back: "http://127.0.0.1:7655/".to_string(), - cookie_name: "iz_session".to_string(), - cookie_key: [7u8; 32], - }; let config = iz_core::Config { database: db, storage, listen: "127.0.0.1:7655".parse().unwrap(), base_url: String::new(), - services: Vec::new(), live_seconds: 300, oidc: iz_core::config::OidcConfig { issuer: fake.url(), @@ -400,6 +405,17 @@ impl App { ignored: Vec::new(), defaulted: false, }; + // The fallback half of the chain, built exactly as `main.rs` builds + // it: the configured public address, else the address bound. + let client = iz_client::Config { + issuer: fake.url(), + client_id: "iz-test".to_string(), + client_secret: "s3cr3t".to_string(), + redirect_uri: "http://127.0.0.1:7655/auth/callback".to_string(), + logout_back: config.public_url(), + cookie_name: "iz_session".to_string(), + cookie_key: [7u8; 32], + }; let (stop, stopping) = tokio::sync::watch::channel(false); let router = iz_client::mount( Router::builder() @@ -416,6 +432,9 @@ impl App { client.clone(), ) .app_context(store.clone()) + .app_context(iz_client::LogoutBack(Arc::new( + iz_web::server::logout_back, + ))) .app_context(config.clone()) .app_context(TEST_LIVE_WINDOW) .app_context(iz_web::live::Shutdown(stopping)) @@ -9580,9 +9599,12 @@ fn the_stylesheet_guard_refuses_a_foreign_bundle() { /// Sign-out leaves through the family's front door: the local cookie is /// cleared, and the browser is handed to im's `/logout` with `back` pointed -/// at this app, so the central session ends with the local one. +/// at this app. Where "here" is resolves per request — the stored public +/// address wins, the configured `base_url` is the fallback, and the +/// address the server binds is the last resort. #[tokio::test] async fn a_sign_out_hands_the_browser_to_the_providers_logout_pointed_home() { + // No stored address, no configured one: the bind address answers. let app = App::open().await; let admin = admin(&app).await; 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() { encode("http://127.0.0.1:7655/") ); assert_eq!(raw.location.as_deref(), Some(expected.as_str())); + + // A configured `base_url` is what the fallback says when nothing is + // stored — a deployment behind a proxy says its name once, in the file. + let configured = App::build_with(Mail::silent(), None, "https://board.example").await; + let raw = configured.get("/auth/logout", None).await; + let expected = format!( + "{}/logout?back={}", + configured.client.issuer, + encode("https://board.example/") + ); + assert_eq!(raw.location.as_deref(), Some(expected.as_str())); + + // A stored public address wins over the configured chain, and it reads + // per request: no restart between the save and the next sign-out. + let stored = App::build_with(Mail::silent(), None, "https://stale.example").await; + stored + .store + .set_setting(iz_web::server::PUBLIC_URL_KEY, "https://stored.example") + .await + .unwrap(); + let raw = stored.get("/auth/logout", None).await; + let expected = format!( + "{}/logout?back={}", + stored.client.issuer, + encode("https://stored.example/") + ); + assert_eq!(raw.location.as_deref(), Some(expected.as_str())); } -/// The signed-in chrome carries the family's wordmark trio when the config -/// lists services: one mark per `[[services]]` row in the file's order, the -/// current app held in ink with `aria-current`, the others plain links out. -/// A deployment that lists none shows no switcher at all. +/// The switcher renders the family list the app mirrors from im — the +/// stored JSON, in stored order, with the current app held in ink with +/// `aria-current`, the others plain links out. A list that is absent, +/// empty, or will not parse shows no switcher at all. #[tokio::test] async fn the_topbar_shows_the_family_switcher_and_marks_this_app_only_when_configured() { - let services = vec![ - iz_core::config::ServiceConfig { - key: "in".to_string(), - name: "Files".to_string(), - url: "http://127.0.0.1:7655".to_string(), - }, - iz_core::config::ServiceConfig { - key: "iz".to_string(), - name: "Board".to_string(), - url: "http://127.0.0.1:7654".to_string(), - }, - iz_core::config::ServiceConfig { - key: "im".to_string(), - name: "Account".to_string(), - url: "http://127.0.0.1:7650".to_string(), - }, - ]; - let app = App::build_with(Mail::silent(), services).await; + let family = "\ + [{\"key\":\"in\",\"name\":\"Files\",\"url\":\"http://127.0.0.1:7655\"},\ + {\"key\":\"iz\",\"name\":\"Board\",\"url\":\"http://127.0.0.1:7654\"},\ + {\"key\":\"im\",\"name\":\"Account\",\"url\":\"http://127.0.0.1:7650\"}]" + .to_string(); + let app = App::build_with(Mail::silent(), Some(family), "").await; let board_admin = admin(&app).await; let html = String::from_utf8_lossy(&app.get("/", Some(&board_admin)).await.bytes).to_string(); assert!(html.contains("service-switcher"), "{html}"); assert!(html.contains("service-mark-on"), "{html}"); assert!(html.contains("aria-current=\"page\""), "{html}"); - // The trio reads in the order the config gave, with the current app + // The mirror reads in the order im served it, with the current app // between its neighbours, not pushed to an end. let in_at = html.find("href=\"http://127.0.0.1:7655\"").unwrap(); let iz_at = html.find("service-mark-on").unwrap(); let im_at = html.find("href=\"http://127.0.0.1:7650\"").unwrap(); assert!(in_at < iz_at && iz_at < im_at, "marks out of order: {html}"); - let alone = App::open().await; - let alone_admin = admin(&alone).await; - let plain = String::from_utf8_lossy(&alone.get("/", Some(&alone_admin)).await.bytes).to_string(); + // A list that will not parse hides the switcher rather than rendering + // half of it — and so does an empty one, and a mirror that never + // arrived. + for broken in ["[".to_string(), "[]".to_string()] { + let app = App::build_with(Mail::silent(), Some(broken), "").await; + let board_admin = admin(&app).await; + let html = + String::from_utf8_lossy(&app.get("/", Some(&board_admin)).await.bytes).to_string(); + assert!(!html.contains("service-switcher"), "{html}"); + } + let plain = App::open().await; + let alone_admin = admin(&plain).await; + let plain = + String::from_utf8_lossy(&plain.get("/", Some(&alone_admin)).await.bytes).to_string(); assert!( !plain.contains("service-switcher"), - "no services, no switcher: {plain}" + "no mirror, no switcher: {plain}" ); }