//! `GET /logout` and `POST /logout`: OpenID Connect RP-Initiated Logout (contracts.md 2.5), and the //! sign-out button of the account menu, which posts to the same path with no hint. //! //! The rules, in order: //! - An `id_token_hint` is an ID token of ours: the signature and `iss` are checked, the expiry is not //! (an expired hint still names a session). A hint that fails is ignored, as if it were absent. //! - The client is named by the hint's `aud`. A redirect happens only when the client is enabled and //! `post_logout_redirect_uri` equals one of its registered URIs exactly. Otherwise the answer is the //! signed-out page, never a redirect. //! - `state` is echoed on the redirect only when it is usable (bounded, no control characters). //! - A `GET` never ends a session: a link or an image on another site must not sign the browser out. A //! `GET` with a session answers with a form that carries the session's CSRF token. The form posts itself //! (`data-auto-submit`, run by `assets/pages.js`) only when the hint is this browser's own: its `sid` is //! the viewer's session and its `sub` is the viewer. That is a client's sign-out, so the browser returns //! to the client without a second click. Any other hint (anyone can hold a valid ID token of their own) //! leaves the person to click. The visible button is the fallback without JS. Only the `POST` ends the //! session, and it checks that token before anything changes. //! - Ending the session is `im`'s own: the browser session is deleted (and its clients told by //! back-channel logout, in the store's transaction). When the hint names another session of the same //! person, that one ends too. use im_core::jwt::{self, PublishedKey}; use im_core::model::AuditAction; use im_core::oauth::MAX_ECHO_BYTES; use im_core::store::Store; use im_core::store::backchannel::EndReason; use serde::Deserialize; use serde_json::Value; use topcoat::Result; use topcoat::context::{Cx, app_context}; use topcoat::router::content::Form; use topcoat::router::error::{forbidden, see_other}; use topcoat::router::page; use topcoat::view::{View, view}; use super::signing; use super::{issuer, with_query}; use crate::audit::{Actor, record}; use crate::auth::{Viewer, check_csrf, current_user, end_current_session}; use crate::i18n::Lang; use crate::i18n::oidc::{OidcText, text}; use crate::live::Topic; use crate::state::AppState; use crate::views::{page_lang, shell}; /// The parameters of a logout request, from the query (GET) or the form (POST). Every field is optional. #[derive(Debug, Default, Deserialize)] #[serde(default)] pub struct LogoutForm { /// The CSRF token of the browser session. Required by a POST that would end a session. csrf: String, /// An ID token previously issued to the client. id_token_hint: String, /// Where the client wants the browser to land. post_logout_redirect_uri: String, /// The client's opaque value, echoed back on the redirect. state: String, } /// What a valid hint says: the person it was issued to and the session it names. struct Hint { /// The `sub` claim: the person the ID token was issued to. sub: Option, /// The `im` session of the sign-in, when the hint names one. sid: Option, } /// The checked request: the hint (if valid), the redirect to make (if allowed) and the echoed state. struct Asked { /// The verified hint, if there was one that checks out. hint: Option, /// The post-logout URI, when it equals a registered one of the hinted client. redirect: Option, /// The state to echo, when it is usable. state: Option, /// The hint as given, when it checks out: the confirmation form carries it. raw_hint: Option, } /// Tells a state apart from a value that must not be echoed. fn usable_state(value: &str) -> bool { !value.is_empty() && value.len() <= MAX_ECHO_BYTES && !value.chars().any(char::is_control) } /// Verifies an ID token of ours for logout. `None` when it is not an ID token of this provider, or its /// signature or issuer is wrong. The expiry is not checked. Returns the client it was issued to and the /// hint's claims that matter here. async fn verify_hint( store: &Store, issuer: &str, token: &str, ) -> im_core::Result> { let published = signing::published_keys(store).await?; let keys: Vec = published .iter() .filter_map(|key| PublishedKey::new(key.kid.clone(), &key.public_raw)) .collect(); let Ok(claims) = jwt::verify(&keys, token) else { return Ok(None); }; if jwt::check_issuer(&claims, issuer).is_err() { return Ok(None); } // An access token has `azp` and `scope`; an ID token has neither. Only ID tokens are hints. A logout // token carries `events` and is never a hint either: it would otherwise pass for an ID token here. if claims.contains_key("azp") || claims.contains_key("scope") || claims.contains_key("events") { return Ok(None); } let Some(client_id) = jwt::single_audience(&claims) else { return Ok(None); }; let hint = Hint { sub: claims.get("sub").and_then(Value::as_str).map(str::to_owned), sid: claims.get("sid").and_then(Value::as_str).map(str::to_owned), }; Ok(Some((client_id.to_owned(), hint))) } /// Checks the request. Nothing here changes state. async fn read(app: &AppState, form: &LogoutForm) -> Result { let state = Some(form.state.as_str()) .filter(|value| usable_state(value)) .map(str::to_owned); let mut asked = Asked { hint: None, redirect: None, state, raw_hint: None, }; if form.id_token_hint.is_empty() { return Ok(asked); } let Some((client_id, hint)) = verify_hint(&app.store, issuer(app), &form.id_token_hint).await? else { return Ok(asked); }; asked.raw_hint = Some(form.id_token_hint.clone()); let client = app.store.client_by_id(&client_id).await?; if let Some(client) = client.filter(|c| !c.is_disabled()) && !form.post_logout_redirect_uri.is_empty() && client .post_logout_redirect_uris .iter() .any(|registered| registered == &form.post_logout_redirect_uri) { asked.redirect = Some(form.post_logout_redirect_uri.clone()); } asked.hint = Some(hint); Ok(asked) } /// The redirect to the client, with the state when there is one. `None` means the signed-out page. fn redirect_target(asked: &Asked) -> Option { let uri = asked.redirect.as_deref()?; Some(match asked.state.as_deref() { Some(state) => with_query(uri, &[("state", state)]), None => uri.to_owned(), }) } /// Ends the browser's session and, when the hint names another session of the same person, that one /// too. Audits the sign-out. async fn sign_out(cx: &Cx, viewer: &Viewer, hint_sid: Option<&str>) -> Result<()> { let app = app_context::(cx); end_current_session(cx, viewer, EndReason::Logout).await?; if let Some(other) = hint_sid.filter(|sid| *sid != viewer.session.id) { // The store checks ownership: another person's session is not ended, and the call says so. if app .store .end_session(&viewer.user.id, other, EndReason::Logout) .await? { app.live.bump(&Topic::Account(viewer.user.id.clone())); } } record( cx, Actor::User(&viewer.user.id), AuditAction::Logout, Some(("session", &viewer.session.id)), Value::Null, ) .await; Ok(()) } /// `GET /logout`. Never ends a session: with one, it shows the confirmation form. #[page(GET "/logout")] async fn logout_get(cx: &Cx, Form(form): Form) -> Result { let app = app_context::(cx); let asked = read(app, &form).await?; let viewer = current_user(cx).await?; let lang = page_lang(cx, viewer.as_ref()); match viewer { Some(viewer) => { // Only the browser's own hint (a client's sign-out) may post the form without a click. let own = asked.hint.as_ref().is_some_and(|hint| { hint.sid.as_deref() == Some(viewer.session.id.as_str()) && hint.sub.as_deref() == Some(viewer.user.id.as_str()) }); let confirm = Confirm { csrf: viewer.session.csrf_token.clone(), raw_hint: asked.raw_hint.clone(), auto_submit: own, redirect: asked.redirect.clone(), state: asked.state.clone(), }; Ok(logout_view(cx, lang, Some(confirm))) } // No session to end: only the redirect, if the hint allows one. None => { if let Some(target) = redirect_target(&asked) { return Err(see_other(target).into()); } Ok(logout_view(cx, lang, None)) } } } /// `POST /logout`. Without a session there is nothing to end, so no CSRF check applies. #[page(POST "/logout")] async fn logout_post(cx: &Cx, Form(form): Form) -> Result { let app = app_context::(cx); let asked = read(app, &form).await?; let viewer = current_user(cx).await?; if let Some(viewer) = &viewer { if !check_csrf(&viewer.session, &form.csrf) { return Err(forbidden().into()); } let hint_sid = asked.hint.as_ref().and_then(|hint| hint.sid.clone()); sign_out(cx, viewer, hint_sid.as_deref()).await?; } if let Some(target) = redirect_target(&asked) { return Err(see_other(target).into()); } let lang = page_lang(cx, None); Ok(logout_view(cx, lang, None)) } /// The form that signs the browser out (the GET answer with a session). It posts itself. struct Confirm { csrf: String, raw_hint: Option, /// True when the hint is this browser's own, so the form posts without a click. auto_submit: bool, redirect: Option, state: Option, } /// The confirmation page, or the signed-out page when `confirm` is `None`. The form posts to this same /// path and carries everything the POST needs to finish the same request. fn logout_view(cx: &Cx, lang: Lang, confirm: Option) -> impl View { let title = if confirm.is_some() { text(lang, OidcText::ConfirmTitle) } else { text(lang, OidcText::SignedOutTitle) }; view! { cx => shell(title: title, lang: lang, viewer: None,

(title)

if let Some(confirm) = confirm {

(text(lang, OidcText::ConfirmBody))

if let Some(hint) = confirm.raw_hint { } if let Some(uri) = confirm.redirect { } if let Some(state) = confirm.state { }
} else {

(text(lang, OidcText::SignedOutBody))

}
) } }