forge
Explore
Log in

Don't you dare go Hollow

im

Clone
★ 0

0 watching0 forksRustAGPL-3.0542.8 KiBb9f0726Tahinli27 days ago34 commits

logout.rs283 lines, 11.5 KiBHistoryRawDownload
1//! `GET /logout` and `POST /logout`: OpenID Connect RP-Initiated Logout (contracts.md 2.5), and the
2//! sign-out button of the account menu, which posts to the same path with no hint.
3//!
4//! The rules, in order:
5//! - An `id_token_hint` is an ID token of ours: the signature and `iss` are checked, the expiry is not
6//! (an expired hint still names a session). A hint that fails is ignored, as if it were absent.
7//! - The client is named by the hint's `aud`. A redirect happens only when the client is enabled and
8//! `post_logout_redirect_uri` equals one of its registered URIs exactly. Otherwise the answer is the
9//! signed-out page, never a redirect.
10//! - `state` is echoed on the redirect only when it is usable (bounded, no control characters).
11//! - A `GET` never ends a session: a link or an image on another site must not sign the browser out. A
12//! `GET` with a session answers with a form that carries the session's CSRF token. The form posts itself
13//! (`data-auto-submit`, run by `assets/pages.js`) only when the hint is this browser's own: its `sid` is
14//! the viewer's session and its `sub` is the viewer. That is a client's sign-out, so the browser returns
15//! to the client without a second click. Any other hint (anyone can hold a valid ID token of their own)
16//! leaves the person to click. The visible button is the fallback without JS. Only the `POST` ends the
17//! session, and it checks that token before anything changes.
18//! - Ending the session is `im`'s own: the browser session is deleted (and its clients told by
19//! back-channel logout, in the store's transaction). When the hint names another session of the same
20//! person, that one ends too.
21
22use im_core::jwt::{self, PublishedKey};
23use im_core::model::AuditAction;
24use im_core::oauth::MAX_ECHO_BYTES;
25use im_core::store::Store;
26use im_core::store::backchannel::EndReason;
27use serde::Deserialize;
28use serde_json::Value;
29use topcoat::Result;
30use topcoat::context::{Cx, app_context};
31use topcoat::router::content::Form;
32use topcoat::router::error::{forbidden, see_other};
33use topcoat::router::page;
34use topcoat::view::{View, view};
35
36use super::signing;
37use super::{issuer, with_query};
38use crate::audit::{Actor, record};
39use crate::auth::{Viewer, check_csrf, current_user, end_current_session};
40use crate::i18n::Lang;
41use crate::i18n::oidc::{OidcText, text};
42use crate::live::Topic;
43use crate::state::AppState;
44use crate::views::{page_lang, shell};
45
46/// The parameters of a logout request, from the query (GET) or the form (POST). Every field is optional.
47#[derive(Debug, Default, Deserialize)]
48#[serde(default)]
49pub struct LogoutForm {
50 /// The CSRF token of the browser session. Required by a POST that would end a session.
51 csrf: String,
52 /// An ID token previously issued to the client.
53 id_token_hint: String,
54 /// Where the client wants the browser to land.
55 post_logout_redirect_uri: String,
56 /// The client's opaque value, echoed back on the redirect.
57 state: String,
58}
59
60/// What a valid hint says: the person it was issued to and the session it names.
61struct Hint {
62 /// The `sub` claim: the person the ID token was issued to.
63 sub: Option<String>,
64 /// The `im` session of the sign-in, when the hint names one.
65 sid: Option<String>,
66}
67
68/// The checked request: the hint (if valid), the redirect to make (if allowed) and the echoed state.
69struct Asked {
70 /// The verified hint, if there was one that checks out.
71 hint: Option<Hint>,
72 /// The post-logout URI, when it equals a registered one of the hinted client.
73 redirect: Option<String>,
74 /// The state to echo, when it is usable.
75 state: Option<String>,
76 /// The hint as given, when it checks out: the confirmation form carries it.
77 raw_hint: Option<String>,
78}
79
80/// Tells a state apart from a value that must not be echoed.
81fn usable_state(value: &str) -> bool {
82 !value.is_empty() && value.len() <= MAX_ECHO_BYTES && !value.chars().any(char::is_control)
83}
84
85/// Verifies an ID token of ours for logout. `None` when it is not an ID token of this provider, or its
86/// signature or issuer is wrong. The expiry is not checked. Returns the client it was issued to and the
87/// hint's claims that matter here.
88async fn verify_hint(
89 store: &Store,
90 issuer: &str,
91 token: &str,
92) -> im_core::Result<Option<(String, Hint)>> {
93 let published = signing::published_keys(store).await?;
94 let keys: Vec<PublishedKey> = published
95 .iter()
96 .filter_map(|key| PublishedKey::new(key.kid.clone(), &key.public_raw))
97 .collect();
98 let Ok(claims) = jwt::verify(&keys, token) else {
99 return Ok(None);
100 };
101 if jwt::check_issuer(&claims, issuer).is_err() {
102 return Ok(None);
103 }
104 // An access token has `azp` and `scope`; an ID token has neither. Only ID tokens are hints. A logout
105 // token carries `events` and is never a hint either: it would otherwise pass for an ID token here.
106 if claims.contains_key("azp") || claims.contains_key("scope") || claims.contains_key("events") {
107 return Ok(None);
108 }
109 let Some(client_id) = jwt::single_audience(&claims) else {
110 return Ok(None);
111 };
112 let hint = Hint {
113 sub: claims.get("sub").and_then(Value::as_str).map(str::to_owned),
114 sid: claims.get("sid").and_then(Value::as_str).map(str::to_owned),
115 };
116 Ok(Some((client_id.to_owned(), hint)))
117}
118
119/// Checks the request. Nothing here changes state.
120async fn read(app: &AppState, form: &LogoutForm) -> Result<Asked> {
121 let state = Some(form.state.as_str())
122 .filter(|value| usable_state(value))
123 .map(str::to_owned);
124 let mut asked = Asked {
125 hint: None,
126 redirect: None,
127 state,
128 raw_hint: None,
129 };
130 if form.id_token_hint.is_empty() {
131 return Ok(asked);
132 }
133 let Some((client_id, hint)) = verify_hint(&app.store, issuer(app), &form.id_token_hint).await?
134 else {
135 return Ok(asked);
136 };
137 asked.raw_hint = Some(form.id_token_hint.clone());
138 let client = app.store.client_by_id(&client_id).await?;
139 if let Some(client) = client.filter(|c| !c.is_disabled())
140 && !form.post_logout_redirect_uri.is_empty()
141 && client
142 .post_logout_redirect_uris
143 .iter()
144 .any(|registered| registered == &form.post_logout_redirect_uri)
145 {
146 asked.redirect = Some(form.post_logout_redirect_uri.clone());
147 }
148 asked.hint = Some(hint);
149 Ok(asked)
150}
151
152/// The redirect to the client, with the state when there is one. `None` means the signed-out page.
153fn redirect_target(asked: &Asked) -> Option<String> {
154 let uri = asked.redirect.as_deref()?;
155 Some(match asked.state.as_deref() {
156 Some(state) => with_query(uri, &[("state", state)]),
157 None => uri.to_owned(),
158 })
159}
160
161/// Ends the browser's session and, when the hint names another session of the same person, that one
162/// too. Audits the sign-out.
163async fn sign_out(cx: &Cx, viewer: &Viewer, hint_sid: Option<&str>) -> Result<()> {
164 let app = app_context::<AppState>(cx);
165 end_current_session(cx, viewer, EndReason::Logout).await?;
166 if let Some(other) = hint_sid.filter(|sid| *sid != viewer.session.id) {
167 // The store checks ownership: another person's session is not ended, and the call says so.
168 if app
169 .store
170 .end_session(&viewer.user.id, other, EndReason::Logout)
171 .await?
172 {
173 app.live.bump(&Topic::Account(viewer.user.id.clone()));
174 }
175 }
176 record(
177 cx,
178 Actor::User(&viewer.user.id),
179 AuditAction::Logout,
180 Some(("session", &viewer.session.id)),
181 Value::Null,
182 )
183 .await;
184 Ok(())
185}
186
187/// `GET /logout`. Never ends a session: with one, it shows the confirmation form.
188#[page(GET "/logout")]
189async fn logout_get(cx: &Cx, Form(form): Form<LogoutForm>) -> Result<impl View> {
190 let app = app_context::<AppState>(cx);
191 let asked = read(app, &form).await?;
192 let viewer = current_user(cx).await?;
193 let lang = page_lang(cx, viewer.as_ref());
194 match viewer {
195 Some(viewer) => {
196 // Only the browser's own hint (a client's sign-out) may post the form without a click.
197 let own = asked.hint.as_ref().is_some_and(|hint| {
198 hint.sid.as_deref() == Some(viewer.session.id.as_str())
199 && hint.sub.as_deref() == Some(viewer.user.id.as_str())
200 });
201 let confirm = Confirm {
202 csrf: viewer.session.csrf_token.clone(),
203 raw_hint: asked.raw_hint.clone(),
204 auto_submit: own,
205 redirect: asked.redirect.clone(),
206 state: asked.state.clone(),
207 };
208 Ok(logout_view(cx, lang, Some(confirm)))
209 }
210 // No session to end: only the redirect, if the hint allows one.
211 None => {
212 if let Some(target) = redirect_target(&asked) {
213 return Err(see_other(target).into());
214 }
215 Ok(logout_view(cx, lang, None))
216 }
217 }
218}
219
220/// `POST /logout`. Without a session there is nothing to end, so no CSRF check applies.
221#[page(POST "/logout")]
222async fn logout_post(cx: &Cx, Form(form): Form<LogoutForm>) -> Result<impl View> {
223 let app = app_context::<AppState>(cx);
224 let asked = read(app, &form).await?;
225 let viewer = current_user(cx).await?;
226 if let Some(viewer) = &viewer {
227 if !check_csrf(&viewer.session, &form.csrf) {
228 return Err(forbidden().into());
229 }
230 let hint_sid = asked.hint.as_ref().and_then(|hint| hint.sid.clone());
231 sign_out(cx, viewer, hint_sid.as_deref()).await?;
232 }
233 if let Some(target) = redirect_target(&asked) {
234 return Err(see_other(target).into());
235 }
236 let lang = page_lang(cx, None);
237 Ok(logout_view(cx, lang, None))
238}
239
240/// The form that signs the browser out (the GET answer with a session). It posts itself.
241struct Confirm {
242 csrf: String,
243 raw_hint: Option<String>,
244 /// True when the hint is this browser's own, so the form posts without a click.
245 auto_submit: bool,
246 redirect: Option<String>,
247 state: Option<String>,
248}
249
250/// The confirmation page, or the signed-out page when `confirm` is `None`. The form posts to this same
251/// path and carries everything the POST needs to finish the same request.
252fn logout_view(cx: &Cx, lang: Lang, confirm: Option<Confirm>) -> impl View {
253 let title = if confirm.is_some() {
254 text(lang, OidcText::ConfirmTitle)
255 } else {
256 text(lang, OidcText::SignedOutTitle)
257 };
258 view! { cx =>
259 shell(title: title, lang: lang, viewer: None,
260 <section class="card narrow stack">
261 <h1>(title)</h1>
262 if let Some(confirm) = confirm {
263 <p class="muted">(text(lang, OidcText::ConfirmBody))</p>
264 <form method="post" action="/logout" class="stack" data-hard="true" data-auto-submit=(if confirm.auto_submit { "true" } else { "false" })>
265 <input type="hidden" name="csrf" value=(confirm.csrf)>
266 if let Some(hint) = confirm.raw_hint {
267 <input type="hidden" name="id_token_hint" value=(hint)>
268 }
269 if let Some(uri) = confirm.redirect {
270 <input type="hidden" name="post_logout_redirect_uri" value=(uri)>
271 }
272 if let Some(state) = confirm.state {
273 <input type="hidden" name="state" value=(state)>
274 }
275 <button type="submit" class="button primary">(text(lang, OidcText::ConfirmButton))</button>
276 </form>
277 } else {
278 <p>(text(lang, OidcText::SignedOutBody))</p>
279 }
280 </section>
281 )
282 }
283}