From 6d3e6a76ba71d49b3862a708253895aa4ec20efd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 9 Sep 2026 03:30:19 +0300 Subject: [PATCH] Admin panel: OIDC client management (create/rotate/revoke) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit im-core: list_clients, rotate_client_secret, and revoke_client join create_client — revoke deletes the registry row with every refresh token and app session minted under it in one immediate transaction; user sign-in sessions stay. im-web: a Clients section in the admin panel — list, add (name + whitespace/comma-separated redirect URIs, as loose as the CLI), and per-row rotate/revoke as the confirm disclosures. Create and rotate answer the house 303 whose shown= ticket picks the fresh pair off a short-lived shelf for exactly one render: the secret never rides a URL, a log line, or the database in plaintext. Revoke reads back ok=client_revoked; unknown ids read no_such_client. Events log client_created/client_rotated/client_revoked with the admin as actor and the client name as detail. CLI: rotate-client and revoke-client arms alongside create-client, server-stopped as ever. Router tests cover the panel lifecycle (non-admin refusal, show-once ticket, old pair dies on rotate, revoke kills introspection) and core tests cover rotate/revoke/list at the store level. --- crates/im-core/src/oidc.rs | 206 ++++++++++++++ crates/im-web/src/admin.rs | 547 +++++++++++++++++++++++++++++++++++- crates/im-web/src/i18n.rs | 89 +++++- crates/im-web/src/main.rs | 79 +++++- crates/im-web/src/pages.rs | 2 + crates/im-web/src/server.rs | 42 ++- 6 files changed, 960 insertions(+), 5 deletions(-) diff --git a/crates/im-core/src/oidc.rs b/crates/im-core/src/oidc.rs index 2126131..07df6e4 100644 --- a/crates/im-core/src/oidc.rs +++ b/crates/im-core/src/oidc.rs @@ -115,6 +115,101 @@ pub fn verify_client_secret(client: &OidcClient, secret: &str) -> bool { digests_match(&client.secret_hash, &hash_token(secret)) } +/// A registered client, as the panel's Clients section and the CLI list it: +/// no secret material — the row's digest stays an internal affair. +#[derive(Debug, Clone)] +pub struct ClientSummary { + pub client_id: ClientId, + pub name: String, + pub redirect_uris: Vec, + pub created_at: time::OffsetDateTime, +} + +/// Every registered client, oldest first — the admin panel's roster. +pub async fn list_clients(store: &Store) -> Result> { + let conn = store.conn.lock().await; + let mut rows = conn + .query( + "SELECT client_id, name, redirect_uris, created_at FROM oidc_clients \ + ORDER BY created_at, client_id", + (), + ) + .await + .map_err(backend)?; + let mut out = Vec::new(); + while let Some(row) = rows.next().await.map_err(backend)? { + let uris_raw = store::text(&row, 2)?; + out.push(ClientSummary { + client_id: ClientId::from(store::text(&row, 0)?), + name: store::text(&row, 1)?, + redirect_uris: serde_json::from_str(&uris_raw) + .map_err(|e| StoreError::Corrupt(format!("redirect_uris {uris_raw:?}: {e}")))?, + created_at: store::parse_stamp(&store::text(&row, 3)?)?, + }); + } + Ok(out) +} + +/// Replaces a client's secret, returning the fresh one — shown exactly once; +/// the row keeps only the new digest and every pair minted before is dead. +/// `None` for an unknown client. +pub async fn rotate_client_secret(store: &Store, client_id: &str) -> Result> { + let conn = store.conn.lock().await; + let secret = Token::mint(); + let updated = conn + .execute( + "UPDATE oidc_clients SET secret_hash = ?1 WHERE client_id = ?2", + turso::params![secret.hash(), client_id], + ) + .await + .map_err(backend)?; + Ok((updated > 0).then_some(secret)) +} + +/// Deletes a client outright: the registry row and every refresh token and +/// app session minted under it, one immediate transaction — no token row +/// outlives the pair that minted it, and introspection reads them as +/// inactive on the very next call. The person's sign-in sessions are not +/// touched: the client's doors close, the browsers' stay open. `false` for +/// an unknown client. +pub async fn revoke_client(store: &Store, client_id: &str) -> Result { + let conn = store.conn.lock().await; + conn.execute("BEGIN IMMEDIATE", ()).await.map_err(backend)?; + let outcome = async { + conn.execute( + "DELETE FROM refresh_tokens WHERE client_id = ?1", + turso::params![client_id], + ) + .await + .map_err(backend)?; + conn.execute( + "DELETE FROM app_sessions WHERE client_id = ?1", + turso::params![client_id], + ) + .await + .map_err(backend)?; + let deleted = conn + .execute( + "DELETE FROM oidc_clients WHERE client_id = ?1", + turso::params![client_id], + ) + .await + .map_err(backend)?; + Ok(deleted > 0) + } + .await; + match outcome { + Ok(known) => { + conn.execute("COMMIT", ()).await.map_err(backend)?; + Ok(known) + } + Err(e) => { + let _ = conn.execute("ROLLBACK", ()).await; + Err(e) + } + } +} + // --------------------------------------------------------------------------- // Authorization codes // --------------------------------------------------------------------------- @@ -910,4 +1005,115 @@ mod tests { assert_eq!(apps.len(), 1); assert_eq!(apps[0].client_id, client_id.as_str()); } + + #[tokio::test] + async fn rotate_client_secret_kills_the_old_pair() { + let store = Store::open(Path::new(":memory:")).await.unwrap(); + let (client_id, original_secret) = + create_client(&store, "drive", vec!["http://app/cb".into()]) + .await + .unwrap(); + + // Rotation replaces the digest: the new secret verifies, the old + // one stops, and the unknown id stays a None. + let rotated = rotate_client_secret(&store, client_id.as_str()) + .await + .unwrap() + .expect("a known client rotates"); + let row = client_by_id(&store, client_id.as_str()) + .await + .unwrap() + .unwrap(); + assert!(verify_client_secret(&row, rotated.expose())); + assert!(!verify_client_secret(&row, original_secret.expose())); + assert!( + rotate_client_secret(&store, "no-such-client") + .await + .unwrap() + .is_none() + ); + } + + #[tokio::test] + async fn revoke_client_deletes_its_tokens_in_one_sweep() { + let (store, client_id, user_id) = fixture().await; + let session = create_session(&store, &user_id, &SessionMeta::default()) + .await + .unwrap(); + let app_token = issue_app_session(&store, &user_id, &client_id, &session.hash()) + .await + .unwrap(); + let refresh = issue_refresh(&store, &user_id, &client_id, &session.hash()) + .await + .unwrap(); + + // Alive until revoked: introspection answers. + assert!( + introspect_app_session(&store, app_token.expose(), client_id.as_str()) + .await + .unwrap() + .is_some() + ); + + assert!(revoke_client(&store, client_id.as_str()).await.unwrap()); + + // The pair is gone, and with it every token minted under it: the + // app session no longer introspects, the refresh no longer turns. + // The person's central session is untouched. + assert!( + introspect_app_session(&store, app_token.expose(), client_id.as_str()) + .await + .unwrap() + .is_none(), + "no ghost app session after client revocation" + ); + assert!( + rotate_refresh(&store, refresh.expose()) + .await + .unwrap() + .is_none() + ); + assert!( + client_by_id(&store, client_id.as_str()) + .await + .unwrap() + .is_none(), + "the registry row itself is gone" + ); + assert_eq!( + crate::sessions::list_sessions(&store, &user_id) + .await + .unwrap() + .len(), + 1, + "the person's own sign-in session stays" + ); + + // Revoking again is a quiet false, not an error. + assert!(!revoke_client(&store, client_id.as_str()).await.unwrap()); + } + + #[tokio::test] + async fn list_clients_returns_the_registry_rows() { + let store = Store::open(Path::new(":memory:")).await.unwrap(); + let (first, _) = create_client( + &store, + "drive", + vec!["http://a/cb".into(), "http://127.0.0.1:9000/cb".into()], + ) + .await + .unwrap(); + let (second, _) = create_client(&store, "in", vec!["https://in.dizey.sh/cb".into()]) + .await + .unwrap(); + let rows = list_clients(&store).await.unwrap(); + assert_eq!(rows.len(), 2); + assert_eq!(rows[0].client_id, first); + assert_eq!(rows[0].name, "drive"); + assert_eq!( + rows[0].redirect_uris, + vec!["http://a/cb", "http://127.0.0.1:9000/cb"] + ); + assert_eq!(rows[1].client_id, second); + } } diff --git a/crates/im-web/src/admin.rs b/crates/im-web/src/admin.rs index 2bb6221..9c63dcd 100644 --- a/crates/im-web/src/admin.rs +++ b/crates/im-web/src/admin.rs @@ -81,6 +81,17 @@ const ADMIN_SCRIPT: &str = r#""#; fn back(cx: &Cx, section: &str, extra: &str) -> Result { @@ -111,12 +122,17 @@ async fn admin_page(cx: &Cx) -> Result { let ok = query_value(&query, "ok"); let why = query_value(&query, "why"); let invited = query_value(&query, "invited"); + // The one read that takes a stashed client secret off the shelf: a + // replayed, reloaded, or forged ticket finds the shelf empty. + let shown = query_value(&query, "shown") + .as_deref() + .and_then(server::take_shown_secret); let nav = |current: &str| { [ ("users", t(lang, Key::NavUsers)), ("services", t(lang, Key::NavServices)), - ("mail", t(lang, Key::NavMail)), + ("clients", t(lang, Key::NavClients)), ("message", t(lang, Key::NavMessage)), ("settings", t(lang, Key::NavSettings)), ("logs", t(lang, Key::NavLogs)), @@ -137,7 +153,7 @@ async fn admin_page(cx: &Cx) -> Result { "settings" => settings_section(cx, lang).await?, "logs" => logs_section(cx, lang).await?, "services" => services_section(cx, lang).await?, - "users" => users_section(cx, &me, invited.as_deref(), lang).await?, + "clients" => clients_section(cx, shown, lang).await?, _ => users_section(cx, &me, invited.as_deref(), lang).await?, }; @@ -158,6 +174,7 @@ async fn admin_page(cx: &Cx) -> Result { "settings" => t(lang, Key::OkSettingsSaved), "services" => t(lang, Key::OkServicesSaved), "email_changed" => t(lang, Key::OkEmailChanged), + "client_revoked" => t(lang, Key::OkClientRevoked), _ => t(lang, Key::OkDone), } )), @@ -616,6 +633,176 @@ async fn service_outcome( } } +/// The relying parties: every client the family's apps sign in with. One +/// table in the panel's own skins — rotate and revoke as the two-step +/// disclosures — and the add line under it wearing the invite form's skin. +/// A create or rotate answers a 303 whose `shown` ticket picks the fresh +/// secret off the shelf for exactly one render; the page never learns a +/// secret twice. +async fn clients_section( + cx: &Cx, + shown: Option<(String, String)>, + lang: i18n::Lang, +) -> Result { + let clients = im_core::oidc::list_clients(&app(cx).store).await?; + let mut rows = String::new(); + for client in &clients { + let id = escape(&client.client_id.to_string()); + let name = escape(&client.name); + let uris = client + .redirect_uris + .iter() + .map(|uri| escape(uri)) + .collect::>() + .join("
"); + let registered = client + .created_at + .format(&time::macros::format_description!("[year]-[month]-[day]")) + .unwrap_or_default(); + // Rotation kills the old pair the moment the new one exists, so it + // says what it costs before it does it — like every destructive row + // action here. + let rotate = confirm_action( + "client", + &id, + "/admin/clients_rotate", + t(lang, Key::RotateWord), + "", + &i18n::rotate_client_title(lang, &name), + t(lang, Key::RotateCost), + t(lang, Key::ConfirmRotate), + ); + let revoke_action = confirm_action( + "client", + &id, + "/admin/clients_revoke", + t(lang, Key::RevokeWord), + " admin-danger", + &i18n::revoke_client_title(lang, &name), + t(lang, Key::RevokeCost), + t(lang, Key::ConfirmRevoke), + ); + rows.push_str(&format!( + r#"{name}{id}{uris}{registered}{rotate}{revoke_action}"#, + )); + } + // The show-once banner: the note says what to do with it, the value is + // click-to-copy, and the shelf behind it has already handed it over. + let shown_html = shown + .map(|(client_id, secret)| { + format!( + r#"
{note}
{id_label}: {client_id}
{secret}
"#, + note = t(lang, Key::SecretShownNote), + id_label = t(lang, Key::ClientIdLabel), + client_id = escape(&client_id), + secret = escape(&secret), + copied = t(lang, Key::CopiedWord), + copy = t(lang, Key::CopyWord), + ) + }) + .unwrap_or_default(); + Ok(format!( + r#"
+
{title}
+ {shown_html} +
+ + + {rows} +
{name_label}{id_label}{uris_label}{registered_label}
+
+
+ + + +
+
"#, + title = t(lang, Key::ClientsTitle), + name_label = t(lang, Key::NameCol), + id_label = t(lang, Key::ClientIdLabel), + uris_label = t(lang, Key::RedirectUrisLabel), + registered_label = t(lang, Key::RegisteredCol), + add = t(lang, Key::ClientAdd), + )) +} + +/// One user of the clients forms: the name, and one or more redirect URIs +/// — whitespace- or comma-separated, as loose as the CLI's argument list, +/// because a family dev's `http://127.0.0.1` redirect is a legitimate row. +#[derive(Deserialize)] +struct ClientForm { + name: String, + redirect_uris: String, +} + +#[route(POST "/admin/clients_add")] +async fn clients_add(cx: &Cx, Form(input): Form) -> Result { + let me = match require_admin(cx).await { + Ok(me) => me, + Err(redirect) => return Ok(redirect), + }; + let name = input.name.trim().to_string(); + let uris: Vec = input + .redirect_uris + .split(|c: char| c.is_whitespace() || c == ',') + .map(str::trim) + .filter(|uri| !uri.is_empty()) + .map(str::to_string) + .collect(); + if name.is_empty() || uris.is_empty() { + return back(cx, "clients", "&error=bad_client"); + } + let (id, secret) = im_core::oidc::create_client(&app(cx).store, &name, uris).await?; + server::log_event(cx, "client_created", Some(&me.email), Some(&name)).await; + let shown = server::stash_shown_secret(id.to_string(), secret.expose().to_string()); + back(cx, "clients", &format!("&shown={shown}")) +} + +#[derive(Deserialize)] +struct ClientAction { + client: String, +} + +#[route(POST "/admin/clients_rotate")] +async fn clients_rotate(cx: &Cx, Form(input): Form) -> Result { + let me = match require_admin(cx).await { + Ok(me) => me, + Err(redirect) => return Ok(redirect), + }; + // The log line names the client like a person, so the name comes off + // the row before the secret under it moves. + let name = match im_core::oidc::client_by_id(&app(cx).store, &input.client).await? { + Some(client) => client.name, + None => return back(cx, "clients", "&error=no_such_client"), + }; + match im_core::oidc::rotate_client_secret(&app(cx).store, &input.client).await? { + Some(secret) => { + server::log_event(cx, "client_rotated", Some(&me.email), Some(&name)).await; + let shown = + server::stash_shown_secret(input.client.clone(), secret.expose().to_string()); + back(cx, "clients", &format!("&shown={shown}")) + } + None => back(cx, "clients", "&error=no_such_client"), + } +} + +#[route(POST "/admin/clients_revoke")] +async fn clients_revoke(cx: &Cx, Form(input): Form) -> Result { + let me = match require_admin(cx).await { + Ok(me) => me, + Err(redirect) => return Ok(redirect), + }; + let name = match im_core::oidc::client_by_id(&app(cx).store, &input.client).await? { + Some(client) => client.name, + None => return back(cx, "clients", "&error=no_such_client"), + }; + if !im_core::oidc::revoke_client(&app(cx).store, &input.client).await? { + return back(cx, "clients", "&error=no_such_client"); + } + server::log_event(cx, "client_revoked", Some(&me.email), Some(&name)).await; + back(cx, "clients", "&ok=client_revoked") +} + /// The knobs the code shipped with, now the panel's: invite and reset link /// lifetimes, the sign-in session's days and per-user ceiling, the pending /// marker's minutes, and the sign-in failure ceiling. Same form skin as Mail. @@ -1564,3 +1751,359 @@ async fn probe( // The chip changed; watching tabs re-read it on the next tick. let _ = live.send(server::LiveEvent::Tick); } + +#[cfg(test)] +mod tests { + use std::path::Path; + use std::sync::Arc; + + use im_core::accounts::{create_invite, create_user_from_invite}; + use im_core::model::{ClientId, UserId}; + use im_core::oidc::{introspect_app_session, issue_app_session, list_clients}; + use im_core::sessions::{SessionMeta, create_session}; + use im_core::store::Store; + use topcoat::cookie::RouterBuilderCookieExt as _; + use topcoat::router::{ + Body, Router, RouterBuilderDiscoverExt as _, StatusCode, header, to_bytes, + }; + + use crate::config::Config; + use crate::server::{self, SESSION_COOKIE}; + + struct Setup { + router: Router, + store: Arc, + admin_id: UserId, + admin_cookie: String, + plain_cookie: String, + } + + async fn setup() -> Setup { + let store = Store::open(Path::new(":memory:")).await.unwrap(); + let invite = create_invite(&store, "root@example.com", None, true) + .await + .unwrap(); + let admin = create_user_from_invite(&store, invite.expose(), "Root", "tDLr9!mZQ2xv") + .await + .unwrap(); + let bare = create_invite(&store, "sid@example.com", None, false) + .await + .unwrap(); + let plain = create_user_from_invite(&store, bare.expose(), "Sid", "tDLr9!mZQ2xv") + .await + .unwrap(); + let admin_session = create_session(&store, &admin.id, &SessionMeta::default()) + .await + .unwrap(); + let plain_session = create_session(&store, &plain.id, &SessionMeta::default()) + .await + .unwrap(); + let (live, _) = tokio::sync::broadcast::channel(64); + let store = Arc::new(store); + let app = server::App { + store: store.clone(), + config: Config { + database: ":memory:".into(), + listen: "127.0.0.1:7650".parse().unwrap(), + issuer: "http://127.0.0.1:7650".into(), + services: Vec::new(), + }, + live, + }; + let router = Router::builder() + .discover() + .cookies() + .app_context(app) + .build(); + Setup { + router, + store, + admin_id: admin.id, + admin_cookie: format!("{SESSION_COOKIE}={}", admin_session.expose()), + plain_cookie: format!("{SESSION_COOKIE}={}", plain_session.expose()), + } + } + + /// A form post through the router, answered as (status, Location, body). + async fn post_form( + router: &Router, + uri: &str, + body: &str, + cookie: Option<&str>, + ) -> (StatusCode, Option, String) { + let mut builder = http::Request::builder() + .method(http::Method::POST) + .uri(uri) + .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded"); + if let Some(cookie) = cookie { + builder = builder.header(header::COOKIE, cookie); + } + let response = router + .handle(builder.body(Body::from(body.to_string())).unwrap()) + .await; + let (parts, body) = response.into_parts(); + let location = parts + .headers + .get(header::LOCATION) + .and_then(|v| v.to_str().ok()) + .map(str::to_string); + let bytes = to_bytes(body, usize::MAX).await.unwrap().to_vec(); + (parts.status, location, String::from_utf8(bytes).unwrap()) + } + + /// A GET with (maybe) a session cookie, answered as (status, Location). + async fn get_location( + router: &Router, + uri: &str, + cookie: Option<&str>, + ) -> (StatusCode, Option) { + let mut builder = http::Request::builder().uri(uri); + if let Some(cookie) = cookie { + builder = builder.header(header::COOKIE, cookie); + } + let response = router.handle(builder.body(Body::empty()).unwrap()).await; + let (parts, _) = response.into_parts(); + let location = parts + .headers + .get(header::LOCATION) + .and_then(|v| v.to_str().ok()) + .map(str::to_string); + (parts.status, location) + } + + fn basic(client_id: &str, secret: &str) -> String { + use base64::Engine as _; + format!( + "Basic {}", + base64::engine::general_purpose::STANDARD.encode(format!("{client_id}:{secret}")) + ) + } + + /// Registers a client through the panel itself and returns the pair the + /// one show-once render would carry: the 303's claim ticket, taken off + /// the shelf — first reader wins. + async fn create_via_panel(setup: &Setup, name: &str) -> (String, String) { + let (status, location, _) = post_form( + &setup.router, + "/admin/clients_add", + &format!("name={name}&redirect_uris=http://127.0.0.1:9000/callback"), + Some(&setup.admin_cookie), + ) + .await; + assert_eq!(status, StatusCode::SEE_OTHER); + let location = location.expect("a 303 back to the section"); + assert!(location.starts_with("/admin?section=clients&shown=")); + let ticket = location.trim_start_matches("/admin?section=clients&shown="); + let (id, secret) = server::take_shown_secret(ticket).expect("the one showing"); + let row = list_clients(&setup.store).await.unwrap(); + assert_eq!(id, row[0].client_id.to_string()); + (id, secret) + } + + /// GETs `/directory` with an app's Basic pair. + async fn directory(router: &Router, authorization: String) -> StatusCode { + let response = router + .handle( + http::Request::builder() + .uri("/directory") + .header(header::AUTHORIZATION, authorization) + .body(Body::empty()) + .unwrap(), + ) + .await; + response.into_parts().0.status + } + + #[tokio::test] + async fn clients_add_shows_the_secret_once_and_the_pair_authenticates() { + let setup = setup().await; + + // The add answers a 303 whose query carries only a claim ticket — + // never the secret itself. + let (status, location, _) = post_form( + &setup.router, + "/admin/clients_add", + "name=drive&redirect_uris=http://127.0.0.1:9000/callback", + Some(&setup.admin_cookie), + ) + .await; + assert_eq!(status, StatusCode::SEE_OTHER); + let location = location.expect("a 303 back to the section"); + assert!(location.starts_with("/admin?section=clients&shown=")); + assert!(!location.contains("secret")); + + // First reader wins: the ticket yields the pair exactly once, then + // the shelf is empty — a replayed or reloaded URL shows nothing. + let ticket = location.trim_start_matches("/admin?section=clients&shown="); + let (id, secret) = server::take_shown_secret(ticket).expect("the one showing"); + assert!(server::take_shown_secret(ticket).is_none()); + assert!( + server::take_shown_secret("a-forged-ticket").is_none(), + "a forged ticket shows nothing" + ); + + // The pair the one render showed authenticates on /directory. + assert_eq!( + directory(&setup.router, basic(&id, &secret)).await, + StatusCode::OK + ); + + // The registry row carries the digest only — the listing can never + // leak the secret. + let rows = list_clients(&setup.store).await.unwrap(); + assert_eq!(rows.len(), 1); + assert_eq!(rows[0].name, "drive"); + assert_ne!(rows[0].client_id.to_string(), secret); + } + + #[tokio::test] + async fn clients_rotate_kills_the_old_pair_and_shows_a_new_secret_once() { + let setup = setup().await; + let (id, old_secret) = create_via_panel(&setup, "drive").await; + + let (status, location, _) = post_form( + &setup.router, + "/admin/clients_rotate", + &format!("client={id}"), + Some(&setup.admin_cookie), + ) + .await; + assert_eq!(status, StatusCode::SEE_OTHER); + let location = location.expect("a 303 back to the section"); + assert!(location.starts_with("/admin?section=clients&shown=")); + let ticket = location.trim_start_matches("/admin?section=clients&shown="); + let (rotated_id, new_secret) = server::take_shown_secret(ticket).expect("the one showing"); + assert_eq!(rotated_id, id, "the shelf names the same client"); + assert_ne!(old_secret, new_secret); + + // The old pair is dead; the new one authenticates. + assert_eq!( + directory(&setup.router, basic(&id, &old_secret)).await, + StatusCode::UNAUTHORIZED + ); + assert_eq!( + directory(&setup.router, basic(&id, &new_secret)).await, + StatusCode::OK + ); + + // An unknown client is the section's refusal, not a minted secret. + let (status, location, _) = post_form( + &setup.router, + "/admin/clients_rotate", + "client=no-such-client", + Some(&setup.admin_cookie), + ) + .await; + assert_eq!(status, StatusCode::SEE_OTHER); + assert_eq!( + location.as_deref(), + Some("/admin?section=clients&error=no_such_client") + ); + } + + #[tokio::test] + async fn clients_revoke_kills_the_pair_and_its_tokens() { + let setup = setup().await; + let (id, secret) = create_via_panel(&setup, "drive").await; + let client_id = ClientId::from(id.clone()); + + // An app session minted under the client, alive until revoked. + let session = create_session(&setup.store, &setup.admin_id, &SessionMeta::default()) + .await + .unwrap(); + let app_token = + issue_app_session(&setup.store, &setup.admin_id, &client_id, &session.hash()) + .await + .unwrap(); + assert!( + introspect_app_session(&setup.store, app_token.expose(), &id) + .await + .unwrap() + .is_some() + ); + + let (status, location, _) = post_form( + &setup.router, + "/admin/clients_revoke", + &format!("client={id}"), + Some(&setup.admin_cookie), + ) + .await; + assert_eq!(status, StatusCode::SEE_OTHER); + assert_eq!( + location.as_deref(), + Some("/admin?section=clients&ok=client_revoked") + ); + + // The pair no longer authenticates, and the app session it minted + // no longer introspects — while the admin's own sign-in session + // lives on. + assert_eq!( + directory(&setup.router, basic(&id, &secret)).await, + StatusCode::UNAUTHORIZED + ); + assert!( + introspect_app_session(&setup.store, app_token.expose(), &id) + .await + .unwrap() + .is_none(), + "no ghost app session after revocation" + ); + assert_eq!( + im_core::sessions::list_sessions(&setup.store, &setup.admin_id) + .await + .unwrap() + .len(), + 2, + "the admin's two sign-in sessions — the cookie's and the one that \ + minted the app token — both stay" + ); + } + + #[tokio::test] + async fn client_routes_refuse_non_admins() { + let setup = setup().await; + + // Every client write answers a non-admin with the panel's plain + // redirect home; nothing is created, rotated, or revoked. + let (status, location, _) = post_form( + &setup.router, + "/admin/clients_add", + "name=drive&redirect_uris=http://127.0.0.1:9000/callback", + Some(&setup.plain_cookie), + ) + .await; + assert_eq!(status, StatusCode::SEE_OTHER); + assert_eq!(location.as_deref(), Some("/")); + let (status, location, _) = post_form( + &setup.router, + "/admin/clients_revoke", + "client=no-such-client", + Some(&setup.plain_cookie), + ) + .await; + assert_eq!(status, StatusCode::SEE_OTHER); + assert_eq!(location.as_deref(), Some("/")); + assert!(list_clients(&setup.store).await.unwrap().is_empty()); + + // The section read is gated the same way. + let (status, location) = get_location( + &setup.router, + "/admin?section=clients", + Some(&setup.plain_cookie), + ) + .await; + assert_eq!(status, StatusCode::SEE_OTHER); + assert_eq!(location.as_deref(), Some("/")); + + // And a signed-out visitor cannot even create. + let (status, _, _) = post_form( + &setup.router, + "/admin/clients_add", + "name=drive&redirect_uris=http://127.0.0.1:9000/callback", + None, + ) + .await; + assert_eq!(status, StatusCode::SEE_OTHER); + } +} diff --git a/crates/im-web/src/i18n.rs b/crates/im-web/src/i18n.rs index 697b59a..a246483 100644 --- a/crates/im-web/src/i18n.rs +++ b/crates/im-web/src/i18n.rs @@ -69,6 +69,8 @@ pub enum Key { ErrBadUi, ErrBadLanguage, ErrBadService, + ErrBadClient, + ErrNoSuchClient, ErrFallback, // Good-news codes (`pages.rs`'s `ok_text`). @@ -180,6 +182,7 @@ pub enum Key { OkSettingsSaved, OkServicesSaved, OkMessageSent, + OkClientRevoked, // Admin mail section: the composed notice. MessageTitle, @@ -239,6 +242,22 @@ pub enum Key { RoleAdmin, InviteButton, + // Admin clients section: the family's relying parties. + NavClients, + ClientsTitle, + RedirectUrisLabel, + RegisteredCol, + ClientAdd, + RotateWord, + RevokeWord, + ConfirmRotate, + ConfirmRevoke, + RotateCost, + RevokeCost, + SecretShownNote, + CopyWord, + CopiedWord, + // Admin settings section. SettingsTitle, SettingsSub, @@ -369,6 +388,10 @@ pub fn t(lang: Lang, key: Key) -> &'static str { (ErrBadService, Tr) => { "Bir hizmet; küçük harf, rakam ya da tire ile yazılmış bir anahtar, bir ad ve http(s) adresi ister." } + (ErrBadClient, En) => "A client needs a name and at least one redirect URI.", + (ErrBadClient, Tr) => "Bir istemci; bir ad ve en az bir yönlendirme adresi ister.", + (ErrNoSuchClient, En) => "No such client.", + (ErrNoSuchClient, Tr) => "Böyle bir istemci yok.", (ErrFallback, En) => "Something went wrong. Try again.", (ErrFallback, Tr) => "Bir şeyler ters gitti. Yeniden dene.", @@ -585,7 +608,10 @@ pub fn t(lang: Lang, key: Key) -> &'static str { (OkServicesSaved, Tr) => "Hizmetler kaydedildi.", (OkMessageSent, En) => "Message sent.", (OkMessageSent, Tr) => "Mesaj gönderildi.", - + (OkClientRevoked, En) => "Client revoked — its tokens and app sessions went with it.", + (OkClientRevoked, Tr) => { + "İstemci iptal edildi — jetonları ve uygulama oturumları da gitti." + } (MessageTitle, En) => "Send a message", (MessageTitle, Tr) => "Mesaj gönder", (MessageToLabel, En) => "To", @@ -700,6 +726,47 @@ pub fn t(lang: Lang, key: Key) -> &'static str { (InviteButton, En) => "Invite", (InviteButton, Tr) => "Davet et", + (NavClients, En) => "Clients", + (NavClients, Tr) => "İstemciler", + (ClientsTitle, En) => "Clients", + (ClientsTitle, Tr) => "İstemciler", + (RedirectUrisLabel, En) => "Redirect URIs", + (RedirectUrisLabel, Tr) => "Yönlendirme adresleri", + (RegisteredCol, En) => "Registered", + (RegisteredCol, Tr) => "Kayıt", + (ClientAdd, En) => "Register client", + (ClientAdd, Tr) => "İstemci kaydet", + (RotateWord, En) => "Rotate", + (RotateWord, Tr) => "Yenile", + (RevokeWord, En) => "Revoke", + (RevokeWord, Tr) => "İptal et", + (ConfirmRotate, En) => "Confirm rotate", + (ConfirmRotate, Tr) => "Yenilemeyi onayla", + (ConfirmRevoke, En) => "Confirm revoke", + (ConfirmRevoke, Tr) => "İptali onayla", + (RotateCost, En) => { + "The old secret stops working the moment the new one exists — put the new one in the app's config." + } + (RotateCost, Tr) => { + "Eski anahtar, yenisi oluştuğu anda geçersiz olur — yenisini uygulamanın ayarlarına koy." + } + (RevokeCost, En) => { + "The pair stops working, and its refresh tokens and app sessions go with it." + } + (RevokeCost, Tr) => { + "Anahtar çifti geçersiz olur; yenileme jetonları ve uygulama oturumları da silinir." + } + (SecretShownNote, En) => { + "This secret is shown once. Put the pair in the app's config now — only its digest stays here." + } + (SecretShownNote, Tr) => { + "Bu anahtar bir kez gösterilir. Çifti şimdi uygulamanın ayarlarına koy — buraya yalnızca özeti kalır." + } + (CopyWord, En) => "Copy", + (CopyWord, Tr) => "Kopyala", + (CopiedWord, En) => "Copied", + (CopiedWord, Tr) => "Kopyalandı", + (SettingsTitle, En) => "Settings", (SettingsTitle, Tr) => "Ayarlar", (SettingsSub, En) => { @@ -881,6 +948,9 @@ pub fn kind_word(lang: Lang, kind: &str) -> String { "smtp_checked" => ("Mail server checked", "Posta sunucusu denetlendi"), "message_sent" => ("Message sent", "Mesaj gönderildi"), "message_failed" => ("Message failed", "Mesaj başarısız"), + "client_created" => ("Client created", "İstemci oluşturuldu"), + "client_rotated" => ("Client secret rotated", "İstemci anahtarı yenilendi"), + "client_revoked" => ("Client revoked", "İstemci iptal edildi"), _ => return kind.to_string(), }; match lang { @@ -954,6 +1024,23 @@ pub fn remove_service_title(lang: Lang, name_html: &str) -> String { } } +/// A client row's "Rotate 's secret?" disclosure title. `name_html` +/// is already escaped. +pub fn rotate_client_title(lang: Lang, name_html: &str) -> String { + match lang { + Lang::En => format!("Rotate {name_html}'s secret?"), + Lang::Tr => format!("{name_html} anahtarı yenilensin mi?"), + } +} + +/// See [`rotate_client_title`]. +pub fn revoke_client_title(lang: Lang, name_html: &str) -> String { + match lang { + Lang::En => format!("Revoke {name_html}?"), + Lang::Tr => format!("{name_html} iptal edilsin mi?"), + } +} + /// The mail section's lede: what the sender is for. The mono span is markup. pub fn mail_sub(lang: Lang) -> String { match lang { diff --git a/crates/im-web/src/main.rs b/crates/im-web/src/main.rs index 520509f..d9f9c46 100644 --- a/crates/im-web/src/main.rs +++ b/crates/im-web/src/main.rs @@ -97,9 +97,23 @@ async fn main() { }; set_admin_cli(config, email, false).await; } + Some("rotate-client") => { + let Some(id) = args.get(2) else { + eprintln!("usage: im-web rotate-client "); + std::process::exit(2); + }; + rotate_client(config, id).await; + } + Some("revoke-client") => { + let Some(id) = args.get(2) else { + eprintln!("usage: im-web revoke-client "); + std::process::exit(2); + }; + revoke_client(config, id).await; + } Some(other) => { eprintln!( - "im: unknown command {other:?} (expected: invite, revoke, promote, demote, create-client, or none to serve)" + "im: unknown command {other:?} (expected: invite, revoke, promote, demote, create-client, rotate-client, revoke-client, or none to serve)" ); std::process::exit(2); } @@ -259,6 +273,69 @@ async fn create_client(config: Config, name: &str, uris: &[String]) { println!(" client_secret {}", secret.expose()); println!(" (the secret is shown once; its digest is all the database keeps)"); } + +/// `im-web rotate-client `: replaces the client's secret and +/// prints the new one exactly once — the app's old pair dies with the write. +/// +/// Needs the server stopped, like every CLI arm: Turso is a single-writer +/// engine, and this process would hold the same file. +async fn rotate_client(config: Config, id: &str) { + let store = open_store(&config).await; + let name = client_name(&store, id).await; + match im_core::oidc::rotate_client_secret(&store, id) + .await + .expect("failed to rotate the client secret") + { + Some(secret) => { + im_core::events::log(&store, "client_rotated", Some("cli"), Some(&name)).await; + println!("im client {id} ({name})"); + println!(" client_secret {}", secret.expose()); + println!(" (the secret is shown once; its digest is all the database keeps)"); + } + None => { + eprintln!("im: no client {id}"); + std::process::exit(1); + } + } +} + +/// `im-web revoke-client `: deletes the registry row and every +/// refresh token and app session minted under it; the person's own sign-in +/// sessions stay. +/// +/// Needs the server stopped, like every CLI arm: Turso is a single-writer +/// engine, and this process would hold the same file. +async fn revoke_client(config: Config, id: &str) { + let store = open_store(&config).await; + // The name rides the log line and the goodbye, so it comes off the row + // before the row goes. + let name = client_name(&store, id).await; + match im_core::oidc::revoke_client(&store, id) + .await + .expect("failed to revoke the client") + { + true => { + println!( + "im client {id} ({name}) revoked — its tokens and app sessions went with it" + ); + } + false => { + eprintln!("im: no client {id}"); + std::process::exit(1); + } + } +} + +/// The client's display name, or its id when no row stands behind it — the +/// log's detail is the name when there is one. +async fn client_name(store: &Arc, id: &str) -> String { + im_core::oidc::client_by_id(store, id) + .await + .expect("failed to read the client") + .map(|client| client.name) + .unwrap_or_else(|| id.to_string()) +} + async fn serve(config: Config) { for line in config.report() { println!("im {line}"); diff --git a/crates/im-web/src/pages.rs b/crates/im-web/src/pages.rs index 061f626..5280940 100644 --- a/crates/im-web/src/pages.rs +++ b/crates/im-web/src/pages.rs @@ -45,6 +45,8 @@ pub fn error_text(code: &str, lang: Lang) -> &'static str { "bad_ui" => t(lang, Key::ErrBadUi), "bad_language" => t(lang, Key::ErrBadLanguage), "bad_service" => t(lang, Key::ErrBadService), + "bad_client" => t(lang, Key::ErrBadClient), + "no_such_client" => t(lang, Key::ErrNoSuchClient), "empty_subject" => t(lang, Key::ErrEmptySubject), "empty_body" => t(lang, Key::ErrEmptyBody), "no_such_user" => t(lang, Key::ErrNoSuchUser), diff --git a/crates/im-web/src/server.rs b/crates/im-web/src/server.rs index 9b96e91..ae87c86 100644 --- a/crates/im-web/src/server.rs +++ b/crates/im-web/src/server.rs @@ -8,7 +8,9 @@ //! fetch with `accept: text/html`, so the 303's target document is what //! comes back — no refusal-carrying layer as in İzlek is needed. -use std::sync::Arc; +use std::collections::HashMap; +use std::sync::{Arc, LazyLock, Mutex, PoisonError}; +use std::time::{Duration, Instant}; use im_core::model::User; use im_core::store::Store; @@ -70,6 +72,44 @@ pub async fn log_event(cx: &Cx, kind: &str, actor: Option<&str>, detail: Option< note(cx); } +// --------------------------------------------------------------------------- +// The show-once shelf +// --------------------------------------------------------------------------- + +/// How long a stashed secret waits for its one reader. +const SHOWN_TTL: Duration = Duration::from_secs(10 * 60); + +/// Where a freshly minted client secret waits between its POST and the one +/// GET that shows it. The panel's write answers a 303 — the house idiom — +/// but the secret itself must never ride a URL or a log line, so the query +/// carries only a random claim ticket: the shelf holds the plaintext, the +/// page's read takes it out (`take_shown_secret`), and a replayed or +/// reloaded URL finds the shelf empty and renders no secret at all. A +/// restart drops the shelf — the admin mints another, as with the CLI. +static SHOWN_SECRETS: LazyLock>> = + LazyLock::new(|| Mutex::new(HashMap::new())); + +/// Parks a client's fresh pair on the shelf and returns the claim ticket +/// for its URL. The id travels too — it is the public half of the pair and +/// the one render shows it beside the secret. +pub fn stash_shown_secret(client_id: String, secret: String) -> String { + let ticket = im_core::accounts::Token::mint().expose().to_string(); + let mut shelf = SHOWN_SECRETS.lock().unwrap_or_else(PoisonError::into_inner); + shelf.retain(|_, (_, parked)| parked.elapsed() < SHOWN_TTL); + shelf.insert(ticket.clone(), ((client_id, secret), Instant::now())); + ticket +} + +/// Takes a stashed pair out — exactly once; the second reader of the same +/// ticket gets nothing. +pub fn take_shown_secret(ticket: &str) -> Option<(String, String)> { + SHOWN_SECRETS + .lock() + .unwrap_or_else(PoisonError::into_inner) + .remove(ticket) + .map(|(pair, _)| pair) +} + pub fn app(cx: &Cx) -> &App { try_app_context::(cx).expect("the router always carries the App") }