Skip to main content

beyondigital_auth_sdk/
logout.rs

1//! Logout: the RP-initiated logout URL (OIDC RP-Initiated Logout 1.0) and the claim rules for back-channel logout
2//! tokens (OIDC Back-Channel Logout 1.0, sections 2.4 and 2.6).
3//!
4//! The service ends a hosted-page session at `/oauth/end_session` and, for every client of that session that
5//! registered a `backchannel_logout_uri`, POSTs `logout_token=<jwt>` there (`services/backchannel_logout.rs`). The token
6//! is signed with the key the ID tokens use, so it verifies against the same JWKS:
7//! [`MultiIssuerVerifier::verify_logout_token`](crate::MultiIssuerVerifier::verify_logout_token) does that and then
8//! applies [`check_logout_claims`].
9//!
10//! Errors here are fixed sentences. They never carry the token, an issuer, a key id or any other value taken from the
11//! token: the token comes from the network.
12use std::fmt;
13
14use reqwest::Url;
15use serde_json::{Map, Value};
16
17use crate::error::AuthError;
18use crate::wire::{form_urlencode, non_blank, origin_of};
19
20pub const BACKCHANNEL_LOGOUT_EVENT: &str = "http://schemas.openid.net/event/backchannel-logout";
21/// A logout token the service signed is not accepted when it was issued longer ago than this (the service sends for ten
22/// minutes).
23pub const DEFAULT_LOGOUT_TOKEN_MAX_AGE_SECONDS: u64 = 600;
24/// An `iat` this far ahead of the local clock is tolerated, plus the verifier's clock skew.
25pub const LOGOUT_TOKEN_FUTURE_SECONDS: f64 = 60.0;
26
27/// Which rule a rejected logout token broke.
28#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
29pub enum LogoutFailure {
30    /// The JOSE `typ` is not `logout+jwt`.
31    Typ,
32    /// `iss` is not on the issuer allow-list.
33    Issuer,
34    /// Signed with a key the issuer does not publish.
35    Key,
36    /// The signature does not verify (or the token is not a JWS).
37    Signature,
38    Expired,
39    /// A required claim is missing or the wrong type.
40    Claims,
41    /// `aud` does not include this client.
42    Audience,
43    /// No back-channel logout event member.
44    Events,
45    /// A logout token must not carry a nonce.
46    Nonce,
47    /// Neither `sub` nor `sid`.
48    Subject,
49    /// `iat` is in the future or older than the age bound.
50    Iat,
51    /// The `consume_jti` hook said this `jti` was already used.
52    Replay,
53}
54
55impl LogoutFailure {
56    /// The reason as a short word: `typ`, `issuer`, `key`, `signature`, `expired`, `claims`, `audience`, `events`,
57    /// `nonce`, `subject`, `iat` or `replay`. The words the shared fixture uses (`reject:<reason>`).
58    pub const fn as_str(self) -> &'static str {
59        match self {
60            Self::Typ => "typ",
61            Self::Issuer => "issuer",
62            Self::Key => "key",
63            Self::Signature => "signature",
64            Self::Expired => "expired",
65            Self::Claims => "claims",
66            Self::Audience => "audience",
67            Self::Events => "events",
68            Self::Nonce => "nonce",
69            Self::Subject => "subject",
70            Self::Iat => "iat",
71            Self::Replay => "replay",
72        }
73    }
74
75    /// The `code` an [`AuthError::Jwt`] of the same failure would carry.
76    pub const fn code(self) -> &'static str {
77        match self {
78            Self::Issuer => "issuer_mismatch",
79            Self::Key => "kid_mismatch",
80            Self::Expired => "expired",
81            Self::Audience => "audience_mismatch",
82            _ => "invalid",
83        }
84    }
85
86    const fn message(self) -> &'static str {
87        match self {
88            Self::Typ => "not a logout token: the JOSE typ is not logout+jwt",
89            Self::Issuer => "logout token issuer is not an allow-listed issuer",
90            Self::Key => "logout token is signed with a key the issuer does not publish",
91            Self::Signature => "logout token signature does not verify",
92            Self::Expired => "logout token has expired",
93            Self::Claims => "logout token is missing a required claim",
94            Self::Audience => "logout token audience does not include this client",
95            Self::Events => "logout token has no back-channel logout event",
96            Self::Nonce => "a logout token must not carry a nonce",
97            Self::Subject => "logout token has neither a sub nor a sid",
98            Self::Iat => "logout token was not issued recently",
99            Self::Replay => "logout token was already used",
100        }
101    }
102}
103
104/// A back-channel logout token that must not be acted on. [`reason`](Self::reason) says which rule it broke; the
105/// message is fixed.
106#[derive(Debug, Clone, Copy, PartialEq, Eq)]
107pub struct LogoutTokenError {
108    reason: LogoutFailure,
109}
110
111impl LogoutTokenError {
112    pub const fn new(reason: LogoutFailure) -> Self {
113        Self { reason }
114    }
115    pub const fn reason(&self) -> LogoutFailure {
116        self.reason
117    }
118    /// The `code` of the same failure as an [`AuthError::Jwt`].
119    pub const fn code(&self) -> &'static str {
120        self.reason.code()
121    }
122}
123
124impl fmt::Display for LogoutTokenError {
125    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
126        f.write_str(self.reason.message())
127    }
128}
129
130impl std::error::Error for LogoutTokenError {}
131
132impl From<LogoutFailure> for AuthError {
133    fn from(reason: LogoutFailure) -> Self {
134        AuthError::LogoutToken(LogoutTokenError::new(reason))
135    }
136}
137
138/// What a verified logout token tells the relying party.
139#[derive(Clone, PartialEq)]
140pub struct LogoutToken {
141    pub issuer: String,
142    pub jti: String,
143    pub issued_at: f64,
144    pub expires_at: f64,
145    /// The subject whose sessions end (`None` when the token names only a session).
146    pub subject: Option<String>,
147    /// The session to end (`None` when the token names only a subject).
148    pub session_id: Option<String>,
149    /// Every claim of the token.
150    pub claims: Map<String, Value>,
151}
152
153impl fmt::Debug for LogoutToken {
154    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
155        f.debug_struct("LogoutToken")
156            .field("issuer", &self.issuer)
157            .field("jti", &self.jti)
158            .field("subject", &self.subject)
159            .field("session_id", &self.session_id)
160            .finish_non_exhaustive()
161    }
162}
163
164/// Whether a JOSE `typ` names a logout token: `logout+jwt` or `application/logout+jwt`, in any letter case, and with
165/// any parameters after a `;`.
166pub fn is_logout_typ(typ: Option<&str>) -> bool {
167    let Some(typ) = typ else { return false };
168    let normalised = typ
169        .split(';')
170        .next()
171        .unwrap_or("")
172        .trim()
173        .to_ascii_lowercase();
174    normalised == "logout+jwt" || normalised == "application/logout+jwt"
175}
176
177fn finite_number(value: Option<&Value>) -> Option<f64> {
178    let number = value?.as_f64()?;
179    number.is_finite().then_some(number)
180}
181
182fn non_blank_string(value: Option<&Value>) -> Option<&str> {
183    value?.as_str().filter(|s| non_blank(s))
184}
185
186/// The checks on a logout token whose signature and expiry already verified. `now` is unix seconds.
187pub fn check_logout_claims(
188    claims: &Map<String, Value>,
189    client_ids: &[String],
190    now: f64,
191    max_age_seconds: f64,
192    skew_seconds: f64,
193) -> Result<LogoutToken, LogoutTokenError> {
194    let fail = |reason| LogoutTokenError::new(reason);
195    let audiences: Vec<&str> = match claims.get("aud") {
196        Some(Value::String(one)) => vec![one.as_str()],
197        Some(Value::Array(many)) => many.iter().filter_map(Value::as_str).collect(),
198        _ => Vec::new(),
199    };
200    if !audiences.iter().any(|a| client_ids.iter().any(|c| c == a)) {
201        return Err(fail(LogoutFailure::Audience));
202    }
203    let (Some(iat), Some(exp)) = (
204        finite_number(claims.get("iat")),
205        finite_number(claims.get("exp")),
206    ) else {
207        return Err(fail(LogoutFailure::Claims));
208    };
209    let jti = match claims.get("jti").and_then(Value::as_str) {
210        Some(jti) if non_blank(jti) && jti.chars().count() <= 256 => jti,
211        _ => return Err(fail(LogoutFailure::Claims)),
212    };
213    let has_event = claims
214        .get("events")
215        .and_then(Value::as_object)
216        .is_some_and(|events| {
217            events
218                .get(BACKCHANNEL_LOGOUT_EVENT)
219                .is_some_and(Value::is_object)
220        });
221    if !has_event {
222        return Err(fail(LogoutFailure::Events));
223    }
224    if claims.contains_key("nonce") {
225        return Err(fail(LogoutFailure::Nonce));
226    }
227    let subject = non_blank_string(claims.get("sub")).map(str::to_string);
228    let session_id = non_blank_string(claims.get("sid")).map(str::to_string);
229    if subject.is_none() && session_id.is_none() {
230        return Err(fail(LogoutFailure::Subject));
231    }
232    if iat > now + LOGOUT_TOKEN_FUTURE_SECONDS + skew_seconds
233        || now - iat > max_age_seconds + skew_seconds
234    {
235        return Err(fail(LogoutFailure::Iat));
236    }
237    Ok(LogoutToken {
238        issuer: claims
239            .get("iss")
240            .and_then(Value::as_str)
241            .unwrap_or("")
242            .to_string(),
243        jti: jti.to_string(),
244        issued_at: iat,
245        expires_at: exp,
246        subject,
247        session_id,
248        claims: claims.clone(),
249    })
250}
251
252/// Schemes a post-logout redirect may never use.
253const REFUSED_SCHEMES: &[&str] = &["javascript", "data", "vbscript", "blob", "file", "about"];
254
255/// What to put on the logout URL.
256#[derive(Clone, Default)]
257pub struct EndSessionParams {
258    /// The discovered `end_session_endpoint`. It must be on the issuer's origin; defaults to
259    /// `<issuer>/oauth/end_session`.
260    pub end_session_endpoint: Option<String>,
261    /// The ID token the person signed in with.
262    pub id_token_hint: Option<String>,
263    /// Where to send the browser afterwards: needs `id_token_hint` (the service redirects only for a client it can
264    /// identify) and must be registered for that client.
265    pub post_logout_redirect_uri: Option<String>,
266    /// Echoed on the redirect: needs `post_logout_redirect_uri`.
267    pub state: Option<String>,
268}
269
270// `id_token_hint` is a whole ID token with personal data in it: say whether it is there, never what it is.
271impl fmt::Debug for EndSessionParams {
272    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
273        f.debug_struct("EndSessionParams")
274            .field("end_session_endpoint", &self.end_session_endpoint)
275            .field("id_token_hint", &self.id_token_hint.is_some())
276            .field("post_logout_redirect_uri", &self.post_logout_redirect_uri)
277            .field("state", &self.state)
278            .finish()
279    }
280}
281
282/// The URL to send the person's browser to in order to end their session at the service.
283pub fn build_end_session_url(
284    issuer_url: &str,
285    params: &EndSessionParams,
286) -> Result<String, AuthError> {
287    let issuer = issuer_url.trim_end_matches('/');
288    let endpoint_text = params
289        .end_session_endpoint
290        .clone()
291        .unwrap_or_else(|| format!("{issuer}/oauth/end_session"));
292    let same_origin = matches!(
293        (origin_of(&endpoint_text), origin_of(issuer)),
294        (Some(a), Some(b)) if a == b
295    );
296    if !same_origin {
297        return Err(AuthError::Config(
298            "The end session endpoint must be on the issuer's origin".into(),
299        ));
300    }
301    let endpoint = Url::parse(&endpoint_text)
302        .map_err(|_| AuthError::Config("The end session endpoint is not a safe URL".into()))?;
303    if !endpoint.username().is_empty()
304        || endpoint.password().is_some()
305        || endpoint.fragment().is_some()
306        || !matches!(endpoint.scheme(), "http" | "https")
307    {
308        return Err(AuthError::Config(
309            "The end session endpoint is not a safe URL".into(),
310        ));
311    }
312    let hint = params.id_token_hint.as_deref();
313    if hint.is_some_and(|h| !non_blank(h)) {
314        return Err(AuthError::Config("id_token_hint must not be blank".into()));
315    }
316    if let Some(redirect) = params.post_logout_redirect_uri.as_deref() {
317        if !hint.is_some_and(non_blank) {
318            return Err(AuthError::Config(
319                "post_logout_redirect_uri needs id_token_hint: the service redirects only for a client it can identify"
320                    .into(),
321            ));
322        }
323        let target = Url::parse(redirect).map_err(|_| {
324            AuthError::Config("post_logout_redirect_uri must be an absolute URI".into())
325        })?;
326        if REFUSED_SCHEMES.contains(&target.scheme()) || target.fragment().is_some() {
327            return Err(AuthError::Config(
328                "post_logout_redirect_uri must be a registered redirect URI without a fragment"
329                    .into(),
330            ));
331        }
332    }
333    if params.state.is_some() && params.post_logout_redirect_uri.is_none() {
334        return Err(AuthError::Config(
335            "state is echoed only on a redirect: it needs post_logout_redirect_uri".into(),
336        ));
337    }
338    let updates: Vec<(&str, &str)> = [
339        ("id_token_hint", hint),
340        (
341            "post_logout_redirect_uri",
342            params.post_logout_redirect_uri.as_deref(),
343        ),
344        ("state", params.state.as_deref()),
345    ]
346    .into_iter()
347    .filter_map(|(name, value)| Some((name, value?)))
348    .collect();
349    let mut query = endpoint.query().unwrap_or("").to_string();
350    if !updates.is_empty() {
351        let mut pairs: Vec<(String, String)> = endpoint
352            .query_pairs()
353            .map(|(k, v)| (k.into_owned(), v.into_owned()))
354            .collect();
355        for (name, value) in updates {
356            let mut kept: Vec<(String, String)> = Vec::new();
357            let mut placed = false;
358            for (existing_name, existing_value) in pairs {
359                if existing_name != name {
360                    kept.push((existing_name, existing_value));
361                } else if !placed {
362                    kept.push((name.to_string(), value.to_string()));
363                    placed = true;
364                }
365            }
366            if !placed {
367                kept.push((name.to_string(), value.to_string()));
368            }
369            pairs = kept;
370        }
371        query = pairs
372            .iter()
373            .map(|(k, v)| format!("{}={}", form_urlencode(k), form_urlencode(v)))
374            .collect::<Vec<_>>()
375            .join("&");
376    }
377    let mut url = format!(
378        "{}{}",
379        endpoint.origin().ascii_serialization(),
380        if endpoint.path().is_empty() {
381            "/"
382        } else {
383            endpoint.path()
384        }
385    );
386    if !query.is_empty() {
387        url.push('?');
388        url.push_str(&query);
389    }
390    Ok(url)
391}