forge
Explore
Log in

Don't you dare go Hollow

Admin panel: OIDC client management (create/rotate/revoke)

Browse files at this commit

6d3e6a76ba71d49b3862a708253895aa4ec20efdAhmet Kaan GümüşParent: f7b2081
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.rsmodified+206 -0
@@ -115,6 +115,101 @@ pub fn verify_client_secret(client: &OidcClient, secret: &str) -> bool {
115 digests_match(&client.secret_hash, &hash_token(secret))115 digests_match(&client.secret_hash, &hash_token(secret))
116 }116 }
117 117
118+/// A registered client, as the panel's Clients section and the CLI list it:
119+/// no secret material — the row's digest stays an internal affair.
120+#[derive(Debug, Clone)]
121+pub struct ClientSummary {
122+ pub client_id: ClientId,
123+ pub name: String,
124+ pub redirect_uris: Vec<String>,
125+ pub created_at: time::OffsetDateTime,
126+}
127+
128+/// Every registered client, oldest first — the admin panel's roster.
129+pub async fn list_clients(store: &Store) -> Result<Vec<ClientSummary>> {
130+ let conn = store.conn.lock().await;
131+ let mut rows = conn
132+ .query(
133+ "SELECT client_id, name, redirect_uris, created_at FROM oidc_clients \
134+ ORDER BY created_at, client_id",
135+ (),
136+ )
137+ .await
138+ .map_err(backend)?;
139+ let mut out = Vec::new();
140+ while let Some(row) = rows.next().await.map_err(backend)? {
141+ let uris_raw = store::text(&row, 2)?;
142+ out.push(ClientSummary {
143+ client_id: ClientId::from(store::text(&row, 0)?),
144+ name: store::text(&row, 1)?,
145+ redirect_uris: serde_json::from_str(&uris_raw)
146+ .map_err(|e| StoreError::Corrupt(format!("redirect_uris {uris_raw:?}: {e}")))?,
147+ created_at: store::parse_stamp(&store::text(&row, 3)?)?,
148+ });
149+ }
150+ Ok(out)
151+}
152+
153+/// Replaces a client's secret, returning the fresh one — shown exactly once;
154+/// the row keeps only the new digest and every pair minted before is dead.
155+/// `None` for an unknown client.
156+pub async fn rotate_client_secret(store: &Store, client_id: &str) -> Result<Option<Token>> {
157+ let conn = store.conn.lock().await;
158+ let secret = Token::mint();
159+ let updated = conn
160+ .execute(
161+ "UPDATE oidc_clients SET secret_hash = ?1 WHERE client_id = ?2",
162+ turso::params![secret.hash(), client_id],
163+ )
164+ .await
165+ .map_err(backend)?;
166+ Ok((updated > 0).then_some(secret))
167+}
168+
169+/// Deletes a client outright: the registry row and every refresh token and
170+/// app session minted under it, one immediate transaction — no token row
171+/// outlives the pair that minted it, and introspection reads them as
172+/// inactive on the very next call. The person's sign-in sessions are not
173+/// touched: the client's doors close, the browsers' stay open. `false` for
174+/// an unknown client.
175+pub async fn revoke_client(store: &Store, client_id: &str) -> Result<bool> {
176+ let conn = store.conn.lock().await;
177+ conn.execute("BEGIN IMMEDIATE", ()).await.map_err(backend)?;
178+ let outcome = async {
179+ conn.execute(
180+ "DELETE FROM refresh_tokens WHERE client_id = ?1",
181+ turso::params![client_id],
182+ )
183+ .await
184+ .map_err(backend)?;
185+ conn.execute(
186+ "DELETE FROM app_sessions WHERE client_id = ?1",
187+ turso::params![client_id],
188+ )
189+ .await
190+ .map_err(backend)?;
191+ let deleted = conn
192+ .execute(
193+ "DELETE FROM oidc_clients WHERE client_id = ?1",
194+ turso::params![client_id],
195+ )
196+ .await
197+ .map_err(backend)?;
198+ Ok(deleted > 0)
199+ }
200+ .await;
201+ match outcome {
202+ Ok(known) => {
203+ conn.execute("COMMIT", ()).await.map_err(backend)?;
204+ Ok(known)
205+ }
206+ Err(e) => {
207+ let _ = conn.execute("ROLLBACK", ()).await;
208+ Err(e)
209+ }
210+ }
211+}
212+
118 // ---------------------------------------------------------------------------213 // ---------------------------------------------------------------------------
119 // Authorization codes214 // Authorization codes
120 // ---------------------------------------------------------------------------215 // ---------------------------------------------------------------------------
@@ -910,4 +1005,115 @@ mod tests {
910 assert_eq!(apps.len(), 1);1005 assert_eq!(apps.len(), 1);
911 assert_eq!(apps[0].client_id, client_id.as_str());1006 assert_eq!(apps[0].client_id, client_id.as_str());
912 }1007 }
1008+
1009+ #[tokio::test]
1010+ async fn rotate_client_secret_kills_the_old_pair() {
1011+ let store = Store::open(Path::new(":memory:")).await.unwrap();
1012+ let (client_id, original_secret) =
1013+ create_client(&store, "drive", vec!["http://app/cb".into()])
1014+ .await
1015+ .unwrap();
1016+
1017+ // Rotation replaces the digest: the new secret verifies, the old
1018+ // one stops, and the unknown id stays a None.
1019+ let rotated = rotate_client_secret(&store, client_id.as_str())
1020+ .await
1021+ .unwrap()
1022+ .expect("a known client rotates");
1023+ let row = client_by_id(&store, client_id.as_str())
1024+ .await
1025+ .unwrap()
1026+ .unwrap();
1027+ assert!(verify_client_secret(&row, rotated.expose()));
1028+ assert!(!verify_client_secret(&row, original_secret.expose()));
1029+ assert!(
1030+ rotate_client_secret(&store, "no-such-client")
1031+ .await
1032+ .unwrap()
1033+ .is_none()
1034+ );
1035+ }
1036+
1037+ #[tokio::test]
1038+ async fn revoke_client_deletes_its_tokens_in_one_sweep() {
1039+ let (store, client_id, user_id) = fixture().await;
1040+ let session = create_session(&store, &user_id, &SessionMeta::default())
1041+ .await
1042+ .unwrap();
1043+ let app_token = issue_app_session(&store, &user_id, &client_id, &session.hash())
1044+ .await
1045+ .unwrap();
1046+ let refresh = issue_refresh(&store, &user_id, &client_id, &session.hash())
1047+ .await
1048+ .unwrap();
1049+
1050+ // Alive until revoked: introspection answers.
1051+ assert!(
1052+ introspect_app_session(&store, app_token.expose(), client_id.as_str())
1053+ .await
1054+ .unwrap()
1055+ .is_some()
1056+ );
1057+
1058+ assert!(revoke_client(&store, client_id.as_str()).await.unwrap());
1059+
1060+ // The pair is gone, and with it every token minted under it: the
1061+ // app session no longer introspects, the refresh no longer turns.
1062+ // The person's central session is untouched.
1063+ assert!(
1064+ introspect_app_session(&store, app_token.expose(), client_id.as_str())
1065+ .await
1066+ .unwrap()
1067+ .is_none(),
1068+ "no ghost app session after client revocation"
1069+ );
1070+ assert!(
1071+ rotate_refresh(&store, refresh.expose())
1072+ .await
1073+ .unwrap()
1074+ .is_none()
1075+ );
1076+ assert!(
1077+ client_by_id(&store, client_id.as_str())
1078+ .await
1079+ .unwrap()
1080+ .is_none(),
1081+ "the registry row itself is gone"
1082+ );
1083+ assert_eq!(
1084+ crate::sessions::list_sessions(&store, &user_id)
1085+ .await
1086+ .unwrap()
1087+ .len(),
1088+ 1,
1089+ "the person's own sign-in session stays"
1090+ );
1091+
1092+ // Revoking again is a quiet false, not an error.
1093+ assert!(!revoke_client(&store, client_id.as_str()).await.unwrap());
1094+ }
1095+
1096+ #[tokio::test]
1097+ async fn list_clients_returns_the_registry_rows() {
1098+ let store = Store::open(Path::new(":memory:")).await.unwrap();
1099+ let (first, _) = create_client(
1100+ &store,
1101+ "drive",
1102+ vec!["http://a/cb".into(), "http://127.0.0.1:9000/cb".into()],
1103+ )
1104+ .await
1105+ .unwrap();
1106+ let (second, _) = create_client(&store, "in", vec!["https://in.dizey.sh/cb".into()])
1107+ .await
1108+ .unwrap();
1109+ let rows = list_clients(&store).await.unwrap();
1110+ assert_eq!(rows.len(), 2);
1111+ assert_eq!(rows[0].client_id, first);
1112+ assert_eq!(rows[0].name, "drive");
1113+ assert_eq!(
1114+ rows[0].redirect_uris,
1115+ vec!["http://a/cb", "http://127.0.0.1:9000/cb"]
1116+ );
1117+ assert_eq!(rows[1].client_id, second);
1118+ }
913 }1119 }
crates/im-web/src/admin.rsmodified+545 -2
@@ -81,6 +81,17 @@ const ADMIN_SCRIPT: &str = r#"<script>(function () {
81 if (e.key !== 'Escape') { return; }81 if (e.key !== 'Escape') { return; }
82 document.querySelectorAll('.admin-confirm[open]').forEach(function (d) { d.removeAttribute('open'); });82 document.querySelectorAll('.admin-confirm[open]').forEach(function (d) { d.removeAttribute('open'); });
83 }, true);83 }, true);
84+ // The show-once banner's copy button: copies the secret beside it, flips
85+ // its label, and works without script too — the value is selectable text.
86+ document.addEventListener('click', function (e) {
87+ var b = e.target.closest && e.target.closest('.admin-copy');
88+ if (!b) { return; }
89+ var row = b.closest('.admin-copy-row');
90+ var v = row && row.querySelector('.admin-copy-value');
91+ if (!v) { return; }
92+ var done = function () { b.textContent = b.getAttribute('data-copied-label'); };
93+ if (navigator.clipboard && navigator.clipboard.writeText) { navigator.clipboard.writeText(v.textContent).then(done, done); } else { try { document.execCommand('copy'); } catch (err) {} done(); }
94+ }, true);
84 })();</script>"#;95 })();</script>"#;
85 96
86 fn back(cx: &Cx, section: &str, extra: &str) -> Result<Response> {97 fn back(cx: &Cx, section: &str, extra: &str) -> Result<Response> {
@@ -111,12 +122,17 @@ async fn admin_page(cx: &Cx) -> Result<Response> {
111 let ok = query_value(&query, "ok");122 let ok = query_value(&query, "ok");
112 let why = query_value(&query, "why");123 let why = query_value(&query, "why");
113 let invited = query_value(&query, "invited");124 let invited = query_value(&query, "invited");
125+ // The one read that takes a stashed client secret off the shelf: a
126+ // replayed, reloaded, or forged ticket finds the shelf empty.
127+ let shown = query_value(&query, "shown")
128+ .as_deref()
129+ .and_then(server::take_shown_secret);
114 130
115 let nav = |current: &str| {131 let nav = |current: &str| {
116 [132 [
117 ("users", t(lang, Key::NavUsers)),133 ("users", t(lang, Key::NavUsers)),
118 ("services", t(lang, Key::NavServices)),134 ("services", t(lang, Key::NavServices)),
119- ("mail", t(lang, Key::NavMail)),135+ ("clients", t(lang, Key::NavClients)),
120 ("message", t(lang, Key::NavMessage)),136 ("message", t(lang, Key::NavMessage)),
121 ("settings", t(lang, Key::NavSettings)),137 ("settings", t(lang, Key::NavSettings)),
122 ("logs", t(lang, Key::NavLogs)),138 ("logs", t(lang, Key::NavLogs)),
@@ -137,7 +153,7 @@ async fn admin_page(cx: &Cx) -> Result<Response> {
137 "settings" => settings_section(cx, lang).await?,153 "settings" => settings_section(cx, lang).await?,
138 "logs" => logs_section(cx, lang).await?,154 "logs" => logs_section(cx, lang).await?,
139 "services" => services_section(cx, lang).await?,155 "services" => services_section(cx, lang).await?,
140- "users" => users_section(cx, &me, invited.as_deref(), lang).await?,156+ "clients" => clients_section(cx, shown, lang).await?,
141 _ => users_section(cx, &me, invited.as_deref(), lang).await?,157 _ => users_section(cx, &me, invited.as_deref(), lang).await?,
142 };158 };
143 159
@@ -158,6 +174,7 @@ async fn admin_page(cx: &Cx) -> Result<Response> {
158 "settings" => t(lang, Key::OkSettingsSaved),174 "settings" => t(lang, Key::OkSettingsSaved),
159 "services" => t(lang, Key::OkServicesSaved),175 "services" => t(lang, Key::OkServicesSaved),
160 "email_changed" => t(lang, Key::OkEmailChanged),176 "email_changed" => t(lang, Key::OkEmailChanged),
177+ "client_revoked" => t(lang, Key::OkClientRevoked),
161 _ => t(lang, Key::OkDone),178 _ => t(lang, Key::OkDone),
162 }179 }
163 )),180 )),
@@ -616,6 +633,176 @@ async fn service_outcome(
616 }633 }
617 }634 }
618 635
636+/// The relying parties: every client the family's apps sign in with. One
637+/// table in the panel's own skins — rotate and revoke as the two-step
638+/// disclosures — and the add line under it wearing the invite form's skin.
639+/// A create or rotate answers a 303 whose `shown` ticket picks the fresh
640+/// secret off the shelf for exactly one render; the page never learns a
641+/// secret twice.
642+async fn clients_section(
643+ cx: &Cx,
644+ shown: Option<(String, String)>,
645+ lang: i18n::Lang,
646+) -> Result<String, topcoat::Error> {
647+ let clients = im_core::oidc::list_clients(&app(cx).store).await?;
648+ let mut rows = String::new();
649+ for client in &clients {
650+ let id = escape(&client.client_id.to_string());
651+ let name = escape(&client.name);
652+ let uris = client
653+ .redirect_uris
654+ .iter()
655+ .map(|uri| escape(uri))
656+ .collect::<Vec<_>>()
657+ .join("<br>");
658+ let registered = client
659+ .created_at
660+ .format(&time::macros::format_description!("[year]-[month]-[day]"))
661+ .unwrap_or_default();
662+ // Rotation kills the old pair the moment the new one exists, so it
663+ // says what it costs before it does it — like every destructive row
664+ // action here.
665+ let rotate = confirm_action(
666+ "client",
667+ &id,
668+ "/admin/clients_rotate",
669+ t(lang, Key::RotateWord),
670+ "",
671+ &i18n::rotate_client_title(lang, &name),
672+ t(lang, Key::RotateCost),
673+ t(lang, Key::ConfirmRotate),
674+ );
675+ let revoke_action = confirm_action(
676+ "client",
677+ &id,
678+ "/admin/clients_revoke",
679+ t(lang, Key::RevokeWord),
680+ " admin-danger",
681+ &i18n::revoke_client_title(lang, &name),
682+ t(lang, Key::RevokeCost),
683+ t(lang, Key::ConfirmRevoke),
684+ );
685+ rows.push_str(&format!(
686+ r#"<tr><td>{name}</td><td class="mono">{id}</td><td class="mono">{uris}</td><td class="muted">{registered}</td><td class="actions">{rotate}{revoke_action}</td></tr>"#,
687+ ));
688+ }
689+ // The show-once banner: the note says what to do with it, the value is
690+ // click-to-copy, and the shelf behind it has already handed it over.
691+ let shown_html = shown
692+ .map(|(client_id, secret)| {
693+ format!(
694+ r#"<div class="auth-note">{note}<div class="admin-copy-row"><div class="muted">{id_label}: <span class="mono">{client_id}</span></div><div class="auth-secret admin-copy-value">{secret}</div><button class="admin-action admin-copy" type="button" data-copied-label="{copied}">{copy}</button></div></div>"#,
695+ note = t(lang, Key::SecretShownNote),
696+ id_label = t(lang, Key::ClientIdLabel),
697+ client_id = escape(&client_id),
698+ secret = escape(&secret),
699+ copied = t(lang, Key::CopiedWord),
700+ copy = t(lang, Key::CopyWord),
701+ )
702+ })
703+ .unwrap_or_default();
704+ Ok(format!(
705+ r#"<div class="admin-card">
706+ <div class="auth-title">{title}</div>
707+ {shown_html}
708+ <div class="admin-table-wrap">
709+ <table class="admin-table">
710+ <thead><tr><th>{name_label}</th><th>{id_label}</th><th>{uris_label}</th><th>{registered_label}</th><th></th></tr></thead>
711+ <tbody>{rows}</tbody>
712+ </table>
713+ </div>
714+ <form method="post" action="/admin/clients_add" class="admin-invite">
715+ <input class="auth-input" type="text" name="name" placeholder="drive" aria-label="{name_label}" required>
716+ <input class="auth-input auth-input-mono" type="text" name="redirect_uris" placeholder="http://127.0.0.1:9000/callback https://drive.dizey.sh/callback" aria-label="{uris_label}" required>
717+ <button class="auth-submit admin-invite-go" type="submit"><span class="auth-submit-text">{add}</span></button>
718+ </form>
719+</div>"#,
720+ title = t(lang, Key::ClientsTitle),
721+ name_label = t(lang, Key::NameCol),
722+ id_label = t(lang, Key::ClientIdLabel),
723+ uris_label = t(lang, Key::RedirectUrisLabel),
724+ registered_label = t(lang, Key::RegisteredCol),
725+ add = t(lang, Key::ClientAdd),
726+ ))
727+}
728+
729+/// One user of the clients forms: the name, and one or more redirect URIs
730+/// — whitespace- or comma-separated, as loose as the CLI's argument list,
731+/// because a family dev's `http://127.0.0.1` redirect is a legitimate row.
732+#[derive(Deserialize)]
733+struct ClientForm {
734+ name: String,
735+ redirect_uris: String,
736+}
737+
738+#[route(POST "/admin/clients_add")]
739+async fn clients_add(cx: &Cx, Form(input): Form<ClientForm>) -> Result<Response> {
740+ let me = match require_admin(cx).await {
741+ Ok(me) => me,
742+ Err(redirect) => return Ok(redirect),
743+ };
744+ let name = input.name.trim().to_string();
745+ let uris: Vec<String> = input
746+ .redirect_uris
747+ .split(|c: char| c.is_whitespace() || c == ',')
748+ .map(str::trim)
749+ .filter(|uri| !uri.is_empty())
750+ .map(str::to_string)
751+ .collect();
752+ if name.is_empty() || uris.is_empty() {
753+ return back(cx, "clients", "&error=bad_client");
754+ }
755+ let (id, secret) = im_core::oidc::create_client(&app(cx).store, &name, uris).await?;
756+ server::log_event(cx, "client_created", Some(&me.email), Some(&name)).await;
757+ let shown = server::stash_shown_secret(id.to_string(), secret.expose().to_string());
758+ back(cx, "clients", &format!("&shown={shown}"))
759+}
760+
761+#[derive(Deserialize)]
762+struct ClientAction {
763+ client: String,
764+}
765+
766+#[route(POST "/admin/clients_rotate")]
767+async fn clients_rotate(cx: &Cx, Form(input): Form<ClientAction>) -> Result<Response> {
768+ let me = match require_admin(cx).await {
769+ Ok(me) => me,
770+ Err(redirect) => return Ok(redirect),
771+ };
772+ // The log line names the client like a person, so the name comes off
773+ // the row before the secret under it moves.
774+ let name = match im_core::oidc::client_by_id(&app(cx).store, &input.client).await? {
775+ Some(client) => client.name,
776+ None => return back(cx, "clients", "&error=no_such_client"),
777+ };
778+ match im_core::oidc::rotate_client_secret(&app(cx).store, &input.client).await? {
779+ Some(secret) => {
780+ server::log_event(cx, "client_rotated", Some(&me.email), Some(&name)).await;
781+ let shown =
782+ server::stash_shown_secret(input.client.clone(), secret.expose().to_string());
783+ back(cx, "clients", &format!("&shown={shown}"))
784+ }
785+ None => back(cx, "clients", "&error=no_such_client"),
786+ }
787+}
788+
789+#[route(POST "/admin/clients_revoke")]
790+async fn clients_revoke(cx: &Cx, Form(input): Form<ClientAction>) -> Result<Response> {
791+ let me = match require_admin(cx).await {
792+ Ok(me) => me,
793+ Err(redirect) => return Ok(redirect),
794+ };
795+ let name = match im_core::oidc::client_by_id(&app(cx).store, &input.client).await? {
796+ Some(client) => client.name,
797+ None => return back(cx, "clients", "&error=no_such_client"),
798+ };
799+ if !im_core::oidc::revoke_client(&app(cx).store, &input.client).await? {
800+ return back(cx, "clients", "&error=no_such_client");
801+ }
802+ server::log_event(cx, "client_revoked", Some(&me.email), Some(&name)).await;
803+ back(cx, "clients", "&ok=client_revoked")
804+}
805+
619 /// The knobs the code shipped with, now the panel's: invite and reset link806 /// The knobs the code shipped with, now the panel's: invite and reset link
620 /// lifetimes, the sign-in session's days and per-user ceiling, the pending807 /// lifetimes, the sign-in session's days and per-user ceiling, the pending
621 /// marker's minutes, and the sign-in failure ceiling. Same form skin as Mail.808 /// marker's minutes, and the sign-in failure ceiling. Same form skin as Mail.
@@ -1564,3 +1751,359 @@ async fn probe(
1564 // The chip changed; watching tabs re-read it on the next tick.1751 // The chip changed; watching tabs re-read it on the next tick.
1565 let _ = live.send(server::LiveEvent::Tick);1752 let _ = live.send(server::LiveEvent::Tick);
1566 }1753 }
1754+
1755+#[cfg(test)]
1756+mod tests {
1757+ use std::path::Path;
1758+ use std::sync::Arc;
1759+
1760+ use im_core::accounts::{create_invite, create_user_from_invite};
1761+ use im_core::model::{ClientId, UserId};
1762+ use im_core::oidc::{introspect_app_session, issue_app_session, list_clients};
1763+ use im_core::sessions::{SessionMeta, create_session};
1764+ use im_core::store::Store;
1765+ use topcoat::cookie::RouterBuilderCookieExt as _;
1766+ use topcoat::router::{
1767+ Body, Router, RouterBuilderDiscoverExt as _, StatusCode, header, to_bytes,
1768+ };
1769+
1770+ use crate::config::Config;
1771+ use crate::server::{self, SESSION_COOKIE};
1772+
1773+ struct Setup {
1774+ router: Router,
1775+ store: Arc<Store>,
1776+ admin_id: UserId,
1777+ admin_cookie: String,
1778+ plain_cookie: String,
1779+ }
1780+
1781+ async fn setup() -> Setup {
1782+ let store = Store::open(Path::new(":memory:")).await.unwrap();
1783+ let invite = create_invite(&store, "root@example.com", None, true)
1784+ .await
1785+ .unwrap();
1786+ let admin = create_user_from_invite(&store, invite.expose(), "Root", "tDLr9!mZQ2xv")
1787+ .await
1788+ .unwrap();
1789+ let bare = create_invite(&store, "sid@example.com", None, false)
1790+ .await
1791+ .unwrap();
1792+ let plain = create_user_from_invite(&store, bare.expose(), "Sid", "tDLr9!mZQ2xv")
1793+ .await
1794+ .unwrap();
1795+ let admin_session = create_session(&store, &admin.id, &SessionMeta::default())
1796+ .await
1797+ .unwrap();
1798+ let plain_session = create_session(&store, &plain.id, &SessionMeta::default())
1799+ .await
1800+ .unwrap();
1801+ let (live, _) = tokio::sync::broadcast::channel(64);
1802+ let store = Arc::new(store);
1803+ let app = server::App {
1804+ store: store.clone(),
1805+ config: Config {
1806+ database: ":memory:".into(),
1807+ listen: "127.0.0.1:7650".parse().unwrap(),
1808+ issuer: "http://127.0.0.1:7650".into(),
1809+ services: Vec::new(),
1810+ },
1811+ live,
1812+ };
1813+ let router = Router::builder()
1814+ .discover()
1815+ .cookies()
1816+ .app_context(app)
1817+ .build();
1818+ Setup {
1819+ router,
1820+ store,
1821+ admin_id: admin.id,
1822+ admin_cookie: format!("{SESSION_COOKIE}={}", admin_session.expose()),
1823+ plain_cookie: format!("{SESSION_COOKIE}={}", plain_session.expose()),
1824+ }
1825+ }
1826+
1827+ /// A form post through the router, answered as (status, Location, body).
1828+ async fn post_form(
1829+ router: &Router,
1830+ uri: &str,
1831+ body: &str,
1832+ cookie: Option<&str>,
1833+ ) -> (StatusCode, Option<String>, String) {
1834+ let mut builder = http::Request::builder()
1835+ .method(http::Method::POST)
1836+ .uri(uri)
1837+ .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded");
1838+ if let Some(cookie) = cookie {
1839+ builder = builder.header(header::COOKIE, cookie);
1840+ }
1841+ let response = router
1842+ .handle(builder.body(Body::from(body.to_string())).unwrap())
1843+ .await;
1844+ let (parts, body) = response.into_parts();
1845+ let location = parts
1846+ .headers
1847+ .get(header::LOCATION)
1848+ .and_then(|v| v.to_str().ok())
1849+ .map(str::to_string);
1850+ let bytes = to_bytes(body, usize::MAX).await.unwrap().to_vec();
1851+ (parts.status, location, String::from_utf8(bytes).unwrap())
1852+ }
1853+
1854+ /// A GET with (maybe) a session cookie, answered as (status, Location).
1855+ async fn get_location(
1856+ router: &Router,
1857+ uri: &str,
1858+ cookie: Option<&str>,
1859+ ) -> (StatusCode, Option<String>) {
1860+ let mut builder = http::Request::builder().uri(uri);
1861+ if let Some(cookie) = cookie {
1862+ builder = builder.header(header::COOKIE, cookie);
1863+ }
1864+ let response = router.handle(builder.body(Body::empty()).unwrap()).await;
1865+ let (parts, _) = response.into_parts();
1866+ let location = parts
1867+ .headers
1868+ .get(header::LOCATION)
1869+ .and_then(|v| v.to_str().ok())
1870+ .map(str::to_string);
1871+ (parts.status, location)
1872+ }
1873+
1874+ fn basic(client_id: &str, secret: &str) -> String {
1875+ use base64::Engine as _;
1876+ format!(
1877+ "Basic {}",
1878+ base64::engine::general_purpose::STANDARD.encode(format!("{client_id}:{secret}"))
1879+ )
1880+ }
1881+
1882+ /// Registers a client through the panel itself and returns the pair the
1883+ /// one show-once render would carry: the 303's claim ticket, taken off
1884+ /// the shelf — first reader wins.
1885+ async fn create_via_panel(setup: &Setup, name: &str) -> (String, String) {
1886+ let (status, location, _) = post_form(
1887+ &setup.router,
1888+ "/admin/clients_add",
1889+ &format!("name={name}&redirect_uris=http://127.0.0.1:9000/callback"),
1890+ Some(&setup.admin_cookie),
1891+ )
1892+ .await;
1893+ assert_eq!(status, StatusCode::SEE_OTHER);
1894+ let location = location.expect("a 303 back to the section");
1895+ assert!(location.starts_with("/admin?section=clients&shown="));
1896+ let ticket = location.trim_start_matches("/admin?section=clients&shown=");
1897+ let (id, secret) = server::take_shown_secret(ticket).expect("the one showing");
1898+ let row = list_clients(&setup.store).await.unwrap();
1899+ assert_eq!(id, row[0].client_id.to_string());
1900+ (id, secret)
1901+ }
1902+
1903+ /// GETs `/directory` with an app's Basic pair.
1904+ async fn directory(router: &Router, authorization: String) -> StatusCode {
1905+ let response = router
1906+ .handle(
1907+ http::Request::builder()
1908+ .uri("/directory")
1909+ .header(header::AUTHORIZATION, authorization)
1910+ .body(Body::empty())
1911+ .unwrap(),
1912+ )
1913+ .await;
1914+ response.into_parts().0.status
1915+ }
1916+
1917+ #[tokio::test]
1918+ async fn clients_add_shows_the_secret_once_and_the_pair_authenticates() {
1919+ let setup = setup().await;
1920+
1921+ // The add answers a 303 whose query carries only a claim ticket —
1922+ // never the secret itself.
1923+ let (status, location, _) = post_form(
1924+ &setup.router,
1925+ "/admin/clients_add",
1926+ "name=drive&redirect_uris=http://127.0.0.1:9000/callback",
1927+ Some(&setup.admin_cookie),
1928+ )
1929+ .await;
1930+ assert_eq!(status, StatusCode::SEE_OTHER);
1931+ let location = location.expect("a 303 back to the section");
1932+ assert!(location.starts_with("/admin?section=clients&shown="));
1933+ assert!(!location.contains("secret"));
1934+
1935+ // First reader wins: the ticket yields the pair exactly once, then
1936+ // the shelf is empty — a replayed or reloaded URL shows nothing.
1937+ let ticket = location.trim_start_matches("/admin?section=clients&shown=");
1938+ let (id, secret) = server::take_shown_secret(ticket).expect("the one showing");
1939+ assert!(server::take_shown_secret(ticket).is_none());
1940+ assert!(
1941+ server::take_shown_secret("a-forged-ticket").is_none(),
1942+ "a forged ticket shows nothing"
1943+ );
1944+
1945+ // The pair the one render showed authenticates on /directory.
1946+ assert_eq!(
1947+ directory(&setup.router, basic(&id, &secret)).await,
1948+ StatusCode::OK
1949+ );
1950+
1951+ // The registry row carries the digest only — the listing can never
1952+ // leak the secret.
1953+ let rows = list_clients(&setup.store).await.unwrap();
1954+ assert_eq!(rows.len(), 1);
1955+ assert_eq!(rows[0].name, "drive");
1956+ assert_ne!(rows[0].client_id.to_string(), secret);
1957+ }
1958+
1959+ #[tokio::test]
1960+ async fn clients_rotate_kills_the_old_pair_and_shows_a_new_secret_once() {
1961+ let setup = setup().await;
1962+ let (id, old_secret) = create_via_panel(&setup, "drive").await;
1963+
1964+ let (status, location, _) = post_form(
1965+ &setup.router,
1966+ "/admin/clients_rotate",
1967+ &format!("client={id}"),
1968+ Some(&setup.admin_cookie),
1969+ )
1970+ .await;
1971+ assert_eq!(status, StatusCode::SEE_OTHER);
1972+ let location = location.expect("a 303 back to the section");
1973+ assert!(location.starts_with("/admin?section=clients&shown="));
1974+ let ticket = location.trim_start_matches("/admin?section=clients&shown=");
1975+ let (rotated_id, new_secret) = server::take_shown_secret(ticket).expect("the one showing");
1976+ assert_eq!(rotated_id, id, "the shelf names the same client");
1977+ assert_ne!(old_secret, new_secret);
1978+
1979+ // The old pair is dead; the new one authenticates.
1980+ assert_eq!(
1981+ directory(&setup.router, basic(&id, &old_secret)).await,
1982+ StatusCode::UNAUTHORIZED
1983+ );
1984+ assert_eq!(
1985+ directory(&setup.router, basic(&id, &new_secret)).await,
1986+ StatusCode::OK
1987+ );
1988+
1989+ // An unknown client is the section's refusal, not a minted secret.
1990+ let (status, location, _) = post_form(
1991+ &setup.router,
1992+ "/admin/clients_rotate",
1993+ "client=no-such-client",
1994+ Some(&setup.admin_cookie),
1995+ )
1996+ .await;
1997+ assert_eq!(status, StatusCode::SEE_OTHER);
1998+ assert_eq!(
1999+ location.as_deref(),
2000+ Some("/admin?section=clients&error=no_such_client")
2001+ );
2002+ }
2003+
2004+ #[tokio::test]
2005+ async fn clients_revoke_kills_the_pair_and_its_tokens() {
2006+ let setup = setup().await;
2007+ let (id, secret) = create_via_panel(&setup, "drive").await;
2008+ let client_id = ClientId::from(id.clone());
2009+
2010+ // An app session minted under the client, alive until revoked.
2011+ let session = create_session(&setup.store, &setup.admin_id, &SessionMeta::default())
2012+ .await
2013+ .unwrap();
2014+ let app_token =
2015+ issue_app_session(&setup.store, &setup.admin_id, &client_id, &session.hash())
2016+ .await
2017+ .unwrap();
2018+ assert!(
2019+ introspect_app_session(&setup.store, app_token.expose(), &id)
2020+ .await
2021+ .unwrap()
2022+ .is_some()
2023+ );
2024+
2025+ let (status, location, _) = post_form(
2026+ &setup.router,
2027+ "/admin/clients_revoke",
2028+ &format!("client={id}"),
2029+ Some(&setup.admin_cookie),
2030+ )
2031+ .await;
2032+ assert_eq!(status, StatusCode::SEE_OTHER);
2033+ assert_eq!(
2034+ location.as_deref(),
2035+ Some("/admin?section=clients&ok=client_revoked")
2036+ );
2037+
2038+ // The pair no longer authenticates, and the app session it minted
2039+ // no longer introspects — while the admin's own sign-in session
2040+ // lives on.
2041+ assert_eq!(
2042+ directory(&setup.router, basic(&id, &secret)).await,
2043+ StatusCode::UNAUTHORIZED
2044+ );
2045+ assert!(
2046+ introspect_app_session(&setup.store, app_token.expose(), &id)
2047+ .await
2048+ .unwrap()
2049+ .is_none(),
2050+ "no ghost app session after revocation"
2051+ );
2052+ assert_eq!(
2053+ im_core::sessions::list_sessions(&setup.store, &setup.admin_id)
2054+ .await
2055+ .unwrap()
2056+ .len(),
2057+ 2,
2058+ "the admin's two sign-in sessions — the cookie's and the one that \
2059+ minted the app token — both stay"
2060+ );
2061+ }
2062+
2063+ #[tokio::test]
2064+ async fn client_routes_refuse_non_admins() {
2065+ let setup = setup().await;
2066+
2067+ // Every client write answers a non-admin with the panel's plain
2068+ // redirect home; nothing is created, rotated, or revoked.
2069+ let (status, location, _) = post_form(
2070+ &setup.router,
2071+ "/admin/clients_add",
2072+ "name=drive&redirect_uris=http://127.0.0.1:9000/callback",
2073+ Some(&setup.plain_cookie),
2074+ )
2075+ .await;
2076+ assert_eq!(status, StatusCode::SEE_OTHER);
2077+ assert_eq!(location.as_deref(), Some("/"));
2078+ let (status, location, _) = post_form(
2079+ &setup.router,
2080+ "/admin/clients_revoke",
2081+ "client=no-such-client",
2082+ Some(&setup.plain_cookie),
2083+ )
2084+ .await;
2085+ assert_eq!(status, StatusCode::SEE_OTHER);
2086+ assert_eq!(location.as_deref(), Some("/"));
2087+ assert!(list_clients(&setup.store).await.unwrap().is_empty());
2088+
2089+ // The section read is gated the same way.
2090+ let (status, location) = get_location(
2091+ &setup.router,
2092+ "/admin?section=clients",
2093+ Some(&setup.plain_cookie),
2094+ )
2095+ .await;
2096+ assert_eq!(status, StatusCode::SEE_OTHER);
2097+ assert_eq!(location.as_deref(), Some("/"));
2098+
2099+ // And a signed-out visitor cannot even create.
2100+ let (status, _, _) = post_form(
2101+ &setup.router,
2102+ "/admin/clients_add",
2103+ "name=drive&redirect_uris=http://127.0.0.1:9000/callback",
2104+ None,
2105+ )
2106+ .await;
2107+ assert_eq!(status, StatusCode::SEE_OTHER);
2108+ }
2109+}
crates/im-web/src/i18n.rsmodified+88 -1
@@ -69,6 +69,8 @@ pub enum Key {
69 ErrBadUi,69 ErrBadUi,
70 ErrBadLanguage,70 ErrBadLanguage,
71 ErrBadService,71 ErrBadService,
72+ ErrBadClient,
73+ ErrNoSuchClient,
72 ErrFallback,74 ErrFallback,
73 75
74 // Good-news codes (`pages.rs`'s `ok_text`).76 // Good-news codes (`pages.rs`'s `ok_text`).
@@ -180,6 +182,7 @@ pub enum Key {
180 OkSettingsSaved,182 OkSettingsSaved,
181 OkServicesSaved,183 OkServicesSaved,
182 OkMessageSent,184 OkMessageSent,
185+ OkClientRevoked,
183 186
184 // Admin mail section: the composed notice.187 // Admin mail section: the composed notice.
185 MessageTitle,188 MessageTitle,
@@ -239,6 +242,22 @@ pub enum Key {
239 RoleAdmin,242 RoleAdmin,
240 InviteButton,243 InviteButton,
241 244
245+ // Admin clients section: the family's relying parties.
246+ NavClients,
247+ ClientsTitle,
248+ RedirectUrisLabel,
249+ RegisteredCol,
250+ ClientAdd,
251+ RotateWord,
252+ RevokeWord,
253+ ConfirmRotate,
254+ ConfirmRevoke,
255+ RotateCost,
256+ RevokeCost,
257+ SecretShownNote,
258+ CopyWord,
259+ CopiedWord,
260+
242 // Admin settings section.261 // Admin settings section.
243 SettingsTitle,262 SettingsTitle,
244 SettingsSub,263 SettingsSub,
@@ -369,6 +388,10 @@ pub fn t(lang: Lang, key: Key) -> &'static str {
369 (ErrBadService, Tr) => {388 (ErrBadService, Tr) => {
370 "Bir hizmet; küçük harf, rakam ya da tire ile yazılmış bir anahtar, bir ad ve http(s) adresi ister."389 "Bir hizmet; küçük harf, rakam ya da tire ile yazılmış bir anahtar, bir ad ve http(s) adresi ister."
371 }390 }
391+ (ErrBadClient, En) => "A client needs a name and at least one redirect URI.",
392+ (ErrBadClient, Tr) => "Bir istemci; bir ad ve en az bir yönlendirme adresi ister.",
393+ (ErrNoSuchClient, En) => "No such client.",
394+ (ErrNoSuchClient, Tr) => "Böyle bir istemci yok.",
372 (ErrFallback, En) => "Something went wrong. Try again.",395 (ErrFallback, En) => "Something went wrong. Try again.",
373 (ErrFallback, Tr) => "Bir şeyler ters gitti. Yeniden dene.",396 (ErrFallback, Tr) => "Bir şeyler ters gitti. Yeniden dene.",
374 397
@@ -585,7 +608,10 @@ pub fn t(lang: Lang, key: Key) -> &'static str {
585 (OkServicesSaved, Tr) => "Hizmetler kaydedildi.",608 (OkServicesSaved, Tr) => "Hizmetler kaydedildi.",
586 (OkMessageSent, En) => "Message sent.",609 (OkMessageSent, En) => "Message sent.",
587 (OkMessageSent, Tr) => "Mesaj gönderildi.",610 (OkMessageSent, Tr) => "Mesaj gönderildi.",
588-611+ (OkClientRevoked, En) => "Client revoked — its tokens and app sessions went with it.",
612+ (OkClientRevoked, Tr) => {
613+ "İstemci iptal edildi — jetonları ve uygulama oturumları da gitti."
614+ }
589 (MessageTitle, En) => "Send a message",615 (MessageTitle, En) => "Send a message",
590 (MessageTitle, Tr) => "Mesaj gönder",616 (MessageTitle, Tr) => "Mesaj gönder",
591 (MessageToLabel, En) => "To",617 (MessageToLabel, En) => "To",
@@ -700,6 +726,47 @@ pub fn t(lang: Lang, key: Key) -> &'static str {
700 (InviteButton, En) => "Invite",726 (InviteButton, En) => "Invite",
701 (InviteButton, Tr) => "Davet et",727 (InviteButton, Tr) => "Davet et",
702 728
729+ (NavClients, En) => "Clients",
730+ (NavClients, Tr) => "İstemciler",
731+ (ClientsTitle, En) => "Clients",
732+ (ClientsTitle, Tr) => "İstemciler",
733+ (RedirectUrisLabel, En) => "Redirect URIs",
734+ (RedirectUrisLabel, Tr) => "Yönlendirme adresleri",
735+ (RegisteredCol, En) => "Registered",
736+ (RegisteredCol, Tr) => "Kayıt",
737+ (ClientAdd, En) => "Register client",
738+ (ClientAdd, Tr) => "İstemci kaydet",
739+ (RotateWord, En) => "Rotate",
740+ (RotateWord, Tr) => "Yenile",
741+ (RevokeWord, En) => "Revoke",
742+ (RevokeWord, Tr) => "İptal et",
743+ (ConfirmRotate, En) => "Confirm rotate",
744+ (ConfirmRotate, Tr) => "Yenilemeyi onayla",
745+ (ConfirmRevoke, En) => "Confirm revoke",
746+ (ConfirmRevoke, Tr) => "İptali onayla",
747+ (RotateCost, En) => {
748+ "The old secret stops working the moment the new one exists — put the new one in the app's config."
749+ }
750+ (RotateCost, Tr) => {
751+ "Eski anahtar, yenisi oluştuğu anda geçersiz olur — yenisini uygulamanın ayarlarına koy."
752+ }
753+ (RevokeCost, En) => {
754+ "The pair stops working, and its refresh tokens and app sessions go with it."
755+ }
756+ (RevokeCost, Tr) => {
757+ "Anahtar çifti geçersiz olur; yenileme jetonları ve uygulama oturumları da silinir."
758+ }
759+ (SecretShownNote, En) => {
760+ "This secret is shown once. Put the pair in the app's config now — only its digest stays here."
761+ }
762+ (SecretShownNote, Tr) => {
763+ "Bu anahtar bir kez gösterilir. Çifti şimdi uygulamanın ayarlarına koy — buraya yalnızca özeti kalır."
764+ }
765+ (CopyWord, En) => "Copy",
766+ (CopyWord, Tr) => "Kopyala",
767+ (CopiedWord, En) => "Copied",
768+ (CopiedWord, Tr) => "Kopyalandı",
769+
703 (SettingsTitle, En) => "Settings",770 (SettingsTitle, En) => "Settings",
704 (SettingsTitle, Tr) => "Ayarlar",771 (SettingsTitle, Tr) => "Ayarlar",
705 (SettingsSub, En) => {772 (SettingsSub, En) => {
@@ -881,6 +948,9 @@ pub fn kind_word(lang: Lang, kind: &str) -> String {
881 "smtp_checked" => ("Mail server checked", "Posta sunucusu denetlendi"),948 "smtp_checked" => ("Mail server checked", "Posta sunucusu denetlendi"),
882 "message_sent" => ("Message sent", "Mesaj gönderildi"),949 "message_sent" => ("Message sent", "Mesaj gönderildi"),
883 "message_failed" => ("Message failed", "Mesaj başarısız"),950 "message_failed" => ("Message failed", "Mesaj başarısız"),
951+ "client_created" => ("Client created", "İstemci oluşturuldu"),
952+ "client_rotated" => ("Client secret rotated", "İstemci anahtarı yenilendi"),
953+ "client_revoked" => ("Client revoked", "İstemci iptal edildi"),
884 _ => return kind.to_string(),954 _ => return kind.to_string(),
885 };955 };
886 match lang {956 match lang {
@@ -954,6 +1024,23 @@ pub fn remove_service_title(lang: Lang, name_html: &str) -> String {
954 }1024 }
955 }1025 }
956 1026
1027+/// A client row's "Rotate <name>'s secret?" disclosure title. `name_html`
1028+/// is already escaped.
1029+pub fn rotate_client_title(lang: Lang, name_html: &str) -> String {
1030+ match lang {
1031+ Lang::En => format!("Rotate {name_html}'s secret?"),
1032+ Lang::Tr => format!("{name_html} anahtarı yenilensin mi?"),
1033+ }
1034+}
1035+
1036+/// See [`rotate_client_title`].
1037+pub fn revoke_client_title(lang: Lang, name_html: &str) -> String {
1038+ match lang {
1039+ Lang::En => format!("Revoke {name_html}?"),
1040+ Lang::Tr => format!("{name_html} iptal edilsin mi?"),
1041+ }
1042+}
1043+
957 /// The mail section's lede: what the sender is for. The mono span is markup.1044 /// The mail section's lede: what the sender is for. The mono span is markup.
958 pub fn mail_sub(lang: Lang) -> String {1045 pub fn mail_sub(lang: Lang) -> String {
959 match lang {1046 match lang {
crates/im-web/src/main.rsmodified+78 -1
@@ -97,9 +97,23 @@ async fn main() {
97 };97 };
98 set_admin_cli(config, email, false).await;98 set_admin_cli(config, email, false).await;
99 }99 }
100+ Some("rotate-client") => {
101+ let Some(id) = args.get(2) else {
102+ eprintln!("usage: im-web rotate-client <client_id>");
103+ std::process::exit(2);
104+ };
105+ rotate_client(config, id).await;
106+ }
107+ Some("revoke-client") => {
108+ let Some(id) = args.get(2) else {
109+ eprintln!("usage: im-web revoke-client <client_id>");
110+ std::process::exit(2);
111+ };
112+ revoke_client(config, id).await;
113+ }
100 Some(other) => {114 Some(other) => {
101 eprintln!(115 eprintln!(
102- "im: unknown command {other:?} (expected: invite, revoke, promote, demote, create-client, or none to serve)"116+ "im: unknown command {other:?} (expected: invite, revoke, promote, demote, create-client, rotate-client, revoke-client, or none to serve)"
103 );117 );
104 std::process::exit(2);118 std::process::exit(2);
105 }119 }
@@ -259,6 +273,69 @@ async fn create_client(config: Config, name: &str, uris: &[String]) {
259 println!(" client_secret {}", secret.expose());273 println!(" client_secret {}", secret.expose());
260 println!(" (the secret is shown once; its digest is all the database keeps)");274 println!(" (the secret is shown once; its digest is all the database keeps)");
261 }275 }
276+
277+/// `im-web rotate-client <client_id>`: replaces the client's secret and
278+/// prints the new one exactly once — the app's old pair dies with the write.
279+///
280+/// Needs the server stopped, like every CLI arm: Turso is a single-writer
281+/// engine, and this process would hold the same file.
282+async fn rotate_client(config: Config, id: &str) {
283+ let store = open_store(&config).await;
284+ let name = client_name(&store, id).await;
285+ match im_core::oidc::rotate_client_secret(&store, id)
286+ .await
287+ .expect("failed to rotate the client secret")
288+ {
289+ Some(secret) => {
290+ im_core::events::log(&store, "client_rotated", Some("cli"), Some(&name)).await;
291+ println!("im client {id} ({name})");
292+ println!(" client_secret {}", secret.expose());
293+ println!(" (the secret is shown once; its digest is all the database keeps)");
294+ }
295+ None => {
296+ eprintln!("im: no client {id}");
297+ std::process::exit(1);
298+ }
299+ }
300+}
301+
302+/// `im-web revoke-client <client_id>`: deletes the registry row and every
303+/// refresh token and app session minted under it; the person's own sign-in
304+/// sessions stay.
305+///
306+/// Needs the server stopped, like every CLI arm: Turso is a single-writer
307+/// engine, and this process would hold the same file.
308+async fn revoke_client(config: Config, id: &str) {
309+ let store = open_store(&config).await;
310+ // The name rides the log line and the goodbye, so it comes off the row
311+ // before the row goes.
312+ let name = client_name(&store, id).await;
313+ match im_core::oidc::revoke_client(&store, id)
314+ .await
315+ .expect("failed to revoke the client")
316+ {
317+ true => {
318+ println!(
319+ "im client {id} ({name}) revoked — its tokens and app sessions went with it"
320+ );
321+ }
322+ false => {
323+ eprintln!("im: no client {id}");
324+ std::process::exit(1);
325+ }
326+ }
327+}
328+
329+/// The client's display name, or its id when no row stands behind it — the
330+/// log's detail is the name when there is one.
331+async fn client_name(store: &Arc<im_core::store::Store>, id: &str) -> String {
332+ im_core::oidc::client_by_id(store, id)
333+ .await
334+ .expect("failed to read the client")
335+ .map(|client| client.name)
336+ .unwrap_or_else(|| id.to_string())
337+}
338+
262 async fn serve(config: Config) {339 async fn serve(config: Config) {
263 for line in config.report() {340 for line in config.report() {
264 println!("im {line}");341 println!("im {line}");
crates/im-web/src/pages.rsmodified+2 -0
@@ -45,6 +45,8 @@ pub fn error_text(code: &str, lang: Lang) -> &'static str {
45 "bad_ui" => t(lang, Key::ErrBadUi),45 "bad_ui" => t(lang, Key::ErrBadUi),
46 "bad_language" => t(lang, Key::ErrBadLanguage),46 "bad_language" => t(lang, Key::ErrBadLanguage),
47 "bad_service" => t(lang, Key::ErrBadService),47 "bad_service" => t(lang, Key::ErrBadService),
48+ "bad_client" => t(lang, Key::ErrBadClient),
49+ "no_such_client" => t(lang, Key::ErrNoSuchClient),
48 "empty_subject" => t(lang, Key::ErrEmptySubject),50 "empty_subject" => t(lang, Key::ErrEmptySubject),
49 "empty_body" => t(lang, Key::ErrEmptyBody),51 "empty_body" => t(lang, Key::ErrEmptyBody),
50 "no_such_user" => t(lang, Key::ErrNoSuchUser),52 "no_such_user" => t(lang, Key::ErrNoSuchUser),
crates/im-web/src/server.rsmodified+41 -1
@@ -8,7 +8,9 @@
8 //! fetch with `accept: text/html`, so the 303's target document is what8 //! fetch with `accept: text/html`, so the 303's target document is what
9 //! comes back — no refusal-carrying layer as in İzlek is needed.9 //! comes back — no refusal-carrying layer as in İzlek is needed.
10 10
11-use std::sync::Arc;11+use std::collections::HashMap;
12+use std::sync::{Arc, LazyLock, Mutex, PoisonError};
13+use std::time::{Duration, Instant};
12 14
13 use im_core::model::User;15 use im_core::model::User;
14 use im_core::store::Store;16 use im_core::store::Store;
@@ -70,6 +72,44 @@ pub async fn log_event(cx: &Cx, kind: &str, actor: Option<&str>, detail: Option<
70 note(cx);72 note(cx);
71 }73 }
72 74
75+// ---------------------------------------------------------------------------
76+// The show-once shelf
77+// ---------------------------------------------------------------------------
78+
79+/// How long a stashed secret waits for its one reader.
80+const SHOWN_TTL: Duration = Duration::from_secs(10 * 60);
81+
82+/// Where a freshly minted client secret waits between its POST and the one
83+/// GET that shows it. The panel's write answers a 303 — the house idiom —
84+/// but the secret itself must never ride a URL or a log line, so the query
85+/// carries only a random claim ticket: the shelf holds the plaintext, the
86+/// page's read takes it out (`take_shown_secret`), and a replayed or
87+/// reloaded URL finds the shelf empty and renders no secret at all. A
88+/// restart drops the shelf — the admin mints another, as with the CLI.
89+static SHOWN_SECRETS: LazyLock<Mutex<HashMap<String, ((String, String), Instant)>>> =
90+ LazyLock::new(|| Mutex::new(HashMap::new()));
91+
92+/// Parks a client's fresh pair on the shelf and returns the claim ticket
93+/// for its URL. The id travels too — it is the public half of the pair and
94+/// the one render shows it beside the secret.
95+pub fn stash_shown_secret(client_id: String, secret: String) -> String {
96+ let ticket = im_core::accounts::Token::mint().expose().to_string();
97+ let mut shelf = SHOWN_SECRETS.lock().unwrap_or_else(PoisonError::into_inner);
98+ shelf.retain(|_, (_, parked)| parked.elapsed() < SHOWN_TTL);
99+ shelf.insert(ticket.clone(), ((client_id, secret), Instant::now()));
100+ ticket
101+}
102+
103+/// Takes a stashed pair out — exactly once; the second reader of the same
104+/// ticket gets nothing.
105+pub fn take_shown_secret(ticket: &str) -> Option<(String, String)> {
106+ SHOWN_SECRETS
107+ .lock()
108+ .unwrap_or_else(PoisonError::into_inner)
109+ .remove(ticket)
110+ .map(|(pair, _)| pair)
111+}
112+
73 pub fn app(cx: &Cx) -> &App {113 pub fn app(cx: &Cx) -> &App {
74 try_app_context::<App>(cx).expect("the router always carries the App")114 try_app_context::<App>(cx).expect("the router always carries the App")
75 }115 }