kanidmd_core/https/views/
oauth2.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
use crate::https::{
    extractors::{DomainInfo, DomainInfoRead, VerifiedClientInformation},
    middleware::KOpId,
    ServerState,
};
use kanidmd_lib::idm::oauth2::{
    AuthorisationRequest, AuthorisePermitSuccess, AuthoriseResponse, Oauth2Error,
};
use kanidmd_lib::prelude::*;

use kanidm_proto::internal::COOKIE_OAUTH2_REQ;

use std::collections::BTreeSet;

use askama::Template;

#[cfg(feature = "dev-oauth2-device-flow")]
use axum::http::StatusCode;
use axum::{
    extract::{Query, State},
    http::header::ACCESS_CONTROL_ALLOW_ORIGIN,
    response::{IntoResponse, Redirect, Response},
    Extension, Form,
};
use axum_extra::extract::cookie::{CookieJar, SameSite};
use axum_htmx::HX_REDIRECT;
use serde::Deserialize;

use super::login::{LoginDisplayCtx, Oauth2Ctx};
use super::{cookies, UnrecoverableErrorView};

#[derive(Template)]
#[template(path = "oauth2_consent_request.html")]
struct ConsentRequestView {
    client_name: String,
    // scopes: BTreeSet<String>,
    pii_scopes: BTreeSet<String>,
    consent_token: String,
    redirect: Option<String>,
}

#[derive(Template)]
#[template(path = "oauth2_access_denied.html")]
struct AccessDeniedView {
    operation_id: Uuid,
}

pub async fn view_index_get(
    State(state): State<ServerState>,
    Extension(kopid): Extension<KOpId>,
    VerifiedClientInformation(client_auth_info): VerifiedClientInformation,
    DomainInfo(domain_info): DomainInfo,
    jar: CookieJar,
    Query(auth_req): Query<AuthorisationRequest>,
) -> Response {
    oauth2_auth_req(
        state,
        kopid,
        client_auth_info,
        domain_info,
        jar,
        Some(auth_req),
    )
    .await
}

pub async fn view_resume_get(
    State(state): State<ServerState>,
    Extension(kopid): Extension<KOpId>,
    VerifiedClientInformation(client_auth_info): VerifiedClientInformation,
    DomainInfo(domain_info): DomainInfo,
    jar: CookieJar,
) -> Response {
    let maybe_auth_req =
        cookies::get_signed::<AuthorisationRequest>(&state, &jar, COOKIE_OAUTH2_REQ);

    oauth2_auth_req(
        state,
        kopid,
        client_auth_info,
        domain_info,
        jar,
        maybe_auth_req,
    )
    .await
}

async fn oauth2_auth_req(
    state: ServerState,
    kopid: KOpId,
    client_auth_info: ClientAuthInfo,
    domain_info: DomainInfoRead,
    jar: CookieJar,
    maybe_auth_req: Option<AuthorisationRequest>,
) -> Response {
    // No matter what, we always clear the stored oauth2 cookie to prevent
    // ui loops
    let jar = cookies::destroy(jar, COOKIE_OAUTH2_REQ, &state);

    // If the auth_req was cross-signed, old, or just bad, error. But we have *cleared* it
    // from the cookie which means we won't see it again.
    let Some(auth_req) = maybe_auth_req else {
        error!("unable to resume session, no valid auth_req was found in the cookie. This cookie has been removed.");
        return (
            jar,
            UnrecoverableErrorView {
                err_code: OperationError::UI0003InvalidOauth2Resume,
                operation_id: kopid.eventid,
            },
        )
            .into_response();
    };

    let res: Result<AuthoriseResponse, Oauth2Error> = state
        .qe_r_ref
        .handle_oauth2_authorise(client_auth_info, auth_req.clone(), kopid.eventid)
        .await;

    match res {
        Ok(AuthoriseResponse::Permitted(AuthorisePermitSuccess {
            mut redirect_uri,
            state,
            code,
        })) => {
            redirect_uri
                .query_pairs_mut()
                .clear()
                .append_pair("state", &state)
                .append_pair("code", &code);

            (
                jar,
                [
                    (HX_REDIRECT, redirect_uri.as_str().to_string()),
                    (
                        ACCESS_CONTROL_ALLOW_ORIGIN.as_str(),
                        redirect_uri.origin().ascii_serialization(),
                    ),
                ],
                Redirect::to(redirect_uri.as_str()),
            )
                .into_response()
        }
        Ok(AuthoriseResponse::ConsentRequested {
            client_name,
            scopes: _,
            pii_scopes,
            consent_token,
        }) => {
            // We can just render the form now, the consent token has everything we need.
            (
                jar,
                ConsentRequestView {
                    client_name,
                    // scopes,
                    pii_scopes,
                    consent_token,
                    redirect: None,
                },
            )
                .into_response()
        }

        Ok(AuthoriseResponse::AuthenticationRequired {
            client_name,
            login_hint,
        }) => {
            // Sign the auth req and hide it in our cookie - we'll come back for
            // you later.
            let maybe_jar = cookies::make_signed(&state, COOKIE_OAUTH2_REQ, &auth_req)
                .map(|mut cookie| {
                    cookie.set_same_site(SameSite::Strict);
                    // Expire at the end of the session.
                    cookie.set_expires(None);
                    // Could experiment with this to a shorter value, but session should be enough.
                    cookie.set_max_age(time::Duration::minutes(15));
                    jar.clone().add(cookie)
                })
                .ok_or(OperationError::InvalidSessionState);

            match maybe_jar {
                Ok(new_jar) => {
                    let display_ctx = LoginDisplayCtx {
                        domain_info,
                        oauth2: Some(Oauth2Ctx { client_name }),
                        reauth: None,
                        error: None,
                    };

                    super::login::view_oauth2_get(new_jar, display_ctx, login_hint)
                }
                Err(err_code) => (
                    jar,
                    UnrecoverableErrorView {
                        err_code,
                        operation_id: kopid.eventid,
                    },
                )
                    .into_response(),
            }
        }
        Err(Oauth2Error::AccessDenied) => {
            // If scopes are not available for this account.
            (
                jar,
                AccessDeniedView {
                    operation_id: kopid.eventid,
                },
            )
                .into_response()
        }
        /*
        RFC - If the request fails due to a missing, invalid, or mismatching
              redirection URI, or if the client identifier is missing or invalid,
              the authorization server SHOULD inform the resource owner of the
              error and MUST NOT automatically redirect the user-agent to the
              invalid redirection URI.
        */
        // To further this, it appears that a malicious client configuration can set a phishing
        // site as the redirect URL, and then use that to trigger certain types of attacks. Instead
        // we do NOT redirect in an error condition, and just render the error ourselves.
        Err(err_code) => {
            error!(
                "Unable to authorise - Error ID: {:?} error: {}",
                kopid.eventid,
                &err_code.to_string()
            );

            (
                jar,
                UnrecoverableErrorView {
                    err_code: OperationError::InvalidState,
                    operation_id: kopid.eventid,
                },
            )
                .into_response()
        }
    }
}

#[derive(Debug, Clone, Deserialize)]
pub struct ConsentForm {
    consent_token: String,
    #[serde(default)]
    #[allow(dead_code)] // TODO: do smoething with this
    redirect: Option<String>,
}

pub async fn view_consent_post(
    State(server_state): State<ServerState>,
    Extension(kopid): Extension<KOpId>,
    VerifiedClientInformation(client_auth_info): VerifiedClientInformation,
    jar: CookieJar,
    Form(consent_form): Form<ConsentForm>,
) -> Result<Response, UnrecoverableErrorView> {
    let res = server_state
        .qe_w_ref
        .handle_oauth2_authorise_permit(client_auth_info, consent_form.consent_token, kopid.eventid)
        .await;

    match res {
        Ok(AuthorisePermitSuccess {
            mut redirect_uri,
            state,
            code,
        }) => {
            let jar = cookies::destroy(jar, COOKIE_OAUTH2_REQ, &server_state);

            if let Some(redirect) = consent_form.redirect {
                Ok((
                    jar,
                    [
                        (HX_REDIRECT, redirect_uri.as_str().to_string()),
                        (
                            ACCESS_CONTROL_ALLOW_ORIGIN.as_str(),
                            redirect_uri.origin().ascii_serialization(),
                        ),
                    ],
                    Redirect::to(&redirect),
                )
                    .into_response())
            } else {
                redirect_uri
                    .query_pairs_mut()
                    .clear()
                    .append_pair("state", &state)
                    .append_pair("code", &code);
                Ok((
                    jar,
                    [
                        (HX_REDIRECT, redirect_uri.as_str().to_string()),
                        (
                            ACCESS_CONTROL_ALLOW_ORIGIN.as_str(),
                            redirect_uri.origin().ascii_serialization(),
                        ),
                    ],
                    Redirect::to(redirect_uri.as_str()),
                )
                    .into_response())
            }
        }
        Err(err_code) => {
            error!(
                "Unable to authorise - Error ID: {:?} error: {}",
                kopid.eventid,
                &err_code.to_string()
            );

            Err(UnrecoverableErrorView {
                err_code: OperationError::InvalidState,
                operation_id: kopid.eventid,
            })
        }
    }
}

#[derive(Template, Debug, Clone)]
#[cfg(feature = "dev-oauth2-device-flow")]
#[template(path = "oauth2_device_login.html")]
pub struct Oauth2DeviceLoginView {
    domain_custom_image: bool,
    title: String,
    user_code: String,
}

#[derive(Debug, Clone, Deserialize)]
#[cfg(feature = "dev-oauth2-device-flow")]
pub(crate) struct QueryUserCode {
    pub user_code: Option<String>,
}

#[axum::debug_handler]
#[cfg(feature = "dev-oauth2-device-flow")]
pub async fn view_device_get(
    State(state): State<ServerState>,
    Extension(_kopid): Extension<KOpId>,
    VerifiedClientInformation(_client_auth_info): VerifiedClientInformation,
    Query(user_code): Query<QueryUserCode>,
) -> Result<Oauth2DeviceLoginView, (StatusCode, String)> {
    // TODO: if we have a valid auth session and the user code is valid, prompt the user to allow the session to start
    Ok(Oauth2DeviceLoginView {
        domain_custom_image: state.qe_r_ref.domain_info_read().has_custom_image(),
        title: "Device Login".to_string(),
        user_code: user_code.user_code.unwrap_or("".to_string()),
    })
}

#[derive(Deserialize)]
#[cfg(feature = "dev-oauth2-device-flow")]
pub struct Oauth2DeviceLoginForm {
    user_code: String,
    confirm_login: bool,
}

#[cfg(feature = "dev-oauth2-device-flow")]
#[axum::debug_handler]
pub async fn view_device_post(
    State(_state): State<ServerState>,
    Extension(_kopid): Extension<KOpId>,
    VerifiedClientInformation(_client_auth_info): VerifiedClientInformation,
    Form(form): Form<Oauth2DeviceLoginForm>,
) -> Result<String, (StatusCode, &'static str)> {
    debug!("User code: {}", form.user_code);
    debug!("User confirmed: {}", form.confirm_login);

    // TODO: when the user POST's this form we need to check the user code and see if it's valid
    // then start a login flow which ends up authorizing the token at the end.
    Err((StatusCode::NOT_IMPLEMENTED, "Not implemented yet"))
}