summaryrefslogtreecommitdiff
path: root/server/src/auth.rs
blob: 01ee46746a1c88f2bc0948ed9987b153fd88827f (plain)
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
use std::{
    collections::HashMap,
    env,
    num::NonZeroUsize,
    sync::{Arc, Mutex},
};

use crate::error::BridgeError;
use chrono::Utc;
use lru::LruCache;
use openidconnect::{
    core::{CoreClient, CoreProviderMetadata, CoreResponseType},
    reqwest::async_http_client,
    url::Url,
    AccessTokenHash, AuthenticationFlow, AuthorizationCode, ClientId, ClientSecret, CsrfToken,
    IssuerUrl, Nonce, OAuth2TokenResponse, PkceCodeChallenge, RedirectUrl, Scope, TokenResponse,
};
use serde::{Deserialize, Serialize};
use tracing::info;
use uuid::Uuid;

pub struct LoginState {
    csrf_token: CsrfToken,
    nonce: Nonce,
}

pub struct Authenticator {
    pub client: CoreClient,
    pub login_cache: Arc<Mutex<LruCache<EndUserId, LoginState>>>,
}

#[derive(Eq, PartialEq, Hash, Debug, Clone, Serialize, Deserialize)]
pub struct EndUserId(Uuid);

impl EndUserId {
    pub fn new() -> Self {
        Self(Uuid::new_v4())
    }
}

const LOGIN_CACHE_SIZE: usize = 50;

pub const LOGIN_CALLBACK: &'static str = "/api/login_callback";
fn redirect_url(app_url: &str) -> RedirectUrl {
    RedirectUrl::new(format!("{}{}", app_url, LOGIN_CALLBACK)).unwrap()
}

impl Authenticator {
    pub async fn new(
        issuer_url: IssuerUrl,
        client_id: ClientId,
        client_secret: ClientSecret,
        redirect_uri: RedirectUrl,
    ) -> Self {
        // Use OpenID Connect Discovery to fetch the provider metadata.
        let provider_metadata = CoreProviderMetadata::discover_async(issuer_url, async_http_client)
            .await
            .unwrap();

        let client =
            CoreClient::from_provider_metadata(provider_metadata, client_id, Some(client_secret))
                // Set the URL the user will be redirected to after the authorization process.
                .set_redirect_uri(redirect_uri);

        Self {
            client,
            login_cache: Arc::new(Mutex::new(LruCache::new(
                NonZeroUsize::new(LOGIN_CACHE_SIZE).unwrap(),
            ))),
        }
    }

    pub async fn from_env() -> Self {
        let app_url = env::var("APP_URL").unwrap();
        Authenticator::new(
            IssuerUrl::new(env::var("OPENID_ISSUER_URL").unwrap()).unwrap(),
            ClientId::new(env::var("OPENID_CLIENT_ID").unwrap()),
            ClientSecret::new(env::var("OPENID_CLIENT_SECRET").unwrap()),
            redirect_url(&app_url),
        )
        .await
    }

    pub async fn get_login_url(&self) -> (EndUserId, Url) {
        let (auth_url, csrf_token, nonce) = self
            .client
            .authorize_url(
                AuthenticationFlow::<CoreResponseType>::AuthorizationCode,
                CsrfToken::new_random,
                Nonce::new_random,
            )
            .add_scope(Scope::new("email".to_string()))
            .add_scope(Scope::new("profile".to_string()))
            .url();
        let user_id = EndUserId::new();
        self.login_cache
            .lock()
            .unwrap()
            .put(user_id.clone(), LoginState { csrf_token, nonce });
        (user_id, auth_url)
    }

    pub async fn authenticate(
        &self,
        user_id: EndUserId,
        auth_params: HashMap<String, String>,
    ) -> Result<(), BridgeError> {
        // TODO: If the token is missing from the cache, client should retry logging in.
        let state = self
            .login_cache
            .lock()
            .unwrap()
            .pop(&user_id)
            .ok_or(BridgeError::InvalidRequest("token missing".to_string()))?;
        info!(
            "state: {:?}, {:?}",
            state.csrf_token.secret(),
            state.nonce.secret()
        );
        if Some(state.csrf_token.secret()) != auth_params.get("state") {
            return Err(BridgeError::InvalidRequest(
                "token validation failed".to_string(),
            ));
        }
        let authorization_code = AuthorizationCode::new(
            auth_params
                .get("code")
                .ok_or(BridgeError::InvalidRequest(
                    "missing 'code' param".to_string(),
                ))?
                .to_string(),
        );

        let token = self
            .client
            .exchange_code(authorization_code)
            .request_async(async_http_client)
            .await?;
        info!("Got token {token:#?}");

        let id_token = token
            .id_token()
            .ok_or(BridgeError::InvalidRequest("Server did not return an IdToken".to_string()))?;
        let claims = id_token.claims(&self.client.id_token_verifier(), &state.nonce)?;
	
        info!("Got claims {claims:#?}");

        // params: {"session_state": "909b9959-041b-4a98-84d0-5f978bc8a679", "code": "2b4e95d1-0000-4b28-b49d-7a9de731e82b.909b9959-041b-4a98-84d0-5f978bc8a679.a382d869-4e34-42f1-a64d-24a224b9d338", "state": "a7Hff_hF_FOCqPCxmA1ZXg
        Err(BridgeError::Internal("todo".to_string()))
    }
}