ppoppo-token 0.3.0

JWT (RFC 9068, EdDSA) issuance + verification engine for the Ppoppo ecosystem. Single deep module with a small interface (issue, verify) hiding RFC 8725 mitigations M01-M45, JWKS handling, and substrate ports (epoch, session, replay).
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
//! OIDC id_token wire-payload assembly + β1 runtime allowlist guard.
//!
//! Engine-internal mirror of `encode.rs::IssuePayload::build` but
//! profile-aware over `S: ScopeSet`. Reads `IssueConfig` (deployment
//! identity + RP-knowable bindings) and `IssueRequest<S>` (IdP
//! principal assertions + scope-narrowed PII), produces the wire-shape
//! payload `jsonwebtoken::encode` will serialize.
//!
//! ── β1 runtime allowlist guard (defense in depth) ───────────────────────
//!
//! The HasX-gated builders on `IssueRequest<S>` already enforce
//! "wrong scope, wrong field" as a *compile* error. This module's
//! `build` adds the *runtime* mirror: every populated PII field is
//! checked against `S::names()`, and any populated key outside the
//! allowlist returns `IssueError::EmissionDisallowed(name)`. Symmetric
//! to verify-side M72 (`engine::check_id_token_pii::run`) — the engine
//! refuses to *emit* a claim it would refuse to *accept*.
//!
//! Why both layers (per NEXT_PROMPT 2026-05-10 β1):
//! * The compile-time gate prevents the *typed* misuse (caller cannot
//!   call `with_email` without `S: HasEmail`).
//! * The runtime gate prevents the *struct-literal* misuse (intra-crate
//!   code bypassing the builders by writing
//!   `IssueRequest { email: Some(...), .. }` against the `pub(crate)`
//!   fields). Disallowed from outside the crate by privacy, but engine
//!   layers should not assume the crate boundary holds forever.
//!
//! ── Hash-binding emission ───────────────────────────────────────────────
//!
//! When `cfg.for_access_token` or `cfg.for_authorization_code` are set
//! (γ1), the engine computes `at_hash` / `c_hash` via the shared
//! `engine::hash_binding::compute` primitive (the same code path the
//! verify side reads — symmetric per the primitive's design intent).
//! This guarantees emission and verification agree by construction.
//!
//! ── No `jti` ────────────────────────────────────────────────────────────
//!
//! Unlike the access-token wire (RFC 9068 §2.2.2 requires `jti`), the
//! OIDC id_token wire deliberately omits `jti` — see the `IssueRequest`
//! doc-comment for the full rationale. Replay defense lives on the
//! `nonce` claim.

use serde::Serialize;
use std::marker::PhantomData;

use crate::id_token::claims::AddressClaim;
use crate::id_token::scopes::ScopeSet;
use crate::id_token::{IssueConfig, IssueError, IssueRequest};

use super::hash_binding;

/// Wire shape for the `aud` claim. Mirror of `engine::encode::AudOnWire`
/// — id_token follows the same RFC 7519 §4.1.3 rule (string when length
/// is 1, array otherwise) the access-token side already pinned.
#[derive(Serialize)]
#[serde(untagged)]
enum AudOnWire<'a> {
    One(&'a str),
    Many(&'a [String]),
}

/// Engine-internal id_token wire payload — the typed shape
/// `jsonwebtoken::encode` serializes to the JWS body. Constructed only
/// via [`build`]; no public escape hatch hands callers the unsigned
/// payload (mirrors the `pub(crate)` discipline on access-token's
/// `IssuePayload`).
///
/// `'a` borrows from `IssueConfig` and `IssueRequest<S>`; `at_hash` and
/// `c_hash` are computed at build time and so are owned `String`s.
/// PhantomData carries the scope witness so the type-system can't
/// accidentally confuse two scopes' payloads at higher layers.
#[derive(Serialize)]
pub(crate) struct IssuePayload<'a, S: ScopeSet> {
    iss: &'a str,
    sub: &'a str,
    aud: AudOnWire<'a>,
    exp: i64,
    iat: i64,
    nonce: &'a str,
    cat: &'static str,

    #[serde(skip_serializing_if = "Option::is_none")]
    auth_time: Option<i64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    acr: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    amr: Option<&'a [String]>,
    #[serde(skip_serializing_if = "Option::is_none")]
    azp: Option<&'a str>,

    #[serde(skip_serializing_if = "Option::is_none")]
    at_hash: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    c_hash: Option<String>,

    // ── PII (`Option::is_none` skips when not populated) ─────────────────
    #[serde(skip_serializing_if = "Option::is_none")]
    email: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    email_verified: Option<bool>,

    #[serde(skip_serializing_if = "Option::is_none")]
    name: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    given_name: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    family_name: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    middle_name: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    nickname: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    preferred_username: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    profile: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    picture: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    website: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    gender: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    birthdate: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    zoneinfo: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    locale: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    updated_at: Option<i64>,

    #[serde(skip_serializing_if = "Option::is_none")]
    phone_number: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    phone_number_verified: Option<bool>,

    #[serde(skip_serializing_if = "Option::is_none")]
    address: Option<&'a AddressClaim>,

    #[serde(skip)]
    _scope: PhantomData<S>,
}

impl<'a, S: ScopeSet> IssuePayload<'a, S> {
    /// Build the wire payload from `IssueRequest<S>` + `IssueConfig` at
    /// the supplied `now` (seconds since UNIX_EPOCH).
    ///
    /// `now` is a parameter rather than a system call so tests can pin
    /// timestamps; production paths in `engine::issue_id_token` pass
    /// `time::OffsetDateTime::now_utc().unix_timestamp()`.
    ///
    /// Order:
    /// 1. β1 runtime allowlist guard — refuse populated PII fields
    ///    outside `S::names()`.
    /// 2. Compute hash bindings from `cfg.for_access_token` /
    ///    `cfg.for_authorization_code` (when set) via
    ///    `engine::hash_binding::compute`.
    /// 3. Assemble the borrowed payload.
    ///
    /// Step 1 fires BEFORE 2-3 so a misconfigured pipeline never spends
    /// hash-compute or struct-build cycles on a doomed payload. Per
    /// `feedback_audit_grilled_decisions`: cheap validation runs first
    /// so the engine surfaces the precise audit signal before doing
    /// expensive work.
    pub(crate) fn build(
        req: &'a IssueRequest<S>,
        cfg: &'a IssueConfig,
        now: i64,
    ) -> Result<Self, IssueError> {
        let allowlist = S::names();

        // β1 runtime allowlist guard. The list mirrors `Claims<S>`'s PII
        // fields exactly — adding a new claim is a 4-step change:
        // 1. Field on `Claims<S>` (verify-side accessor).
        // 2. Field on `IssueRequest<S>` (issue-side data).
        // 3. Wire entry on `IssuePayload` (serializer).
        // 4. Row here (runtime guard).
        // Plus `S::names()` slice membership in `id_token::scopes`.
        // Skipping step 4 leaves a populated field flowing through the
        // engine without the M72-symmetric defense-in-depth check.
        let pii_emit_intent: &[(&'static str, bool)] = &[
            ("email", req.email.is_some()),
            ("email_verified", req.email_verified.is_some()),
            ("name", req.name.is_some()),
            ("given_name", req.given_name.is_some()),
            ("family_name", req.family_name.is_some()),
            ("middle_name", req.middle_name.is_some()),
            ("nickname", req.nickname.is_some()),
            ("preferred_username", req.preferred_username.is_some()),
            ("profile", req.profile.is_some()),
            ("picture", req.picture.is_some()),
            ("website", req.website.is_some()),
            ("gender", req.gender.is_some()),
            ("birthdate", req.birthdate.is_some()),
            ("zoneinfo", req.zoneinfo.is_some()),
            ("locale", req.locale.is_some()),
            ("updated_at", req.updated_at.is_some()),
            ("phone_number", req.phone_number.is_some()),
            ("phone_number_verified", req.phone_number_verified.is_some()),
            ("address", req.address.is_some()),
        ];
        for (name, populated) in pii_emit_intent {
            if *populated && !allowlist.contains(name) {
                return Err(IssueError::EmissionDisallowed((*name).to_string()));
            }
        }

        let exp = now + req.ttl.as_secs() as i64;
        let aud = serialize_aud_choice(&cfg.audiences);
        let at_hash = cfg
            .for_access_token
            .as_ref()
            .map(|s| hash_binding::compute(s.as_bytes()));
        let c_hash = cfg
            .for_authorization_code
            .as_ref()
            .map(|s| hash_binding::compute(s.as_bytes()));

        Ok(Self {
            iss: &cfg.issuer,
            sub: &req.sub,
            aud,
            exp,
            iat: now,
            nonce: cfg.nonce.as_str(),
            cat: cfg.cat,
            auth_time: req.auth_time,
            acr: req.acr.as_deref(),
            amr: req.amr.as_deref(),
            azp: req.azp.as_deref(),
            at_hash,
            c_hash,
            email: req.email.as_deref(),
            email_verified: req.email_verified,
            name: req.name.as_deref(),
            given_name: req.given_name.as_deref(),
            family_name: req.family_name.as_deref(),
            middle_name: req.middle_name.as_deref(),
            nickname: req.nickname.as_deref(),
            preferred_username: req.preferred_username.as_deref(),
            profile: req.profile.as_deref(),
            picture: req.picture.as_deref(),
            website: req.website.as_deref(),
            gender: req.gender.as_deref(),
            birthdate: req.birthdate.as_deref(),
            zoneinfo: req.zoneinfo.as_deref(),
            locale: req.locale.as_deref(),
            updated_at: req.updated_at,
            phone_number: req.phone_number.as_deref(),
            phone_number_verified: req.phone_number_verified,
            address: req.address.as_ref(),
            _scope: PhantomData,
        })
    }
}

fn serialize_aud_choice(audiences: &[String]) -> AudOnWire<'_> {
    if audiences.len() == 1 {
        AudOnWire::One(&audiences[0])
    } else {
        AudOnWire::Many(audiences)
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
    //! 5 unit tests pinning the build invariants per NEXT_PROMPT
    //! 2026-05-10 §10.10.B (which became §10.10.C after the verify-side
    //! readiness commit was extracted as 10.10.A).
    //!
    //! Each test forms a `serde_json::Value` of the payload and asserts
    //! on field shape directly — JSON shape is the wire contract, and
    //! letting tests inspect via the `Value` API insulates them from
    //! struct-internal renames.

    use super::*;
    use crate::id_token::scopes::{Email, EmailProfile, Openid};
    use crate::id_token::Nonce;
    use std::time::Duration;

    fn nonce() -> Nonce {
        Nonce::new("rp-stored-nonce-test").unwrap()
    }

    fn cfg() -> IssueConfig {
        IssueConfig::id_token(
            "https://accounts.ppoppo.com",
            "rp-client-1234",
            "k4.test.0",
            nonce(),
        )
    }

    fn payload_json<S: ScopeSet>(req: &IssueRequest<S>, cfg: &IssueConfig, now: i64) -> serde_json::Value {
        let payload = IssuePayload::build(req, cfg, now).expect("build must succeed");
        serde_json::to_value(&payload).unwrap()
    }

    #[test]
    fn openid_minimal_payload_round_trips() {
        // Minimal Openid issuance: sub + ttl + nonce-from-cfg. Wire
        // contains the registered set + `cat="id"` + `nonce` and nothing
        // else (PII absent, no hash bindings, no auth_time/acr/azp).
        let req = IssueRequest::<Openid>::new("01HSAB00000000000000000000", Duration::from_secs(600));
        let cfg = cfg();
        let now = 1_700_000_000_i64;
        let json = payload_json(&req, &cfg, now);

        assert_eq!(json["iss"], "https://accounts.ppoppo.com");
        assert_eq!(json["sub"], "01HSAB00000000000000000000");
        assert_eq!(json["aud"], "rp-client-1234");
        assert!(json["aud"].is_string(), "single aud must serialize as string");
        assert_eq!(json["exp"], now + 600);
        assert_eq!(json["iat"], now);
        assert_eq!(json["nonce"], "rp-stored-nonce-test");
        assert_eq!(json["cat"], "id");

        // None of the optionals appear when absent.
        for absent in [
            "auth_time", "acr", "amr", "azp", "at_hash", "c_hash",
            "email", "name", "phone_number", "address",
        ] {
            assert!(
                json.get(absent).is_none(),
                "absent field {absent:?} must NOT appear on the wire"
            );
        }
    }

    #[test]
    fn email_payload_includes_email_field() {
        // HasEmail-gated builder populates the email field; β1 admits
        // because "email" ∈ Email::names(). Round-trip via JSON to assert
        // shape and value.
        let req = IssueRequest::<Email>::new("01HSAB00000000000000000000", Duration::from_secs(600))
            .with_email("user@example.com")
            .with_email_verified(true);
        let json = payload_json(&req, &cfg(), 1_700_000_000);

        assert_eq!(json["email"], "user@example.com");
        assert_eq!(json["email_verified"], true);
        // Profile fields stay absent at Email scope.
        assert!(json.get("name").is_none());
        assert!(json.get("phone_number").is_none());
    }

    #[test]
    fn unknown_field_population_returns_emission_disallowed() {
        // Hostile struct-literal bypass simulation: construct an
        // `IssueRequest::<Openid>` directly via the `pub(crate)` field
        // privacy boundary (only doable from intra-crate test code) and
        // populate `email` despite `Openid` lacking `HasEmail`. The β1
        // runtime guard MUST refuse with `EmissionDisallowed("email")`.
        //
        // This is the runtime mirror of M72: the engine doesn't trust
        // upstream type narrowing, even though the compile-time gate
        // makes this exact bypass impossible from outside the crate.
        let mut req = IssueRequest::<Openid>::new(
            "01HSAB00000000000000000000",
            Duration::from_secs(600),
        );
        req.email = Some("smuggled@example.com".to_string());

        let cfg_binding = cfg();
        let result = IssuePayload::build(&req, &cfg_binding, 1_700_000_000);
        assert_eq!(
            result.err(),
            Some(IssueError::EmissionDisallowed("email".to_string())),
            "β1 runtime guard MUST fire on a populated field outside S::names()"
        );
    }

    #[test]
    fn at_hash_emitted_when_cfg_has_access_token() {
        // γ1 verification: when `IssueConfig::with_access_token_for_at_hash`
        // sets the binding subject, the engine computes
        // `BASE64URL(SHA-256(access_token)[..16])` via the shared
        // `engine::hash_binding::compute` primitive. Asserting the
        // emitted value matches a freshly-computed reference proves
        // both sides of the M67 contract agree by construction (issue
        // and verify read the same primitive).
        const ACCESS_TOKEN: &str = "fake.access.token.three.dots";
        let req = IssueRequest::<Openid>::new("01HSAB00000000000000000000", Duration::from_secs(600));
        let cfg = cfg().with_access_token_for_at_hash(ACCESS_TOKEN);
        let json = payload_json(&req, &cfg, 1_700_000_000);

        let expected = hash_binding::compute(ACCESS_TOKEN.as_bytes());
        assert_eq!(json["at_hash"], expected);
        // c_hash unset because no authorization_code binding.
        assert!(json.get("c_hash").is_none());
    }

    #[test]
    fn c_hash_emitted_when_cfg_has_authorization_code() {
        // Symmetric mirror of the at_hash test: verifies the c_hash
        // emission path. Hybrid flow is the only place both at_hash
        // and c_hash co-exist; here we test c_hash alone (pure
        // authorization-code-bearing implicit flow doesn't really
        // exist, but the engine handles each binding independently).
        const AUTH_CODE: &str = "oauth2-authorization-code-test";
        let req = IssueRequest::<Openid>::new("01HSAB00000000000000000000", Duration::from_secs(600));
        let cfg = cfg().with_authorization_code_for_c_hash(AUTH_CODE);
        let json = payload_json(&req, &cfg, 1_700_000_000);

        let expected = hash_binding::compute(AUTH_CODE.as_bytes());
        assert_eq!(json["c_hash"], expected);
        assert!(json.get("at_hash").is_none());
    }

    #[test]
    fn email_profile_includes_email_and_profile_fields() {
        // Bonus: maximal-permitted scope at EmailProfile populates both
        // email and profile fields without runtime guard firing. Pins
        // the union case so a future regression that splits S::names()
        // into per-trait sets and forgets the union surfaces here.
        let req = IssueRequest::<EmailProfile>::new(
            "01HSAB00000000000000000000",
            Duration::from_secs(600),
        )
        .with_email("u@example.com")
        .with_name("Test User")
        .with_locale("en-US");

        let json = payload_json(&req, &cfg(), 1_700_000_000);
        assert_eq!(json["email"], "u@example.com");
        assert_eq!(json["name"], "Test User");
        assert_eq!(json["locale"], "en-US");
    }

    #[test]
    fn aud_emits_array_when_multi_audience() {
        // Multi-audience configurations switch the aud serialization
        // shape; pin the array form here since it's the only place
        // configurable from the issue side.
        let req = IssueRequest::<Openid>::new("01HSAB00000000000000000000", Duration::from_secs(600));
        let cfg = cfg().with_audiences(vec!["primary".to_string(), "secondary".to_string()]);
        let json = payload_json(&req, &cfg, 1_700_000_000);
        let aud = &json["aud"];
        assert!(aud.is_array(), "multi aud must serialize as array");
        assert_eq!(aud[0], "primary");
        assert_eq!(aud[1], "secondary");
    }
}