ppoppo-identity 0.31.0

Principal-identity vocabulary for the ppoppo ecosystem — the Ppnum/PpnumId pair, the EntityType, LifecycleState and OAuth Scope value-sets, and the admin predicate, shared by the token engine, both services and every SDK
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
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
//! Ppnum — the `scaccounts.ppnums.ppnum` format, its paired `ppnums.id`, and
//! the one display grammar. Private module; [`Ppnum`], [`PpnumError`] and
//! [`PpnumId`] are re-exported at the crate root, which is the only public
//! path. **Why they live in this crate rather than in any organ or SDK: see
//! the crate docs, §`Ppnum` / `PpnumId`.**

use core::fmt;
use core::str::FromStr;

use ulid::Ulid;

/// A validated Ppoppo Number — the digit string in `scaccounts.ppnums.ppnum`.
///
/// Holding a `Ppnum` proves the value satisfies the column's format rule,
/// which is stated exactly once, here, as [`MIN_LEN`](Self::MIN_LEN) and the
/// digit-only check in [`parse`](Self::parse): **at least 11 ASCII digits**,
/// the [`ck_ppnums_format`](Self::CONSTRAINT) `CHECK`
/// [`^[0-9]{11,}$`](Self::PATTERN). Every organ and every SDK reads the rule
/// through this type; before this crate carried it the rule was restated six
/// times and two of the copies said `== 11`, which refused every dependent
/// (15-digit) ppnum PAS mints.
///
/// # What this type is not
///
/// - **Not the issuance ladder.** PAS mints lengths `11 + 4·depth` for
///   `depth ≤ 5` (11 / 15 / … / 31). That is *issuance policy* PCS never
///   reads, so it stays in `accounts-core` (`PpnumLength`) — the same rule
///   that keeps `number_class` out of this crate. A 12-digit string is a valid
///   `Ppnum` here because the column admits it; whether PAS would ever mint
///   one is PAS's business.
/// - **Not a display value.** [`Display`](fmt::Display) and
///   [`as_str`](Self::as_str) are the **wire/storage form** — raw digits — the
///   spelling every `.proto` field, JSON claim, DB column and `Cargo` consumer
///   agrees on. Humans see the hyphenated form; that is a rendering, produced
///   by [`display`](Self::display) / [`display_form`](Self::display_form) and
///   accepted back by [`from_display`](Self::from_display), and it never
///   leaks into a `Ppnum`'s representation.
/// - **Not prefix-aware.** The leading digits are a band-allocation
///   convention with no semantic meaning; class is decided by
///   `ppnums.entity_type` server-side (PAS Constitution Principle III). Nothing
///   here inspects them.
///
/// The `serde` impls are **feature-gated and off by default** and go through
/// [`TryFrom<String>`] / [`Into<String>`], so a deserialized `Ppnum` is
/// validated exactly as a parsed one — the wire cannot smuggle a malformed
/// value past the constructor.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(try_from = "String", into = "String"))]
pub struct Ppnum(String);

impl Ppnum {
    /// Minimum digit count — the `{11,}` of [`PATTERN`](Self::PATTERN).
    ///
    /// The one place the number 11 is a *rule*. Callers that need the
    /// independent-tier length (band-slot arithmetic, display grouping) read
    /// it from here.
    pub const MIN_LEN: usize = 11;

    /// The `CHECK` constraint this type is the Rust reading of — named on the
    /// fact, the way [`EntityType`](crate::EntityType) names
    /// `ck_ppnums_entity_type_enum`. Not an enrollment: the constraint is a
    /// regex over a text column, not a value-set, so
    /// `ppoppo-schema-constrained` has no binding for it; the drift guard is
    /// the owning service's schema test asserting the materialized definition
    /// still reads [`PATTERN`](Self::PATTERN).
    pub const CONSTRAINT: &'static str = "ck_ppnums_format";

    /// The constraint's pattern, verbatim from the baseline migration.
    pub const PATTERN: &'static str = "^[0-9]{11,}$";

    /// Parse the wire form: ASCII digits only, at least
    /// [`MIN_LEN`](Self::MIN_LEN) of them. Exact inverse of
    /// [`as_str`](Self::as_str).
    ///
    /// Rejects separators — `"123-1234-5678"` is [`PpnumError::NonDigit`],
    /// not a lenient success. A caller holding a human-typed string wants
    /// [`from_display`](Self::from_display).
    ///
    /// # Errors
    ///
    /// [`PpnumError::Empty`] for `""`; [`PpnumError::NonDigit`] at the first
    /// non-digit byte (checked before length, so `"12a"` names the byte
    /// rather than the shortfall); [`PpnumError::TooShort`] below
    /// [`MIN_LEN`](Self::MIN_LEN).
    pub fn parse(s: &str) -> Result<Self, PpnumError> {
        validate(s)?;
        Ok(Self(s.to_owned()))
    }

    /// Parse a human spelling: the wire form with optional `-` and ASCII
    /// whitespace separators (`"100-0020-7095"`, `"100 0020 7095"`).
    ///
    /// Only those two separator classes are stripped. This is deliberately
    /// **not** a digit scrape: `"@bot-100-0020-7095"` must fail rather than
    /// resolve a real human's number from a string that is not a ppnum at
    /// all — the `@alias` form 1st-party clients invent client-side was
    /// silently projected onto an account by exactly such a scrape once
    /// (`chat-database/tests/accounts_api_adapter_ppnum_display_form.rs`).
    ///
    /// # Errors
    ///
    /// As [`parse`](Self::parse), evaluated over the separator-stripped
    /// input (so a [`PpnumError::NonDigit`] position counts digits and other
    /// non-separators only).
    pub fn from_display(s: &str) -> Result<Self, PpnumError> {
        let digits: String = s
            .chars()
            .filter(|c| !(*c == '-' || c.is_ascii_whitespace()))
            .collect();
        validate(&digits)?;
        Ok(Self(digits))
    }

    /// The wire/storage form: raw digits.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Consume into the owned digit string.
    #[must_use]
    pub fn into_string(self) -> String {
        self.0
    }

    /// The human form of this ppnum — see [`display_form`](Self::display_form).
    #[must_use]
    pub fn display(&self) -> String {
        Self::display_form(&self.0)
    }

    /// The one display grammar: `XXX-XXXX-XXXX[-XXXX]*` — the independent
    /// 11-digit tier grouped 3-4-4, then every further nesting level as its
    /// own 4-digit group (`100-3829-1750-0001` for a depth-1 dependent).
    ///
    /// Takes a `&str` rather than `&self` because the strings a renderer holds
    /// come off the wire or a row and are not `Ppnum`s. For a string that is
    /// not a valid ppnum the input is echoed **unchanged**: a renderer must
    /// never fail on a value it did not mint, and a wrong-looking string
    /// shown verbatim is a better signal than a wrong-looking string dressed
    /// up as a ppnum.
    #[must_use]
    pub fn display_form(s: &str) -> String {
        if validate(s).is_err() {
            return s.to_owned();
        }
        let mut out = String::with_capacity(s.len() + s.len() / 4 + 1);
        out.push_str(&s[0..3]);
        out.push('-');
        out.push_str(&s[3..7]);
        out.push('-');
        out.push_str(&s[7..Self::MIN_LEN]);
        let mut pos = Self::MIN_LEN;
        while pos < s.len() {
            let end = (pos + 4).min(s.len());
            out.push('-');
            out.push_str(&s[pos..end]);
            pos = end;
        }
        out
    }
}

/// The format rule, stated once. Every constructor goes through here.
fn validate(s: &str) -> Result<(), PpnumError> {
    if s.is_empty() {
        return Err(PpnumError::Empty);
    }
    if let Some(pos) = s.bytes().position(|b| !b.is_ascii_digit()) {
        return Err(PpnumError::NonDigit { pos });
    }
    if s.len() < Ppnum::MIN_LEN {
        return Err(PpnumError::TooShort { len: s.len() });
    }
    Ok(())
}

impl fmt::Display for Ppnum {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

impl AsRef<str> for Ppnum {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

impl FromStr for Ppnum {
    type Err = PpnumError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::parse(s)
    }
}

impl TryFrom<String> for Ppnum {
    type Error = PpnumError;

    fn try_from(s: String) -> Result<Self, Self::Error> {
        validate(&s)?;
        Ok(Self(s))
    }
}

impl From<Ppnum> for String {
    fn from(p: Ppnum) -> Self {
        p.0
    }
}

/// Why a string is not a [`Ppnum`].
///
/// Three variants rather than one opaque "invalid" so a rejection can say
/// *which* rule the input broke — the shape both published SDKs already
/// exposed before the type moved here.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum PpnumError {
    /// The input was `""`.
    Empty,
    /// Fewer than [`Ppnum::MIN_LEN`] digits.
    TooShort {
        /// How many digits were supplied.
        len: usize,
    },
    /// A byte that is not an ASCII digit.
    NonDigit {
        /// Byte index of the first non-digit.
        pos: usize,
    },
}

impl fmt::Display for PpnumError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Empty => f.write_str("ppnum is empty"),
            Self::TooShort { len } => write!(
                f,
                "ppnum too short ({len} digits, minimum {})",
                Ppnum::MIN_LEN
            ),
            Self::NonDigit { pos } => {
                write!(f, "ppnum contains non-digit character at position {pos}")
            }
        }
    }
}

impl std::error::Error for PpnumError {}

/// The `scaccounts.ppnums.id` ULID — the identifier every organ stores
/// **paired** with the [`Ppnum`] it names.
///
/// One type for the three places that used to declare it: PAS's
/// `PpnumAccountId` (the primary key it mints), PCS's `PpnumId` (the
/// cross-schema foreign key it stores), and the SDK's `PpnumId` (the OAuth
/// `sub` claim it verifies). They were the same 26-character ULID under three
/// names, and a value that crosses the organ boundary under one name in the
/// database deserves one name in Rust.
///
/// [`new`](Self::new) mints a fresh id. That is PAS's job in production — PCS
/// and the SDKs only ever receive one — but every organ's tests need one, and
/// a vocabulary crate that can name a value but not construct it is the wrong
/// shape.
///
/// The `serde` impl is feature-gated like the crate's other types and is
/// `transparent`: the JSON form is the bare ULID string, byte-identical to
/// [`Display`](fmt::Display) — the encoding every existing row, cache entry
/// and claim already uses.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(transparent))]
pub struct PpnumId(pub Ulid);

impl PpnumId {
    /// Mint a fresh, time-ordered id.
    #[must_use]
    pub fn new() -> Self {
        Self(Ulid::generate())
    }

    /// The all-zero id. A fixture value, never a real account.
    #[must_use]
    pub const fn nil() -> Self {
        Self(Ulid::nil())
    }
}

impl Default for PpnumId {
    fn default() -> Self {
        Self::new()
    }
}

impl fmt::Display for PpnumId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(&self.0, f)
    }
}

impl FromStr for PpnumId {
    type Err = ulid::DecodeError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ulid::from_str(s).map(Self)
    }
}

impl From<Ulid> for PpnumId {
    fn from(u: Ulid) -> Self {
        Self(u)
    }
}

impl From<PpnumId> for Ulid {
    fn from(id: PpnumId) -> Self {
        id.0
    }
}

#[cfg(test)]
// Outer, not the usual inner `#![allow(..)]`: see `lib.rs`'s test module.
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod tests {
    use super::*;

    #[test]
    fn eleven_digits_is_the_floor_and_any_first_digit_is_valid() {
        for first in '0'..='9' {
            let s = format!("{first}0012345678");
            assert_eq!(Ppnum::parse(&s).unwrap().as_str(), s, "{s} must parse");
        }
        assert_eq!(
            Ppnum::parse("1234567890"),
            Err(PpnumError::TooShort { len: 10 })
        );
    }

    /// The rule is `{11,}`, not `== 11`. A dependent-agent ppnum is 15, 19,
    /// … digits and PCS used to refuse every one of them.
    #[test]
    fn longer_tiers_are_valid_ppnums() {
        for s in [
            "123123456780001",
            "1231234567800010001",
            "12312345678000100010001",
        ] {
            assert!(Ppnum::parse(s).is_ok(), "{s} must parse");
        }
        // The column admits any length ≥ 11; the ladder is PAS's, not ours.
        assert!(Ppnum::parse("123456789012").is_ok());
    }

    #[test]
    fn non_digits_are_named_by_position_before_length_is_judged() {
        assert_eq!(
            Ppnum::parse("1234567890a"),
            Err(PpnumError::NonDigit { pos: 10 })
        );
        assert_eq!(Ppnum::parse("12a"), Err(PpnumError::NonDigit { pos: 2 }));
        assert_eq!(
            Ppnum::parse("123-1234-5678"),
            Err(PpnumError::NonDigit { pos: 3 })
        );
        assert_eq!(
            Ppnum::parse("12312345678 "),
            Err(PpnumError::NonDigit { pos: 11 })
        );
        assert_eq!(Ppnum::parse(""), Err(PpnumError::Empty));
    }

    /// `is_ascii_digit` is a byte predicate: fullwidth, Arabic-Indic and
    /// Bengali digits are multi-byte and must not pass.
    #[test]
    fn unicode_digits_are_not_digits() {
        for s in ["12312345678", "١٢٣١٢٣٤٥٦٧٨", "১২৩১২৩৪৫৬৭৮"]
        {
            assert!(matches!(
                Ppnum::parse(s),
                Err(PpnumError::NonDigit { pos: 0 })
            ));
        }
    }

    #[test]
    fn from_display_strips_only_hyphens_and_whitespace() {
        let want = Ppnum::parse("10000207095").unwrap();
        assert_eq!(Ppnum::from_display("100-0020-7095").unwrap(), want);
        assert_eq!(Ppnum::from_display("100 0020 7095").unwrap(), want);
        assert_eq!(Ppnum::from_display(" 100-0020-7095\t").unwrap(), want);
        assert_eq!(Ppnum::from_display("10000207095").unwrap(), want);
        // Not a digit scrape: an alias-shaped string stays a miss.
        assert!(matches!(
            Ppnum::from_display("@bot-100-0020-7095"),
            Err(PpnumError::NonDigit { pos: 0 })
        ));
        assert!(matches!(
            Ppnum::from_display("kr:010-1234-5678"),
            Err(PpnumError::NonDigit { .. })
        ));
        assert_eq!(Ppnum::from_display("- -"), Err(PpnumError::Empty));
    }

    #[test]
    fn display_form_groups_three_four_four_then_fours() {
        assert_eq!(Ppnum::display_form("77712345678"), "777-1234-5678");
        assert_eq!(Ppnum::display_form("100382917500001"), "100-3829-1750-0001");
        assert_eq!(
            Ppnum::display_form("1003829175000010001"),
            "100-3829-1750-0001-0001"
        );
        assert_eq!(
            Ppnum::display_form("10038291750000100015678"),
            "100-3829-1750-0001-0001-5678"
        );
        // A 12-digit value is a valid ppnum; its tail is a short group.
        assert_eq!(Ppnum::display_form("123456789012"), "123-4567-8901-2");
    }

    /// A renderer never fails on a string it did not mint.
    #[test]
    fn display_form_echoes_anything_that_is_not_a_ppnum() {
        for s in ["123", "", "abc", "777-1234-5678", "1234567890"] {
            assert_eq!(Ppnum::display_form(s), s);
        }
    }

    #[test]
    fn display_and_from_display_round_trip() {
        for s in ["77712345678", "100382917500001", "1003829175000010001"] {
            let p = Ppnum::parse(s).unwrap();
            assert_eq!(Ppnum::from_display(&p.display()).unwrap(), p);
            assert_eq!(p.to_string(), s, "Display is the wire form");
        }
    }

    #[test]
    fn errors_render_the_rule_they_name() {
        assert_eq!(PpnumError::Empty.to_string(), "ppnum is empty");
        assert_eq!(
            PpnumError::TooShort { len: 10 }.to_string(),
            "ppnum too short (10 digits, minimum 11)"
        );
        assert_eq!(
            PpnumError::NonDigit { pos: 3 }.to_string(),
            "ppnum contains non-digit character at position 3"
        );
    }

    #[test]
    fn ppnum_id_round_trips_through_its_string_form() {
        let id = PpnumId::new();
        assert_eq!(id.to_string().len(), 26);
        assert_eq!(id.to_string().parse::<PpnumId>().unwrap(), id);
        assert!("not-a-ulid".parse::<PpnumId>().is_err());
        assert_eq!(PpnumId::nil().to_string(), "00000000000000000000000000");
        assert_ne!(PpnumId::new(), PpnumId::new());
    }

    #[cfg(feature = "serde")]
    #[test]
    fn serde_forms_are_the_wire_forms() {
        let p = Ppnum::parse("12312345678").unwrap();
        let json = serde_json::to_string(&p).unwrap();
        assert_eq!(json, "\"12312345678\"");
        assert_eq!(serde_json::from_str::<Ppnum>(&json).unwrap(), p);
        // Deserialization is a constructor: it validates.
        for bad in ["\"123\"", "\"abc12345678\"", "\"\"", "\"123-1234-5678\""] {
            assert!(serde_json::from_str::<Ppnum>(bad).is_err(), "{bad}");
        }

        let id = PpnumId::nil();
        let json = serde_json::to_string(&id).unwrap();
        assert_eq!(json, format!("\"{id}\""));
        assert_eq!(serde_json::from_str::<PpnumId>(&json).unwrap(), id);
    }
}