rs-identity-model 0.7.0

Production-grade, RFC-compliant OIDC/OAuth2 client library for Rust
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
616
617
618
//! Async OIDC Discovery client: fetch, validate, and cache provider metadata.

use std::time::Duration;

use reqwest::Client as HttpClient;
use reqwest::header::ACCEPT;

use crate::IdentityError;

use super::DiscoveryError;

use super::cache::Cache;
use super::metadata::ProviderMetadata;

/// The discovery document path appended to the issuer (OIDC Discovery 1.0 §4.1).
const WELL_KNOWN_PATH: &str = "/.well-known/openid-configuration";

/// Default lifetime of a cached discovery document.
const DEFAULT_CACHE_TTL: Duration = Duration::from_secs(24 * 60 * 60);

/// Default per-request timeout so a hung server cannot block indefinitely.
const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);

/// Caps the discovery response read into memory. A discovery document is a small
/// JSON object; this guards against an issuer streaming an unbounded body
/// (memory-exhaustion DoS).
const MAX_BODY_BYTES: usize = 1 << 20; // 1 MiB

/// Default maximum number of distinct issuer entries the cache retains. The
/// cache is keyed by issuer URL; without a bound it grows one entry per distinct
/// issuer forever, so a multi-tenant gateway or attacker-supplied issuer header
/// could accumulate entries until the process exhausts memory (unbounded-growth
/// DoS). 64 covers any realistic multi-IdP deployment while keeping worst-case
/// memory bounded. Mirrors the Python reference's `DEFAULT_MAX_CACHE_ENTRIES`.
const DEFAULT_MAX_CACHE_ENTRIES: usize = 64;

/// Environment variable overriding [`DEFAULT_MAX_CACHE_ENTRIES`]. A value of `0`
/// disables the bound (explicit unbounded escape hatch); garbage falls back to
/// the default.
const MAX_CACHE_ENTRIES_ENV: &str = "DISCO_CACHE_MAX_ENTRIES";

/// An async client that fetches, validates, and caches OIDC provider metadata.
///
/// Construct one with [`DiscoveryClient::new`] for the defaults (24h cache TTL,
/// 30s request timeout, HTTPS-only issuers) or [`DiscoveryClient::builder`] to
/// customise them. A single client should be reused across calls so its cache
/// and the underlying connection pool are shared.
///
/// ```no_run
/// # async fn run() -> rs_identity_model::Result<()> {
/// use rs_identity_model::DiscoveryClient;
///
/// let client = DiscoveryClient::new();
/// let metadata = client.discover("https://accounts.example.com").await?;
/// println!("jwks_uri = {}", metadata.jwks_uri);
/// # Ok(())
/// # }
/// ```
pub struct DiscoveryClient {
    http: HttpClient,
    cache: Cache,
    cache_ttl: Duration,
    timeout: Duration,
    allow_http: bool,
}

impl DiscoveryClient {
    /// Returns a client with the default configuration.
    pub fn new() -> Self {
        Self::builder().build()
    }

    /// Returns a builder for customising the client's cache TTL, request
    /// timeout, HTTP client, and HTTPS enforcement.
    pub fn builder() -> DiscoveryClientBuilder {
        DiscoveryClientBuilder::new()
    }

    /// Fetches, validates, and caches the OIDC provider metadata for
    /// `issuer_url`.
    ///
    /// The request targets `{issuer_url}/.well-known/openid-configuration`. A
    /// fresh cache entry is served without any HTTP request (DISC-004); the
    /// entry is refreshed once its TTL elapses (DISC-005). The issuer scheme
    /// must be `https` unless [`DiscoveryClientBuilder::allow_http`] was set
    /// (DISC-010).
    ///
    /// # Errors
    ///
    /// - [`DiscoveryError::HttpsRequired`] — a non-HTTPS issuer (DISC-010).
    /// - [`DiscoveryError::UnexpectedStatus`] — a non-2xx response (DISC-006).
    /// - [`DiscoveryError::InvalidJson`] — a body that is not valid JSON
    ///   metadata (DISC-007).
    /// - [`DiscoveryError::MissingFields`] — a missing required field (DISC-008).
    /// - [`DiscoveryError::IssuerMismatch`] — the document's issuer does not
    ///   match the requested one (DISC-003).
    /// - [`DiscoveryError::Other`] — an empty issuer URL, a transport failure,
    ///   or an oversized body.
    pub async fn discover(
        &self,
        issuer_url: &str,
    ) -> std::result::Result<ProviderMetadata, DiscoveryError> {
        let issuer = issuer_url.trim().trim_end_matches('/').to_string();
        if issuer.is_empty() {
            return Err(IdentityError::Validation("issuer URL is empty".to_string()).into());
        }

        // DISC-004: a fresh cache entry is served without any HTTP request.
        if let Some(metadata) = self.cache.get(&issuer).await {
            return Ok(metadata);
        }

        // DISC-010: require an https issuer unless http was explicitly allowed
        // (for local development / integration against non-TLS providers). URL
        // schemes are case-insensitive (RFC 3986 §3.1), so compare on a
        // lowercased copy while keeping the original-case issuer for the
        // exact-match check and cache key.
        let scheme = issuer.to_ascii_lowercase();
        let is_https = scheme.starts_with("https://");
        let scheme_ok = is_https || (self.allow_http && scheme.starts_with("http://"));
        if !scheme_ok {
            return Err(DiscoveryError::HttpsRequired { issuer });
        }

        let metadata = self.fetch_and_validate(&issuer).await?;
        self.cache
            .put(issuer, metadata.clone(), self.cache_ttl)
            .await;
        Ok(metadata)
    }

    /// Performs the HTTP request, parses the body, and validates the document.
    /// Contains no caching logic.
    async fn fetch_and_validate(
        &self,
        issuer: &str,
    ) -> std::result::Result<ProviderMetadata, DiscoveryError> {
        let endpoint = format!("{issuer}{WELL_KNOWN_PATH}");

        let mut response = self
            .http
            .get(&endpoint)
            .header(ACCEPT, "application/json")
            .timeout(self.timeout)
            .send()
            .await
            .map_err(|e| IdentityError::Http(format!("fetch {endpoint}: {e}")))?;

        // DISC-006: a non-2xx response is a transport error carrying the status.
        let status = response.status();
        if !status.is_success() {
            return Err(DiscoveryError::UnexpectedStatus {
                status: status.as_u16(),
                endpoint,
            });
        }

        // Read the body in chunks so an oversized response is rejected before it
        // is fully buffered, bounding memory regardless of Content-Length.
        let mut body = Vec::new();
        while let Some(chunk) = response
            .chunk()
            .await
            .map_err(|e| IdentityError::Http(format!("read body from {endpoint}: {e}")))?
        {
            if body.len() + chunk.len() > MAX_BODY_BYTES {
                return Err(IdentityError::Deserialization(format!(
                    "discovery document from {endpoint} exceeds {MAX_BODY_BYTES} bytes"
                ))
                .into());
            }
            body.extend_from_slice(&chunk);
        }

        // DISC-007: a non-JSON body is rejected.
        let metadata: ProviderMetadata =
            serde_json::from_slice(&body).map_err(|e| DiscoveryError::InvalidJson {
                endpoint: endpoint.clone(),
                reason: e.to_string(),
            })?;

        // DISC-002 / DISC-008: every required field must be present.
        let missing = metadata.missing_required_fields();
        if !missing.is_empty() {
            return Err(DiscoveryError::MissingFields {
                fields: missing.into_iter().map(str::to_owned).collect(),
                endpoint,
            });
        }

        // DISC-003: the document's issuer must match the requested issuer.
        // Trailing slashes are trimmed on both sides so they normalise
        // symmetrically (a trailing-slash-only difference is not a mismatch).
        if metadata.issuer.trim_end_matches('/') != issuer {
            return Err(DiscoveryError::IssuerMismatch {
                requested: issuer.to_owned(),
                actual: metadata.issuer,
            });
        }

        Ok(metadata)
    }
}

impl Default for DiscoveryClient {
    fn default() -> Self {
        Self::new()
    }
}

/// Builder for [`DiscoveryClient`]. Obtain one via [`DiscoveryClient::builder`].
pub struct DiscoveryClientBuilder {
    http: Option<HttpClient>,
    cache_ttl: Duration,
    timeout: Duration,
    allow_http: bool,
    max_cache_entries: usize,
}

impl DiscoveryClientBuilder {
    /// Returns a builder seeded with the default configuration. The cache bound
    /// defaults to [`DEFAULT_MAX_CACHE_ENTRIES`], overridable by the
    /// `DISCO_CACHE_MAX_ENTRIES` environment variable.
    fn new() -> Self {
        Self {
            http: None,
            cache_ttl: DEFAULT_CACHE_TTL,
            timeout: DEFAULT_TIMEOUT,
            allow_http: false,
            max_cache_entries: crate::env::max_cache_entries_from_env(
                MAX_CACHE_ENTRIES_ENV,
                DEFAULT_MAX_CACHE_ENTRIES,
            ),
        }
    }

    /// Sets how long a fetched document is cached before the next call
    /// re-fetches it. A non-positive duration is ignored and the default (24h)
    /// is retained.
    pub fn cache_ttl(mut self, ttl: Duration) -> Self {
        if !ttl.is_zero() {
            self.cache_ttl = ttl;
        }
        self
    }

    /// Bounds each discovery request with a per-request timeout. A non-positive
    /// duration is ignored and the default (30s) is retained.
    pub fn timeout(mut self, timeout: Duration) -> Self {
        if !timeout.is_zero() {
            self.timeout = timeout;
        }
        self
    }

    /// Permits `http://` issuer URLs, which are otherwise rejected (DISC-010).
    /// Intended for local development and integration tests against non-TLS
    /// providers; do not enable in production.
    pub fn allow_http(mut self, allow: bool) -> Self {
        self.allow_http = allow;
        self
    }

    /// Uses `client` for discovery requests instead of a default
    /// [`reqwest::Client`], letting callers share a connection pool or supply
    /// custom transport configuration.
    pub fn http_client(mut self, client: HttpClient) -> Self {
        self.http = Some(client);
        self
    }

    /// Bounds the number of distinct issuer entries the cache retains, evicting
    /// the least-recently-used entry once the bound is exceeded. The cache is
    /// keyed by issuer URL, so without a bound it grows one entry per distinct
    /// issuer forever (unbounded-growth DoS). Defaults to
    /// [`DEFAULT_MAX_CACHE_ENTRIES`] (overridable via `DISCO_CACHE_MAX_ENTRIES`).
    /// A value of `0` disables the bound (unbounded).
    pub fn max_cache_entries(mut self, max_entries: usize) -> Self {
        self.max_cache_entries = max_entries;
        self
    }

    /// Builds the [`DiscoveryClient`].
    pub fn build(self) -> DiscoveryClient {
        DiscoveryClient {
            http: self.http.unwrap_or_else(crate::http::secure_client),
            cache: Cache::new(self.max_cache_entries),
            cache_ttl: self.cache_ttl,
            timeout: self.timeout,
            allow_http: self.allow_http,
        }
    }
}

impl Default for DiscoveryClientBuilder {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use wiremock::matchers::{method, path};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    /// A valid discovery document whose issuer is `issuer`, including an
    /// unmodelled extension field (DISC-009).
    fn valid_doc(issuer: &str) -> String {
        format!(
            r#"{{
                "issuer": "{issuer}",
                "authorization_endpoint": "{issuer}/auth",
                "token_endpoint": "{issuer}/token",
                "userinfo_endpoint": "{issuer}/userinfo",
                "jwks_uri": "{issuer}/jwks",
                "response_types_supported": ["code", "id_token"],
                "subject_types_supported": ["public"],
                "id_token_signing_alg_values_supported": ["RS256", "ES256"],
                "code_challenge_methods_supported": ["S256"],
                "x_custom_extension_field": "should-be-ignored-not-rejected"
            }}"#
        )
    }

    /// Mounts a single GET handler on the discovery path returning `template`.
    async fn mount(server: &MockServer, template: ResponseTemplate) {
        Mock::given(method("GET"))
            .and(path(WELL_KNOWN_PATH))
            .respond_with(template)
            .mount(server)
            .await;
    }

    // DISC-001 / DISC-002: fetch a valid document; every required field parses
    // with the correct type and is accessible.
    #[tokio::test]
    async fn fetches_and_parses_valid_document() {
        let server = MockServer::start().await;
        let issuer = server.uri();
        mount(
            &server,
            ResponseTemplate::new(200).set_body_string(valid_doc(&issuer)),
        )
        .await;

        let client = DiscoveryClient::builder().allow_http(true).build();
        let meta = client.discover(&issuer).await.expect("discovery succeeds");

        assert_eq!(meta.issuer, issuer);
        assert_eq!(meta.authorization_endpoint, format!("{issuer}/auth"));
        assert_eq!(meta.token_endpoint, format!("{issuer}/token"));
        assert_eq!(meta.jwks_uri, format!("{issuer}/jwks"));
        assert_eq!(meta.response_types_supported, vec!["code", "id_token"]);
        assert_eq!(meta.subject_types_supported, vec!["public"]);
        assert_eq!(
            meta.id_token_signing_alg_values_supported,
            vec!["RS256", "ES256"]
        );
        assert_eq!(
            meta.userinfo_endpoint.as_deref(),
            Some(format!("{issuer}/userinfo").as_str())
        );
    }

    // DISC-003: a document whose issuer differs from the requested issuer is a
    // validation error.
    #[tokio::test]
    async fn rejects_issuer_mismatch() {
        let server = MockServer::start().await;
        let body = valid_doc("https://attacker.example.com");
        mount(&server, ResponseTemplate::new(200).set_body_string(body)).await;

        let client = DiscoveryClient::builder().allow_http(true).build();
        let err = client
            .discover(&server.uri())
            .await
            .expect_err("issuer mismatch must error");

        match err {
            DiscoveryError::IssuerMismatch { requested, actual } => {
                assert_eq!(requested, server.uri());
                assert_eq!(actual, "https://attacker.example.com");
            }
            other => panic!("expected IssuerMismatch, got {other:?}"),
        }
    }

    // DISC-004: a second discover() within the TTL makes no HTTP request.
    #[tokio::test]
    async fn caches_within_ttl() {
        let server = MockServer::start().await;
        let issuer = server.uri();
        mount(
            &server,
            ResponseTemplate::new(200).set_body_string(valid_doc(&issuer)),
        )
        .await;

        let client = DiscoveryClient::builder().allow_http(true).build();
        client.discover(&issuer).await.expect("first fetch");
        client.discover(&issuer).await.expect("cache hit");

        let received = server.received_requests().await.unwrap();
        assert_eq!(received.len(), 1, "second call must be served from cache");
    }

    // DISC-005: once the TTL expires, discover() re-fetches.
    #[tokio::test]
    async fn refreshes_after_ttl_expiry() {
        let server = MockServer::start().await;
        let issuer = server.uri();
        mount(
            &server,
            ResponseTemplate::new(200).set_body_string(valid_doc(&issuer)),
        )
        .await;

        let client = DiscoveryClient::builder()
            .allow_http(true)
            .cache_ttl(Duration::from_millis(10))
            .build();
        client.discover(&issuer).await.expect("first fetch");
        tokio::time::sleep(Duration::from_millis(30)).await;
        client
            .discover(&issuer)
            .await
            .expect("refetch after expiry");

        let received = server.received_requests().await.unwrap();
        assert_eq!(received.len(), 2, "expired entry must be refetched");
    }

    // DISC-006: a non-2xx response is rejected with its status.
    #[tokio::test]
    async fn maps_http_status_errors() {
        for status in [404u16, 500] {
            let server = MockServer::start().await;
            mount(&server, ResponseTemplate::new(status)).await;

            let client = DiscoveryClient::builder().allow_http(true).build();
            let err = client
                .discover(&server.uri())
                .await
                .expect_err("non-2xx must error");

            match err {
                DiscoveryError::UnexpectedStatus { status: got, .. } => assert_eq!(got, status),
                other => panic!("expected UnexpectedStatus for {status}, got {other:?}"),
            }
        }
    }

    // DISC-007: a non-JSON body is rejected.
    #[tokio::test]
    async fn maps_invalid_json() {
        let server = MockServer::start().await;
        mount(
            &server,
            ResponseTemplate::new(200).set_body_string("not-json"),
        )
        .await;

        let client = DiscoveryClient::builder().allow_http(true).build();
        let err = client
            .discover(&server.uri())
            .await
            .expect_err("invalid JSON must error");

        assert!(
            matches!(err, DiscoveryError::InvalidJson { .. }),
            "expected InvalidJson, got {err:?}"
        );
    }

    // DISC-008: a document missing a required field is rejected with that field.
    #[tokio::test]
    async fn reports_missing_required_field() {
        let server = MockServer::start().await;
        let issuer = server.uri();
        // A valid document with jwks_uri removed.
        let body = format!(
            r#"{{
                "issuer": "{issuer}",
                "authorization_endpoint": "{issuer}/auth",
                "token_endpoint": "{issuer}/token",
                "response_types_supported": ["code"],
                "subject_types_supported": ["public"],
                "id_token_signing_alg_values_supported": ["RS256"]
            }}"#
        );
        mount(&server, ResponseTemplate::new(200).set_body_string(body)).await;

        let client = DiscoveryClient::builder().allow_http(true).build();
        let err = client
            .discover(&issuer)
            .await
            .expect_err("missing field must error");

        match err {
            DiscoveryError::MissingFields { fields, .. } => assert_eq!(fields, ["jwks_uri"]),
            other => panic!("expected MissingFields, got {other:?}"),
        }
    }

    // DISC-009: unknown fields are ignored (captured in `extra`), not rejected.
    #[tokio::test]
    async fn ignores_unknown_fields() {
        let server = MockServer::start().await;
        let issuer = server.uri();
        mount(
            &server,
            ResponseTemplate::new(200).set_body_string(valid_doc(&issuer)),
        )
        .await;

        let client = DiscoveryClient::builder().allow_http(true).build();
        let meta = client
            .discover(&issuer)
            .await
            .expect("parses despite extra");

        assert!(meta.extra.contains_key("x_custom_extension_field"));
        assert!(
            !meta.jwks_uri.is_empty(),
            "required fields remain accessible"
        );
    }

    // DISC-010: an http issuer is rejected by default and permitted with
    // allow_http; no HTTP request is made for the rejected case.
    #[tokio::test]
    async fn requires_https_by_default() {
        let client = DiscoveryClient::new();
        let err = client
            .discover("http://insecure.example.com")
            .await
            .expect_err("http issuer must be rejected");

        assert!(
            matches!(err, DiscoveryError::HttpsRequired { .. }),
            "expected HttpsRequired, got {err:?}"
        );
    }

    // DISC-003: a trailing-slash-only difference between the requested issuer
    // and the document issuer is normalised on both sides and is NOT a
    // mismatch. This matches the merged Go reference
    // (go/pkg/discovery/discovery.go:204 + TestFetchConfiguration_TrailingSlash);
    // see decisions.md DEC-001 for the conflict with the epic's "no trailing
    // slash normalization" prose.
    #[tokio::test]
    async fn accepts_trailing_slash_only_difference() {
        let server = MockServer::start().await;
        let issuer = server.uri();
        // Document declares the issuer WITH a trailing slash...
        mount(
            &server,
            ResponseTemplate::new(200).set_body_string(valid_doc(&format!("{issuer}/"))),
        )
        .await;

        let client = DiscoveryClient::builder().allow_http(true).build();
        // ...requested WITHOUT one: still accepted.
        let meta = client
            .discover(&issuer)
            .await
            .expect("trailing-slash-only difference is accepted");

        assert_eq!(meta.issuer, format!("{issuer}/"));
    }

    // DISC-010: URL schemes are case-insensitive (RFC 3986 §3.1), so a
    // mixed-case `HTTP://` / `HTTPS://` scheme passes the scheme gate. The
    // issuer itself stays case-sensitive for the exact-match check.
    #[tokio::test]
    async fn accepts_case_insensitive_scheme() {
        let server = MockServer::start().await;
        let issuer = server.uri();
        let mixed_case = issuer.replacen("http://", "HTTP://", 1);
        mount(
            &server,
            ResponseTemplate::new(200).set_body_string(valid_doc(&mixed_case)),
        )
        .await;

        let client = DiscoveryClient::builder().allow_http(true).build();
        let meta = client
            .discover(&mixed_case)
            .await
            .expect("mixed-case scheme is accepted");

        assert_eq!(meta.issuer, mixed_case);
    }

    // A very large TTL (`Duration::MAX`) must not overflow `Instant` and panic
    // when computing the expiry; the entry is stored and served from cache.
    #[tokio::test]
    async fn handles_max_ttl_without_panicking() {
        let server = MockServer::start().await;
        let issuer = server.uri();
        mount(
            &server,
            ResponseTemplate::new(200).set_body_string(valid_doc(&issuer)),
        )
        .await;

        let client = DiscoveryClient::builder()
            .allow_http(true)
            .cache_ttl(Duration::MAX)
            .build();
        client.discover(&issuer).await.expect("first fetch");
        client.discover(&issuer).await.expect("cache hit");

        let received = server.received_requests().await.unwrap();
        assert_eq!(received.len(), 1, "max-ttl entry stays cached");
    }
}