cf-modkit-auth 0.5.0

ModKit authentication 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
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
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
use std::time::Duration;

use aliri_clock::DurationSecs;
use aliri_tokens::sources::AsyncTokenSource;
use aliri_tokens::{AccessToken, IdToken, TokenLifetimeConfig, TokenWithLifetime};
use async_trait::async_trait;
use base64::{Engine as _, engine::general_purpose};
use http::header::AUTHORIZATION;
use url::Url;
use zeroize::Zeroizing;

use super::config::OAuthClientConfig;
use super::error::TokenError;
use super::types::ClientAuthMethod;
use modkit_utils::SecretString;

/// Token source that exchanges client credentials for an access token using
/// `modkit-http::HttpClient`.
///
/// It implements [`aliri_tokens::AsyncTokenSource`] so that
/// `aliri_tokens` can drive refresh scheduling, jitter, and backoff.
pub struct OAuthTokenSource {
    client: modkit_http::HttpClient,
    token_endpoint: Url,
    client_id: String,
    client_secret: SecretString,
    /// Pre-joined scopes (space-separated), or `None` when the scope list is
    /// empty.
    scopes: Option<String>,
    auth_method: ClientAuthMethod,
    extra_headers: Vec<(String, String)>,
    default_ttl: Duration,
    refresh_offset: Duration,
    min_refresh_period: Duration,
}

impl OAuthTokenSource {
    /// Build a new token source from the given configuration.
    ///
    /// # Errors
    ///
    /// Returns [`TokenError::ConfigError`] if `token_endpoint` is `None`.
    ///
    /// Returns [`TokenError::Http`] if the underlying `HttpClient` fails to
    /// build.
    pub fn new(config: &OAuthClientConfig) -> Result<Self, TokenError> {
        let token_endpoint = config
            .token_endpoint
            .clone()
            .ok_or_else(|| TokenError::ConfigError("token_endpoint is required".into()))?;

        let http_config = config
            .http_config
            .clone()
            .unwrap_or_else(modkit_http::HttpClientConfig::token_endpoint);

        let client = modkit_http::HttpClientBuilder::with_config(http_config)
            .build()
            .map_err(|e| {
                TokenError::Http(crate::http_error::format_http_error(&e, "OAuth2 token"))
            })?;

        let scopes = if config.scopes.is_empty() {
            None
        } else {
            Some(config.scopes.join(" "))
        };

        Ok(Self {
            client,
            token_endpoint,
            client_id: config.client_id.clone(),
            client_secret: config.client_secret.clone(),
            scopes,
            auth_method: config.auth_method,
            extra_headers: config.extra_headers.clone(),
            default_ttl: config.default_ttl,
            refresh_offset: config.refresh_offset,
            min_refresh_period: config.min_refresh_period,
        })
    }
}

#[async_trait]
impl AsyncTokenSource for OAuthTokenSource {
    type Error = TokenError;

    async fn request_token(&mut self) -> Result<TokenWithLifetime, Self::Error> {
        // -- build form fields ---------------------------------------------------
        let mut fields: Vec<(&str, &str)> = vec![("grant_type", "client_credentials")];

        if let Some(ref scope) = self.scopes {
            fields.push(("scope", scope));
        }

        // For Form auth, credentials go into the form body.
        // Wrap the temporary copy in `Zeroizing` so it is scrubbed on drop.
        let secret_expose;
        if self.auth_method == ClientAuthMethod::Form {
            secret_expose = Zeroizing::new(self.client_secret.expose().to_owned());
            fields.push(("client_id", &self.client_id));
            fields.push(("client_secret", &secret_expose));
        }

        // -- build request -------------------------------------------------------
        let mut builder = self.client.post(self.token_endpoint.as_str());

        // For Basic auth, credentials go into the Authorization header.
        // Wrap intermediates in `Zeroizing` so the plaintext is scrubbed on drop.
        if self.auth_method == ClientAuthMethod::Basic {
            let credentials = Zeroizing::new(format!(
                "{}:{}",
                self.client_id,
                self.client_secret.expose()
            ));
            let encoded = Zeroizing::new(general_purpose::STANDARD.encode(credentials.as_bytes()));
            let header_value = Zeroizing::new(format!("Basic {}", &*encoded));
            builder = builder.header(AUTHORIZATION.as_str(), &header_value);
        }

        // Apply vendor-specific extra headers.
        for (name, value) in &self.extra_headers {
            builder = builder.header(name, value);
        }

        let response = builder
            .form(fields.as_slice())
            .map_err(|e| {
                TokenError::Http(crate::http_error::format_http_error(&e, "OAuth2 token"))
            })?
            .send()
            .await
            .map_err(|e| {
                TokenError::Http(crate::http_error::format_http_error(&e, "OAuth2 token"))
            })?;

        // -- check status, then parse response ------------------------------------
        let token_resp: super::types::TokenResponse = response
            .error_for_status()
            .map_err(|e| {
                TokenError::Http(crate::http_error::format_http_error(&e, "OAuth2 token"))
            })?
            .json()
            .await
            .map_err(|e| {
                TokenError::Http(crate::http_error::format_http_error(&e, "OAuth2 token"))
            })?;

        // -- validate token_type -------------------------------------------------
        if let Some(ref tt) = token_resp.token_type
            && !tt.eq_ignore_ascii_case("bearer")
        {
            return Err(TokenError::UnsupportedTokenType(tt.clone()));
        }

        // -- compute lifetime ----------------------------------------------------
        let lifetime_secs = token_resp.expires_in.unwrap_or(self.default_ttl.as_secs());

        // Compute per-token refresh parameters so that the stale time
        // never exceeds the expiry time, even for short-lived tokens.
        let (freshness, min_stale) = refresh_params(
            lifetime_secs,
            &self.refresh_offset,
            &self.min_refresh_period,
        );
        let lifetime_config = TokenLifetimeConfig::new(freshness, min_stale);

        let access_token = AccessToken::new(token_resp.access_token);
        let token = lifetime_config.create_token(
            &access_token,
            None::<&IdToken>,
            DurationSecs(lifetime_secs),
        );

        Ok(token)
    }
}

/// Compute refresh parameters for [`TokenLifetimeConfig`].
///
/// Returns `(freshness_period, min_staleness_period)` such that
/// `max(lifetime × freshness_period, min_staleness_period) <= lifetime`,
/// guaranteeing the stale time never exceeds the expiry time.
///
/// `min_refresh_period` is used as a **lower bound on the staleness
/// window** (the minimum time the token spends in the "stale" state
/// before expiry), not as a refresh deadline. It is capped to
/// `desired_delay` so it can never push the stale time past expiry.
/// In `aliri_tokens` terms it maps to `min_staleness_period`.
///
/// - Normal case (`offset < lifetime`): stale `offset` seconds before
///   expiry.
/// - Short-lived token (`offset >= lifetime`): stale at 50% of lifetime.
/// - Zero lifetime: immediately stale.
#[allow(clippy::integer_division, clippy::cast_precision_loss)]
fn refresh_params(
    lifetime_secs: u64,
    refresh_offset: &Duration,
    min_refresh_period: &Duration,
) -> (f64, DurationSecs) {
    if lifetime_secs == 0 {
        return (0.0, DurationSecs(0));
    }

    let offset = refresh_offset.as_secs();
    let desired_delay = if offset < lifetime_secs {
        lifetime_secs - offset
    } else {
        // Fallback: stale at 50% of lifetime (truncation is fine).
        lifetime_secs / 2
    };

    // Precision loss is negligible — token lifetimes are practical
    // values well within f64 mantissa range.
    let freshness = (desired_delay as f64) / (lifetime_secs as f64);
    let min_stale = min_refresh_period.as_secs().min(desired_delay);

    (freshness, DurationSecs(min_stale))
}

#[cfg(test)]
#[cfg_attr(coverage_nightly, coverage(off))]
mod tests {
    use super::*;
    use httpmock::prelude::*;

    /// Build a minimal valid config pointing at the mock server.
    fn test_config(server: &MockServer) -> OAuthClientConfig {
        OAuthClientConfig {
            token_endpoint: Some(
                Url::parse(&format!("http://localhost:{}/token", server.port())).unwrap(),
            ),
            client_id: "test-client".into(),
            client_secret: SecretString::new("test-secret"),
            http_config: Some(modkit_http::HttpClientConfig::for_testing()),
            ..Default::default()
        }
    }

    #[tokio::test]
    async fn request_token_basic_auth_success() {
        let server = MockServer::start();

        let mock = server.mock(|when, then| {
            when.method(POST)
                .path("/token")
                .header_exists("authorization")
                .body_includes("grant_type=client_credentials");
            then.status(200)
                .header("content-type", "application/json")
                .body(r#"{"access_token":"tok-123","expires_in":3600,"token_type":"Bearer"}"#);
        });

        let mut source = OAuthTokenSource::new(&test_config(&server)).unwrap();
        let token = source.request_token().await.unwrap();

        assert_eq!(token.access_token().as_str(), "tok-123");
        assert_eq!(token.lifetime(), DurationSecs(3600));
        mock.assert();
    }

    #[tokio::test]
    async fn missing_expires_in_uses_default_ttl() {
        let server = MockServer::start();

        let mock = server.mock(|when, then| {
            when.method(POST).path("/token");
            then.status(200)
                .header("content-type", "application/json")
                .body(r#"{"access_token":"tok-456"}"#);
        });

        let mut source = OAuthTokenSource::new(&test_config(&server)).unwrap();
        let token = source.request_token().await.unwrap();

        // default_ttl from OAuthClientConfig::default() is 5 min = 300s
        assert_eq!(token.lifetime(), DurationSecs(300));
        mock.assert();
    }

    #[tokio::test]
    async fn expires_in_zero_honoured() {
        let server = MockServer::start();

        let mock = server.mock(|when, then| {
            when.method(POST).path("/token");
            then.status(200)
                .header("content-type", "application/json")
                .body(r#"{"access_token":"tok-zero","expires_in":0}"#);
        });

        let mut source = OAuthTokenSource::new(&test_config(&server)).unwrap();
        let token = source.request_token().await.unwrap();

        // Server-provided expires_in is honoured as-is; aliri handles refresh scheduling.
        assert_eq!(token.lifetime(), DurationSecs(0));
        mock.assert();
    }

    #[tokio::test]
    async fn unsupported_token_type_returns_error() {
        let server = MockServer::start();

        let mock = server.mock(|when, then| {
            when.method(POST).path("/token");
            then.status(200)
                .header("content-type", "application/json")
                .body(r#"{"access_token":"tok","token_type":"mac"}"#);
        });

        let mut source = OAuthTokenSource::new(&test_config(&server)).unwrap();
        let err = source.request_token().await.unwrap_err();

        assert!(
            matches!(err, TokenError::UnsupportedTokenType(ref t) if t == "mac"),
            "expected UnsupportedTokenType(\"mac\"), got: {err}"
        );
        mock.assert();
    }

    #[tokio::test]
    async fn empty_scopes_omits_scope_param() {
        let server = MockServer::start();

        let mock = server.mock(|when, then| {
            when.method(POST)
                .path("/token")
                .body_includes("grant_type=client_credentials")
                .body_excludes("scope");
            then.status(200)
                .header("content-type", "application/json")
                .body(r#"{"access_token":"tok"}"#);
        });

        let mut source = OAuthTokenSource::new(&test_config(&server)).unwrap();
        source.request_token().await.unwrap();
        mock.assert();
    }

    #[tokio::test]
    async fn scopes_are_space_joined() {
        let server = MockServer::start();

        let mock = server.mock(|when, then| {
            when.method(POST)
                .path("/token")
                .body_includes("scope=read+write");
            then.status(200)
                .header("content-type", "application/json")
                .body(r#"{"access_token":"tok"}"#);
        });

        let mut cfg = test_config(&server);
        cfg.scopes = vec!["read".into(), "write".into()];
        let mut source = OAuthTokenSource::new(&cfg).unwrap();
        source.request_token().await.unwrap();
        mock.assert();
    }

    #[tokio::test]
    async fn basic_auth_header_present() {
        let server = MockServer::start();

        let expected = format!(
            "Basic {}",
            general_purpose::STANDARD.encode("test-client:test-secret")
        );

        let mock = server.mock(|when, then| {
            when.method(POST)
                .path("/token")
                .header("authorization", &expected);
            then.status(200)
                .header("content-type", "application/json")
                .body(r#"{"access_token":"tok"}"#);
        });

        let mut source = OAuthTokenSource::new(&test_config(&server)).unwrap();
        source.request_token().await.unwrap();
        mock.assert();
    }

    #[tokio::test]
    async fn form_auth_sends_credentials_in_body() {
        let server = MockServer::start();

        let mock = server.mock(|when, then| {
            when.method(POST)
                .path("/token")
                .body_includes("client_id=test-client")
                .body_includes("client_secret=test-secret")
                .body_includes("grant_type=client_credentials");
            then.status(200)
                .header("content-type", "application/json")
                .body(r#"{"access_token":"tok"}"#);
        });

        let mut cfg = test_config(&server);
        cfg.auth_method = ClientAuthMethod::Form;
        let mut source = OAuthTokenSource::new(&cfg).unwrap();
        source.request_token().await.unwrap();
        mock.assert();
    }

    #[tokio::test]
    async fn form_auth_does_not_send_basic_header() {
        let server = MockServer::start();

        // Mock that REQUIRES a Basic auth header — should NOT be hit.
        let basic_mock = server.mock(|when, then| {
            when.method(POST)
                .path("/token")
                .header_exists("authorization");
            then.status(200)
                .header("content-type", "application/json")
                .body(r#"{"access_token":"tok"}"#);
        });

        // Catch-all mock for the POST.
        let fallback_mock = server.mock(|when, then| {
            when.method(POST).path("/token");
            then.status(200)
                .header("content-type", "application/json")
                .body(r#"{"access_token":"tok"}"#);
        });

        let mut cfg = test_config(&server);
        cfg.auth_method = ClientAuthMethod::Form;
        let mut source = OAuthTokenSource::new(&cfg).unwrap();
        source.request_token().await.unwrap();

        assert_eq!(
            basic_mock.calls(),
            0,
            "Form auth must not send Authorization header"
        );
        fallback_mock.assert();
    }

    #[tokio::test]
    async fn extra_headers_are_applied() {
        let server = MockServer::start();

        let mock = server.mock(|when, then| {
            when.method(POST)
                .path("/token")
                .header("x-vendor-key", "vendor-value");
            then.status(200)
                .header("content-type", "application/json")
                .body(r#"{"access_token":"tok"}"#);
        });

        let mut cfg = test_config(&server);
        cfg.extra_headers = vec![("x-vendor-key".into(), "vendor-value".into())];
        let mut source = OAuthTokenSource::new(&cfg).unwrap();
        source.request_token().await.unwrap();
        mock.assert();
    }

    #[tokio::test]
    async fn http_error_mapped_via_format_http_error() {
        let server = MockServer::start();

        let mock = server.mock(|when, then| {
            when.method(POST).path("/token");
            then.status(401)
                .header("content-type", "application/json")
                .body(r#"{"error":"invalid_client"}"#);
        });

        let mut source = OAuthTokenSource::new(&test_config(&server)).unwrap();
        let err = source.request_token().await.unwrap_err();

        assert!(
            matches!(
                err,
                TokenError::Http(ref msg)
                    if msg.contains("OAuth2 token")
                        && msg.contains("401")
            ),
            "expected Http error with OAuth2 token prefix and 401, got: {err}"
        );
        mock.assert();
    }

    #[test]
    fn config_error_when_token_endpoint_missing() {
        let cfg = OAuthClientConfig::default();
        let result = OAuthTokenSource::new(&cfg);
        let Err(err) = result else {
            panic!("expected ConfigError, got Ok");
        };
        assert!(
            matches!(err, TokenError::ConfigError(ref msg) if msg.contains("token_endpoint")),
            "expected ConfigError about token_endpoint, got: {err}"
        );
    }

    #[tokio::test]
    async fn bearer_case_insensitive() {
        let server = MockServer::start();

        let mock = server.mock(|when, then| {
            when.method(POST).path("/token");
            then.status(200)
                .header("content-type", "application/json")
                .body(r#"{"access_token":"tok","token_type":"bEaReR"}"#);
        });

        let mut source = OAuthTokenSource::new(&test_config(&server)).unwrap();
        let token = source.request_token().await.unwrap();

        assert_eq!(token.access_token().as_str(), "tok");
        mock.assert();
    }

    // -- refresh_params -------------------------------------------------------

    /// Helper: verify that the aliri formula
    /// `max(lifetime * freshness, min_stale) <= lifetime`
    /// holds for the given params.
    #[allow(clippy::cast_precision_loss)]
    fn assert_stale_before_expiry(lifetime: u64, freshness: f64, min_stale: DurationSecs) {
        let delay_a = (lifetime as f64) * freshness;
        let delay_b = min_stale.0 as f64;
        let delay = delay_a.max(delay_b);
        assert!(
            delay <= lifetime as f64,
            "stale ({delay}) must not exceed lifetime ({lifetime})"
        );
    }

    #[test]
    fn refresh_normal_token() {
        // 1-hour token, 30-min offset → stale at 50%
        let (r, ms) = refresh_params(
            3600,
            &Duration::from_secs(30 * 60),
            &Duration::from_secs(10),
        );
        assert!((r - 0.5).abs() < f64::EPSILON);
        assert_eq!(ms, DurationSecs(10));
        assert_stale_before_expiry(3600, r, ms);
    }

    #[test]
    fn refresh_short_lived_token() {
        // 20-min token, 30-min offset → fallback 0.5
        let (r, ms) = refresh_params(
            1200,
            &Duration::from_secs(30 * 60),
            &Duration::from_secs(10),
        );
        assert!((r - 0.5).abs() < f64::EPSILON);
        assert_eq!(ms, DurationSecs(10));
        assert_stale_before_expiry(1200, r, ms);
    }

    #[test]
    fn refresh_equal_lifetime_and_offset() {
        // 30-min token, 30-min offset → fallback 0.5
        let (r, ms) = refresh_params(
            1800,
            &Duration::from_secs(30 * 60),
            &Duration::from_secs(10),
        );
        assert!((r - 0.5).abs() < f64::EPSILON);
        assert_stale_before_expiry(1800, r, ms);
    }

    #[test]
    fn refresh_zero_lifetime() {
        // Both values must be zero so stale == expiry.
        let (r, ms) = refresh_params(0, &Duration::from_secs(30 * 60), &Duration::from_secs(10));
        assert!((r - 0.0).abs() < f64::EPSILON);
        assert_eq!(ms, DurationSecs(0));
    }

    #[test]
    fn refresh_small_offset() {
        // 5-min token, 1-min offset → stale at 80%
        let (r, ms) = refresh_params(300, &Duration::from_secs(60), &Duration::from_secs(10));
        assert!((r - 0.8).abs() < f64::EPSILON);
        assert_eq!(ms, DurationSecs(10));
        assert_stale_before_expiry(300, r, ms);
    }

    #[test]
    fn refresh_zero_offset() {
        // No offset → stale at 100% (only stale when expired)
        let (r, ms) = refresh_params(3600, &Duration::from_secs(0), &Duration::from_secs(10));
        assert!((r - 1.0).abs() < f64::EPSILON);
        assert_eq!(ms, DurationSecs(10));
        assert_stale_before_expiry(3600, r, ms);
    }

    #[test]
    fn refresh_min_period_exceeds_lifetime() {
        // min_refresh_period (600s) > lifetime (300s) — must be capped
        let (r, ms) = refresh_params(300, &Duration::from_secs(60), &Duration::from_secs(600));
        // desired_delay = 300 - 60 = 240
        assert!((r - 0.8).abs() < f64::EPSILON);
        // min_stale capped to desired_delay, not 600
        assert_eq!(ms, DurationSecs(240));
        assert_stale_before_expiry(300, r, ms);
    }

    #[test]
    fn refresh_zero_lifetime_nonzero_min_period() {
        // expires_in=0 with min_refresh_period=10 — both must be zero
        let (r, ms) = refresh_params(0, &Duration::from_secs(30 * 60), &Duration::from_secs(10));
        assert!((r - 0.0).abs() < f64::EPSILON);
        assert_eq!(ms, DurationSecs(0));
    }
}