diff --git a/crates/iz-web/Cargo.toml b/crates/iz-web/Cargo.toml index cf168e1..189a235 100644 --- a/crates/iz-web/Cargo.toml +++ b/crates/iz-web/Cargo.toml @@ -28,6 +28,7 @@ time.workspace = true thiserror.workspace = true tokio = { workspace = true } async-trait = "0.1.92" +parking_lot = "0.12" # The live stream is built with `futures_util::stream::unfold`; topcoat does # not re-export the futures traits, so this is named directly. futures-util = { version = "0.3", default-features = false } @@ -63,4 +64,3 @@ http = "1.5" http-body-util = "0.1" ulid = { workspace = true } iz-client = { workspace = true, features = ["test-seam"] } -parking_lot = "0.12" diff --git a/crates/iz-web/src/directory.rs b/crates/iz-web/src/directory.rs new file mode 100644 index 0000000..ad38b10 --- /dev/null +++ b/crates/iz-web/src/directory.rs @@ -0,0 +1,99 @@ +//! How the identity mirror stands against im — the facts the Settings +//! Connection card renders. The mirror task writes; the page reads. +//! +//! Deliberately dumb: one mutex over four plain fields, because the card +//! renders once per view and the stream updates a few times a minute. The +//! client id and issuer are public by OIDC design; the client secret never +//! comes near this struct, so the render path cannot leak what it was never +//! given. + +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use parking_lot::Mutex; +use topcoat::context::{Cx, try_app_context}; + +/// The mirror's health, shared between the stream task and the renderer. +#[derive(Clone, Default)] +pub struct DirectoryHealth(Arc>); + +#[derive(Default)] +struct Inner { + /// The `/directory/live` stream is open. + connected: bool, + opened_at: Option, + event_at: Option, + pass_at: Option, +} + +/// One rendered view of [`DirectoryHealth`]: the state word the card shows +/// and the ages behind the two quiet facts. +#[derive(Clone, Copy)] +pub struct Snapshot { + pub connected: bool, + pub event_age: Option, + pub pass_age: Option, +} + +impl DirectoryHealth { + pub fn new() -> Self { + Self::default() + } + + /// The stream opened (or reopened): the card may say Connected. + pub fn connected(&self) { + let mut inner = self.0.lock(); + inner.connected = true; + inner.opened_at = Some(Instant::now()); + } + + /// The stream ended or im refused it: the card says Reconnecting until + /// the next full pass opens a fresh one. + pub fn reconnecting(&self) { + self.0.lock().connected = false; + } + + /// A Profile event came off the stream. + pub fn event(&self) { + self.0.lock().event_at = Some(Instant::now()); + } + + /// A full roster pass finished — the stream's boot replay, a resync + /// after a drop, or the watchdog beat's pass. + pub fn pass(&self) { + self.0.lock().pass_at = Some(Instant::now()); + } + + pub fn snapshot(&self) -> Snapshot { + let inner = self.0.lock(); + let now = Instant::now(); + Snapshot { + connected: inner.connected, + event_age: inner.event_at.map(|at| now.saturating_duration_since(at)), + pass_age: inner.pass_at.map(|at| now.saturating_duration_since(at)), + } + } +} + +/// The health `main.rs` registers on the router beside the directory +/// client it describes. +pub fn health(cx: &Cx) -> &DirectoryHealth { + try_app_context::(cx) + .expect("the directory health was registered on the router") +} + +/// The stream's age in whole seconds, as the card prints it — a short +/// number with its unit, the same shape in every language. +pub fn age_text(age: Option) -> String { + match age { + Some(age) => { + let secs = age.as_secs(); + if secs >= 60 { + format!("{}m", secs / 60) + } else { + format!("{secs}s") + } + } + None => String::new(), + } +} diff --git a/crates/iz-web/src/i18n.rs b/crates/iz-web/src/i18n.rs index fd7bdad..8648c6d 100644 --- a/crates/iz-web/src/i18n.rs +++ b/crates/iz-web/src/i18n.rs @@ -122,6 +122,15 @@ pub enum Key { // settings.rs YourProfile, + Connection, + ConnectionIssuer, + ConnectionClientId, + ConnectionStream, + ConnectionConnected, + ConnectionReconnecting, + ConnectionLastEvent, + ConnectionLastPass, + ConnectionNever, EmailLabel, TimezoneLabel, ThemeLabel, @@ -539,6 +548,24 @@ pub fn t(lang: Lang, key: Key) -> &'static str { (YourProfile, En) => "Your profile", (YourProfile, Tr) => "Profilin", + (Connection, En) => "Connection", + (Connection, Tr) => "Bağlantı", + (ConnectionIssuer, En) => "Issuer", + (ConnectionIssuer, Tr) => "Sağlayıcı", + (ConnectionClientId, En) => "Client ID", + (ConnectionClientId, Tr) => "İstemci kimliği", + (ConnectionStream, En) => "Directory stream", + (ConnectionStream, Tr) => "Dizin akışı", + (ConnectionConnected, En) => "Connected", + (ConnectionConnected, Tr) => "Bağlı", + (ConnectionReconnecting, En) => "Reconnecting", + (ConnectionReconnecting, Tr) => "Yeniden bağlanıyor", + (ConnectionLastEvent, En) => "Last roster event", + (ConnectionLastEvent, Tr) => "Son dizin olayı", + (ConnectionLastPass, En) => "Last full pass", + (ConnectionLastPass, Tr) => "Son tam geçiş", + (ConnectionNever, En) => "never", + (ConnectionNever, Tr) => "hiç", (EmailLabel, En) => "EMAIL", (EmailLabel, Tr) => "E-POSTA", (TimezoneLabel, En) => "TIMEZONE", diff --git a/crates/iz-web/src/lib.rs b/crates/iz-web/src/lib.rs index df56aae..3e08e1a 100644 --- a/crates/iz-web/src/lib.rs +++ b/crates/iz-web/src/lib.rs @@ -6,6 +6,7 @@ pub mod avatar; pub mod board; pub mod detail; +pub mod directory; pub mod dropdown; pub mod files; pub mod i18n; diff --git a/crates/iz-web/src/main.rs b/crates/iz-web/src/main.rs index 1a0798a..eedd751 100644 --- a/crates/iz-web/src/main.rs +++ b/crates/iz-web/src/main.rs @@ -134,7 +134,10 @@ async fn main() { // The shared identity directory: the same issuer and Basic pair the OIDC // side holds, pointed at im's roster. One HTTP pool inside, cheap to // clone — the avatar route reaches it through the router context below, - // and the two mirror tasks carry their own handles. + // and the two mirror tasks carry their own handles. The health beside + // it is what the Settings Connection card renders: the mirror writes, + // the page reads. + let health = iz_web::directory::DirectoryHealth::new(); let directory = im_client::directory::DirectoryClient::new( config.oidc.issuer.clone(), config.oidc.client_id.clone(), @@ -167,8 +170,9 @@ async fn main() { directory.clone(), iz_client::IzClient::new(oidc.clone()), config.base_url.clone(), + health.clone(), )); - tokio::spawn(directory_stream(store.clone(), directory.clone())); + tokio::spawn(directory_stream(store.clone(), directory.clone(), health.clone())); // Told when the process is stopping, so the live streams end instead of // being waited out. See `iz_web::live::Shutdown`. let (stop, stopping) = tokio::sync::watch::channel(false); @@ -186,6 +190,7 @@ async fn main() { ) .app_context(store.clone()) .app_context(directory) + .app_context(health) .app_context(iz_client::LogoutBack(Arc::new(iz_web::server::logout_back))) .app_context(config.clone()) .app_context(iz_web::live::LiveWindow(std::time::Duration::from_secs( @@ -347,13 +352,14 @@ async fn directory_sync( directory: im_client::directory::DirectoryClient, client: iz_client::IzClient, configured_url: String, + health: iz_web::directory::DirectoryHealth, ) { // An address that never arrives would otherwise say so every beat, // five minutes apart, forever. It is one deployment fact, so it is // said once and the mirror goes on without it. let mut said_no_address = false; loop { - mirror_directory(&store, &directory).await; + mirror_directory(&store, &directory, &health).await; // Before asking for the family, this app files itself in it, so a // deployment appears in everyone's switcher without an admin // typing its address. Resolved per beat in the order a sign-out @@ -400,16 +406,19 @@ async fn directory_sync( /// One full pass of im's roster through the member rows: every entry /// through [`iz_core::store::Store::sync_member`], which announces only -/// the rows that actually changed. +/// the rows that actually changed. A pass that landed also stamps the +/// Connection card's "last full pass". async fn mirror_directory( store: &Arc, directory: &im_client::directory::DirectoryClient, + health: &iz_web::directory::DirectoryHealth, ) { match directory.directory().await { Ok(members) => { for member in members { apply_member(store, &member).await; } + health.pass(); } Err(problem) => { eprintln!("directory sync: im did not answer ({problem}); keeping the rows there are") @@ -441,37 +450,47 @@ async fn apply_member( /// closing — wait out a backoff that doubles from one second to thirty, /// replay a full pass (the resync that heals whatever the dead stream /// carried or dropped), and redial. A stream error inside the body is the -/// same exit as a clean close: the pass below is what converges. +/// same exit as a clean close: the pass below is what converges. The +/// Connection card reads its state from the same marks this loop leaves: +/// Connected from the open stream and each event, Reconnecting from every +/// exit in between. async fn directory_stream( store: Arc, directory: im_client::directory::DirectoryClient, + health: iz_web::directory::DirectoryHealth, ) { let mut backoff = std::time::Duration::from_secs(1); loop { - mirror_directory(&store, &directory).await; + mirror_directory(&store, &directory, &health).await; match directory.open_stream().await { Ok(mut stream) => { + health.connected(); backoff = std::time::Duration::from_secs(1); while let Some(event) = stream.next().await { match event { Ok(im_client::directory::DirectoryEvent::Profile(member)) => { + health.event(); apply_member(&store, &member).await; } Err(problem) => { eprintln!("directory stream: {problem}; re-listing"); + health.reconnecting(); break; } } } + health.reconnecting(); } Err(problem) => { eprintln!("directory stream: im did not answer ({problem})"); + health.reconnecting(); } } tokio::time::sleep(backoff).await; backoff = (backoff * 2).min(std::time::Duration::from_secs(30)); } } + /// Waits for something to happen to the mail queue specifically. /// /// The channel carries every topic, and the sweep cares about one. Filtering diff --git a/crates/iz-web/src/settings.rs b/crates/iz-web/src/settings.rs index 323caa4..3eb91e6 100644 --- a/crates/iz-web/src/settings.rs +++ b/crates/iz-web/src/settings.rs @@ -929,6 +929,48 @@ async fn send_message( // Page // --------------------------------------------------------------------------- + +/// The Connection card's body: who im is, as whom iz introduces itself, +/// and whether the live identity feed is open at this moment. Read from +/// the config and the mirror's health only — the client secret is not +/// read here, so no render path can carry it. +async fn connection_card(cx: &Cx, lang: Lang) -> Result { + let oidc = &config(cx).oidc; + let snap = crate::directory::health(cx).snapshot(); + let (state_word, state_class) = if snap.connected { + (t(lang, Key::ConnectionConnected), "connection-on") + } else { + (t(lang, Key::ConnectionReconnecting), "connection-wait") + }; + let event_age = crate::directory::age_text(snap.event_age); + let pass_age = crate::directory::age_text(snap.pass_age); + let never = t(lang, Key::ConnectionNever).to_string(); + let event_line = if event_age.is_empty() { + never.clone() + } else { + format!("{event_age} ago") + }; + let pass_line = if pass_age.is_empty() { never } else { format!("{pass_age} ago") }; + view! { + cx => +
+
(t(lang, Key::ConnectionIssuer))
+
(oidc.issuer.clone())
+
(t(lang, Key::ConnectionClientId))
+
(oidc.client_id.clone())
+
(t(lang, Key::ConnectionStream))
+
+ + (state_word) +
+
(t(lang, Key::ConnectionLastEvent))
+
(event_line)
+
(t(lang, Key::ConnectionLastPass))
+
(pass_line)
+
+ } +} + /// One row of the member list, as an admin may see it. Identity is im's to /// vouch — the row carries no password and no link token, only what the /// workspace itself decides: the role and whether the account is disabled. @@ -1324,6 +1366,20 @@ async fn settings_page(cx: &Cx) -> Result { + + // The identity mirror's stand, for every signed-in member: + // who iz trusts and as whom, and whether the live feed from + // im is open right now. Read-only — the issuer and client id + // are public by OIDC design, and the client secret is never + // read into this page at all. +
+
+

(t(lang, Key::Connection))

+
+
+ (connection_card(cx, lang).await?) +
+
} if section == Section::Outgoing && let Some(sender) = &sender { diff --git a/crates/iz-web/tests/http.rs b/crates/iz-web/tests/http.rs index 8d5cf05..c4804a8 100644 --- a/crates/iz-web/tests/http.rs +++ b/crates/iz-web/tests/http.rs @@ -273,6 +273,9 @@ struct App { store: Arc, client: iz_client::Config, fake: FakeIm, + /// What the Settings Connection card renders: poked by hand in tests + /// the way the mirror task pokes it in the process. + health: iz_web::directory::DirectoryHealth, /// Stands in for Ctrl+C. Held so a test can stop this router the way the /// process stops the real one. stop: tokio::sync::watch::Sender, @@ -333,6 +336,7 @@ impl App { cookie_name: "iz_session".to_string(), cookie_key: [7u8; 32], }; + let health = iz_web::directory::DirectoryHealth::new(); let (stop, stopping) = tokio::sync::watch::channel(false); let router = iz_client::mount( Router::builder() @@ -354,6 +358,7 @@ impl App { "iz-test", "s3cr3t", )) + .app_context(health.clone()) .app_context(iz_client::LogoutBack(Arc::new( iz_web::server::logout_back, ))) @@ -368,6 +373,7 @@ impl App { store, client, fake, + health, stop, } } @@ -421,6 +427,7 @@ impl App { cookie_name: "iz_session".to_string(), cookie_key: [7u8; 32], }; + let health = iz_web::directory::DirectoryHealth::new(); let (stop, stopping) = tokio::sync::watch::channel(false); let router = iz_client::mount( Router::builder() @@ -442,6 +449,7 @@ impl App { "iz-test", "s3cr3t", )) + .app_context(health.clone()) .app_context(iz_client::LogoutBack(Arc::new( iz_web::server::logout_back, ))) @@ -456,6 +464,7 @@ impl App { store, client, fake, + health, stop, } } @@ -5325,6 +5334,64 @@ async fn the_board_carries_the_avatar_fallback_script() { "avatars without the fallback script show the broken-image box: {html}" ); } + +// --------------------------------------------------------------------------- +// Connection card: the identity mirror's stand, on every member's Settings +// --------------------------------------------------------------------------- + +/// The card names the provider and the app's public id, and says Connected +/// while the mirror's health holds an open stream. The client secret is +/// nowhere on the page — it must not even be read into the render path. +#[tokio::test] +async fn the_connection_card_names_its_provider_without_its_secret() { + let app = App::open().await; + let admin = admin(&app).await; + app.health.connected(); + app.health.event(); + app.health.pass(); + + let page = app.get("/settings", Some(&admin)).await; + assert_eq!(page.status.as_u16(), 200); + let html = String::from_utf8(page.bytes).unwrap(); + assert!(html.contains("id=\"connection\""), "no Connection card: {html}"); + assert!( + html.contains("iz-test:s3cr3t") == false, + "the client secret leaked onto the page: {html}" + ); + assert!( + !html.contains("s3cr3t"), + "the client secret leaked onto the page: {html}" + ); + assert!( + html.contains("iz-test"), + "the client id is the card's public fact: {html}" + ); + assert!( + html.contains("Connected"), + "an open stream says Connected: {html}" + ); +} + +/// Between passes — before the first stream opens, or after one died — +/// the card says Reconnecting, and still carries the public facts without +/// the secret. +#[tokio::test] +async fn the_connection_card_says_reconnecting_while_the_stream_is_down() { + let app = App::open().await; + let admin = admin(&app).await; + + let page = app.get("/settings", Some(&admin)).await; + assert_eq!(page.status.as_u16(), 200); + let html = String::from_utf8(page.bytes).unwrap(); + assert!( + html.contains("Reconnecting"), + "a stream that never opened says Reconnecting: {html}" + ); + assert!( + html.contains("iz-test") && !html.contains("s3cr3t"), + "the card names the client without the secret: {html}" + ); +} /// Polls the store until a `Rule` send for `rule_id` addressed to `recipient` /// exists beyond the `already` count — the engine runs off the request in a /// spawned task, so the row is not there yet when the triggering call diff --git a/style/main.scss b/style/main.scss index c4a7026..d5b3ebc 100644 --- a/style/main.scss +++ b/style/main.scss @@ -4365,3 +4365,35 @@ input[type="radio"] { // their columns stack instead of squeezing into slivers. .field-row { flex-wrap: wrap; } } + +// The Settings Connection card: the identity mirror's stand, as facts and a +// state dot — green while the /directory/live stream is open, amber while +// iz waits out a reconnection. +.connection-facts { + display: grid; + grid-template-columns: max-content 1fr; + gap: 0.4rem 1.5rem; + margin: 0; + + dt { + font-weight: 600; + white-space: nowrap; + } +} + +.connection-dot { + display: inline-block; + width: 0.55rem; + height: 0.55rem; + border-radius: 50%; + margin-right: 0.4rem; + vertical-align: baseline; + + &.connection-on { + background: #2e9e5b; + } + + &.connection-wait { + background: #d99a26; + } +}