diff --git a/config/in.toml b/config/in.toml index d11aa8a..2068813 100644 --- a/config/in.toml +++ b/config/in.toml @@ -20,31 +20,13 @@ base_url = "" # created on boot. Not written here: it defaults to beside the database file, # and the boot completes this file with the value it resolved. -# The suite the signed-in chrome's switcher links to: one [[services]] -# table per app — `key` the word the switcher renders, `name` its hover -# label, `url` the address the link points at (scheme and host, no -# trailing slash). In names itself among them so the switcher can mark -# where the reader is. Production sets these on the deploy side as -# https://.dizey.sh; this committed copy carries only the -# development addresses. +# The suite the switcher's wordmarks link to is im's to keep — im's admin +# panel owns the list, and In fetches it from im and keeps a mirror. This +# file no longer names the suite; a `[[services]]` block left behind by an +# older file is reported as ignored and then passed over. # Where drive files, thumbnails and staged upload chunks live as files, created on boot. storage = "/home/tahinli/Documents/Code/Rust/in/storage" -[[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 = "http://127.0.0.1:7650" diff --git a/crates/in-client/src/lib.rs b/crates/in-client/src/lib.rs index 0423966..4679917 100644 --- a/crates/in-client/src/lib.rs +++ b/crates/in-client/src/lib.rs @@ -11,6 +11,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; @@ -44,12 +47,16 @@ pub struct Config { pub cookie_name: String, /// 32 bytes, generated once per app and kept out of the repository. pub cookie_key: [u8; 32], - /// The app's public origin — `base_url` when the file sets one, else - /// the address bound, derived the way the app derives its public links. - /// After clearing the local cookie, `/auth/logout` walks the browser on - /// to im's `/logout?back={logout_back}/`, so the central session ends - /// and the person lands back at this app's front door. Empty is legal — - /// im catches a stray `back` on its own `/` — but a real app sets it. + /// The app's public origin as boot knew it — `base_url` when the file + /// sets one, else the address bound. After clearing the local cookie, + /// `/auth/logout` walks the browser on to im's `/logout?back={origin}/`, + /// so the central session ends and the person lands back at this app's + /// front door. This is the fallback: an app that keeps its public + /// address live mounts a [`LogoutBack`] beside [`mount`], and the + /// sign-out asks that first — per exit, so an address changed while the + /// process runs is honored without a restart. Empty is legal — im + /// catches a stray `back` on its own `/` — but a real app sets one of + /// the two. pub logout_back: String, } @@ -88,6 +95,18 @@ impl InClient { } } +/// Where im's `/logout` should send the browser after a sign-out that +/// started here: the app's public origin as it is *now*, asked per +/// sign-out. Apps that keep the address live — a database setting an +/// admin edits while the process runs — mount one of these as an app +/// context beside [`mount`]; absent, or answering `None`, the sign-out +/// falls back to [`Config::logout_back`], the origin as boot knew it. +pub struct LogoutBack(pub Arc Fn(&'a Cx) -> BackAnswer<'a> + Send + Sync>); + +/// The boxed answer a [`LogoutBack`] resolver returns: the origin, or +/// `None` to fall back to [`Config::logout_back`]. +pub type BackAnswer<'a> = Pin> + Send + 'a>>; + /// Registers the client state on the router. The routes themselves register /// through `discover()` — call it as usual. pub fn mount(builder: RouterBuilder, config: Config) -> RouterBuilder { @@ -189,6 +208,49 @@ pub async fn directory(cx: &Cx) -> Option> { reply.json().await.ok() } +/// One entry of im's family list: the word the switcher renders, the +/// human label for its title, and the service's base URL — the shape im's +/// `/family` answers with. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ServiceJson { + pub key: String, + pub name: String, + pub url: String, +} + +impl InClient { + /// The fetch behind [`family`], on the state directly — the shape the + /// background mirror takes, which holds its own `InClient` and has no + /// request context to borrow. + 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() + } +} + +/// im's family list — the suite the signed-in chrome's switcher renders — +/// fetched as the app (`Authorization: Basic base64(client_id ":" +/// client_secret)`, the same credentials the photo route and the +/// introspection round-trip take) from `{issuer}/family`. Only a +/// registered app gets an answer at all. +/// +/// `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 suite: the caller keeps the list it +/// has and asks again next time. +pub async fn family(cx: &Cx) -> Option> { + client(cx).family().await +} + /// Path of im's RFC 7662 introspection endpoint, relative to the issuer. const INTROSPECT_PATH: &str = "/introspect"; @@ -544,19 +606,27 @@ async fn in_callback(cx: &Cx) -> Result { /// Signs out of the app, then out of im: the local cookie is cleared /// first — this app forgets the person even if the central hop never /// lands — and the browser is sent on to im's `/logout` with this app's -/// public address as `back`. im revokes the central session and returns -/// them here. The hop is a top-level navigation (the user menu's sign-out -/// link carries `data-hard`), never a fetch. +/// public address as `back`. The address is resolved here, per sign-out: +/// a [`LogoutBack`] mounted beside `mount` answers first, so an origin +/// changed while the process runs is honored on the very next exit, and +/// `Config::logout_back` — the origin as boot knew it — stands in when +/// nothing live answers. im revokes the central session and returns the +/// browser to wherever `back` named. The hop is a top-level navigation +/// (the user menu's sign-out link carries `data-hard`), never a fetch. #[route(GET "/auth/logout")] async fn in_logout(cx: &Cx) -> Result { let state = client(cx); clear_cookie(cx, &state.config.cookie_name); + let back = match try_app_context::(cx) { + Some(ask) => (ask.0)(cx).await.unwrap_or_else(|| state.config.logout_back.clone()), + None => state.config.logout_back.clone(), + }; see( cx, &format!( "{}/logout?back={}", state.config.issuer, - urlencoded(&format!("{}/", state.config.logout_back)), + urlencoded(&format!("{}/", back)), ), ) } diff --git a/crates/in-core/src/config.rs b/crates/in-core/src/config.rs index 23e7237..21e78f6 100644 --- a/crates/in-core/src/config.rs +++ b/crates/in-core/src/config.rs @@ -202,14 +202,6 @@ struct R2Toml { other: std::collections::BTreeMap, } -/// One `[[services]]` entry, before the values are checked. -#[derive(Deserialize)] -struct ServiceToml { - key: Option, - name: Option, - url: Option, -} - /// The shape of `config/in.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. @@ -223,7 +215,6 @@ struct Toml { default_quota_bytes: Option, base_url: Option, oidc: Option, - services: Option>, #[serde(flatten)] other: std::collections::BTreeMap, } @@ -258,21 +249,6 @@ pub struct R2Config { pub key_file: PathBuf, } -/// One entry of the `[[services]]` list: an app of the suite the signed-in -/// chrome's switcher links to. -#[derive(Clone, Debug, PartialEq, Eq, Deserialize)] -pub struct ServiceConfig { - /// The word the switcher renders for it — `in`, `im`, `iz`. The entry - /// whose key is this app's own (`"in"`) is the one marked as where the - /// reader already is. - pub key: String, - /// The human label — "Files", "Account", "Board" — the link's title. - pub name: String, - /// The service's base URL: scheme and host, no trailing slash — the - /// shape `base_url` has, refused on the same terms. - pub url: String, -} - /// What the process needs to know before it opens a socket. #[derive(Clone, Debug, PartialEq, Eq)] pub struct Config { @@ -302,10 +278,6 @@ pub struct Config { /// banners that mint them — when the file sets one. `None` follows the /// address bound. pub base_url: Option, - /// The suite the signed-in chrome's switcher links to, from the - /// `[[services]]` tables. An empty list is a file silent about any - /// suite, and the chrome stays exactly as it has always been. - pub services: Vec, /// The OIDC provider In trusts. pub oidc: OidcConfig, /// Keys the file sets that nothing here reads, in the order the file @@ -482,22 +454,6 @@ impl Config { })?; } - // The suite the chrome's switcher links to. A silent list keeps the - // single-app chrome; an entry present must be whole, because a - // wordmark pointing nowhere is worse than none — and its url must - // be joinable to a link for the same reason `base_url` must. - let mut services = Vec::new(); - for (i, entry) in toml.services.unwrap_or_default().into_iter().enumerate() { - let key = value(entry.key) - .ok_or_else(|| service_error(i, "its key is missing or empty".into()))?; - let name = value(entry.name) - .ok_or_else(|| service_error(i, "its name is missing or empty".into()))?; - let url = value(entry.url) - .ok_or_else(|| service_error(i, "its url is missing or empty".into()))?; - Config::validate_base_url(&url).map_err(|why| service_error(i, why))?; - services.push(ServiceConfig { key, name, url }); - } - let oidc_toml = toml.oidc.ok_or(ConfigError::Missing("[oidc]"))?; let issuer = value(oidc_toml.issuer).ok_or(ConfigError::Missing("oidc.issuer"))?; let client_id = value(oidc_toml.client_id).ok_or(ConfigError::Missing("oidc.client_id"))?; @@ -521,7 +477,6 @@ impl Config { purge_after_days, default_quota_bytes, base_url, - services, oidc: OidcConfig { issuer, client_id, @@ -602,15 +557,6 @@ fn listen_url_of(listen: &SocketAddr) -> String { } } -/// The boot error for a `[[services]]` entry that is not whole. Entries are -/// numbered from one, so the message names the offender a human can find. -fn service_error(index: usize, why: String) -> ConfigError { - ConfigError::Invalid { - key: "services", - why: format!("entry {}: {why}", index + 1), - } -} - impl Config { /// Whether a base URL is an origin a public link can be built on: an /// `http` or `https` scheme and no trailing slash. Shared by the file's @@ -947,78 +893,6 @@ redirect_uri = "https://files.example.com/auth/callback" )); } - /// The switcher is off until the file names a suite: a `[[services]]`-less - /// file is the chrome as it has always been, no half-rendered trio. - #[test] - fn a_file_without_services_leaves_the_switcher_off() { - let scratch = Scratch::new(); - scratch.write(FULL); - let config = scratch.load().unwrap(); - assert!(config.services.is_empty()); - } - - #[test] - fn services_parse_in_the_order_the_file_gives_them() { - let scratch = Scratch::new(); - scratch.write(&FULL.replace( - "[oidc]", - "[[services]]\n\ - key = \"in\"\n\ - name = \"Files\"\n\ - url = \"https://files.example.com\"\n\ - \n\ - [[services]]\n\ - key = \"im\"\n\ - name = \"Account\"\n\ - url = \"https://id.example.com\"\n\ - [oidc]", - )); - let config = scratch.load().unwrap(); - assert_eq!( - config.services, - vec![ - ServiceConfig { - key: "in".into(), - name: "Files".into(), - url: "https://files.example.com".into(), - }, - ServiceConfig { - key: "im".into(), - name: "Account".into(), - url: "https://id.example.com".into(), - }, - ] - ); - } - - #[test] - fn a_service_url_without_a_scheme_is_refused() { - let scratch = Scratch::new(); - scratch.write(&FULL.replace( - "[oidc]", - "[[services]]\nkey = \"im\"\nname = \"Account\"\nurl = \"id.example.com\"\n[oidc]", - )); - assert!(matches!( - scratch.load().unwrap_err(), - ConfigError::Invalid { key: "services", .. } - )); - } - - #[test] - fn an_incomplete_service_entry_names_the_offender() { - let scratch = Scratch::new(); - scratch.write(&FULL.replace( - "[oidc]", - "[[services]]\nkey = \"im\"\nname = \"\"\nurl = \"https://id.example.com\"\n[oidc]", - )); - let err = scratch.load().unwrap_err(); - assert!(matches!( - err, - ConfigError::Invalid { key: "services", .. } - )); - assert!(err.to_string().contains("entry 1"), "{err}"); - } - #[test] fn zero_live_seconds_is_refused() { let scratch = Scratch::new(); diff --git a/crates/in-core/src/lib.rs b/crates/in-core/src/lib.rs index 8e27f17..771c786 100644 --- a/crates/in-core/src/lib.rs +++ b/crates/in-core/src/lib.rs @@ -20,7 +20,7 @@ pub use store::{ }; #[cfg(feature = "server")] -pub use config::{Config, ConfigError, OidcConfig, ServiceConfig}; +pub use config::{Config, ConfigError, OidcConfig}; #[cfg(feature = "server")] pub use live::{Change, Topic, next_seq}; #[cfg(feature = "server")] diff --git a/crates/in-web/src/layout.rs b/crates/in-web/src/layout.rs index 96151c1..c935ba4 100644 --- a/crates/in-web/src/layout.rs +++ b/crates/in-web/src/layout.rs @@ -221,23 +221,34 @@ pub async fn topbar_nav(cx: &Cx, active: NavPage, lang: Lang) -> Result { } } -/// This app's key in the `[[services]]` list: the entry matching it is the -/// one marked as where the reader already is. +/// This app's key in the family list: the entry matching it is the one +/// marked as where the reader already is. const SELF_KEY: &str = "in"; -/// The topbar's suite switcher: every `[[services]]` entry as its wordmark, -/// beside the page nav, the current one marked. Rendered only when the file -/// names a suite — a file silent about the others keeps the chrome exactly -/// as it has always been. The links point at the services' own addresses, -/// so the cross-origin ones navigate the browser natively; this app's entry -/// lands where a soft-nav swap would have gone anyway. +/// The suite list as im keeps it, mirrored into the `setting` store under +/// `family` by the background fetch that started at boot. A list that is +/// absent, or not parseable JSON, reads as empty — a suite nobody told +/// this app about keeps the chrome exactly as it has always been. +async fn family_of(cx: &Cx) -> Vec { + match app(cx).store.get_setting("family").await { + Ok(Some(raw)) => serde_json::from_str(&raw).unwrap_or_default(), + _ => Vec::new(), + } +} + +/// The topbar's suite switcher: every family entry as its wordmark, +/// beside the page nav, the current one marked. Rendered only when a +/// mirrored list is actually there. The links point at the services' own +/// addresses, so the cross-origin ones navigate the browser natively; +/// this app's entry lands where a soft-nav swap would have gone anyway. async fn app_switcher(cx: &Cx) -> Result { - let empty = app(cx).config.services.is_empty(); + let family = family_of(cx).await; + let empty = family.is_empty(); view! { cx => if !empty {