axum-security 0.0.2

A security toolbox for the Axum library
Documentation
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
use std::{borrow::Cow, error::Error, fmt::Display, sync::Arc, time::Duration};

use axum_security_oidc::{
    ConfigError, DiscoveryError, HttpClient, OidcBuilderError as CrateBuilderError, OidcClient,
    OidcClientBuilder,
};
use cookie_monster::CookieBuilder;

use crate::utils::get_env;

use super::{OidcContext, OidcHandler, context::OidcContextInner, cookie::OidcCookieBuilder};

/// Builder for an [`OidcContext`]. Wraps the `axum-security-oidc`
/// [`OidcClientBuilder`] with axum-security's signed-cookie and route config.
pub struct OidcContextBuilder {
    cookie_builder: OidcCookieBuilder,
    login_path: Option<Cow<'static, str>>,
    logout_path: Option<Cow<'static, str>>,
    post_logout_redirect_url: Option<String>,
    client: OidcClientBuilder,
}

impl OidcContextBuilder {
    pub fn new(provider_name: Cow<'static, str>) -> Self {
        Self {
            cookie_builder: OidcCookieBuilder::new(provider_name),
            login_path: None,
            logout_path: None,
            post_logout_redirect_url: None,
            client: OidcClient::builder(),
        }
    }

    pub(crate) async fn discover(
        provider_name: Cow<'static, str>,
        issuer_url: &str,
    ) -> Result<Self, OidcBuilderError> {
        let client = OidcClient::discover(issuer_url, HttpClient::default_reqwest())
            .await
            .map_err(|e| OidcBuilderError::DiscoveryError(e.to_string()))?;

        Ok(Self {
            cookie_builder: OidcCookieBuilder::new(provider_name),
            login_path: None,
            logout_path: None,
            post_logout_redirect_url: None,
            client,
        })
    }

    pub fn redirect_url(mut self, url: impl Into<String>) -> Self {
        self.client = self.client.redirect_url(url);
        self
    }

    pub fn redirect_uri_env(self, name: &str) -> Self {
        self.redirect_url(get_env(name))
    }

    pub fn client_id(mut self, client_id: impl Into<String>) -> Self {
        self.client = self.client.client_id(client_id);
        self
    }

    pub fn client_id_env(self, name: &str) -> Self {
        self.client_id(get_env(name))
    }

    pub fn client_secret(mut self, client_secret: impl Into<String>) -> Self {
        self.client = self.client.client_secret(client_secret);
        self
    }

    pub fn client_secret_env(self, name: &str) -> Self {
        self.client_secret(get_env(name))
    }

    pub fn issuer_url(mut self, url: impl Into<String>) -> Self {
        self.client = self.client.issuer_url(url);
        self
    }

    pub fn auth_url(mut self, url: impl Into<String>) -> Self {
        self.client = self.client.auth_url(url);
        self
    }

    pub fn token_url(mut self, url: impl Into<String>) -> Self {
        self.client = self.client.token_url(url);
        self
    }

    pub fn jwks_url(mut self, url: impl Into<String>) -> Self {
        self.client = self.client.jwks_url(url);
        self
    }

    pub fn scopes(mut self, scopes: &[&str]) -> Self {
        self.client = self.client.scopes(scopes);
        self
    }

    pub fn cookie(mut self, f: impl FnOnce(CookieBuilder) -> CookieBuilder) -> Self {
        self.cookie_builder.cookie_builder.apply_cookie(f);
        self
    }

    pub fn dev_cookie(mut self, f: impl FnOnce(CookieBuilder) -> CookieBuilder) -> Self {
        self.cookie_builder.cookie_builder.apply_dev_cookie(f);
        self
    }

    pub fn login_path(mut self, path: impl Into<Cow<'static, str>>) -> Self {
        self.login_path = Some(path.into());
        self
    }

    pub fn logout_path(mut self, path: impl Into<Cow<'static, str>>) -> Self {
        self.logout_path = Some(path.into());
        self
    }

    pub fn post_logout_redirect_url(mut self, url: impl Into<String>) -> Self {
        self.post_logout_redirect_url = Some(url.into());
        self
    }

    pub fn end_session_url(mut self, url: impl Into<String>) -> Self {
        self.client = self.client.end_session_url(url);
        self
    }

    pub fn use_dev_cookies(mut self, dev: bool) -> Self {
        self.cookie_builder.cookie_builder.dev = dev;
        self
    }

    pub fn http_client(mut self, http_client: HttpClient) -> Self {
        self.client = self.client.http_client(http_client);
        self
    }

    /// Minimum interval between JWKS refetch attempts on the manual
    /// (hard-coded endpoint) path.
    ///
    /// An ID token with an unknown signing key (key rotation) triggers a JWKS
    /// refetch, at most one attempt per this interval. Defaults to 60 seconds.
    pub fn jwks_min_refetch_interval(mut self, interval: Duration) -> Self {
        self.client = self.client.min_refetch_interval(interval);
        self
    }

    /// Sets the secret used to sign the login state cookie.
    ///
    /// A secret is **required**: [`try_build`](Self::try_build) fails with
    /// [`OidcBuilderError::MissingCookieSecret`] if none is set. Use a stable
    /// secret (e.g. from the environment) so that in-flight logins survive
    /// restarts and work across instances; for local development
    /// [`random_cookie_secret`](Self::random_cookie_secret) opts into an
    /// ephemeral one.
    pub fn cookie_secret(mut self, secret: impl AsRef<[u8]>) -> Self {
        self.cookie_builder.secret = Some(secret.as_ref().to_vec());
        self
    }

    /// Signs the login state cookie with a fresh random per-process secret.
    ///
    /// The secret is regenerated on every restart and differs between
    /// instances, so a login begun on one process cannot be completed on
    /// another. Only appropriate for local development or single-instance
    /// deployments; otherwise set a stable [`cookie_secret`](Self::cookie_secret).
    pub fn random_cookie_secret(mut self) -> Self {
        self.cookie_builder.use_random_secret();
        self
    }

    pub fn max_login_duration(mut self, duration: Duration) -> Self {
        self.cookie_builder
            .set_max_login_duration_secs(duration.as_secs());
        self
    }

    pub fn max_login_duration_minutes(self, minutes: u64) -> Self {
        self.max_login_duration(Duration::from_mins(minutes))
    }

    pub fn build<T>(self, handler: T) -> OidcContext<T>
    where
        T: OidcHandler,
    {
        self.try_build(handler).unwrap()
    }

    pub fn try_build<T>(self, handler: T) -> Result<OidcContext<T>, OidcBuilderError>
    where
        T: OidcHandler,
    {
        // Build the OIDC client first (client-config errors), then the signed
        // cookie (provider-name errors) — matching the old ordering.
        let client = self.client.try_build().map_err(OidcBuilderError::from)?;
        let session = self.cookie_builder.try_build()?;

        Ok(OidcContext(Arc::new(OidcContextInner {
            client,
            handler,
            session,
            login_path: self.login_path,
            logout_path: self.logout_path,
            post_logout_redirect_url: self.post_logout_redirect_url,
        })))
    }
}

#[derive(Debug)]
pub enum OidcBuilderError {
    MissingClientId,
    MissingRedirectUrl,
    MissingAuthUrl,
    MissingTokenUrl,
    MissingIssuerUrl,
    MissingJwksUrl,
    InvalidRedirectUrl(url::ParseError),
    InvalidAuthUrl(url::ParseError),
    InvalidTokenUrl(url::ParseError),
    InvalidJwksUrl(url::ParseError),
    InvalidEndSessionUrl(url::ParseError),
    WhitespaceInProviderName,
    /// No cookie signing secret was set. Provide one with `cookie_secret`
    /// or opt into an ephemeral one with `random_cookie_secret`.
    MissingCookieSecret,
    DiscoveryError(String),
    /// Another OAuth2 client configuration error.
    Config(String),
}

impl From<CrateBuilderError> for OidcBuilderError {
    fn from(error: CrateBuilderError) -> Self {
        match error {
            CrateBuilderError::MissingClientId => Self::MissingClientId,
            CrateBuilderError::MissingRedirectUrl => Self::MissingRedirectUrl,
            CrateBuilderError::MissingIssuerUrl => Self::MissingIssuerUrl,
            CrateBuilderError::MissingAuthUrl => Self::MissingAuthUrl,
            CrateBuilderError::MissingTokenUrl => Self::MissingTokenUrl,
            CrateBuilderError::MissingJwksUrl => Self::MissingJwksUrl,
            CrateBuilderError::InvalidJwksUrl(e) => Self::InvalidJwksUrl(e),
            CrateBuilderError::InvalidEndSessionUrl(e) => Self::InvalidEndSessionUrl(e),
            CrateBuilderError::OAuth2(config) => match config {
                ConfigError::InvalidAuthUrl(e) => Self::InvalidAuthUrl(e),
                ConfigError::InvalidTokenUrl(e) => Self::InvalidTokenUrl(e),
                ConfigError::InvalidRedirectUrl(e) => Self::InvalidRedirectUrl(e),
                ConfigError::MissingClientId => Self::MissingClientId,
                ConfigError::MissingAuthUrl => Self::MissingAuthUrl,
                ConfigError::MissingTokenUrl => Self::MissingTokenUrl,
                other => Self::Config(other.to_string()),
            },
            other => Self::Config(other.to_string()),
        }
    }
}

impl From<DiscoveryError> for OidcBuilderError {
    fn from(error: DiscoveryError) -> Self {
        OidcBuilderError::DiscoveryError(error.to_string())
    }
}

impl Error for OidcBuilderError {}

impl Display for OidcBuilderError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            OidcBuilderError::MissingClientId => f.write_str("client id is missing"),
            OidcBuilderError::MissingRedirectUrl => f.write_str("redirect url is missing"),
            OidcBuilderError::MissingAuthUrl => f.write_str("authorization url is missing"),
            OidcBuilderError::MissingTokenUrl => f.write_str("token url is missing"),
            OidcBuilderError::MissingIssuerUrl => f.write_str("issuer url is missing"),
            OidcBuilderError::MissingJwksUrl => f.write_str("JWKS url is missing"),
            OidcBuilderError::InvalidRedirectUrl(e) => {
                write!(f, "could not parse redirect url: {e}")
            }
            OidcBuilderError::InvalidAuthUrl(e) => {
                write!(f, "could not parse authorization url: {e}")
            }
            OidcBuilderError::InvalidTokenUrl(e) => write!(f, "could not parse token url: {e}"),
            OidcBuilderError::InvalidJwksUrl(e) => write!(f, "could not parse JWKS url: {e}"),
            OidcBuilderError::InvalidEndSessionUrl(e) => {
                write!(f, "could not parse end-session url: {e}")
            }
            OidcBuilderError::WhitespaceInProviderName => {
                f.write_str("provider name can't contain whitespaces")
            }
            OidcBuilderError::MissingCookieSecret => f.write_str(
                "cookie signing secret is missing (set one with `cookie_secret`, or opt into an ephemeral one with `random_cookie_secret`)",
            ),
            OidcBuilderError::DiscoveryError(e) => write!(f, "OIDC discovery failed: {e}"),
            OidcBuilderError::Config(e) => write!(f, "OIDC client configuration error: {e}"),
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::{
        after_login::AfterLoginCookies,
        oidc::{OidcBuilderError, OidcContext, OidcHandler, OidcTokenResponse},
    };
    use axum::response::IntoResponse;

    const CLIENT_ID: &str = "test_client_id";
    const CLIENT_SECRET: &str = "test_client_secret";
    const REDIRECT_URL: &str = "http://localhost:3000/auth/callback";
    const ISSUER_URL: &str = "https://accounts.google.com";
    const AUTH_URL: &str = "https://accounts.google.com/o/oauth2/v2/auth";
    const TOKEN_URL: &str = "https://oauth2.googleapis.com/token";
    const JWKS_URL: &str = "https://www.googleapis.com/oauth2/v3/certs";

    struct TestHandler;

    impl OidcHandler for TestHandler {
        async fn after_login(
            &self,
            _token_res: OidcTokenResponse<'_>,
            _context: &mut AfterLoginCookies<'_>,
        ) -> impl IntoResponse {
            ()
        }
    }

    #[test]
    fn builder_ok_manual() {
        let res = OidcContext::builder("google")
            .client_id(CLIENT_ID)
            .client_secret(CLIENT_SECRET)
            .issuer_url(ISSUER_URL)
            .auth_url(AUTH_URL)
            .token_url(TOKEN_URL)
            .jwks_url(JWKS_URL)
            .redirect_url(REDIRECT_URL)
            .random_cookie_secret()
            .try_build(TestHandler);

        assert!(res.is_ok());
    }

    #[test]
    fn missing_cookie_secret() {
        let res = OidcContext::builder("google")
            .client_id(CLIENT_ID)
            .client_secret(CLIENT_SECRET)
            .issuer_url(ISSUER_URL)
            .auth_url(AUTH_URL)
            .token_url(TOKEN_URL)
            .jwks_url(JWKS_URL)
            .redirect_url(REDIRECT_URL)
            .try_build(TestHandler);

        assert!(matches!(res, Err(OidcBuilderError::MissingCookieSecret)));
    }

    #[test]
    fn missing_client_id() {
        let res = OidcContext::builder("google")
            .client_secret(CLIENT_SECRET)
            .issuer_url(ISSUER_URL)
            .auth_url(AUTH_URL)
            .token_url(TOKEN_URL)
            .jwks_url(JWKS_URL)
            .redirect_url(REDIRECT_URL)
            .try_build(TestHandler);

        assert!(matches!(res, Err(OidcBuilderError::MissingClientId)));
    }

    #[test]
    fn missing_redirect_url() {
        let res = OidcContext::builder("google")
            .client_id(CLIENT_ID)
            .issuer_url(ISSUER_URL)
            .auth_url(AUTH_URL)
            .token_url(TOKEN_URL)
            .jwks_url(JWKS_URL)
            .try_build(TestHandler);

        assert!(matches!(res, Err(OidcBuilderError::MissingRedirectUrl)));
    }

    #[test]
    fn missing_issuer_url() {
        let res = OidcContext::builder("google")
            .client_id(CLIENT_ID)
            .auth_url(AUTH_URL)
            .token_url(TOKEN_URL)
            .jwks_url(JWKS_URL)
            .redirect_url(REDIRECT_URL)
            .try_build(TestHandler);

        assert!(matches!(res, Err(OidcBuilderError::MissingIssuerUrl)));
    }

    #[test]
    fn missing_auth_url() {
        let res = OidcContext::builder("google")
            .client_id(CLIENT_ID)
            .issuer_url(ISSUER_URL)
            .token_url(TOKEN_URL)
            .jwks_url(JWKS_URL)
            .redirect_url(REDIRECT_URL)
            .try_build(TestHandler);

        assert!(matches!(res, Err(OidcBuilderError::MissingAuthUrl)));
    }

    #[test]
    fn missing_token_url() {
        let res = OidcContext::builder("google")
            .client_id(CLIENT_ID)
            .issuer_url(ISSUER_URL)
            .auth_url(AUTH_URL)
            .jwks_url(JWKS_URL)
            .redirect_url(REDIRECT_URL)
            .try_build(TestHandler);

        assert!(matches!(res, Err(OidcBuilderError::MissingTokenUrl)));
    }

    #[test]
    fn missing_jwks_url() {
        let res = OidcContext::builder("google")
            .client_id(CLIENT_ID)
            .issuer_url(ISSUER_URL)
            .auth_url(AUTH_URL)
            .token_url(TOKEN_URL)
            .redirect_url(REDIRECT_URL)
            .try_build(TestHandler);

        assert!(matches!(res, Err(OidcBuilderError::MissingJwksUrl)));
    }

    #[test]
    fn invalid_redirect_url() {
        let res = OidcContext::builder("google")
            .client_id(CLIENT_ID)
            .issuer_url(ISSUER_URL)
            .auth_url(AUTH_URL)
            .token_url(TOKEN_URL)
            .jwks_url(JWKS_URL)
            .redirect_url("not an url")
            .try_build(TestHandler);

        assert!(matches!(res, Err(OidcBuilderError::InvalidRedirectUrl(_))));
    }

    #[test]
    fn provider_name_whitespace() {
        let res = OidcContext::builder("google ")
            .client_id(CLIENT_ID)
            .issuer_url(ISSUER_URL)
            .auth_url(AUTH_URL)
            .token_url(TOKEN_URL)
            .jwks_url(JWKS_URL)
            .redirect_url(REDIRECT_URL)
            .try_build(TestHandler);

        assert!(matches!(
            res,
            Err(OidcBuilderError::WhitespaceInProviderName)
        ));
    }
}