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.
228    Human,
229    /// Business or organization.
230    Enterprise,
231    /// LLM-backed agent holding its own ppnum.
232    AiAgent,
233    /// Developer-programmable number (template / auto-reply). Infra class.
234    Programmable,
235    /// Ephemeral privacy-mediation proxy number with a TTL. Industry
236    /// analogue: Twilio Masking Numbers / 안심번호.
237    Mask,
238}
239
240// SSOT binding: the vocabulary must equal `ck_ppnums_entity_type_enum`.
241//
242// The enrollment lives here, next to the enum, rather than in PAS — which is
243// what `RFC_202607252223` T-03's tier move bought. While it sat in
244// `accounts-core` the DB binding could not follow the type up the lattice, so
245// a second PAS-local enum had to stay alive purely to hold it, and every
246// textual analysis of this vocabulary was ambiguous between the two.
247//
248// PAS still owns the *column* (and `number_class`, which is a `GENERATED`
249// column PCS never reads); this crate owns the *value-set*. Verification is
250// unchanged — `accounts-api/tests/schema_check_drift.rs` reads the
251// materialized `CHECK` via `pg_get_constraintdef` and asserts set-equality.
252ppoppo_schema_constrained::impl_schema_constrained!(EntityType via as_str {
253    all: [Human, Enterprise, AiAgent, Programmable, Mask],
254    constraints: ["ck_ppnums_entity_type_enum"],
255});
256
257/// One row of [`TABLE`] — every attribute of one entity type.
258#[derive(Debug, Clone, Copy, PartialEq, Eq)]
259pub struct EntityFacts {
260    /// The variant this row describes. Present so the row is self-describing
261    /// and the table↔enum wiring is checkable at compile time.
262    pub entity: EntityType,
263    /// Canonical wire/DB string. The value in `ppnums.entity_type`, in the
264    /// `entity_type` JWT claim, and on every wire that names an entity type.
265    pub wire: &'static str,
266    /// May this entity hold a minted credential (OAuth `client_credentials`)?
267    ///
268    /// **This is a policy, not an identity fact** — which is why it lives in
269    /// a table column rather than in the type. `false` means *no
270    /// credential-issuing flow exists today*, not *never will*: the External
271    /// Developer / enterprise lane is designed and unbuilt
272    /// (`STS_AUTH_PPOPPO` §6.4).
273    ///
274    /// Load-bearing in two places that must agree — the mint refuses a
275    /// principal with `false`, and the engine's M40 gate refuses such a
276    /// value on the wire. One declaration, two enforcement points, which is
277    /// what lets the K8 reachability guard assert an *equality* rather than
278    /// an inclusion.
279    pub can_hold_credential: bool,
280    /// Does a message from this entity carry a mandatory AI-disclosure
281    /// obligation? (EU AI Act Art.50 / KR AI기본법.)
282    ///
283    /// Keyed on the *entity*, and that is the whole obligation: an agent
284    /// speaks as itself, under its own `AiAgent` ppnum. There is no human
285    /// ppnum driven by an agent to disclose separately — ppoppo refuses
286    /// identity lending (`ADR_202609271736`).
287    pub requires_ai_disclosure: bool,
288}
289
290/// **The lookup table — SSOT of every per-variant attribute.**
291///
292/// Ordered identically to [`EntityType::ALL`]; the const gate below proves
293/// it, so the two can never be read out of step.
294pub const TABLE: [EntityFacts; 5] = [
295    EntityFacts {
296        entity: EntityType::Human,
297        wire: "human",
298        can_hold_credential: true,
299        requires_ai_disclosure: false,
300    },
301    EntityFacts {
302        entity: EntityType::Enterprise,
303        wire: "enterprise",
304        // No credential-issuing flow. AUTH §6.4 records the lane as
305        // designed-but-unbuilt; opening it flips this cell, and the K8
306        // guard fails until the mint path moves with it.
307        can_hold_credential: false,
308        requires_ai_disclosure: false,
309    },
310    EntityFacts {
311        entity: EntityType::AiAgent,
312        wire: "ai_agent",
313        can_hold_credential: true,
314        requires_ai_disclosure: true,
315    },
316    EntityFacts {
317        entity: EntityType::Programmable,
318        wire: "programmable",
319        can_hold_credential: true,
320        // Infra class — a template/auto-reply number is not an AI system.
321        requires_ai_disclosure: false,
322    },
323    EntityFacts {
324        entity: EntityType::Mask,
325        wire: "mask",
326        // A mask is a presentation alias for someone else; it does not
327        // authenticate as itself.
328        can_hold_credential: false,
329        requires_ai_disclosure: false,
330    },
331];
332
333impl EntityType {
334    /// Every variant. Ordered as [`TABLE`].
335    pub const ALL: [EntityType; 5] = [
336        Self::Human,
337        Self::Enterprise,
338        Self::AiAgent,
339        Self::Programmable,
340        Self::Mask,
341    ];
342
343    /// Stable position in [`ALL`](Self::ALL) / [`TABLE`].
344    ///
345    /// The exhaustive `match` is the compile-time gate: a sixth variant
346    /// fails to build here, so it cannot reach a claim by defaulting.
347    #[must_use]
348    pub const fn index(self) -> usize {
349        match self {
350            Self::Human => 0,
351            Self::Enterprise => 1,
352            Self::AiAgent => 2,
353            Self::Programmable => 3,
354            Self::Mask => 4,
355        }
356    }
357
358    /// This variant's row. Every attribute accessor below reads through it,
359    /// so [`TABLE`] is the only place an attribute is stated.
360    #[must_use]
361    pub const fn facts(self) -> &'static EntityFacts {
362        &TABLE[self.index()]
363    }
364
365    /// Canonical wire/DB string.
366    #[must_use]
367    pub const fn as_str(self) -> &'static str {
368        self.facts().wire
369    }
370
371    /// May this entity hold a minted credential? See
372    /// [`EntityFacts::can_hold_credential`].
373    #[must_use]
374    pub const fn can_hold_credential(self) -> bool {
375        self.facts().can_hold_credential
376    }
377
378    /// Does this entity carry an AI-disclosure obligation? See
379    /// [`EntityFacts::requires_ai_disclosure`].
380    #[must_use]
381    pub const fn requires_ai_disclosure(self) -> bool {
382        self.facts().requires_ai_disclosure
383    }
384
385    /// Parse a canonical wire string. Exact inverse of
386    /// [`as_str`](Self::as_str).
387    ///
388    /// `None` for anything outside the vocabulary — notably `"delegated"`,
389    /// which is a *session mode* and never an entity type. Callers on a
390    /// verify path MUST treat `None` as a forgery signal, not as an
391    /// unknown-but-tolerable value.
392    #[must_use]
393    pub fn parse(s: &str) -> Option<Self> {
394        Self::ALL.into_iter().find(|e| e.as_str() == s)
395    }
396}
397
398impl fmt::Display for EntityType {
399    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
400        f.write_str(self.as_str())
401    }
402}
403
404// ── Compile-time gates ──────────────────────────────────────────────────
405//
406// `TABLE` and `ALL` are two orderings of one fact; nothing at runtime would
407// notice them diverging, so it is settled at build time.
408const _: () = {
409    assert!(TABLE.len() == EntityType::ALL.len());
410
411    // Row i describes variant i — a mis-ordered table cannot compile.
412    let mut i = 0;
413    while i < EntityType::ALL.len() {
414        assert!(TABLE[i].entity.index() == EntityType::ALL[i].index());
415        i += 1;
416    }
417
418    // `facts()` resolves each variant to its OWN row (a copy-paste slip in
419    // the `index()` match would otherwise hand back a neighbour's
420    // attributes — including `can_hold_credential`, a security gate).
421    let mut i = 0;
422    while i < EntityType::ALL.len() {
423        assert!(EntityType::ALL[i].facts().entity.index() == EntityType::ALL[i].index());
424        i += 1;
425    }
426};
427
428#[cfg(test)]
429// Outer, not the usual inner `#![allow(..)]`: ARCH-BOUNDARY pins the exact
430// inner-attribute block of a published-tier `lib.rs` and scans every line,
431// so an indented inner attribute inside this module trips it too.
432#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
433mod tests {
434    use super::*;
435
436    #[test]
437    fn parse_is_the_inverse_of_as_str() {
438        for e in EntityType::ALL {
439            assert_eq!(EntityType::parse(e.as_str()), Some(e));
440        }
441    }
442
443    /// The value this crate exists to make unspellable. `"delegated"` is a
444    /// session mode carried by `act`; it was never an entity type and must
445    /// not become one again.
446    #[test]
447    fn delegated_is_not_an_entity_type() {
448        assert_eq!(EntityType::parse("delegated"), None);
449    }
450
451    #[test]
452    fn unknown_strings_do_not_parse() {
453        for s in ["", "HUMAN", "human ", "user", "bot", "service", "virtual"] {
454            assert_eq!(EntityType::parse(s), None, "{s:?} must not parse");
455        }
456    }
457
458    /// Pins the credential-eligible set. This is the M40 admitted set and a
459    /// security boundary — widening it is a deliberate act, so it should
460    /// require editing an assertion that says so.
461    #[test]
462    fn credential_eligible_set_is_pinned() {
463        let eligible: Vec<_> = EntityType::ALL
464            .into_iter()
465            .filter(|e| e.can_hold_credential())
466            .collect();
467        assert_eq!(
468            eligible,
469            vec![
470                EntityType::Human,
471                EntityType::AiAgent,
472                EntityType::Programmable
473            ],
474            "the credential-eligible set changed — this is the M40 admitted \
475             set (a forgery gate). Widening it must move the mint path in the \
476             same change, or the K8 reachability guard will fail."
477        );
478    }
479
480    /// **The `serde` derive must encode exactly `as_str`.**
481    ///
482    /// Load-bearing beyond tidiness: PCS caches `PpnumAccount` as JSON in
483    /// KVRocks and `get_typed` propagates a deserialize failure rather than
484    /// treating it as a miss, so an encoding change would turn every cached
485    /// account into a hard error until the TTL expired. The retired
486    /// `chat_core::port::EntityClass` encoded via `rename_all = "snake_case"`
487    /// over the same five variants; this pins that the replacement is
488    /// byte-identical, so live cache entries written before the collapse still
489    /// read back.
490    ///
491    /// It also pins the claim in the type's doc comment that `snake_case`
492    /// *is* the canonical string — asserted over `ALL`, so a variant whose
493    /// `snake_case` diverges from its `TABLE` row fails here instead of
494    /// silently minting a second wire spelling.
495    #[cfg(feature = "serde")]
496    #[test]
497    fn serde_encoding_is_exactly_as_str() {
498        for e in EntityType::ALL {
499            let json = serde_json::to_string(&e).expect("serialize");
500            assert_eq!(
501                json,
502                format!("\"{}\"", e.as_str()),
503                "the serde derive drifted from `as_str` for {e:?} — this breaks \
504                 every JSON-cached PpnumAccount and mints a second spelling of \
505                 the wire strings"
506            );
507            assert_eq!(
508                serde_json::from_str::<EntityType>(&json).expect("deserialize"),
509                e,
510            );
511        }
512    }
513
514    /// AI disclosure is an entity property.
515    #[test]
516    fn ai_disclosure_is_agent_only() {
517        for e in EntityType::ALL {
518            assert_eq!(e.requires_ai_disclosure(), e == EntityType::AiAgent);
519        }
520    }
521}