ppoppo-token 0.28.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
//! `act` (RFC 8693 §4.1) — **who is acting** for the subject.
//!
//! The second of the two axes this vocabulary admits. [`EntityType`]
//! answers *what the principal is*; this answers *who is currently driving
//! it*. Keeping them apart is the whole point of RFC_202607252223 — a human
//! identity operated by an agent is `entity_type = "human"` **plus** an
//! `act`, never a third value in the identity vocabulary.
//!
//! ## Why the registered claim name
//!
//! RFC 8693 §4.1 defines `act` as *"a means within a JWT to express that
//! delegation has occurred and identify the acting party to whom authority
//! has been delegated"* — a JSON **object**, with chains expressed by
//! nesting (outermost = most recent actor). PAS mints these tokens from an
//! RPC literally named `ExchangeToken`; RFC 8693 *is* OAuth 2.0 Token
//! Exchange, so the semantics apply exactly rather than "don't apply here"
//! as the retired `delegator` claim's rationale asserted.
//!
//! ## Depth is the nesting, not a second claim
//!
//! The retired `dlg_depth` claim reified a fact the structure already
//! carries. Counting [`Act::depth`] is strictly stronger: a token cannot
//! *misreport* its own depth when the depth is the shape.
//!
//! ## Deliberately stricter than the RFC
//!
//! RFC 8693 §4.1 permits arbitrary actor-identifying claims inside `act`.
//! This type admits `sub` and a nested `act` and nothing else. That is not
//! an oversight to be "fixed" toward RFC permissiveness: M45's PII
//! allowlist scans **top-level keys only**, so the interior of the first
//! object-valued claim would otherwise be a region the allowlist
//! structurally cannot see (`act: {"sub": …, "email": …}` would sail
//! through). PAS is the only issuer and emits only `sub`; M45's premise is
//! that anything PAS would not emit is forgery.
//!
//! Two strictnesses are load-bearing, and both recurse because the nested
//! field is this same type:
//!
//! 1. **`deny_unknown_fields`** — no extra interior keys.
//! 2. **Map form only.** serde's derived `Deserialize` also accepts a
//!    *sequence* whose elements are the fields in declaration order, and
//!    it does not reject trailing elements — so `["actor", null, "…"]`
//!    would parse *and* carry an unnamed payload past both the allowlist
//!    and `deny_unknown_fields`. Rejecting anything but a JSON object is
//!    what makes point 1 airtight rather than decorative.
//!
//! [`EntityType`]: super::EntityType

use std::fmt;

use serde::de::{MapAccess, Visitor, value::MapAccessDeserializer};
use serde::{Deserialize, Deserializer, Serialize};

/// The acting party (RFC 8693 §4.1), and — through [`Self::act`] — the
/// delegation chain behind it.
///
/// Wire shape is the RFC's: `{"sub": "…", "act": {"sub": "…"}}`. The
/// outermost value is the *current* actor; each nested `act` is the party
/// that authorized the one enclosing it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Act {
    /// Identifier of the acting party. PAS stamps the actor's `ppnum_id`
    /// (ULID); the engine does not validate the format, because a future
    /// Token Exchange phase may carry non-ppoppo principals here.
    pub sub: String,

    /// The prior link in the delegation chain, if any. `Box` because the
    /// type is self-referential; `None` for the common single-hop case.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub act: Option<Box<Act>>,
}

/// The map-form fields, derived so `deny_unknown_fields` does the interior
/// allowlisting. Kept private: [`Act`]'s own `Deserialize` is the only way
/// in, and it refuses every wire form but a JSON object.
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct ActFields {
    sub: String,
    #[serde(default)]
    act: Option<Box<Act>>,
}

impl<'de> Deserialize<'de> for Act {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        struct MapOnly;

        impl<'de> Visitor<'de> for MapOnly {
            type Value = Act;

            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                f.write_str("an RFC 8693 `act` object")
            }

            fn visit_map<A: MapAccess<'de>>(self, map: A) -> Result<Act, A::Error> {
                let fields = ActFields::deserialize(MapAccessDeserializer::new(map))?;
                Ok(Act {
                    sub: fields.sub,
                    act: fields.act,
                })
            }
        }

        // `deserialize_map`, not `deserialize_struct`: the latter also
        // admits the sequence form (see the module docs).
        deserializer.deserialize_map(MapOnly)
    }
}

impl Act {
    /// A single-hop actor — the shape both PAS agent-flow mint sites emit.
    ///
    /// There is deliberately no chain builder: no mint site nests today
    /// (the retired flat `delegator` claim could not express a chain
    /// either, so nothing regresses). The engine still enforces
    /// [`Self::depth`] on *inbound* tokens regardless, because a nested
    /// `act` arriving at verify is either another issuer's or a forgery.
    #[must_use]
    pub fn new(sub: impl Into<String>) -> Self {
        Self {
            sub: sub.into(),
            act: None,
        }
    }

    /// Delegation depth — `1` for a single actor, `+1` per nested link.
    ///
    /// Iterative rather than recursive: the payload is attacker-supplied,
    /// and a bound that could blow the stack while measuring it would be
    /// no bound at all.
    #[must_use]
    pub fn depth(&self) -> usize {
        let mut depth = 1;
        let mut link = self.act.as_deref();
        while let Some(next) = link {
            depth += 1;
            link = next.act.as_deref();
        }
        depth
    }
}

#[cfg(test)]
mod tests {
    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
    use super::*;

    #[test]
    fn single_actor_is_depth_one() {
        assert_eq!(Act::new("01HSAB00000000000000000000").depth(), 1);
    }

    #[test]
    fn depth_counts_every_nested_link() {
        let chain = Act {
            sub: "a".into(),
            act: Some(Box::new(Act {
                sub: "b".into(),
                act: Some(Box::new(Act::new("c"))),
            })),
        };
        assert_eq!(chain.depth(), 3);
    }

    /// The wire shape is the RFC's, and a single-hop actor must not emit a
    /// `"act": null` key — absent means absent.
    #[test]
    fn single_hop_serializes_to_the_rfc_shape() {
        let json = serde_json::to_value(Act::new("actor")).expect("serialize");
        assert_eq!(json, serde_json::json!({"sub": "actor"}));
    }

    #[test]
    fn nested_shape_round_trips() {
        let chain = Act {
            sub: "outer".into(),
            act: Some(Box::new(Act::new("inner"))),
        };
        let json = serde_json::to_value(&chain).expect("serialize");
        assert_eq!(
            json,
            serde_json::json!({"sub":"outer","act":{"sub":"inner"}})
        );
        assert_eq!(serde_json::from_value::<Act>(json).expect("parse"), chain);
    }

    /// **The M45 blind spot this type closes.** The PII allowlist scans
    /// top-level keys; without `deny_unknown_fields` an interior `email`
    /// would never be looked at by anything.
    #[test]
    fn interior_pii_is_rejected_at_every_level() {
        for smuggled in [
            serde_json::json!({"sub": "actor", "email": "a@b.c"}),
            serde_json::json!({"sub": "outer", "act": {"sub": "inner", "email": "a@b.c"}}),
        ] {
            assert!(
                serde_json::from_value::<Act>(smuggled.clone()).is_err(),
                "{smuggled} smuggles a claim past M45's top-level-only scan",
            );
        }
    }

    #[test]
    fn sub_is_mandatory() {
        assert!(serde_json::from_value::<Act>(serde_json::json!({})).is_err());
    }

    /// **The reason `Deserialize` is hand-written.** serde's derive also
    /// accepts a sequence of the fields in declaration order *and ignores
    /// trailing elements* — so this array would otherwise parse into a
    /// valid `Act` while carrying an unnamed payload that neither M45 nor
    /// `deny_unknown_fields` can see. Map form only, at every depth.
    #[test]
    fn sequence_form_is_not_an_actor_object() {
        for seq in [
            serde_json::json!(["actor"]),
            serde_json::json!(["actor", null, "smuggled"]),
            serde_json::json!({"sub": "outer", "act": ["inner", null, "smuggled"]}),
        ] {
            assert!(
                serde_json::from_value::<Act>(seq.clone()).is_err(),
                "{seq} is not the RFC 8693 object form",
            );
        }
    }
}