entropy-auth 2026.7.31

Authentication and authorization for Entropy Softworks server and API projects
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
//! `OpenID` Connect Discovery document parsing.
//!
//! Parses the `.well-known/openid-configuration` JSON document per the
//! `OpenID` Connect Discovery 1.0 specification. Required fields are
//! validated; optional fields default to empty values when absent.

use core::fmt;

use crate::json::JsonValue;
use crate::util::log::{info, warn};
use crate::util::validation::is_https_url;

// ---------------------------------------------------------------------------
// Discovery struct
// ---------------------------------------------------------------------------

/// Parsed OIDC Discovery (`.well-known/openid-configuration`) document.
///
/// Contains the provider metadata required for OIDC client configuration:
/// issuer, endpoints, supported scopes, response types, and signing
/// algorithms.
#[doc(alias = "openid_configuration")]
#[derive(Debug, Clone)]
pub struct OidcDiscovery {
    /// The issuer identifier (must exactly match the `iss` claim in ID tokens).
    issuer: String,
    /// URL of the authorization endpoint.
    authorization_endpoint: String,
    /// URL of the token endpoint.
    token_endpoint: String,
    /// URL of the `UserInfo` endpoint (optional per spec).
    userinfo_endpoint: Option<String>,
    /// URL of the JWKS endpoint for signature verification keys.
    jwks_uri: String,
    /// OAuth 2.0 scopes supported by this provider.
    scopes_supported: Vec<String>,
    /// OAuth 2.0 response types supported by this provider.
    response_types_supported: Vec<String>,
    /// JWS `alg` values supported for ID token signing.
    id_token_signing_alg_values_supported: Vec<String>,
}

impl OidcDiscovery {
    /// Returns the issuer identifier.
    #[must_use]
    #[inline]
    pub fn issuer(&self) -> &str {
        &self.issuer
    }

    /// Returns the authorization endpoint URL.
    #[must_use]
    #[inline]
    pub fn authorization_endpoint(&self) -> &str {
        &self.authorization_endpoint
    }

    /// Returns the token endpoint URL.
    #[must_use]
    #[inline]
    pub fn token_endpoint(&self) -> &str {
        &self.token_endpoint
    }

    /// Returns the `UserInfo` endpoint URL, if present.
    #[must_use]
    #[inline]
    pub fn userinfo_endpoint(&self) -> Option<&str> {
        self.userinfo_endpoint.as_deref()
    }

    /// Returns the JWKS endpoint URL.
    #[must_use]
    #[inline]
    pub fn jwks_uri(&self) -> &str {
        &self.jwks_uri
    }

    /// Returns the supported OAuth 2.0 scopes.
    #[must_use]
    #[inline]
    pub fn scopes_supported(&self) -> &[String] {
        &self.scopes_supported
    }

    /// Returns the supported OAuth 2.0 response types.
    #[must_use]
    #[inline]
    pub fn response_types_supported(&self) -> &[String] {
        &self.response_types_supported
    }

    /// Returns the supported JWS signing algorithms for ID tokens.
    #[must_use]
    #[inline]
    pub fn id_token_signing_alg_values_supported(&self) -> &[String] {
        &self.id_token_signing_alg_values_supported
    }
}

impl OidcDiscovery {
    /// Parses an OIDC Discovery document from its JSON representation.
    ///
    /// # Errors
    ///
    /// Returns [`OidcDiscoveryError`] if the JSON is malformed or any
    /// required field is missing.
    pub fn parse(json: &str) -> Result<Self, OidcDiscoveryError> {
        let value = JsonValue::parse(json).map_err(|_| {
            warn!("oidc: discovery parse failed");
            OidcDiscoveryError {
                kind: OidcDiscoveryErrorKind::InvalidJson,
            }
        })?;

        let log_parse_failure = |_: &OidcDiscoveryError| {
            warn!("oidc: discovery parse failed");
        };

        // SECURITY: The issuer identifier must use HTTPS per OpenID Connect
        // Discovery 1.0 §4.1. An HTTP issuer would allow token forgery via
        // man-in-the-middle attacks.
        let issuer = required_https_url(&value, "issuer").inspect_err(log_parse_failure)?;
        // SECURITY: per OpenID Connect Discovery §3 / RFC 8414 §2 the issuer
        // identifier MUST be a bare `https` URL with no query or fragment
        // component. Rejecting these prevents a sloppy/hostile discovery
        // document from smuggling a confusing issuer that is later string-
        // compared against the token's `iss` claim.
        if issuer.contains(['?', '#']) {
            let err = OidcDiscoveryError {
                kind: OidcDiscoveryErrorKind::MalformedIssuer,
            };
            log_parse_failure(&err);
            return Err(err);
        }
        // SECURITY: Enforce HTTPS on all endpoint URLs to prevent
        // credential leakage if the discovery document is compromised.
        let authorization_endpoint =
            required_https_url(&value, "authorization_endpoint").inspect_err(log_parse_failure)?;
        let token_endpoint =
            required_https_url(&value, "token_endpoint").inspect_err(log_parse_failure)?;
        let jwks_uri = required_https_url(&value, "jwks_uri").inspect_err(log_parse_failure)?;

        let userinfo_endpoint = match value.get_str("userinfo_endpoint") {
            Some(url) if !is_https_url(url) => {
                let err = OidcDiscoveryError {
                    kind: OidcDiscoveryErrorKind::InsecureEndpoint("userinfo_endpoint".to_string()),
                };
                log_parse_failure(&err);
                return Err(err);
            }
            Some(url) => Some(String::from(url)),
            None => None,
        };

        let scopes_supported = string_array(&value, "scopes_supported");
        let response_types_supported = string_array(&value, "response_types_supported");
        let id_token_signing_alg_values_supported =
            string_array(&value, "id_token_signing_alg_values_supported");

        info!(issuer = %issuer, "oidc: discovery parsed");

        Ok(Self {
            issuer,
            authorization_endpoint,
            token_endpoint,
            userinfo_endpoint,
            jwks_uri,
            scopes_supported,
            response_types_supported,
            id_token_signing_alg_values_supported,
        })
    }
}

/// Extracts a required string field from a JSON object.
fn required_str(value: &JsonValue, key: &str) -> Result<String, OidcDiscoveryError> {
    value
        .get_str(key)
        .map(String::from)
        .ok_or_else(|| OidcDiscoveryError {
            kind: OidcDiscoveryErrorKind::MissingField(key.to_string()),
        })
}

/// Extracts a required endpoint URL and validates it uses HTTPS.
///
/// SECURITY: Discovery documents fetched from an OIDC provider could
/// redirect token exchanges to HTTP endpoints if not validated, leaking
/// credentials in transit.
fn required_https_url(value: &JsonValue, key: &str) -> Result<String, OidcDiscoveryError> {
    let url = required_str(value, key)?;
    if !is_https_url(&url) {
        return Err(OidcDiscoveryError {
            kind: OidcDiscoveryErrorKind::InsecureEndpoint(key.to_string()),
        });
    }
    Ok(url)
}

/// Extracts an optional array of strings from a JSON object.
///
/// Returns an empty `Vec` if the key is absent or not an array.
fn string_array(value: &JsonValue, key: &str) -> Vec<String> {
    value
        .get(key)
        .and_then(JsonValue::as_array)
        .map(|arr| {
            arr.iter()
                .filter_map(JsonValue::as_str)
                .map(String::from)
                .collect()
        })
        .unwrap_or_default()
}

// ---------------------------------------------------------------------------
// Error type
// ---------------------------------------------------------------------------

/// The category of OIDC Discovery parse failure.
#[derive(Debug, Clone, PartialEq, Eq)]
enum OidcDiscoveryErrorKind {
    /// The input is not valid JSON.
    InvalidJson,
    /// A required field is missing from the document.
    MissingField(String),
    /// An endpoint URL does not use HTTPS.
    InsecureEndpoint(String),
    /// The issuer identifier contains a query or fragment component
    /// (forbidden by `OpenID` Connect Discovery §3 / RFC 8414 §2).
    MalformedIssuer,
}

/// Error returned when OIDC Discovery document parsing fails.
#[doc(alias = "discovery_error")]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OidcDiscoveryError {
    kind: OidcDiscoveryErrorKind,
}

impl fmt::Display for OidcDiscoveryError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self.kind {
            OidcDiscoveryErrorKind::InvalidJson => {
                write!(f, "oidc discovery: invalid JSON")
            }
            OidcDiscoveryErrorKind::MissingField(field) => {
                write!(f, "oidc discovery: missing required field '{field}'")
            }
            OidcDiscoveryErrorKind::InsecureEndpoint(field) => {
                write!(f, "oidc discovery: endpoint '{field}' must use HTTPS")
            }
            OidcDiscoveryErrorKind::MalformedIssuer => {
                write!(
                    f,
                    "oidc discovery: issuer must not contain a query or fragment"
                )
            }
        }
    }
}

impl std::error::Error for OidcDiscoveryError {}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;

    /// A complete, valid discovery document for testing.
    const VALID_DISCOVERY: &str = r#"{
        "issuer": "https://accounts.example.com",
        "authorization_endpoint": "https://accounts.example.com/authorize",
        "token_endpoint": "https://accounts.example.com/token",
        "userinfo_endpoint": "https://accounts.example.com/userinfo",
        "jwks_uri": "https://accounts.example.com/.well-known/jwks.json",
        "scopes_supported": ["openid", "profile", "email"],
        "response_types_supported": ["code", "id_token", "code id_token"],
        "id_token_signing_alg_values_supported": ["HS256", "RS256"]
    }"#;

    #[test]
    fn parse_valid_discovery_doc() {
        let doc = OidcDiscovery::parse(VALID_DISCOVERY).unwrap();
        assert_eq!(doc.issuer(), "https://accounts.example.com");
        assert_eq!(
            doc.authorization_endpoint(),
            "https://accounts.example.com/authorize",
        );
        assert_eq!(doc.token_endpoint(), "https://accounts.example.com/token");
        assert_eq!(
            doc.userinfo_endpoint(),
            Some("https://accounts.example.com/userinfo"),
        );
        assert_eq!(
            doc.jwks_uri(),
            "https://accounts.example.com/.well-known/jwks.json",
        );
        assert_eq!(doc.scopes_supported(), ["openid", "profile", "email"]);
        assert_eq!(
            doc.response_types_supported(),
            ["code", "id_token", "code id_token"],
        );
        assert_eq!(
            doc.id_token_signing_alg_values_supported(),
            ["HS256", "RS256"],
        );
    }

    #[test]
    fn parse_missing_issuer() {
        let json = r#"{
            "authorization_endpoint": "https://example.com/authorize",
            "token_endpoint": "https://example.com/token",
            "jwks_uri": "https://example.com/jwks"
        }"#;
        let err = OidcDiscovery::parse(json).unwrap_err();
        assert!(err.to_string().contains("issuer"), "got: {err}");
    }

    #[test]
    fn parse_missing_authorization_endpoint() {
        let json = r#"{
            "issuer": "https://example.com",
            "token_endpoint": "https://example.com/token",
            "jwks_uri": "https://example.com/jwks"
        }"#;
        let err = OidcDiscovery::parse(json).unwrap_err();
        assert!(
            err.to_string().contains("authorization_endpoint"),
            "got: {err}",
        );
    }

    #[test]
    fn parse_missing_token_endpoint() {
        let json = r#"{
            "issuer": "https://example.com",
            "authorization_endpoint": "https://example.com/authorize",
            "jwks_uri": "https://example.com/jwks"
        }"#;
        let err = OidcDiscovery::parse(json).unwrap_err();
        assert!(err.to_string().contains("token_endpoint"), "got: {err}");
    }

    #[test]
    fn parse_missing_jwks_uri() {
        let json = r#"{
            "issuer": "https://example.com",
            "authorization_endpoint": "https://example.com/authorize",
            "token_endpoint": "https://example.com/token"
        }"#;
        let err = OidcDiscovery::parse(json).unwrap_err();
        assert!(err.to_string().contains("jwks_uri"), "got: {err}");
    }

    #[test]
    fn parse_optional_userinfo_absent() {
        let json = r#"{
            "issuer": "https://example.com",
            "authorization_endpoint": "https://example.com/authorize",
            "token_endpoint": "https://example.com/token",
            "jwks_uri": "https://example.com/jwks"
        }"#;
        let doc = OidcDiscovery::parse(json).unwrap();
        assert_eq!(doc.userinfo_endpoint(), None);
        assert!(doc.scopes_supported().is_empty());
        assert!(doc.response_types_supported().is_empty());
        assert!(doc.id_token_signing_alg_values_supported().is_empty());
    }

    #[test]
    fn parse_invalid_json() {
        let err = OidcDiscovery::parse("not json at all").unwrap_err();
        assert!(err.to_string().contains("JSON"), "got: {err}");
    }

    #[test]
    fn parse_rejects_issuer_with_query_or_fragment() {
        // RFC 8414 §2 / OIDC Discovery §3: the issuer must carry no query
        // or fragment. A document smuggling one (e.g. to confuse a later
        // `iss` string comparison) must be rejected.
        for issuer in [
            "https://accounts.example.com/?x=https://evil.example.com",
            "https://accounts.example.com/#frag",
        ] {
            let json = format!(
                r#"{{
                    "issuer": "{issuer}",
                    "authorization_endpoint": "https://accounts.example.com/authorize",
                    "token_endpoint": "https://accounts.example.com/token",
                    "jwks_uri": "https://accounts.example.com/jwks"
                }}"#,
            );
            let err = OidcDiscovery::parse(&json).unwrap_err();
            assert!(err.to_string().contains("query or fragment"), "got: {err}");
        }
    }

    #[test]
    fn error_implements_std_error() {
        let err: Box<dyn std::error::Error> = Box::new(OidcDiscoveryError {
            kind: OidcDiscoveryErrorKind::InvalidJson,
        });
        let _ = err.to_string();
    }

    // --- SECURITY: HTTPS enforcement on endpoints ---

    #[test]
    fn reject_http_authorization_endpoint() {
        let json = r#"{
            "issuer": "https://example.com",
            "authorization_endpoint": "http://example.com/authorize",
            "token_endpoint": "https://example.com/token",
            "jwks_uri": "https://example.com/jwks"
        }"#;
        let err = OidcDiscovery::parse(json).unwrap_err();
        assert!(err.to_string().contains("HTTPS"), "got: {err}");
    }

    #[test]
    fn reject_http_token_endpoint() {
        let json = r#"{
            "issuer": "https://example.com",
            "authorization_endpoint": "https://example.com/authorize",
            "token_endpoint": "http://example.com/token",
            "jwks_uri": "https://example.com/jwks"
        }"#;
        let err = OidcDiscovery::parse(json).unwrap_err();
        assert!(err.to_string().contains("HTTPS"), "got: {err}");
    }

    #[test]
    fn reject_http_jwks_uri() {
        let json = r#"{
            "issuer": "https://example.com",
            "authorization_endpoint": "https://example.com/authorize",
            "token_endpoint": "https://example.com/token",
            "jwks_uri": "http://example.com/jwks"
        }"#;
        let err = OidcDiscovery::parse(json).unwrap_err();
        assert!(err.to_string().contains("HTTPS"), "got: {err}");
    }

    #[test]
    fn reject_http_userinfo_endpoint() {
        let json = r#"{
            "issuer": "https://example.com",
            "authorization_endpoint": "https://example.com/authorize",
            "token_endpoint": "https://example.com/token",
            "jwks_uri": "https://example.com/jwks",
            "userinfo_endpoint": "http://example.com/userinfo"
        }"#;
        let err = OidcDiscovery::parse(json).unwrap_err();
        assert!(err.to_string().contains("HTTPS"), "got: {err}");
    }

    #[test]
    fn insecure_endpoint_error_display() {
        let err = OidcDiscoveryError {
            kind: OidcDiscoveryErrorKind::InsecureEndpoint("token_endpoint".to_string()),
        };
        assert_eq!(
            err.to_string(),
            "oidc discovery: endpoint 'token_endpoint' must use HTTPS",
        );
    }
}