1use 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";
21pub const DEFAULT_LOGOUT_TOKEN_MAX_AGE_SECONDS: u64 = 600;
24pub const LOGOUT_TOKEN_FUTURE_SECONDS: f64 = 60.0;
26
27#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
29pub enum LogoutFailure {
30 Typ,
32 Issuer,
34 Key,
36 Signature,
38 Expired,
39 Claims,
41 Audience,
43 Events,
45 Nonce,
47 Subject,
49 Iat,
51 Replay,
53}
54
55impl LogoutFailure {
56 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 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#[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 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#[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 pub subject: Option<String>,
147 pub session_id: Option<String>,
149 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
164pub 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
186pub 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
252const REFUSED_SCHEMES: &[&str] = &["javascript", "data", "vbscript", "blob", "file", "about"];
254
255#[derive(Clone, Default)]
257pub struct EndSessionParams {
258 pub end_session_endpoint: Option<String>,
261 pub id_token_hint: Option<String>,
263 pub post_logout_redirect_uri: Option<String>,
266 pub state: Option<String>,
268}
269
270impl 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
282pub 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}