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
// use always_cell::AlwaysCell;
use anyhow::{Context, Result};
use chrono::{DateTime, Utc};
use indexmap::IndexMap;
use log::warn;
use openid::{
    error::ClientError, Bearer, Client, DiscoveredClient, OAuth2Error, OAuth2ErrorCode, Options,
    StandardClaims, Token, Userinfo,
};
use serde::{Deserialize, Serialize};
use std::{sync::Arc, time::Duration};
use tokio::sync::RwLock;
use url::Url;

#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct OidcConfig {
    pub name: String,
    pub client_id: String,
    pub client_secret: String,
    pub issuer: Url,
    pub redirect: Url,
    pub refresh_cycle: Duration,
}

pub struct OidcController {
    handlers: IndexMap<String, OidcHandler>,
}

impl OidcController {
    pub async fn new(configs: &[OidcConfig]) -> Self {
        let mut handlers = IndexMap::new();
        for config in configs {
            handlers.insert(config.name.clone(), OidcHandler::new(config).await);
        }
        Self { handlers }
    }

    pub fn handler(&self, name: &str) -> Option<&OidcHandler> {
        self.handlers.get(name)
    }

    pub fn handlers(&self) -> impl Iterator<Item = &String> {
        self.handlers.keys()
    }
}

#[derive(Clone)]
pub struct OidcHandler {
    client: Arc<RwLock<(DateTime<Utc>, Client)>>,
    config: OidcConfig,
}

impl OidcHandler {
    pub async fn new(config: &OidcConfig) -> Self {
        let client = loop {
            match DiscoveredClient::discover(
                config.client_id.to_string(),
                config.client_secret.to_string(),
                Some(config.redirect.to_string()),
                config.issuer.clone(),
            )
            .await
            {
                Ok(x) => break x,
                Err(e) => {
                    warn!("failed to discover OIDC: {e:?}");
                    tokio::time::sleep(Duration::from_secs(1)).await;
                }
            }
        };
        Self {
            client: Arc::new(RwLock::new((
                Utc::now() + chrono::Duration::from_std(config.refresh_cycle).unwrap(),
                client,
            ))),
            config: config.clone(),
        }
    }

    async fn recreate(&self) -> Client {
        loop {
            match DiscoveredClient::discover(
                self.config.client_id.clone(),
                self.config.client_secret.clone(),
                Some(self.config.redirect.to_string()),
                self.config.issuer.clone(),
            )
            .await
            {
                Ok(x) => break x,
                Err(e) => {
                    warn!("failed to rediscover OIDC: {e:?}");
                    tokio::time::sleep(Duration::from_secs(1)).await;
                }
            }
        }
    }

    pub async fn auth_url(&self, redirect: Option<&Url>) -> Url {
        let client = self.client.read().await;
        let mut tclient;
        let client = if let Some(redirect) = redirect {
            tclient = client.1.clone();
            tclient.redirect_uri = Some(redirect.to_string());
            &tclient
        } else {
            &client.1
        };
        client.auth_url(&Options {
            scope: Some("openid email profile".into()),
            state: None,
            ..Default::default()
        })
    }

    pub async fn validate_code(
        &self,
        code: &str,
        redirect: Option<&Url>,
    ) -> Result<Option<(Bearer, StandardClaims, Userinfo)>> {
        let mut client = self.client.read().await;
        let now = Utc::now();
        if client.0 < now {
            drop(client);
            let mut old_client = self.client.write().await;
            if old_client.0 < now {
                let new_client = self.recreate().await;
                *old_client = (
                    now + chrono::Duration::from_std(self.config.refresh_cycle).unwrap(),
                    new_client,
                )
            }
            drop(old_client);
            client = self.client.read().await;
        }
        let mut tclient;
        let client = if let Some(redirect) = redirect {
            tclient = client.1.clone();
            tclient.redirect_uri = Some(redirect.to_string());
            &tclient
        } else {
            &client.1
        };
        let mut token: Token = match client.request_token(code).await {
            Ok(x) => x.into(),
            Err(ClientError::OAuth2(OAuth2Error {
                error: OAuth2ErrorCode::InvalidGrant,
                ..
            })) => {
                return Ok(None);
            }
            Err(e) => return Err(e.into()),
        };

        if let Some(id_token) = &mut token.id_token {
            client
                .decode_token(id_token)
                .context("failed to decode token")?;
            client
                .validate_token(id_token, None, None)
                .context("failed to validate token")?;
        } else {
            return Ok(None);
        };

        let info = client.request_userinfo(&token).await?;

        Ok(Some((
            token.bearer,
            token.id_token.unwrap().unwrap_decoded().1,
            info,
        )))
    }
}