ppoppo-token 0.2.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
//! OIDC Core 1.0 §5.4 scope vocabulary as a *type-system* construct.
//!
//! ── Why types, not strings ──────────────────────────────────────────────
//!
//! M45 (`access_token`) is a flat PII allowlist enforced at runtime: the
//! engine refuses any payload claim outside `ALLOWED_CLAIMS`. M72
//! (`id_token`) is *per-scope* — `email` is admissible iff the OAuth
//! request carried `scope=openid email`, etc. Encoding M72 the same way
//! M45 does (string match) reproduces the runtime cost on every verify
//! and leaves no compile-time evidence that the engine actually narrows
//! visibility.
//!
//! The phantom-typed approach (this file + `claims.rs`) makes M72
//! *structural*: a `Claims<Openid>` value has no `.email()` method —
//! calling it produces `error[E0599]: no method named 'email' found`.
//! Adding a new scope (`offline_access`) is mechanical (one struct + one
//! trait impl); adding a new PII *leak path* requires editing the engine
//! invariant (the `pub(crate)` field privacy), which is the surface the
//! security review reads.
//!
//! ── Vocabulary ──────────────────────────────────────────────────────────
//!
//! * [`ScopeSet`] — sealed trait every scope marker implements; the
//!   `verify<S: ScopeSet>` engine entry-point bounds on it so callers
//!   cannot fabricate ad-hoc scope structs that bypass deserialization
//!   narrowing.
//! * [`HasEmail`] / [`HasProfile`] / [`HasPhone`] / [`HasAddress`] —
//!   marker traits gating the scope-bounded `impl Claims<S>` accessor
//!   blocks in `claims.rs`. Composition is via *concrete combination
//!   structs*, not blanket impls — see "Combination structs" below.
//!
//! ── Combination structs ─────────────────────────────────────────────────
//!
//! OIDC scope is a request-time bag: `scope=openid email profile phone`
//! is a single OAuth string. We mint one struct per *useful* combination
//! the consumer will actually request — the surface is small (RP apps
//! pick one of {`Openid`, `Email`, `Profile`, `EmailProfile`,
//! `EmailProfilePhone`, `EmailProfilePhoneAddress`}) and the structs are
//! not parameterised. Combinatorial blow-up (2^4 = 16) is bounded by
//! adding combinations *only when a real RP needs them*, not preemptively.
//!
//! Why not a generic combinator `(Email, Profile)` tuple? The OIDC scope
//! request is an unordered set; a tuple imposes order. A type-level set
//! type would work but adds machinery (`HList`, frunk) for no engineering
//! win at 16-element scale.

/// Sealed trait. Every scope marker (the 6 structs below) implements it;
/// nothing outside this module can. Bounds `verify<S>` and `Claims<S>` so
/// callers cannot smuggle in `Claims<()>` and bypass the Has* gating.
///
/// ── `names()` (M72) ─────────────────────────────────────────────────────
///
/// The full per-scope claim allowlist — every payload key the engine is
/// permitted to deserialize for this scope. Returned as a `&'static`
/// slice so the engine's M72 check (`engine::check_id_token_pii::run`)
/// iterates without allocation. The slice is the COMPLETE allowlist
/// (registered base claims `iss`/`sub`/`aud`/`exp`/`iat`/`nonce`/`azp`/
/// `auth_time`/`acr`/`amr` UNIONED with the scope's PII fields), so
/// auditing is single-file: every allowlist lives in this module.
///
/// Adding a new claim is a 3-step change (in this order):
/// 1. Append the wire name to the appropriate const slice below
///    (`BASE_CLAIMS` for registered claims, `EMAIL_CLAIMS` /
///    `PROFILE_CLAIMS` / `PHONE_CLAIMS` / `ADDRESS_CLAIMS` for PII).
/// 2. Append the same name to every per-variant `static NAMES_*` array
///    that should permit it (the union sets are NOT auto-derived —
///    explicit listing is the audit surface).
/// 3. Surface the field on `Claims<S>` (or extend the deserializer) per
///    the scope-bounded accessor pattern in `claims.rs`.
///
/// Skipping step 2 leaves `verify::<EmailProfile>` rejecting a token
/// that legitimately carries the new claim. The unit test
/// `email_profile_phone_address_is_union_of_components` is the
/// regression guard for accidental drift in the maximal scope.
pub trait ScopeSet: sealed::Sealed {
    /// Complete per-scope claim allowlist (union of base + PII for this
    /// scope). M72 enforcement iterates this set; any payload key
    /// outside it is refused with `AuthError::UnknownClaim(name)`.
    fn names() -> &'static [&'static str];
}

/// Token grants `openid email` (or any superset including `email`).
/// Gates `Claims::email()` / `Claims::email_verified()`.
pub trait HasEmail: ScopeSet {}

/// Token grants `profile` (name fields + locale + updated_at — OIDC §5.4).
/// Gates `Claims::name()` / `given_name()` / `family_name()`.
pub trait HasProfile: ScopeSet {}

/// Token grants `phone`. Gates `Claims::phone_number()` /
/// `phone_number_verified()`.
pub trait HasPhone: ScopeSet {}

/// Token grants `address`. Gates `Claims::address()`.
pub trait HasAddress: ScopeSet {}

mod sealed {
    pub trait Sealed {}
}

// ── Per-scope claim allowlists (M72 source of truth) ────────────────────
//
// `BASE_CLAIMS` is the registered/core OIDC set every scope permits.
// Each PII slice (`EMAIL_CLAIMS` / `PROFILE_CLAIMS` / `PHONE_CLAIMS` /
// `ADDRESS_CLAIMS`) lists the names OIDC §5.4 binds to the matching
// scope. The per-variant `NAMES_*` static arrays below are the
// hand-listed unions that `ScopeSet::names()` returns — they are NOT
// auto-derived because the explicit form is the audit surface.

/// Registered + always-permitted core claims.
///
/// Members:
/// * `iss`, `sub`, `aud`, `exp`, `iat` — RFC 7519 baseline.
/// * `nonce` — M66 (always required: `VerifyConfig::id_token` mandates
///   `expected_nonce`, so a verified id_token always carries it).
/// * `at_hash` — M67 (OIDC §3.1.3.8; conditionally required when
///   `response_type` includes `token`). Surfaces in BASE because
///   verification reads it via `with_access_token_binding`; the IdP
///   emits it on hybrid + implicit flows even at base scope.
/// * `c_hash` — M68 (OIDC §3.3.2.11; conditionally required on hybrid
///   flow). Same shape as at_hash.
/// * `azp` — M69 (populated whenever multi-aud or whenever the IdP
///   asserts authorized party — surfaces unconditionally).
/// * `auth_time` — M70 (gated opt-in by `cfg.max_age`; engine surfaces
///   regardless of opt-in).
/// * `acr`, `amr` — M71 (acr step-up; amr authentication-method list).
/// * `cat` — profile-routing token-category discriminator. PAS issues
///   id_tokens with `cat="id"` (mirror of access tokens' `cat="access"`
///   per RFC 9068 §2.2). Symmetric verify-side gate lives in
///   `engine::check_id_token_cat` (the M29 mirror — refuses a non-`id`
///   value with `CatMismatch`); membership here is the M72 allowlist
///   side of the same coin: M72 admits the *key*, the cat-check binds
///   the *value*. Carrying `cat` on the id_token wire also strengthens
///   M73 defense in depth — `pas-external::token::jwt::peek_id_token_shape`
///   reads it as a second signal beyond the `typ="JWT"` header.
///
/// Forgetting any of these silently causes M72 to refuse a legitimately
/// bound token (a token with valid `nonce` / `at_hash` / `c_hash` /
/// `azp` / `auth_time` / `acr` / `cat` suddenly fails post-10.8 with
/// `UnknownClaim`). The unit test
/// `openid_names_includes_all_binding_claims` is the regression guard.
///
/// Audit surface only — the engine reads `S::names()` (the per-variant
/// `NAMES_*` arrays below). The component slices exist so the union
/// regression tests can prove no claim was silently dropped from a
/// scope; `#[allow(dead_code)]` is correct outside test builds.
#[allow(dead_code)]
pub(crate) const BASE_CLAIMS: &[&str] = &[
    "iss",
    "sub",
    "aud",
    "exp",
    "iat",
    "nonce",
    "at_hash",
    "c_hash",
    "azp",
    "auth_time",
    "acr",
    "amr",
    "cat",
];

/// `email` scope claims (OIDC Core §5.4).
#[allow(dead_code)]
pub(crate) const EMAIL_CLAIMS: &[&str] = &["email", "email_verified"];

/// `profile` scope claims (OIDC Core §5.4 — name family + locale +
/// updated_at). Field set matches the accessors in
/// `claims.rs::impl<S: HasProfile>` exactly.
#[allow(dead_code)]
pub(crate) const PROFILE_CLAIMS: &[&str] = &[
    "name",
    "given_name",
    "family_name",
    "middle_name",
    "nickname",
    "preferred_username",
    "profile",
    "picture",
    "website",
    "gender",
    "birthdate",
    "zoneinfo",
    "locale",
    "updated_at",
];

/// `phone` scope claims (OIDC Core §5.4).
#[allow(dead_code)]
pub(crate) const PHONE_CLAIMS: &[&str] = &["phone_number", "phone_number_verified"];

/// `address` scope claim (OIDC Core §5.4 — single structured value).
#[allow(dead_code)]
pub(crate) const ADDRESS_CLAIMS: &[&str] = &["address"];

// Per-variant unions. Hand-listed (not auto-concatenated) so each
// allowlist's exact membership is greppable from this file. The unit
// tests below assert each `NAMES_*` equals the expected union as a set.

static NAMES_OPENID: &[&str] = &[
    "iss", "sub", "aud", "exp", "iat", "nonce", "at_hash", "c_hash", "azp", "auth_time", "acr", "amr", "cat",
];

static NAMES_EMAIL: &[&str] = &[
    "iss", "sub", "aud", "exp", "iat", "nonce", "at_hash", "c_hash", "azp", "auth_time", "acr", "amr", "cat",
    "email", "email_verified",
];

static NAMES_PROFILE: &[&str] = &[
    "iss", "sub", "aud", "exp", "iat", "nonce", "at_hash", "c_hash", "azp", "auth_time", "acr", "amr", "cat",
    "name", "given_name", "family_name", "middle_name", "nickname", "preferred_username",
    "profile", "picture", "website", "gender", "birthdate", "zoneinfo", "locale",
    "updated_at",
];

static NAMES_EMAIL_PROFILE: &[&str] = &[
    "iss", "sub", "aud", "exp", "iat", "nonce", "at_hash", "c_hash", "azp", "auth_time", "acr", "amr", "cat",
    "email", "email_verified",
    "name", "given_name", "family_name", "middle_name", "nickname", "preferred_username",
    "profile", "picture", "website", "gender", "birthdate", "zoneinfo", "locale",
    "updated_at",
];

static NAMES_EMAIL_PROFILE_PHONE: &[&str] = &[
    "iss", "sub", "aud", "exp", "iat", "nonce", "at_hash", "c_hash", "azp", "auth_time", "acr", "amr", "cat",
    "email", "email_verified",
    "name", "given_name", "family_name", "middle_name", "nickname", "preferred_username",
    "profile", "picture", "website", "gender", "birthdate", "zoneinfo", "locale",
    "updated_at",
    "phone_number", "phone_number_verified",
];

static NAMES_EMAIL_PROFILE_PHONE_ADDRESS: &[&str] = &[
    "iss", "sub", "aud", "exp", "iat", "nonce", "at_hash", "c_hash", "azp", "auth_time", "acr", "amr", "cat",
    "email", "email_verified",
    "name", "given_name", "family_name", "middle_name", "nickname", "preferred_username",
    "profile", "picture", "website", "gender", "birthdate", "zoneinfo", "locale",
    "updated_at",
    "phone_number", "phone_number_verified",
    "address",
];

// ── Concrete scope structs ──────────────────────────────────────────────
//
// Each is a zero-sized type used solely as the `S` parameter on
// `Claims<S>` and `verify::<S>`. They carry no runtime state — the
// invariant they witness is "the issuance pipeline emitted a token whose
// scope claim is a superset of this struct's name".

/// `scope=openid` — the mandatory baseline. No PII accessors.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Openid;
impl sealed::Sealed for Openid {}
impl ScopeSet for Openid {
    fn names() -> &'static [&'static str] {
        NAMES_OPENID
    }
}

/// `scope=openid email`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Email;
impl sealed::Sealed for Email {}
impl ScopeSet for Email {
    fn names() -> &'static [&'static str] {
        NAMES_EMAIL
    }
}
impl HasEmail for Email {}

/// `scope=openid profile`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Profile;
impl sealed::Sealed for Profile {}
impl ScopeSet for Profile {
    fn names() -> &'static [&'static str] {
        NAMES_PROFILE
    }
}
impl HasProfile for Profile {}

/// `scope=openid email profile`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct EmailProfile;
impl sealed::Sealed for EmailProfile {}
impl ScopeSet for EmailProfile {
    fn names() -> &'static [&'static str] {
        NAMES_EMAIL_PROFILE
    }
}
impl HasEmail for EmailProfile {}
impl HasProfile for EmailProfile {}

/// `scope=openid email profile phone`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct EmailProfilePhone;
impl sealed::Sealed for EmailProfilePhone {}
impl ScopeSet for EmailProfilePhone {
    fn names() -> &'static [&'static str] {
        NAMES_EMAIL_PROFILE_PHONE
    }
}
impl HasEmail for EmailProfilePhone {}
impl HasProfile for EmailProfilePhone {}
impl HasPhone for EmailProfilePhone {}

/// `scope=openid email profile phone address` — the maximal request.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct EmailProfilePhoneAddress;
impl sealed::Sealed for EmailProfilePhoneAddress {}
impl ScopeSet for EmailProfilePhoneAddress {
    fn names() -> &'static [&'static str] {
        NAMES_EMAIL_PROFILE_PHONE_ADDRESS
    }
}
impl HasEmail for EmailProfilePhoneAddress {}
impl HasProfile for EmailProfilePhoneAddress {}
impl HasPhone for EmailProfilePhoneAddress {}
impl HasAddress for EmailProfilePhoneAddress {}

#[cfg(test)]
mod tests {
    //! M72 acceptance — every per-variant `names()` slice must equal
    //! the union of `BASE_CLAIMS` and the scope-specific PII slices,
    //! treated as sets (order-insensitive).
    //!
    //! The test method is set-equality, not slice-equality: a future
    //! refactor that reorders members should not require touching these
    //! tests. Drift in the union itself (a PII claim added to one slice
    //! but forgotten in `EmailProfilePhoneAddress`) IS what we catch.
    use super::*;
    use std::collections::HashSet;

    fn set(slice: &[&'static str]) -> HashSet<&'static str> {
        slice.iter().copied().collect()
    }

    fn union(slices: &[&[&'static str]]) -> HashSet<&'static str> {
        slices.iter().flat_map(|s| s.iter().copied()).collect()
    }

    #[test]
    fn openid_names_includes_all_binding_claims() {
        // Audit guard: every M66/M69/M70/M71 binding claim plus the M29-mirror
        // profile-routing claim (`cat`, Phase 10.10) MUST appear at base
        // scope. Forgetting any one means a verified token with valid
        // nonce/azp/auth_time/acr/cat suddenly fails M72 with UnknownClaim.
        let names = set(Openid::names());
        for required in [
            "iss", "sub", "aud", "exp", "iat",
            "nonce", "at_hash", "c_hash", "azp", "auth_time", "acr", "amr", "cat",
        ] {
            assert!(
                names.contains(required),
                "Openid::names() missing binding claim {required:?} — M72 would refuse a valid token"
            );
        }
        assert_eq!(names, set(BASE_CLAIMS));
    }

    #[test]
    fn email_names_is_union_of_base_and_email() {
        assert_eq!(set(Email::names()), union(&[BASE_CLAIMS, EMAIL_CLAIMS]));
    }

    #[test]
    fn profile_names_is_union_of_base_and_profile() {
        assert_eq!(set(Profile::names()), union(&[BASE_CLAIMS, PROFILE_CLAIMS]));
    }

    #[test]
    fn email_profile_names_is_union_of_base_email_profile() {
        assert_eq!(
            set(EmailProfile::names()),
            union(&[BASE_CLAIMS, EMAIL_CLAIMS, PROFILE_CLAIMS]),
        );
    }

    #[test]
    fn email_profile_phone_names_is_union_of_base_email_profile_phone() {
        assert_eq!(
            set(EmailProfilePhone::names()),
            union(&[BASE_CLAIMS, EMAIL_CLAIMS, PROFILE_CLAIMS, PHONE_CLAIMS]),
        );
    }

    #[test]
    fn email_profile_phone_address_is_union_of_components() {
        // Maximal scope: catches drift where a claim is added to one
        // component slice (e.g. EMAIL_CLAIMS gains `email_locale`) but the
        // hand-listed NAMES_EMAIL_PROFILE_PHONE_ADDRESS array isn't
        // updated to match — silent narrowing of the maximal allowlist.
        assert_eq!(
            set(EmailProfilePhoneAddress::names()),
            union(&[
                BASE_CLAIMS,
                EMAIL_CLAIMS,
                PROFILE_CLAIMS,
                PHONE_CLAIMS,
                ADDRESS_CLAIMS,
            ]),
        );
    }
}