Skip to main content

ppoppo_identity/
lib.rs

1//! **NOT a stable public API.** Engine-tier identity vocabulary — published
2//! to crates.io only because the SDK closure requires it on the registry;
3//! 3rd parties never name this crate. They meet these types through an SDK
4//! product facade or a wire contract, never here.
5//!
6//! # Principal identity — the `scaccounts.ppnums` vocabularies
7//!
8//! The identifier pair, three value-sets, and one predicate over them — all
9//! owned by the `scaccounts.ppnums` table (or, for [`Scope`], by the OAuth
10//! catalog PAS mints from it) and all read by *more than one* organ, so none
11//! of them can live in either organ. The rows first:
12//!
13//! | Type | Column / fact | Binding |
14//! |---|---|---|
15//! | [`Ppnum`] | `ppnum` | `ck_ppnums_format` — named on [`Ppnum::CONSTRAINT`] |
16//! | [`PpnumId`] | `id` | the 26-char ULID PK / FK / `sub` |
17//! | [`EntityType`] | `entity_type` | `ck_ppnums_entity_type_enum` |
18//! | [`LifecycleState`] | `lifecycle_state` (+ 2 audit columns) | `ck_ppnums_lifecycle_state_enum`, `ck_ppnum_lifecycle_events_{from,to}_state_enum` |
19//! | [`Scope`] | the `scopes` claim / `scopes_supported` | [`SCOPE_TABLE`] + const gates in each organ |
20//!
21//! They are here for one reason, applied five times: **a value consumed
22//! across the organ boundary collapses into one vocabulary** rather than
23//! being mirrored and then bound. `EntityType` arrived by `RFC_202607252223`,
24//! `LifecycleState` by `RFC_202607251658` P1 — and the second move is also
25//! what finally makes the *cross-fact* between them stateable exactly once
26//! ([`LifecycleState::can_transition_for_entity`], the
27//! `ck_ppnums_expired_only_mask` rule). `Ppnum`, `PpnumId` and `Scope`
28//! followed on 2026-08-29 (the ADR named in this crate's CHANGELOG), each
29//! for the same reason the first two moved: the rule already had several
30//! homes and at least two of them disagreed.
31//!
32//! ## `Ppnum` / `PpnumId` — the identifier pair
33//!
34//! **The number, and the id that names its row.** Consumers store the two
35//! *paired*; both are immutable for a human. Before this crate the format rule
36//! behind [`Ppnum`] was restated six times across the SDKs, PCS and PAS — and
37//! PCS's two copies said `== 11` while the column, PAS and the SDKs said
38//! `≥ 11`, so every 15-digit dependent-agent ppnum PAS minted was un-addable
39//! as a PCS contact. The rule is stated once here ([`Ppnum::MIN_LEN`], the
40//! `ck_ppnums_format` regex), the two renderings that every organ needs
41//! (wire digits, hyphen-grouped display) are stated once, and the ladder PAS
42//! mints on (`11 + 4·depth`) is deliberately **not** here — it is issuance
43//! policy PCS never reads.
44//!
45//! [`PpnumId`] was the same ULID under three names (`PpnumAccountId` in PAS,
46//! `PpnumId` in PCS and the SDK). A value that crosses the organ boundary
47//! under one name in the database has one name in Rust.
48//!
49//! ## `Scope` — the one OAuth scope vocabulary
50//!
51//! **Every scope PAS mints**, with the two attributes both organs decide on:
52//! its [`ScopeTier`] (reach) and its [`ScopeEnforcer`] (which organ's
53//! perimeter matches it). Before this crate the catalog was a PAS string list,
54//! a PAS `plims:*` const module, a 15-member PCS enum with three parallel
55//! lists, and bare string atoms in the SDK's tiers — held together by three
56//! dev-dependency tests that compiled the other organ to compare strings. Now
57//! a scope the SDK requests *is* a scope PAS mints, by type, and the K8
58//! inclusions (`DIRECTION_COUPLING_PASPCS` §6 I10) are const gates in
59//! `chat-core`: every `Pcs`-enforced scope backs a gate, every gate is keyed
60//! on a `Pcs`-enforced scope, and a mislabel fails to compile.
61//!
62//! What stays in PAS is what only PAS reads: `registerable` (the `/oauth/apps`
63//! form's allow-list) and the consent-screen glyph, in a PAS policy table
64//! keyed by [`Scope`] and const-gated to [`Scope::ALL`]'s order.
65//!
66//! ## `EntityType` — the one entity vocabulary
67//!
68//! **What kind of entity a ppnum is.** One type, one name, one value-set,
69//! shared by the token engine and both services. Before this crate the same
70//! fact was reified four times — `accounts_core::EntityType` (6 variants),
71//! `chat_core::port::EntityClass` (5, a hand-maintained mirror),
72//! `ppoppo_token::EntityType` (3), and the `ppnum.EntityType` proto enum —
73//! and two of those disagreed about whether `delegated` was a member.
74//!
75//! ### The axis this crate is NOT
76//!
77//! `EntityType` answers *what the principal is*. It does **not** answer *who
78//! is currently acting for it* — that is the RFC 8693 §4.1 `act` claim, and
79//! keeping the two apart is the entire point.
80//!
81//! **There is deliberately no `Delegated` variant.** A human identity driven
82//! by an agent is `Human` **plus** `act` — two facts, two fields. Compressing
83//! them into one string field is the mistake
84//! `STS_AUTH_PPOPPO` §4.2.1 already rejected for the retired `role`
85//! claim; that rule was never applied to its two siblings
86//! (`EntityType::Delegated`, `SenderBadge::Delegated`), and this crate is
87//! where it finally is. Recovering "is this delegated?" from a *single* value
88//! is impossible by construction here.
89//!
90//! ### Why an engine-tier crate with no IO or transport dependency
91//!
92//! The type must be reachable from three places at once, and the crate
93//! lattice leaves exactly one option:
94//!
95//! - `ppoppo-token` needs it for the `entity_type` claim — and `engine →
96//!   shared` is **forbidden** (`xtask::policy::rules::taxonomy`), so a
97//!   `crates/shared/*` home is illegal. Engine tier it is.
98//! - `chat-core` needs it, and bans IO/transport crates (Constitution
99//!   Principle I). `std` plus the ULID codec both cores already carry is the
100//!   only shape it can accept — the same stance that already lets it depend
101//!   on `ppoppo-clock`.
102//!
103//! Sharing one type also **removes a value-set mirror**: `EntityClass`
104//! existed only to restate `scaccounts.ppnums.entity_type` inside PCS, and
105//! `DIRECTION_COUPLING_PASPCS` §4 **K5** records that mirror as a gap
106//! (PCS's drift test scopes `nspname='scchat'` and structurally cannot see
107//! `scaccounts`). With one type there is nothing left to drift.
108//!
109//! ### Table, not scattered predicates
110//!
111//! [`TABLE`] is the SSOT of per-variant *attributes*. Each fact previously
112//! lived somewhere else — the wire string in an `as_str` match,
113//! credential-eligibility in a PAS use-case, the AI-disclosure obligation in
114//! a doc comment. The enum is retained because exhaustive `match` is
115//! load-bearing: a sixth variant must fail to compile rather than default
116//! into a claim.
117//!
118//! Attributes that belong to **one** owner stay with that owner and are
119//! deliberately absent here — notably `number_class` (people/infra/
120//! ephemeral), a `GENERATED` column in `scaccounts` that PCS never reads.
121//! A shared table is not a dumping ground.
122//!
123//! ## `LifecycleState` — the one lifecycle vocabulary
124//!
125//! **What state a ppnum is in**, plus the legal transitions between states.
126//! Arrived by `RFC_202607251658` P1 for two reasons, and it carries the
127//! *transition lattice* as well as the value-set because of the second:
128//!
129//! - **PCS reads the value-set.** `chat-core` classifies
130//!   `scaccounts.ppnums.lifecycle_state` on its liveness path, and did so
131//!   through a hand-maintained 8-variant copy. Same unguardable shape as
132//!   `EntityClass` above — PCS's drift test is schema-scoped to `scchat` and
133//!   structurally cannot see a `scaccounts` `CHECK`
134//!   (`DIRECTION_COUPLING_PASPCS` §4 **K5** / §6 **I7**).
135//! - **[`can_transition_for_entity`](LifecycleState::can_transition_for_entity)
136//!   is a cross-fact.** It layers `ck_ppnums_expired_only_mask` — only
137//!   [`EntityType::Mask`] may reach [`LifecycleState::Expired`] — which is a
138//!   statement about *both* value-sets. Rust's orphan rule means whichever crate
139//!   does not own the type cannot say it as an inherent method, so leaving the
140//!   state machine in `accounts-core` would have required an extension trait:
141//!   the invariant expressible in two places again.
142//!
143//! This is not the dumping ground the paragraph above rules out. PAS keeps what
144//! only PAS reads — the column, the business triggers that drive transitions,
145//! and the audit trail. What moved is the fact neither organ could own alone.
146//!
147//! ## `effective_admin` — the one admin predicate
148//!
149//! **Not a value-set: a decision.** [`effective_admin`] answers "is this
150//! principal an effective admin" from three facts — the `is_admin` grant, the
151//! [`LifecycleState`] it is (or is not) in effect under, and how many active
152//! passkeys the principal holds. It arrived by `RFC_202608241353` T-01, and it
153//! arrived because the two organs had **stopped agreeing**:
154//!
155//! | Premise | PAS `/admin` | PCS admin RPCs (before) |
156//! |---|---|---|
157//! | `is_admin = TRUE` | checked | checked |
158//! | `lifecycle_state = 'active'` | checked | **not checked** |
159//! | at least one active passkey | checked, bounded | **not checked** |
160//!
161//! A deactivated account whose grant was never revoked was refused by one organ
162//! and admitted by the other. Roles persisting across lifecycle state is
163//! deliberate (`GUIDE_ADMIN_PAS` §4.8), which is exactly what made the missing
164//! term reachable rather than theoretical.
165//!
166//! The collapse is the same one the two value-sets above took, applied to a
167//! predicate: **one declaration, two callers.** Each organ's adapter gathers the
168//! premises from its own tier — PAS from `accounts-database`, PCS from its
169//! cross-schema read into `scaccounts` — and both hand them to the same
170//! function. Duplicating the conjunction in `chat-core` was the fast path and is
171//! rejected in the RFC's §8: a second declaration of a security predicate is the
172//! shape **K5** exists to forbid.
173//!
174//! Two things travel with the predicate rather than with its callers, because a
175//! caller-local copy of either would let the organs diverge again while both
176//! "used the shared function": the Layer-2 budget
177//! ([`ADMIN_PASSKEY_CHECK_TIMEOUT`]) and the *unknown* premise
178//! ([`ActivePasskeys::Unknown`]) that a blown budget produces. Protocol mapping
179//! — which status code, which page, which gRPC metadata — stays at each
180//! caller's edge, exactly as with everything else here.
181
182#![deny(rust_2018_idioms)]
183#![warn(missing_debug_implementations)]
184
185use core::fmt;
186
187mod admin;
188mod lifecycle;
189mod ppnum;
190mod scope;
191
192pub use admin::{
193    ACCESS_RECORD_RETENTION_DAYS, ACCESS_RECORD_RETENTION_FLOOR_DAYS, ADMIN_PASSKEY_CHECK_TIMEOUT,
194    ADMIN_PREMISE_COLUMNS, ActivePasskeys, AdminFacts, AdminLayer1, AdminPremiseColumn,
195    AdminVerdict, effective_admin,
196};
197pub use lifecycle::LifecycleState;
198pub use ppnum::{Ppnum, PpnumError, PpnumId};
199pub use scope::{SCOPE_TABLE, Scope, ScopeEnforcer, ScopeFacts, ScopeTier};
200
201/// What kind of entity a ppnum is.
202///
203/// Members are exactly the storable values of
204/// `scaccounts.ppnums.entity_type` (`ck_ppnums_entity_type_enum`) — bound to
205/// that constraint by the enrollment directly below, so the constraint name
206/// lives *on the fact*.
207///
208/// There is **no `non_stored` list**, and that is the point: every member of
209/// this vocabulary is a real, storable entity kind. The render-only
210/// `Delegated` that the retired PAS enum had to declare as an exception is not
211/// an exception here — it is simply not an entity type. See the module docs.
212///
213/// The `serde` impls are **feature-gated and off by default** (PCS caches
214/// `PpnumAccount` as JSON in KVRocks and needs them; the only other consumer is
215/// PAS's [`AdminLayer1`] cache value, which carries a [`LifecycleState`]). The
216/// wire form is `rename_all = "snake_case"` — byte-identical to
217/// [`as_str`](Self::as_str), and not by coincidence: `snake_case` of each
218/// variant *is* the canonical string, so the derive cannot drift from
219/// [`TABLE`]. If a variant ever needs a form `snake_case` does not produce,
220/// delete the derive and write a manual impl that delegates to `as_str` — a
221/// second spelling of the wire strings is precisely the mirror this crate
222/// exists to remove.
223#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
224#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
225#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
226pub enum EntityType {
227    /// Natural person. Also the class of a token whose `sub` is a human
228    /// being driven by an agent (ppnum lending) — the agent is `act`, not a
229    /// different entity type.
230    Human,
231    /// Business or organization.
232    Enterprise,
233    /// LLM-backed agent holding its own ppnum.
234    AiAgent,
235    /// Developer-programmable number (template / auto-reply). Infra class.
236    Programmable,
237    /// Ephemeral privacy-mediation proxy number with a TTL. Industry
238    /// analogue: Twilio Masking Numbers / 안심번호.
239    Mask,
240}
241
242// SSOT binding: the vocabulary must equal `ck_ppnums_entity_type_enum`.
243//
244// The enrollment lives here, next to the enum, rather than in PAS — which is
245// what `RFC_202607252223` T-03's tier move bought. While it sat in
246// `accounts-core` the DB binding could not follow the type up the lattice, so
247// a second PAS-local enum had to stay alive purely to hold it, and every
248// textual analysis of this vocabulary was ambiguous between the two.
249//
250// PAS still owns the *column* (and `number_class`, which is a `GENERATED`
251// column PCS never reads); this crate owns the *value-set*. Verification is
252// unchanged — `accounts-api/tests/schema_check_drift.rs` reads the
253// materialized `CHECK` via `pg_get_constraintdef` and asserts set-equality.
254ppoppo_schema_constrained::impl_schema_constrained!(EntityType via as_str {
255    all: [Human, Enterprise, AiAgent, Programmable, Mask],
256    constraints: ["ck_ppnums_entity_type_enum"],
257});
258
259/// One row of [`TABLE`] — every attribute of one entity type.
260#[derive(Debug, Clone, Copy, PartialEq, Eq)]
261pub struct EntityFacts {
262    /// The variant this row describes. Present so the row is self-describing
263    /// and the table↔enum wiring is checkable at compile time.
264    pub entity: EntityType,
265    /// Canonical wire/DB string. The value in `ppnums.entity_type`, in the
266    /// `entity_type` JWT claim, and on every wire that names an entity type.
267    pub wire: &'static str,
268    /// May this entity hold a minted credential (OAuth `client_credentials`)?
269    ///
270    /// **This is a policy, not an identity fact** — which is why it lives in
271    /// a table column rather than in the type. `false` means *no
272    /// credential-issuing flow exists today*, not *never will*: the External
273    /// Developer / enterprise lane is designed and unbuilt
274    /// (`STS_AUTH_PPOPPO` §6.4).
275    ///
276    /// Load-bearing in two places that must agree — the mint refuses a
277    /// principal with `false`, and the engine's M40 gate refuses such a
278    /// value on the wire. One declaration, two enforcement points, which is
279    /// what lets the K8 reachability guard assert an *equality* rather than
280    /// an inclusion.
281    pub can_hold_credential: bool,
282    /// Does a message from this entity carry a mandatory AI-disclosure
283    /// obligation? (EU AI Act Art.50 / KR AI기본법.)
284    ///
285    /// Note this is keyed on the *entity*, so it does **not** cover a human
286    /// ppnum driven by an agent — that case is `Human` + `act`, and the
287    /// obligation there follows from the delegation, not from this column.
288    pub requires_ai_disclosure: bool,
289}
290
291/// **The lookup table — SSOT of every per-variant attribute.**
292///
293/// Ordered identically to [`EntityType::ALL`]; the const gate below proves
294/// it, so the two can never be read out of step.
295pub const TABLE: [EntityFacts; 5] = [
296    EntityFacts {
297        entity: EntityType::Human,
298        wire: "human",
299        can_hold_credential: true,
300        requires_ai_disclosure: false,
301    },
302    EntityFacts {
303        entity: EntityType::Enterprise,
304        wire: "enterprise",
305        // No credential-issuing flow. AUTH §6.4 records the lane as
306        // designed-but-unbuilt; opening it flips this cell, and the K8
307        // guard fails until the mint path moves with it.
308        can_hold_credential: false,
309        requires_ai_disclosure: false,
310    },
311    EntityFacts {
312        entity: EntityType::AiAgent,
313        wire: "ai_agent",
314        can_hold_credential: true,
315        requires_ai_disclosure: true,
316    },
317    EntityFacts {
318        entity: EntityType::Programmable,
319        wire: "programmable",
320        can_hold_credential: true,
321        // Infra class — a template/auto-reply number is not an AI system.
322        requires_ai_disclosure: false,
323    },
324    EntityFacts {
325        entity: EntityType::Mask,
326        wire: "mask",
327        // A mask is a presentation alias for someone else; it does not
328        // authenticate as itself.
329        can_hold_credential: false,
330        requires_ai_disclosure: false,
331    },
332];
333
334impl EntityType {
335    /// Every variant. Ordered as [`TABLE`].
336    pub const ALL: [EntityType; 5] = [
337        Self::Human,
338        Self::Enterprise,
339        Self::AiAgent,
340        Self::Programmable,
341        Self::Mask,
342    ];
343
344    /// Stable position in [`ALL`](Self::ALL) / [`TABLE`].
345    ///
346    /// The exhaustive `match` is the compile-time gate: a sixth variant
347    /// fails to build here, so it cannot reach a claim by defaulting.
348    #[must_use]
349    pub const fn index(self) -> usize {
350        match self {
351            Self::Human => 0,
352            Self::Enterprise => 1,
353            Self::AiAgent => 2,
354            Self::Programmable => 3,
355            Self::Mask => 4,
356        }
357    }
358
359    /// This variant's row. Every attribute accessor below reads through it,
360    /// so [`TABLE`] is the only place an attribute is stated.
361    #[must_use]
362    pub const fn facts(self) -> &'static EntityFacts {
363        &TABLE[self.index()]
364    }
365
366    /// Canonical wire/DB string.
367    #[must_use]
368    pub const fn as_str(self) -> &'static str {
369        self.facts().wire
370    }
371
372    /// May this entity hold a minted credential? See
373    /// [`EntityFacts::can_hold_credential`].
374    #[must_use]
375    pub const fn can_hold_credential(self) -> bool {
376        self.facts().can_hold_credential
377    }
378
379    /// Does this entity carry an AI-disclosure obligation? See
380    /// [`EntityFacts::requires_ai_disclosure`].
381    #[must_use]
382    pub const fn requires_ai_disclosure(self) -> bool {
383        self.facts().requires_ai_disclosure
384    }
385
386    /// Parse a canonical wire string. Exact inverse of
387    /// [`as_str`](Self::as_str).
388    ///
389    /// `None` for anything outside the vocabulary — notably `"delegated"`,
390    /// which is a *session mode* and never an entity type. Callers on a
391    /// verify path MUST treat `None` as a forgery signal, not as an
392    /// unknown-but-tolerable value.
393    #[must_use]
394    pub fn parse(s: &str) -> Option<Self> {
395        Self::ALL.into_iter().find(|e| e.as_str() == s)
396    }
397}
398
399impl fmt::Display for EntityType {
400    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
401        f.write_str(self.as_str())
402    }
403}
404
405// ── Compile-time gates ──────────────────────────────────────────────────
406//
407// `TABLE` and `ALL` are two orderings of one fact; nothing at runtime would
408// notice them diverging, so it is settled at build time.
409const _: () = {
410    assert!(TABLE.len() == EntityType::ALL.len());
411
412    // Row i describes variant i — a mis-ordered table cannot compile.
413    let mut i = 0;
414    while i < EntityType::ALL.len() {
415        assert!(TABLE[i].entity.index() == EntityType::ALL[i].index());
416        i += 1;
417    }
418
419    // `facts()` resolves each variant to its OWN row (a copy-paste slip in
420    // the `index()` match would otherwise hand back a neighbour's
421    // attributes — including `can_hold_credential`, a security gate).
422    let mut i = 0;
423    while i < EntityType::ALL.len() {
424        assert!(EntityType::ALL[i].facts().entity.index() == EntityType::ALL[i].index());
425        i += 1;
426    }
427};
428
429#[cfg(test)]
430// Outer, not the usual inner `#![allow(..)]`: ARCH-BOUNDARY pins the exact
431// inner-attribute block of a published-tier `lib.rs` and scans every line,
432// so an indented inner attribute inside this module trips it too.
433#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
434mod tests {
435    use super::*;
436
437    #[test]
438    fn parse_is_the_inverse_of_as_str() {
439        for e in EntityType::ALL {
440            assert_eq!(EntityType::parse(e.as_str()), Some(e));
441        }
442    }
443
444    /// The value this crate exists to make unspellable. `"delegated"` is a
445    /// session mode carried by `act`; it was never an entity type and must
446    /// not become one again.
447    #[test]
448    fn delegated_is_not_an_entity_type() {
449        assert_eq!(EntityType::parse("delegated"), None);
450    }
451
452    #[test]
453    fn unknown_strings_do_not_parse() {
454        for s in ["", "HUMAN", "human ", "user", "bot", "service", "virtual"] {
455            assert_eq!(EntityType::parse(s), None, "{s:?} must not parse");
456        }
457    }
458
459    /// Pins the credential-eligible set. This is the M40 admitted set and a
460    /// security boundary — widening it is a deliberate act, so it should
461    /// require editing an assertion that says so.
462    #[test]
463    fn credential_eligible_set_is_pinned() {
464        let eligible: Vec<_> = EntityType::ALL
465            .into_iter()
466            .filter(|e| e.can_hold_credential())
467            .collect();
468        assert_eq!(
469            eligible,
470            vec![
471                EntityType::Human,
472                EntityType::AiAgent,
473                EntityType::Programmable
474            ],
475            "the credential-eligible set changed — this is the M40 admitted \
476             set (a forgery gate). Widening it must move the mint path in the \
477             same change, or the K8 reachability guard will fail."
478        );
479    }
480
481    /// **The `serde` derive must encode exactly `as_str`.**
482    ///
483    /// Load-bearing beyond tidiness: PCS caches `PpnumAccount` as JSON in
484    /// KVRocks and `get_typed` propagates a deserialize failure rather than
485    /// treating it as a miss, so an encoding change would turn every cached
486    /// account into a hard error until the TTL expired. The retired
487    /// `chat_core::port::EntityClass` encoded via `rename_all = "snake_case"`
488    /// over the same five variants; this pins that the replacement is
489    /// byte-identical, so live cache entries written before the collapse still
490    /// read back.
491    ///
492    /// It also pins the claim in the type's doc comment that `snake_case`
493    /// *is* the canonical string — asserted over `ALL`, so a variant whose
494    /// `snake_case` diverges from its `TABLE` row fails here instead of
495    /// silently minting a second wire spelling.
496    #[cfg(feature = "serde")]
497    #[test]
498    fn serde_encoding_is_exactly_as_str() {
499        for e in EntityType::ALL {
500            let json = serde_json::to_string(&e).expect("serialize");
501            assert_eq!(
502                json,
503                format!("\"{}\"", e.as_str()),
504                "the serde derive drifted from `as_str` for {e:?} — this breaks \
505                 every JSON-cached PpnumAccount and mints a second spelling of \
506                 the wire strings"
507            );
508            assert_eq!(
509                serde_json::from_str::<EntityType>(&json).expect("deserialize"),
510                e,
511            );
512        }
513    }
514
515    /// AI disclosure is an entity property; delegation is not covered here
516    /// (a human driven by an agent is `Human` + `act`).
517    #[test]
518    fn ai_disclosure_is_agent_only() {
519        for e in EntityType::ALL {
520            assert_eq!(e.requires_ai_disclosure(), e == EntityType::AiAgent);
521        }
522    }
523}