1- //! RP-initiated logout: the request, sent on to the logout page to confirm, and the
2- //! end of the session once confirmed .
1+ //! RP-initiated logout: the request, validated when the logout page asks to confirm
2+ //! it and again when its form confirms it, and the end of the sessions it names .
33
44use super :: { Claim , MAX_STATE_BYTES , OAuthCode , OAuthError , OidcApplication , Reject } ;
5- use crate :: { account:: AccountService , routes, security:: RequestContext , sessions:: SignedOut } ;
6- use axum:: {
7- Form ,
8- extract:: { State , rejection:: FormRejection } ,
9- http:: HeaderMap ,
10- response:: Redirect ,
5+ use crate :: {
6+ account:: AccountService ,
7+ routes,
8+ security:: { RequestContext , Session } ,
9+ sessions:: SignedOut ,
1110} ;
11+ use axum:: http:: HeaderMap ;
1212use serde:: { Deserialize , Deserializer } ;
1313use serde_json:: Value ;
14- use sourceorigin_common:: { ClientId , events:: RevocationReason } ;
14+ use sourceorigin_common:: { ClientId , SessionId , UserId , events:: RevocationReason } ;
15+ use sourceorigin_repository:: SessionScope ;
1516use sourceorigin_ui:: LoginQuery ;
1617use url:: Url ;
1718
18- /// RP-initiated logout parameters bound to a registered destination and optional ID
19- /// hint. A parameter sent empty is kept, as sent, whichever decoder reads it, so it
20- /// means the same at the endpoint and on the logout page: an included `state` goes
21- /// back to the client even when empty (RP-Initiated Logout §2), and Topcoat's own
22- /// decoder would read an empty value as absent.
19+ /// RP-initiated logout parameters, by `GET` query or form `POST`, which the logout
20+ /// page's form posts back as hidden fields. None at all is the user signing out of
21+ /// auth itself, from the settings or the admin dashboard. A parameter sent empty is
22+ /// kept as sent, whichever decoder reads it: an included `state` goes back to the
23+ /// client even when empty (RP-Initiated Logout §2), and Topcoat's own decoder would
24+ /// read an empty value as absent.
2325#[ derive( Deserialize ) ]
2426pub ( crate ) struct LogoutQuery {
2527 /// Registered relying-party identifier.
@@ -34,6 +36,11 @@ pub(crate) struct LogoutQuery {
3436 /// Opaque client correlation value returned unchanged.
3537 #[ serde( default , deserialize_with = "LogoutQuery::parameter" ) ]
3638 state : Option < String > ,
39+ /// Set by the logout page's own form once it warned that the hint names
40+ /// another account than the browser's. Only auth's pages may post to
41+ /// `/logout`, so an application can't skip the warning.
42+ #[ serde( default , deserialize_with = "LogoutQuery::parameter" ) ]
43+ warned : Option < String > ,
3744}
3845
3946impl LogoutQuery {
@@ -43,8 +50,13 @@ impl LogoutQuery {
4350 String :: deserialize ( deserializer) . map ( Some )
4451 }
4552
46- /// The parameters that are present, by name, in the order the logout page
47- /// sends them on.
53+ /// Whether the logout page already warned that the hint names another account.
54+ pub ( crate ) const fn warned ( & self ) -> bool {
55+ self . warned . is_some ( )
56+ }
57+
58+ /// The application's parameters that are present, by name, which the logout
59+ /// page's form posts back.
4860 pub ( crate ) fn fields ( & self ) -> impl Iterator < Item = ( & ' static str , & str ) > {
4961 [
5062 ( "client_id" , & self . client_id ) ,
@@ -55,72 +67,130 @@ impl LogoutQuery {
5567 . into_iter ( )
5668 . filter_map ( |( name, value) | Some ( ( name, value. as_deref ( ) ?) ) )
5769 }
70+ }
5871
59- /// Unwraps the extracted parameters, describing why they could not be read.
60- fn parse ( form : Result < Form < Self > , FormRejection > ) -> Result < Self , OAuthError > {
61- form. map ( |Form ( q) | q) . map_err ( |error| {
62- OAuthCode :: InvalidRequest
63- . reject_with ( format ! ( "logout request is malformed: {error}" ) , error)
72+ /// What a verified `id_token_hint` says: the client auth issued it to, and the
73+ /// account and session it names.
74+ struct Hint {
75+ /// The token's audience.
76+ client : ClientId ,
77+ /// The token's `sub`.
78+ user : Option < UserId > ,
79+ /// The token's `sid`.
80+ session : Option < SessionId > ,
81+ }
82+
83+ impl Hint {
84+ /// Reads the claims of an ID token auth signed. Auth signed it, so its audience
85+ /// is a client ID it issued to.
86+ fn read ( claims : & Value ) -> Result < Self , OAuthError > {
87+ let text = |claim : Claim | claims. get ( claim. as_str ( ) ) . and_then ( Value :: as_str) ;
88+ let client = text ( Claim :: Audience )
89+ . unwrap_or_default ( )
90+ . parse ( )
91+ . map_err ( |error| {
92+ OAuthCode :: InvalidRequest
93+ . reject_with ( "id_token_hint audience is not a client ID" , error)
94+ } ) ?;
95+ Ok ( Self {
96+ client,
97+ user : text ( Claim :: Subject ) . and_then ( |sub| sub. parse ( ) . ok ( ) ) ,
98+ session : text ( Claim :: Session ) . and_then ( |sid| sid. parse ( ) . ok ( ) ) ,
6499 } )
65100 }
66101}
67102
103+ /// A validated logout request: who asked, what its hint names, and where the
104+ /// browser goes once signed out.
105+ struct LogoutRequest {
106+ /// The application that asked, when a verified hint or a registered
107+ /// post-logout URI names it.
108+ client : Option < ClientId > ,
109+ /// The verified hint, kept only when it was issued to `client`.
110+ hint : Option < Hint > ,
111+ /// Whether a hint was sent that auth could not verify, and was ignored.
112+ unverified : bool ,
113+ /// Where the browser goes once signed out.
114+ destination : Url ,
115+ }
116+
117+ /// A logout request, as the logout page asking to confirm it shows it.
118+ pub ( crate ) struct LogoutView {
119+ /// Whether the application's `id_token_hint` could not be verified, so it was
120+ /// ignored and the browser stays on auth afterwards.
121+ pub ( crate ) unverified : bool ,
122+ /// Whether the hint names another account than the one signed in to this
123+ /// browser.
124+ pub ( crate ) another_account : bool ,
125+ /// Where the browser goes once signed out.
126+ pub ( crate ) destination : Url ,
127+ }
128+
68129impl OidcApplication {
69- /// Validates the client, hint and exact registered post-logout redirect. Returns
70- /// the destination, and the client that asked for the logout when a verified
71- /// `id_token_hint` or a registered `post_logout_redirect_uri` names it.
72- pub ( crate ) async fn logout_destination (
73- & self ,
74- q : & LogoutQuery ,
75- ) -> Result < ( Url , Option < ClientId > ) , OAuthError > {
130+ /// Validates an RP-initiated logout request. An `id_token_hint` auth can't
131+ /// verify, signed by a retired key or forged, is ignored: the logout goes on,
132+ /// attributed to no client and back to auth's sign-in page. An unregistered
133+ /// `post_logout_redirect_uri`, or one naming no client, is refused.
134+ async fn validate_logout ( & self , q : & LogoutQuery ) -> Result < LogoutRequest , OAuthError > {
76135 if q. state . as_ref ( ) . is_some_and ( |s| s. len ( ) > MAX_STATE_BYTES ) {
77136 return Err ( OAuthCode :: InvalidRequest
78137 . reject ( format ! ( "state must be at most {MAX_STATE_BYTES} bytes" ) ) ) ;
79138 }
80- let hint = q
139+ let keys = self . keys . current ( ) ?;
140+ let verified = q
81141 . id_token_hint
82142 . as_ref ( )
83- . map ( |token| {
84- self . keys
85- . current ( ) ?
86- . verify_id_token_hint ( token, & self . issuer )
87- . map_err ( |error| {
88- OAuthCode :: InvalidRequest
89- . reject_with ( format ! ( "id_token_hint is invalid: {error}" ) , error)
90- } )
91- } )
143+ . map ( |token| keys. verify_id_token_hint ( token, & self . issuer ) ) ;
144+ let unverified = verified. as_ref ( ) . is_some_and ( Result :: is_err) ;
145+ let hint = verified
146+ . and_then ( Result :: ok)
147+ . map ( |claims| Hint :: read ( & claims) )
92148 . transpose ( ) ?;
93- // Auth signed the hint, so its audience is a client ID it issued to.
94- let hinted_client = hint
95- . as_ref ( )
96- . and_then ( |c| c. get ( Claim :: Audience . as_str ( ) ) )
97- . and_then ( Value :: as_str)
98- . map ( str:: parse :: < ClientId > )
99- . transpose ( )
100- . map_err ( |error| {
101- OAuthCode :: InvalidRequest
102- . reject_with ( "id_token_hint audience is not a client ID" , error)
103- } ) ?;
104- if q. client_id
105- . as_deref ( )
106- . zip ( hinted_client. as_ref ( ) )
107- . is_some_and ( |( a, b) | a != b. as_str ( ) )
149+ if let ( Some ( client_id) , Some ( hint) ) = ( q. client_id . as_deref ( ) , & hint)
150+ && client_id != hint. client . as_str ( )
108151 {
109152 return Err ( OAuthCode :: InvalidRequest
110153 . reject ( "client_id does not match the id_token_hint audience" ) ) ;
111154 }
112- let Some ( uri) = q. post_logout_redirect_uri . as_ref ( ) else {
113- let login = self . page ( routes:: page:: LOGIN , & LoginQuery :: default ( ) ) ?;
114- return Ok ( ( login, hinted_client) ) ;
155+ let ( destination, client) = match & q. post_logout_redirect_uri {
156+ // The application asked to come back, but auth can't tell it sent the
157+ // request: the browser stays on auth.
158+ Some ( _) if unverified => ( self . signed_out_page ( ) ?, None ) ,
159+ Some ( uri) => {
160+ let named = q
161+ . client_id
162+ . as_deref ( )
163+ . or ( hint. as_ref ( ) . map ( |hint| hint. client . as_str ( ) ) ) ;
164+ let ( url, client) = self . post_logout ( uri, named, q. state . as_deref ( ) ) . await ?;
165+ ( url, Some ( client) )
166+ }
167+ None => (
168+ self . signed_out_page ( ) ?,
169+ hint. as_ref ( ) . map ( |hint| hint. client . clone ( ) ) ,
170+ ) ,
115171 } ;
116- let id = q
117- . client_id
118- . as_deref ( )
119- . or ( hinted_client. as_ref ( ) . map ( ClientId :: as_str) )
120- . ok_or_else ( || {
121- OAuthCode :: InvalidRequest
122- . reject ( "post_logout_redirect_uri needs client_id or id_token_hint" )
123- } ) ?;
172+ Ok ( LogoutRequest {
173+ // A hint names the account and session only for the client it was
174+ // issued to.
175+ hint : hint. filter ( |hint| client. as_ref ( ) == Some ( & hint. client ) ) ,
176+ client,
177+ unverified,
178+ destination,
179+ } )
180+ }
181+
182+ /// The registered post-logout `uri` of the client `named`, with `state`, and
183+ /// that client.
184+ async fn post_logout (
185+ & self ,
186+ uri : & str ,
187+ named : Option < & str > ,
188+ state : Option < & str > ,
189+ ) -> Result < ( Url , ClientId ) , OAuthError > {
190+ let id = named. ok_or_else ( || {
191+ OAuthCode :: InvalidRequest
192+ . reject ( "post_logout_redirect_uri needs client_id or id_token_hint" )
193+ } ) ?;
124194 let client = self
125195 . database
126196 . oidc ( )
@@ -130,7 +200,11 @@ impl OidcApplication {
130200 . ok_or_else ( || {
131201 OAuthCode :: InvalidRequest . reject ( "client_id is not a registered, enabled client" )
132202 } ) ?;
133- if !client. post_logout_uris . contains ( uri) {
203+ if !client
204+ . post_logout_uris
205+ . iter ( )
206+ . any ( |registered| registered == uri)
207+ {
134208 return Err ( OAuthCode :: InvalidRequest . reject (
135209 "post_logout_redirect_uri is not registered for this client; it must match exactly" ,
136210 ) ) ;
@@ -139,45 +213,79 @@ impl OidcApplication {
139213 OAuthCode :: InvalidRequest
140214 . reject_with ( "post_logout_redirect_uri is not a valid URL" , error)
141215 } ) ?;
142- if let Some ( state) = & q . state {
216+ if let Some ( state) = state {
143217 url. query_pairs_mut ( ) . append_pair ( "state" , state) ;
144218 }
145- Ok ( ( url, Some ( client. id ) ) )
219+ Ok ( ( url, client. id ) )
146220 }
147221
148- /// Validates RP logout parameters, by GET query or form POST, before sending the
149- /// browser to confirm on the logout page. `Form` reads the query string of GET
150- /// requests.
151- pub ( super ) async fn start_logout (
152- State ( app) : State < Self > ,
153- form : Result < Form < LogoutQuery > , FormRejection > ,
154- ) -> Result < Redirect , OAuthError > {
155- app. confirm_logout ( & LogoutQuery :: parse ( form) ?) . await
222+ /// Auth's sign-in page, where a logout that goes back to no application ends.
223+ fn signed_out_page ( & self ) -> Result < Url , OAuthError > {
224+ self . page ( routes:: page:: LOGIN , & LoginQuery :: default ( ) )
156225 }
157226
158- /// Sends the browser to the logout confirmation page with the validated parameters.
159- async fn confirm_logout ( & self , q : & LogoutQuery ) -> Result < Redirect , OAuthError > {
160- self . logout_destination ( q) . await ?;
161- let mut url = Url :: parse ( & format ! ( "{}{}" , self . issuer, routes:: page:: LOGOUT ) ) ?;
162- url. query_pairs_mut ( ) . extend_pairs ( q. fields ( ) ) ;
163- Ok ( Redirect :: to ( url. as_str ( ) ) )
227+ /// The logout request `q`, validated, as the logout page shows it to the
228+ /// browser whose request `headers` are.
229+ pub ( crate ) async fn logout_request (
230+ & self ,
231+ headers : & HeaderMap ,
232+ q : & LogoutQuery ,
233+ ) -> Result < LogoutView , OAuthError > {
234+ let request = self . validate_logout ( q) . await ?;
235+ let hinted = request. hint . as_ref ( ) . and_then ( |hint| hint. user ) ;
236+ let signed_in = match hinted {
237+ Some ( _) => Session :: optional ( & self . database , headers) . await ?,
238+ None => None ,
239+ } ;
240+ Ok ( LogoutView {
241+ unverified : request. unverified ,
242+ another_account : hinted
243+ . zip ( signed_in)
244+ . is_some_and ( |( hinted, session) | hinted != session. user_id ) ,
245+ destination : request. destination ,
246+ } )
164247 }
165248
166- /// Ends the browser's session, once the logout page confirmed `q`, and returns
167- /// where the browser goes next, with the sign-out its response applies.
249+ /// Ends the browser's session, once the logout page's form confirmed `q`,
250+ /// validated again, and the session the application's hint names, which may
251+ /// be its own inline sign-in, with no cookie in this browser: only if it is the
252+ /// hinted account's. Answers where the browser goes next, with the sign-out its
253+ /// response applies.
168254 pub ( crate ) async fn end_session (
169255 & self ,
170256 context : RequestContext ,
171257 headers : & HeaderMap ,
172258 q : & LogoutQuery ,
173259 ) -> Result < ( Url , SignedOut ) , OAuthError > {
174- let ( destination, client) = self . logout_destination ( q) . await ?;
175- let reason = client. map_or ( RevocationReason :: Logout , |client_id| {
176- RevocationReason :: RelyingPartyLogout { client_id }
177- } ) ;
260+ let request = self . validate_logout ( q) . await ?;
261+ let reason = request
262+ . client
263+ . clone ( )
264+ . map_or ( RevocationReason :: Logout , |client_id| {
265+ RevocationReason :: RelyingPartyLogout { client_id }
266+ } ) ;
178267 let signed_out = AccountService :: new ( self . database . clone ( ) )
179- . sign_out ( context, headers, reason)
268+ . sign_out ( context, headers, reason. clone ( ) )
180269 . await ?;
181- Ok ( ( destination, signed_out) )
270+ if let (
271+ Some ( client) ,
272+ Some ( Hint {
273+ user : Some ( user) ,
274+ session : Some ( session) ,
275+ ..
276+ } ) ,
277+ ) = ( & request. client , & request. hint )
278+ {
279+ let mut tx = self . database . begin ( ) . await ?;
280+ tx. revoke_sessions (
281+ & context. client ( client) ,
282+ * user,
283+ SessionScope :: One ( * session) ,
284+ & reason,
285+ )
286+ . await ?;
287+ tx. commit ( ) . await ?;
288+ }
289+ Ok ( ( request. destination , signed_out) )
182290 }
183291}
0 commit comments