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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
use super::utils::{redirect_to_dashboard, redirect_to_home};
use super::GoatState;
use crate::config::ConfigFile;
use crate::db::{DBEntity, User};
use crate::web::GoatStateTrait;
use crate::COOKIE_NAME;
use askama::Template;
use axum::extract::{Query, State};
use axum::response::{IntoResponse, Redirect, Response};
use axum::routing::{get, post};
use axum::{Form, Router};
use chrono::{DateTime, Utc};
use concread::cowcell::asynch::CowCellReadTxn;
use oauth2::{PkceCodeChallenge, PkceCodeVerifier, RedirectUrl};
use openidconnect::reqwest::async_http_client;
use openidconnect::EmptyAdditionalProviderMetadata;
use openidconnect::{
    core::*, ClaimsVerificationError, EmptyAdditionalClaims, IdTokenClaims, TokenResponse,
};
use openidconnect::{
    AuthenticationFlow, AuthorizationCode, CsrfToken, IssuerUrl, Nonce, ProviderMetadata, Scope,
};
use serde::Deserialize;
use tower_sessions::cookie::time::Duration;
use tower_sessions::{session_store::ExpiredDeletion, sqlx::SqlitePool, SqliteStore};

// pub(crate) mod sessionstore;
pub mod traits;
use tower_sessions::{Expiry, Session, SessionManagerLayer};
use tracing::error;
use traits::*;

#[derive(Deserialize)]
/// Parser for path bits
pub struct QueryForLogin {
    /// OAuth2 CSRF token
    pub state: Option<String>,
    /// OAuth2 code
    pub code: Option<String>,
    /// Where we'll redirect users to after successful login
    pub redirect: Option<String>,
}

/// Used in the parsing of the OIDC Provider metadata
pub type CustomProviderMetadata = ProviderMetadata<
    EmptyAdditionalProviderMetadata,
    CoreAuthDisplay,
    CoreClientAuthMethod,
    CoreClaimName,
    CoreClaimType,
    CoreGrantType,
    CoreJweContentEncryptionAlgorithm,
    CoreJweKeyManagementAlgorithm,
    CoreJwsSigningAlgorithm,
    CoreJsonWebKeyType,
    CoreJsonWebKeyUse,
    CoreJsonWebKey,
    CoreResponseMode,
    CoreResponseType,
    CoreSubjectIdentifierType,
>;
type CustomClaimType = IdTokenClaims<EmptyAdditionalClaims, CoreGenderClaim>;

#[derive(Template)]
#[template(path = "auth_login.html.j2")]
struct AuthLoginTemplate {
    errors: Vec<String>,
    redirect_url: String,
    pub user_is_admin: bool,
}

#[derive(Template)]
#[template(path = "auth_new_user.html")]
struct AuthNewUserTemplate {
    state: String,
    code: String,
    email: String,
    displayname: String,
    redirect_url: String,
    errors: Vec<String>,
    pub user_is_admin: bool,
}

#[derive(Template)]
#[template(path = "auth_logout.html")]
struct AuthLogoutTemplate {
    pub user_is_admin: bool,
}

#[derive(Template)]
#[template(path = "auth_provisioning_disabled.html")]
/// This renders a page telling the user that auto-provisioning is disabled and to tell the admin which username to add
struct AuthProvisioningDisabledTemplate {
    username: String,
    authref: String,

    admin_contact_name: String,
    admin_contact_url: String,
    pub user_is_admin: bool,
}

pub enum ParserError {
    Redirect { content: Redirect },
    ErrorMessage { content: &'static str },
    ClaimsVerificationError { content: ClaimsVerificationError },
}

/// Pull the OIDC Discovery details
pub async fn oauth_get_discover(state: &mut GoatState) -> Result<CustomProviderMetadata, String> {
    log::debug!("Getting discovery data");
    let issuer_url = IssuerUrl::new(state.read().await.config.oauth2_config_url.clone());
    match CoreProviderMetadata::discover_async(issuer_url.unwrap(), async_http_client).await {
        Err(e) => Err(format!("{e:?}")),
        Ok(val) => {
            state.oidc_update(val.clone()).await;
            Ok(val)
        }
    }
}

pub async fn oauth_start(state: &mut GoatState) -> Result<url::Url, String> {
    let last_updated: DateTime<Utc> = state.read().await.oidc_config_updated;
    let now: DateTime<Utc> = Utc::now();

    let delta = now - last_updated;
    let provider_metadata: CustomProviderMetadata = match delta.num_minutes() > 5 {
        true => oauth_get_discover(state).await.unwrap(),
        false => {
            log::debug!("using cached OIDC discovery data");
            let config = state.read().await.oidc_config.clone();
            let meta = config.unwrap_or(oauth_get_discover(state).await.unwrap());
            state.oidc_update(meta.clone()).await;
            meta
        }
    };
    log::trace!("provider metadata: {provider_metadata:?}");

    // Generate a PKCE challenge.
    let (pkce_challenge, pkce_verifier) = PkceCodeChallenge::new_random_sha256();
    let client = CoreClient::from_provider_metadata(
        provider_metadata,
        state.oauth2_client_id().await,
        state.oauth2_secret().await,
    )
    // This example will be running its own server at localhost:8080.
    // See below for the server implementation.
    .set_redirect_uri(RedirectUrl::from_url(
        state.read().await.config.oauth2_redirect_url.clone(),
    ));

    // Generate the authorization URL to which we'll redirect the user.
    let (authorize_url, csrf_state, nonce) = client
        .authorize_url(
            AuthenticationFlow::<CoreResponseType>::AuthorizationCode,
            CsrfToken::new_random,
            Nonce::new_random,
        )
        // This example is requesting access to the the user's profile including email.
        .add_scope(Scope::new("email".to_string()))
        .add_scope(Scope::new("profile".to_string()))
        .set_pkce_challenge(pkce_challenge)
        .url();
    state
        .push_verifier(
            csrf_state.secret().to_owned(),
            (pkce_verifier.secret().to_owned(), nonce),
        )
        .await;
    Ok(authorize_url)
}

pub async fn parse_state_code(
    shared_state: &GoatState,
    query_code: String,
    pkce_verifier: PkceCodeVerifier,
    nonce: Nonce,
) -> Result<CustomClaimType, ParserError> {
    let auth_code = AuthorizationCode::new(query_code);
    let reader = shared_state.read().await;
    let provider_metadata = match &reader.oidc_config {
        Some(value) => value,
        None => {
            return Err(ParserError::ErrorMessage {
                content: "Failed to pull provider metadata!",
            })
        }
    };

    let client = CoreClient::from_provider_metadata(
        provider_metadata.to_owned(),
        shared_state.oauth2_client_id().await,
        shared_state.oauth2_secret().await,
    )
    .set_redirect_uri(RedirectUrl::from_url(
        shared_state.read().await.config.oauth2_redirect_url.clone(),
    ));
    let verifier_copy = PkceCodeVerifier::new(pkce_verifier.secret().clone());
    assert_eq!(verifier_copy.secret(), pkce_verifier.secret());
    // Now you can exchange it for an access token and ID token.
    let token_response = client
        .exchange_code(auth_code)
        // Set the PKCE code verifier.
        .set_pkce_verifier(pkce_verifier)
        .request_async(async_http_client)
        .await
        .map_err(|e| format!("{e:?}"))
        .unwrap();

    // Extract the ID token claims after verifying its authenticity and nonce.
    let id_token = match token_response.id_token() {
        Some(token) => token,
        None => {
            return Err(ParserError::ErrorMessage {
                content: "couldn't parse token",
            })
        }
    };
    log::trace!("id_token: {id_token:?}");
    let allowed_algs = vec![
        CoreJwsSigningAlgorithm::EcdsaP256Sha256,
        CoreJwsSigningAlgorithm::RsaSsaPkcs1V15Sha256,
        CoreJwsSigningAlgorithm::RsaSsaPkcs1V15Sha384,
        CoreJwsSigningAlgorithm::RsaSsaPkcs1V15Sha512,
    ];
    let verifier = &client.id_token_verifier().set_allowed_algs(allowed_algs);
    // if verifier.is_none() {
    // return Err(ParserError::ErrorMessage{content: "Couldn't find a known session!"});
    // }
    id_token
        .claims(verifier, &nonce)
        .map_err(|e| ParserError::ClaimsVerificationError { content: e })
        .cloned()
}

// #[debug_handler]
pub async fn login(
    Query(query): Query<QueryForLogin>,
    session: Session,
    axum::extract::State(mut state): axum::extract::State<GoatState>,
) -> impl IntoResponse {
    // check if we've got an existing, valid session

    if let Some(signed_in) = session.get("signed_in").await.unwrap() {
        if signed_in {
            return Redirect::to("/ui").into_response();
        }
    }

    if query.state.is_none() || query.code.is_none() {
        let auth_url = &oauth_start(&mut state).await.unwrap().to_string();
        return Redirect::to(auth_url).into_response();
    }

    // if we get the state and code back then we can go back to the server for a token
    // ref <https://github.com/kanidm/kanidm/blob/master/kanidmd/testkit/tests/oauth2_test.rs#L276>

    let verifier = state.pop_verifier(query.state.clone().unwrap()).await;

    let (pkce_verifier_secret, nonce) = match verifier {
        Some((p, n)) => (p, n),
        None => {
            log::error!("Couldn't find a session, redirecting...");
            return Redirect::to("/auth/login").into_response();
        }
    };
    let verifier_copy = PkceCodeVerifier::new(pkce_verifier_secret.clone());

    let claims = parse_state_code(
        &state,
        query.code.clone().unwrap(),
        PkceCodeVerifier::new(pkce_verifier_secret),
        nonce.clone(),
    )
    .await;
    match claims {
        Ok(claims) => {
            // check if they're in the database

            let email = claims.get_email().unwrap();

            let dbuser = match User::get_by_subject(&state.connpool().await, claims.subject()).await
            {
                Ok(user) => user,
                Err(error) => {
                    match error {
                        sqlx::Error::RowNotFound => {
                            if !state.read().await.config.user_auto_provisioning {
                                // TODO: show a "sorry" page when auto-provisioning's not enabled
                                // log::warn!("User attempted login when auto-provisioning is not enabled, yeeting them to the home page.");
                                let (admin_contact_name, admin_contact_url) =
                                    state.read().await.config.admin_contact.to_html_parts();

                                let context = AuthProvisioningDisabledTemplate {
                                    username: claims.get_username(),
                                    authref: claims.subject().to_string(),
                                    admin_contact_name,
                                    admin_contact_url,
                                    user_is_admin: false, // TODO: ... probably not an admin but we can check
                                };
                                return Response::builder()
                                    .status(200)
                                    .body(context.render().unwrap())
                                    .unwrap()
                                    .into_response();
                            }

                            let new_user_page = AuthNewUserTemplate {
                                state: query.state.clone().unwrap(),
                                code: query.code.clone().unwrap(),
                                email,
                                displayname: claims.get_displayname(),
                                redirect_url: "".to_string(),
                                errors: vec![],
                                user_is_admin: false, // TODO: ... probably not an admin but we can check
                            };
                            let pagebody = new_user_page.render().unwrap();
                            // push it back into the stack for signup
                            state
                                .push_verifier(
                                    query.state.clone().unwrap(),
                                    (verifier_copy.secret().to_owned(), nonce),
                                )
                                .await;

                            return Response::builder()
                                .status(200)
                                .body(pagebody)
                                .unwrap()
                                .into_response();
                        }
                        _ => {
                            log::error!(
                                "Database error finding user {:?}: {error:?}",
                                email.clone()
                            );
                            let redirect: Option<String> = session.get("redirect").await.unwrap();
                            return match redirect {
                                Some(destination) => {
                                    session.remove_value("redirect").await.map_err(
                                        |err| {
                                            error!("Failed to flush session: {err:?}");
                                            (
                                                axum::http::StatusCode::INTERNAL_SERVER_ERROR,
                                                "Failed to remove redirect value from session store!"
                                            )
                                        },
                                    ).unwrap();
                                    Redirect::to(&destination).into_response()
                                }
                                None => redirect_to_home().into_response(),
                            };
                        }
                    }
                }
            };
            log::debug!("Found user in database: {dbuser:?}");

            if dbuser.disabled {
                session
                    .flush()
                    .await
                    .map_err(|err| {
                        error!("Failed to flush session: {err:?}");
                        (
                            axum::http::StatusCode::INTERNAL_SERVER_ERROR,
                            "Failed to flush session store!",
                        )
                    })
                    .unwrap();
                log::info!("Disabled user attempted to log in: {dbuser:?}");
                return redirect_to_home().into_response();
            }

            session
                .insert("authref", claims.subject().to_string())
                .await
                .unwrap();
            session.insert("user", dbuser).await.unwrap();
            session.insert("signed_in", true).await.unwrap();

            redirect_to_dashboard().into_response()
        }
        Err(error) => match error {
            ParserError::Redirect { content } => content.into_response(),
            ParserError::ErrorMessage { content } => {
                log::debug!("Failed to parse state: {content}");
                todo!();
            }
            ParserError::ClaimsVerificationError { content } => {
                log::error!("Failed to verify claim token: {content:?}");
                redirect_to_home().into_response()
            }
        },
    }
}

pub async fn logout(session: Session) -> impl IntoResponse {
    session
        .flush()
        .await
        .map_err(|err| {
            error!("Failed to flush session: {err:?}");
            (
                axum::http::StatusCode::INTERNAL_SERVER_ERROR,
                "Failed to flush session store!",
            )
        })
        .unwrap();
    Redirect::to("/")
}

pub async fn build_auth_stores(
    config: CowCellReadTxn<ConfigFile>,
    connpool: SqlitePool,
) -> SessionManagerLayer<SqliteStore> {
    let session_store = SqliteStore::new(connpool)
        .with_table_name("sessions")
        .expect("Failed to start session store!");

    session_store
        .migrate()
        .await
        .expect("Could not migrate session store database on startup!");

    let _deletion_task = tokio::task::spawn(
        session_store
            .clone()
            .continuously_delete_expired(tokio::time::Duration::from_secs(60)),
    );

    SessionManagerLayer::new(session_store)
        .with_expiry(Expiry::OnInactivity(Duration::minutes(5)))
        .with_name(COOKIE_NAME)
        .with_secure(true)
        // If the cookies start being weird it's because they were appending a "." on the start...
        .with_domain(config.hostname.clone())
}

#[derive(Deserialize, Debug)]
/// This handles the POST from "would you like to create your user"
pub struct SignupForm {
    pub state: String,
    pub code: String,
}

/// /auth/signup
pub async fn signup(
    State(mut state): State<GoatState>,
    Form(form): Form<SignupForm>,
) -> Result<Response, ()> {
    log::debug!("Dumping form: {form:?}");

    let query_state = form.state;

    let verifier = state.pop_verifier(query_state).await;

    let (pkce_verifier, nonce) = match verifier {
        Some((p, n)) => (p, n),
        None => {
            log::error!("Couldn't find a signup session, redirecting user...");
            return Ok(Redirect::to("/auth/login").into_response());
        }
    };
    let claims = parse_state_code(
        &state,
        form.code,
        PkceCodeVerifier::new(pkce_verifier),
        nonce.clone(),
    )
    .await;
    match claims {
        Err(error) => match error {
            ParserError::Redirect { content } => Ok(content.into_response()),
            ParserError::ErrorMessage { content } => {
                log::debug!("{content}");
                todo!();
            }
            ParserError::ClaimsVerificationError { content } => {
                log::error!("Failed to verify claim token: {content:?}");
                Ok(redirect_to_home().into_response())
            }
        },
        Ok(claims) => {
            log::debug!("Verified claims in signup form: {claims:?}");
            let email = claims.get_email().unwrap();
            let user = User {
                id: None,
                displayname: claims.get_displayname(),
                username: claims.get_username(),
                email,
                disabled: false,
                authref: Some(claims.subject().to_string()),
                admin: false,
            };
            match user.save(&state.connpool().await).await {
                Ok(_) => Ok(redirect_to_dashboard().into_response()),
                Err(error) => {
                    log::debug!("Failed to save new user signup... oh no! {error:?}");
                    // TODO: throw an error page on this one
                    Ok(redirect_to_home().into_response())
                }
            }
        }
    }
}

pub fn new() -> Router<GoatState> {
    Router::new()
        .route("/login", get(login))
        .route("/logout", get(logout))
        .route("/signup", post(signup))
}