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
//! Standard OIDC ID token claims.
//!
//! Extracts the standard claims defined by `OpenID` Connect Core 1.0 §2
//! from a parsed [`JwtClaims`] structure. Required claims (`iss`, `sub`,
//! `aud`, `exp`, `iat`) are validated for presence; optional claims
//! (`nonce`, `email`, `name`, etc.) are extracted when present.

use core::fmt;

use crate::jwt::JwtClaims;

use super::standard_claims::StandardClaims;

// ---------------------------------------------------------------------------
// Claims struct
// ---------------------------------------------------------------------------

/// Parsed standard OIDC ID token claims.
///
/// Contains the required and commonly-used optional claims from an
/// `OpenID` Connect ID token per OIDC Core 1.0 §2.
#[doc(alias = "id_token_claims")]
#[derive(Debug, Clone)]
pub struct IdTokenClaims {
    /// Issuer identifier.
    iss: String,
    /// Subject identifier (unique user ID at the issuer).
    sub: String,
    /// Audience(s) the token is intended for.
    aud: Vec<String>,
    /// Expiration time (seconds since Unix epoch).
    exp: u64,
    /// Issued-at time (seconds since Unix epoch).
    iat: u64,
    /// Nonce value (if the authentication request included one).
    nonce: Option<String>,
    /// Authorized party — the `client_id` the token was issued to. Required
    /// by OIDC Core §3.1.3.7 to be checked when `aud` has multiple values.
    azp: Option<String>,
    /// Standard profile claims shared with `UserInfo`.
    standard: StandardClaims,
}

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

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

    /// Returns the audience(s) the token is intended for.
    #[must_use]
    #[inline]
    pub fn aud(&self) -> &[String] {
        &self.aud
    }

    /// Returns the expiration time (seconds since Unix epoch).
    #[must_use]
    #[inline]
    pub fn exp(&self) -> u64 {
        self.exp
    }

    /// Returns the issued-at time (seconds since Unix epoch).
    #[must_use]
    #[inline]
    pub fn iat(&self) -> u64 {
        self.iat
    }

    /// Returns the nonce value, if present.
    #[must_use]
    #[inline]
    pub fn nonce(&self) -> Option<&str> {
        self.nonce.as_deref()
    }

    /// Returns the authorized party (`azp`) claim, if present.
    ///
    /// Per OIDC Core §3.1.3.7, when the token's audience contains more than
    /// one value this claim identifies the `client_id` the token was issued
    /// to and must equal the relying party's own client ID.
    #[must_use]
    #[inline]
    pub fn azp(&self) -> Option<&str> {
        self.azp.as_deref()
    }

    /// Returns the user's email address, if present.
    #[must_use]
    #[inline]
    pub fn email(&self) -> Option<&str> {
        self.standard.email()
    }

    /// Returns whether the user's email has been verified, if present.
    #[must_use]
    #[inline]
    pub fn email_verified(&self) -> Option<bool> {
        self.standard.email_verified()
    }

    /// Returns the user's full name, if present.
    #[must_use]
    #[inline]
    pub fn name(&self) -> Option<&str> {
        self.standard.name()
    }

    /// Returns the user's preferred username, if present.
    #[must_use]
    #[inline]
    pub fn preferred_username(&self) -> Option<&str> {
        self.standard.preferred_username()
    }

    /// Returns the URL of the user's profile picture, if present.
    #[must_use]
    #[inline]
    pub fn picture(&self) -> Option<&str> {
        self.standard.picture()
    }
}

/// Extracts an optional string claim from JWT claims by key.
fn optional_string_claim(claims: &JwtClaims, key: &str) -> Option<String> {
    claims
        .get_claim(key)
        .and_then(|v| v.as_str())
        .map(String::from)
}

/// Coerces a boolean-ish OIDC claim (e.g. `email_verified`) to a `bool`.
///
/// The OIDC spec defines `email_verified` as a JSON boolean, but some
/// identity providers historically emit the string forms `"true"` /
/// `"false"`. Accept both so a verified user is never silently treated as
/// unverified; any other shape yields `None`.
pub(super) fn coerce_bool_claim(value: &crate::json::JsonValue) -> Option<bool> {
    if let Some(b) = value.as_bool() {
        return Some(b);
    }
    match value.as_str()? {
        "true" => Some(true),
        "false" => Some(false),
        _ => None,
    }
}

impl IdTokenClaims {
    /// Extracts OIDC ID token claims from parsed JWT claims.
    ///
    /// Required claims (`iss`, `sub`, `aud`, `exp`, `iat`) must be present
    /// in the JWT payload. Optional claims are extracted when available.
    ///
    /// # Errors
    ///
    /// Returns [`IdTokenClaimsError`] if any required claim is missing (an
    /// empty `iss`/`sub` string counts as missing).
    pub fn from_jwt_claims(claims: &JwtClaims) -> Result<Self, IdTokenClaimsError> {
        // An empty `iss`/`sub` is malformed: treat it as missing rather than
        // a valid (and trivially-collidable) identifier — an empty `sub`
        // could otherwise satisfy a naive equality join against another
        // empty subject.
        let iss = claims
            .iss()
            .filter(|s| !s.is_empty())
            .map(String::from)
            .ok_or_else(|| IdTokenClaimsError::missing("iss"))?;
        let sub = claims
            .sub()
            .filter(|s| !s.is_empty())
            .map(String::from)
            .ok_or_else(|| IdTokenClaimsError::missing("sub"))?;

        if claims.aud().is_empty() {
            return Err(IdTokenClaimsError::missing("aud"));
        }
        let aud = claims.aud().to_vec();

        let exp = claims
            .exp()
            .ok_or_else(|| IdTokenClaimsError::missing("exp"))?;
        let iat = claims
            .iat()
            .ok_or_else(|| IdTokenClaimsError::missing("iat"))?;

        // Optional standard claims — extracted from the raw JSON payload.
        let nonce = optional_string_claim(claims, "nonce");
        let azp = optional_string_claim(claims, "azp");

        let standard = StandardClaims::new(
            optional_string_claim(claims, "name"),
            optional_string_claim(claims, "email"),
            claims
                .get_claim("email_verified")
                .and_then(coerce_bool_claim),
            optional_string_claim(claims, "preferred_username"),
            optional_string_claim(claims, "picture"),
        );

        Ok(Self {
            iss,
            sub,
            aud,
            exp,
            iat,
            nonce,
            azp,
            standard,
        })
    }
}

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

/// The category of ID token claims extraction failure.
#[derive(Debug, Clone, PartialEq, Eq)]
enum IdTokenClaimsErrorKind {
    /// A required claim is missing from the ID token.
    MissingClaim(String),
}

/// Error returned when OIDC ID token claims extraction fails.
///
/// Error messages identify the missing claim name but never include
/// the raw claim values to avoid leaking user data.
#[doc(alias = "id_claims_error")]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IdTokenClaimsError {
    kind: IdTokenClaimsErrorKind,
}

impl IdTokenClaimsError {
    /// Creates an error for a missing required claim.
    fn missing(claim: &str) -> Self {
        Self {
            kind: IdTokenClaimsErrorKind::MissingClaim(claim.to_string()),
        }
    }

    /// Returns the name of the missing claim, if applicable.
    #[must_use]
    pub(crate) fn claim_name(&self) -> &str {
        match &self.kind {
            IdTokenClaimsErrorKind::MissingClaim(name) => name,
        }
    }
}

impl fmt::Display for IdTokenClaimsError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self.kind {
            IdTokenClaimsErrorKind::MissingClaim(claim) => {
                write!(f, "oidc id token: missing required claim '{claim}'")
            }
        }
    }
}

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

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

#[cfg(test)]
mod tests {
    use super::*;
    use crate::encoding::base64url_encode;
    use crate::jwt::JwtClaims;

    /// Helper: encode a JSON string as base64url and parse as JWT claims.
    fn parse_claims(json: &str) -> JwtClaims {
        let b64 = base64url_encode(json.as_bytes());
        JwtClaims::parse(&b64).unwrap()
    }

    #[test]
    fn extract_full_claims() {
        let jwt_claims = parse_claims(
            r#"{
                "iss": "https://accounts.example.com",
                "sub": "user-123",
                "aud": "my-client",
                "exp": 1700000000,
                "iat": 1699999000,
                "nonce": "abc123",
                "email": "user@example.com",
                "email_verified": true,
                "name": "Test User",
                "preferred_username": "testuser",
                "picture": "https://example.com/photo.jpg"
            }"#,
        );
        let claims = IdTokenClaims::from_jwt_claims(&jwt_claims).unwrap();

        assert_eq!(claims.iss(), "https://accounts.example.com");
        assert_eq!(claims.sub(), "user-123");
        assert_eq!(claims.aud(), ["my-client"]);
        assert_eq!(claims.exp(), 1_700_000_000);
        assert_eq!(claims.iat(), 1_699_999_000);
        assert_eq!(claims.nonce(), Some("abc123"));
        assert_eq!(claims.email(), Some("user@example.com"));
        assert_eq!(claims.email_verified(), Some(true));
        assert_eq!(claims.name(), Some("Test User"));
        assert_eq!(claims.preferred_username(), Some("testuser"));
        assert_eq!(claims.picture(), Some("https://example.com/photo.jpg"));
    }

    #[test]
    fn email_verified_accepts_string_boolean() {
        // Some IdPs emit `email_verified` as the string "true"/"false";
        // coerce both so a verified user is not read as unverified.
        let claims = IdTokenClaims::from_jwt_claims(&parse_claims(
            r#"{
                "iss": "https://example.com",
                "sub": "user-1",
                "aud": "client-id",
                "exp": 9999999999,
                "iat": 1000,
                "email_verified": "true"
            }"#,
        ))
        .unwrap();
        assert_eq!(claims.email_verified(), Some(true));

        let claims = IdTokenClaims::from_jwt_claims(&parse_claims(
            r#"{
                "iss": "https://example.com",
                "sub": "user-1",
                "aud": "client-id",
                "exp": 9999999999,
                "iat": 1000,
                "email_verified": "false"
            }"#,
        ))
        .unwrap();
        assert_eq!(claims.email_verified(), Some(false));
    }

    #[test]
    fn extract_minimal_required_claims() {
        let jwt_claims = parse_claims(
            r#"{
                "iss": "https://example.com",
                "sub": "user-1",
                "aud": "client-id",
                "exp": 9999999999,
                "iat": 1000
            }"#,
        );
        let claims = IdTokenClaims::from_jwt_claims(&jwt_claims).unwrap();

        assert_eq!(claims.iss(), "https://example.com");
        assert_eq!(claims.sub(), "user-1");
        assert_eq!(claims.aud(), ["client-id"]);
        assert_eq!(claims.nonce(), None::<&str>);
        assert_eq!(claims.email(), None::<&str>);
        assert_eq!(claims.email_verified(), None);
        assert_eq!(claims.name(), None::<&str>);
        assert_eq!(claims.preferred_username(), None::<&str>);
        assert_eq!(claims.picture(), None::<&str>);
    }

    #[test]
    fn missing_iss() {
        let jwt_claims = parse_claims(r#"{"sub": "user-1", "aud": "c", "exp": 1000, "iat": 1000}"#);
        let err = IdTokenClaims::from_jwt_claims(&jwt_claims).unwrap_err();
        assert!(err.to_string().contains("iss"), "got: {err}");
    }

    #[test]
    fn missing_sub() {
        let jwt_claims =
            parse_claims(r#"{"iss": "https://example.com", "aud": "c", "exp": 1000, "iat": 1000}"#);
        let err = IdTokenClaims::from_jwt_claims(&jwt_claims).unwrap_err();
        assert!(err.to_string().contains("sub"), "got: {err}");
    }

    #[test]
    fn empty_sub_is_rejected_as_missing() {
        let jwt_claims = parse_claims(
            r#"{"iss": "https://example.com", "sub": "", "aud": "c", "exp": 1000, "iat": 1000}"#,
        );
        let err = IdTokenClaims::from_jwt_claims(&jwt_claims).unwrap_err();
        assert!(err.to_string().contains("sub"), "got: {err}");
    }

    #[test]
    fn empty_iss_is_rejected_as_missing() {
        let jwt_claims =
            parse_claims(r#"{"iss": "", "sub": "u", "aud": "c", "exp": 1000, "iat": 1000}"#);
        let err = IdTokenClaims::from_jwt_claims(&jwt_claims).unwrap_err();
        assert!(err.to_string().contains("iss"), "got: {err}");
    }

    #[test]
    fn missing_aud() {
        let jwt_claims =
            parse_claims(r#"{"iss": "https://example.com", "sub": "u", "exp": 1000, "iat": 1000}"#);
        let err = IdTokenClaims::from_jwt_claims(&jwt_claims).unwrap_err();
        assert!(err.to_string().contains("aud"), "got: {err}");
    }

    #[test]
    fn missing_exp() {
        let jwt_claims =
            parse_claims(r#"{"iss": "https://example.com", "sub": "u", "aud": "c", "iat": 1000}"#);
        let err = IdTokenClaims::from_jwt_claims(&jwt_claims).unwrap_err();
        assert!(err.to_string().contains("exp"), "got: {err}");
    }

    #[test]
    fn missing_iat() {
        let jwt_claims =
            parse_claims(r#"{"iss": "https://example.com", "sub": "u", "aud": "c", "exp": 1000}"#);
        let err = IdTokenClaims::from_jwt_claims(&jwt_claims).unwrap_err();
        assert!(err.to_string().contains("iat"), "got: {err}");
    }

    #[test]
    fn error_implements_std_error() {
        let err: Box<dyn std::error::Error> = Box::new(IdTokenClaimsError::missing("test"));
        let _ = err.to_string();
    }
}