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
//! OIDC ID-token claims helper (`OpenID` Connect Core §2, §3.1.3.6).
//!
//! [`IdTokenBuilder`] is a thin convenience that assembles the standard
//! ID-token claims an authorization server emits and feeds them into the
//! generic [`JwtEncoder`](crate::jwt::JwtEncoder). It exists so the `IdP` does
//! not have to remember which claim is registered (`iss`, `sub`, `aud`,
//! `exp`, `iat`, `nonce`) versus standard-profile (`email`,
//! `email_verified`, `name`, `preferred_username`) versus deployment-custom
//! (`roles`, `groups`, `tenant`).
//!
//! It deliberately wraps rather than reimplements: the actual signing,
//! JSON emission, and `alg=none`-is-unrepresentable guarantee all come from
//! [`JwtEncoder`]. For OIDC the signing key is the relying party's
//! `client_secret` (the `client_secret_jwt`-style symmetric signing of OIDC
//! Core §10.1), so the produced token verifies with the crate's existing
//! [`verify_jwt`](crate::jwt::verify_jwt) and the `oidc` feature's
//! `IdTokenValidator`.
//!
//! # Example
//!
//! ```
//! use entropy_auth::jwt::JwtSigningAlgorithm;
//! use entropy_auth::oauth::server::IdTokenBuilder;
//! use entropy_auth::verify_jwt;
//!
//! let token = IdTokenBuilder::new("https://auth.example.com", "user-123", "entropy_website")
//!     .issued_at(1_700_000_000)
//!     .expiration(1_700_003_600)
//!     .nonce("n-0S6_WzA2Mj")
//!     .email("frodo@example.com", true)
//!     .name("Frodo Baggins")
//!     .preferred_username("frodo")
//!     .roles(["user", "developer"])
//!     .tenant("entropy")
//!     .sign(JwtSigningAlgorithm::Hs256, b"client-secret");
//!
//! let (_, claims) = verify_jwt(&token, b"client-secret").unwrap();
//! assert_eq!(claims.sub(), Some("user-123"));
//! assert!(claims.validate_aud("entropy_website"));
//! ```

use crate::jwt::{CustomClaimValueOpaque, IntoCustomClaim, JwtEncoder, JwtSigningAlgorithm};

// ---------------------------------------------------------------------------
// Builder
// ---------------------------------------------------------------------------

/// Builds OIDC ID-token claims and signs them as a JWT.
///
/// The three mandatory ID-token claims — `iss`, `sub`, `aud` (OIDC Core
/// §2) — are required at construction; the temporal claims and standard
/// profile claims are optional setters. Although `iat` and `exp` are
/// mandatory in a spec-complete ID token, they are left as setters so the
/// caller supplies its own clock and lifetime (the crate is time-source
/// free); callers SHOULD always set both.
#[doc(alias = "id_token")]
#[derive(Debug, Clone)]
#[must_use = "a builder does nothing until `sign` is called"]
pub struct IdTokenBuilder {
    issuer: String,
    subject: String,
    audience: String,
    iat: Option<u64>,
    exp: Option<u64>,
    nonce: Option<String>,
    auth_time: Option<u64>,
    email: Option<String>,
    email_verified: Option<bool>,
    name: Option<String>,
    preferred_username: Option<String>,
    roles: Option<Vec<String>>,
    groups: Option<Vec<String>>,
    tenant: Option<String>,
    extra: Vec<(String, CustomClaimValueOpaque)>,
}

impl IdTokenBuilder {
    /// Starts an ID token with the three mandatory claims.
    ///
    /// * `issuer` — the `iss` claim (the `IdP`'s issuer identifier).
    /// * `subject` — the `sub` claim (the authenticated user's stable id).
    /// * `audience` — the `aud` claim (the relying party's `client_id`).
    pub fn new(
        issuer: impl Into<String>,
        subject: impl Into<String>,
        audience: impl Into<String>,
    ) -> Self {
        Self {
            issuer: issuer.into(),
            subject: subject.into(),
            audience: audience.into(),
            iat: None,
            exp: None,
            nonce: None,
            auth_time: None,
            email: None,
            email_verified: None,
            name: None,
            preferred_username: None,
            roles: None,
            groups: None,
            tenant: None,
            extra: Vec::new(),
        }
    }

    /// Sets the issued-at (`iat`) claim as seconds since the Unix epoch.
    pub fn issued_at(mut self, iat: u64) -> Self {
        self.iat = Some(iat);
        self
    }

    /// Sets the expiration (`exp`) claim as seconds since the Unix epoch.
    pub fn expiration(mut self, exp: u64) -> Self {
        self.exp = Some(exp);
        self
    }

    /// Sets the `nonce` claim, binding the token to the authorization
    /// request (OIDC Core §3.1.3.6).
    pub fn nonce(mut self, nonce: impl Into<String>) -> Self {
        self.nonce = Some(nonce.into());
        self
    }

    /// Sets the `auth_time` claim — the time of the end-user's authentication
    /// as seconds since the Unix epoch (OIDC Core §2). REQUIRED when the
    /// authorization request asked for `max_age` (or `auth_time` as an
    /// essential claim); the caller decides when to emit it.
    pub fn auth_time(mut self, auth_time: u64) -> Self {
        self.auth_time = Some(auth_time);
        self
    }

    /// Sets the `email` and `email_verified` standard claims.
    pub fn email(mut self, email: impl Into<String>, verified: bool) -> Self {
        self.email = Some(email.into());
        self.email_verified = Some(verified);
        self
    }

    /// Sets the `name` standard claim (the user's full display name).
    pub fn name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }

    /// Sets the `preferred_username` standard claim.
    pub fn preferred_username(mut self, username: impl Into<String>) -> Self {
        self.preferred_username = Some(username.into());
        self
    }

    /// Sets the deployment-custom `roles` claim (a string array).
    pub fn roles<I, S>(mut self, roles: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.roles = Some(roles.into_iter().map(Into::into).collect());
        self
    }

    /// Sets the deployment-custom `groups` claim (a string array of the
    /// user's directory group names). Emitted only when the caller opts in
    /// (e.g. behind a per-client toggle), so a token never carries group
    /// membership a relying party wasn't configured to receive.
    pub fn groups<I, S>(mut self, groups: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.groups = Some(groups.into_iter().map(Into::into).collect());
        self
    }

    /// Sets the deployment-custom `tenant` claim.
    pub fn tenant(mut self, tenant: impl Into<String>) -> Self {
        self.tenant = Some(tenant.into());
        self
    }

    /// Adds a deployment-defined **custom claim** (per-client "claims
    /// mapping"). Emitted after the standard claims, so a custom claim whose
    /// name collides with a standard one (`sub`, `roles`, `groups`, …) is
    /// dropped by the encoder — the standard setter always wins. Repeated
    /// custom names keep the first value. Accepts the same value shapes as
    /// [`JwtEncoder::custom_claim`](crate::jwt::JwtEncoder::custom_claim)
    /// (string, bool, integer, string array).
    pub fn extra_claim(mut self, name: impl Into<String>, value: impl IntoCustomClaim) -> Self {
        self.extra.push((name.into(), value.into_custom_claim()));
        self
    }

    /// Assembles the claim set onto a [`JwtEncoder`], ready to sign.
    ///
    /// Both [`sign`](Self::sign) (HMAC) and
    /// [`sign_asymmetric`](Self::sign_asymmetric) (EdDSA/ES256) funnel
    /// through here, so the two signing paths emit byte-identical claims and
    /// differ only in the signature — there is no second place a claim can be
    /// added or renamed for only one algorithm.
    fn into_encoder(self) -> JwtEncoder {
        let mut encoder = JwtEncoder::new()
            .issuer(self.issuer)
            .subject(self.subject)
            .audience(self.audience);

        if let Some(iat) = self.iat {
            encoder = encoder.issued_at(iat);
        }
        if let Some(exp) = self.exp {
            encoder = encoder.expiration(exp);
        }
        if let Some(nonce) = self.nonce {
            encoder = encoder.nonce(nonce);
        }
        if let Some(auth_time) = self.auth_time {
            encoder = encoder.custom_claim("auth_time", auth_time);
        }
        if let Some(email) = self.email {
            encoder = encoder.custom_claim("email", email);
        }
        if let Some(verified) = self.email_verified {
            encoder = encoder.custom_claim("email_verified", verified);
        }
        if let Some(name) = self.name {
            encoder = encoder.custom_claim("name", name);
        }
        if let Some(username) = self.preferred_username {
            encoder = encoder.custom_claim("preferred_username", username);
        }
        if let Some(roles) = self.roles {
            encoder = encoder.custom_claim("roles", roles);
        }
        if let Some(groups) = self.groups {
            encoder = encoder.custom_claim("groups", groups);
        }
        if let Some(tenant) = self.tenant {
            encoder = encoder.custom_claim("tenant", tenant);
        }
        // Custom claims LAST: the encoder drops any that collide with a
        // registered/standard claim already set above (standard wins).
        for (name, value) in self.extra {
            encoder = encoder.custom_claim(name, value);
        }

        encoder
    }

    /// Signs the assembled ID-token claims with an HMAC key, returning the
    /// compact JWT.
    ///
    /// # Security
    ///
    /// `key` is the signing secret — for OIDC `client_secret_jwt` this is
    /// the relying party's `client_secret`. It is never logged or embedded
    /// in the token beyond the HMAC. As with
    /// [`JwtEncoder::sign`](crate::jwt::JwtEncoder::sign), the key must be at
    /// least the hash output length (32 bytes for `HS256`, 64 for `HS512`,
    /// RFC 7518 §3.2); a shorter `client_secret` weakens the signature.
    #[must_use = "this returns the signed ID token"]
    pub fn sign(self, alg: JwtSigningAlgorithm, key: &[u8]) -> String {
        self.into_encoder().sign(alg, key)
    }

    /// Signs the assembled ID-token claims with an asymmetric (EdDSA/ES256)
    /// key, stamping the key's `kid` into the JOSE header so a relying party
    /// can select the matching public key from the issuer's JWKS.
    ///
    /// This is the asymmetric counterpart of [`sign`](Self::sign): the claim
    /// set is identical (assembled by the same `into_encoder` helper),
    /// only the signature algorithm differs. Use this when a client's
    /// `id_token_signed_response_alg` is `EdDSA`/`ES256`, or for any public
    /// client that has no `client_secret` to HMAC with.
    ///
    /// # Security
    ///
    /// The private key never leaves the [`AsymmetricSigningKey`](crate::jwt::AsymmetricSigningKey); only the
    /// public half is published via JWKS. The algorithm is fixed by the key
    /// type, so it cannot be downgraded by the caller.
    #[cfg(feature = "asym-jwt")]
    #[must_use = "this returns the signed ID token"]
    pub fn sign_asymmetric(self, key: &crate::jwt::AsymmetricSigningKey) -> String {
        self.into_encoder().key_id(key.kid()).sign_asymmetric(key)
    }
}

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

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

    const KEY: &[u8] = b"client-secret-value";

    #[test]
    fn mandatory_claims_only() {
        let token =
            IdTokenBuilder::new("iss", "sub-1", "aud-1").sign(JwtSigningAlgorithm::Hs256, KEY);
        let (_, claims) = verify_jwt(&token, KEY).unwrap();
        assert_eq!(claims.iss(), Some("iss"));
        assert_eq!(claims.sub(), Some("sub-1"));
        assert_eq!(claims.aud(), &["aud-1"]);
    }

    #[test]
    fn extra_claims_emitted_but_never_override_standard() {
        let token = IdTokenBuilder::new("iss", "sub-1", "aud-1")
            .roles(["user"])
            .extra_claim("department", "engineering")
            .extra_claim("employee_id", 4242u64)
            .extra_claim("is_contractor", false)
            .extra_claim("scopes", vec!["read".to_string(), "write".to_string()])
            // Collides with the standard `roles` claim → must be dropped.
            .extra_claim("roles", vec!["admin".to_string()])
            // Collides with the registered `sub` claim → must be dropped.
            .extra_claim("sub", "attacker")
            .sign(JwtSigningAlgorithm::Hs256, KEY);

        let (_, c) = verify_jwt(&token, KEY).unwrap();
        assert_eq!(c.sub(), Some("sub-1"), "custom sub cannot override");
        assert_eq!(
            c.get_claim("department").and_then(|v| v.as_str()),
            Some("engineering")
        );
        assert_eq!(
            c.get_claim("employee_id")
                .and_then(crate::json::JsonValue::as_i64),
            Some(4242)
        );
        assert_eq!(
            c.get_claim("is_contractor")
                .and_then(crate::json::JsonValue::as_bool),
            Some(false)
        );
        assert_eq!(
            c.get_claim("scopes")
                .and_then(|v| v.as_array())
                .unwrap()
                .len(),
            2
        );
        // The standard roles setter wins over the colliding custom one.
        let roles: Vec<&str> = c
            .get_claim("roles")
            .and_then(|v| v.as_array())
            .unwrap()
            .iter()
            .filter_map(|v| v.as_str())
            .collect();
        assert_eq!(roles, ["user"]);
    }

    #[test]
    fn full_id_token_round_trips() {
        let token = IdTokenBuilder::new("https://auth.example.com", "user-123", "entropy_website")
            .issued_at(1_700_000_000)
            .expiration(1_700_003_600)
            .nonce("n-abc")
            .email("frodo@example.com", true)
            .name("Frodo Baggins")
            .preferred_username("frodo")
            .roles(["user", "developer"])
            .groups(["engineering", "admins"])
            .tenant("entropy")
            .sign(JwtSigningAlgorithm::Hs256, KEY);

        let (_, c) = verify_jwt(&token, KEY).unwrap();
        assert_eq!(c.iss(), Some("https://auth.example.com"));
        assert_eq!(c.sub(), Some("user-123"));
        assert!(c.validate_aud("entropy_website"));
        assert_eq!(c.iat(), Some(1_700_000_000));
        assert_eq!(c.exp(), Some(1_700_003_600));
        assert_eq!(c.get_claim("nonce").and_then(|v| v.as_str()), Some("n-abc"));
        assert_eq!(
            c.get_claim("email").and_then(|v| v.as_str()),
            Some("frodo@example.com")
        );
        assert_eq!(
            c.get_claim("email_verified")
                .and_then(crate::json::JsonValue::as_bool),
            Some(true)
        );
        assert_eq!(
            c.get_claim("name").and_then(|v| v.as_str()),
            Some("Frodo Baggins")
        );
        assert_eq!(
            c.get_claim("preferred_username").and_then(|v| v.as_str()),
            Some("frodo"),
        );
        assert_eq!(
            c.get_claim("tenant").and_then(|v| v.as_str()),
            Some("entropy")
        );
        let roles: Vec<&str> = c
            .get_claim("roles")
            .and_then(|v| v.as_array())
            .unwrap()
            .iter()
            .filter_map(|v| v.as_str())
            .collect();
        assert_eq!(roles, ["user", "developer"]);
        let groups: Vec<&str> = c
            .get_claim("groups")
            .and_then(|v| v.as_array())
            .unwrap()
            .iter()
            .filter_map(|v| v.as_str())
            .collect();
        assert_eq!(groups, ["engineering", "admins"]);
    }

    #[test]
    fn groups_claim_absent_when_not_set() {
        // The groups claim is opt-in: a builder that never calls `.groups()`
        // must not emit it (a client not configured for groups gets none).
        let token = IdTokenBuilder::new("iss", "sub", "aud")
            .roles(["user"])
            .sign(JwtSigningAlgorithm::Hs256, KEY);
        let (_, c) = verify_jwt(&token, KEY).unwrap();
        assert!(c.get_claim("groups").is_none());
    }

    #[test]
    fn auth_time_emitted_as_number() {
        let token = IdTokenBuilder::new("iss", "sub", "aud")
            .auth_time(1_700_000_000)
            .sign(JwtSigningAlgorithm::Hs256, KEY);
        let (_, c) = verify_jwt(&token, KEY).unwrap();
        assert_eq!(
            c.get_claim("auth_time")
                .and_then(crate::json::JsonValue::as_i64),
            Some(1_700_000_000)
        );
    }

    #[test]
    fn email_unverified() {
        let token = IdTokenBuilder::new("iss", "sub", "aud")
            .email("x@y.z", false)
            .sign(JwtSigningAlgorithm::Hs256, KEY);
        let (_, c) = verify_jwt(&token, KEY).unwrap();
        assert_eq!(
            c.get_claim("email_verified")
                .and_then(crate::json::JsonValue::as_bool),
            Some(false)
        );
    }

    #[test]
    fn hs512_signing() {
        let token = IdTokenBuilder::new("iss", "sub", "aud").sign(JwtSigningAlgorithm::Hs512, KEY);
        assert!(verify_jwt(&token, KEY).is_ok());
    }

    #[test]
    fn wrong_secret_fails() {
        let token = IdTokenBuilder::new("iss", "sub", "aud").sign(JwtSigningAlgorithm::Hs256, KEY);
        assert!(verify_jwt(&token, b"different-secret").is_err());
    }
}