ppoppo_token/access_token/act.rs
1//! `act` (RFC 8693 §4.1) — **who is acting** for the subject.
2//!
3//! The second of the two axes this vocabulary admits. [`EntityType`]
4//! answers *what the principal is*; this answers *who is currently driving
5//! it*. Keeping them apart is the whole point of RFC_202607252223 — a human
6//! identity operated by an agent is `entity_type = "human"` **plus** an
7//! `act`, never a third value in the identity vocabulary.
8//!
9//! ## Why the registered claim name
10//!
11//! RFC 8693 §4.1 defines `act` as *"a means within a JWT to express that
12//! delegation has occurred and identify the acting party to whom authority
13//! has been delegated"* — a JSON **object**, with chains expressed by
14//! nesting (outermost = most recent actor). PAS mints these tokens from an
15//! RPC literally named `ExchangeToken`; RFC 8693 *is* OAuth 2.0 Token
16//! Exchange, so the semantics apply exactly rather than "don't apply here"
17//! as the retired `delegator` claim's rationale asserted.
18//!
19//! ## Depth is the nesting, not a second claim
20//!
21//! The retired `dlg_depth` claim reified a fact the structure already
22//! carries. Counting [`Act::depth`] is strictly stronger: a token cannot
23//! *misreport* its own depth when the depth is the shape.
24//!
25//! ## Deliberately stricter than the RFC
26//!
27//! RFC 8693 §4.1 permits arbitrary actor-identifying claims inside `act`.
28//! This type admits `sub` and a nested `act` and nothing else. That is not
29//! an oversight to be "fixed" toward RFC permissiveness: M45's PII
30//! allowlist scans **top-level keys only**, so the interior of the first
31//! object-valued claim would otherwise be a region the allowlist
32//! structurally cannot see (`act: {"sub": …, "email": …}` would sail
33//! through). PAS is the only issuer and emits only `sub`; M45's premise is
34//! that anything PAS would not emit is forgery.
35//!
36//! Two strictnesses are load-bearing, and both recurse because the nested
37//! field is this same type:
38//!
39//! 1. **`deny_unknown_fields`** — no extra interior keys.
40//! 2. **Map form only.** serde's derived `Deserialize` also accepts a
41//! *sequence* whose elements are the fields in declaration order, and
42//! it does not reject trailing elements — so `["actor", null, "…"]`
43//! would parse *and* carry an unnamed payload past both the allowlist
44//! and `deny_unknown_fields`. Rejecting anything but a JSON object is
45//! what makes point 1 airtight rather than decorative.
46//!
47//! [`EntityType`]: super::EntityType
48
49use std::fmt;
50
51use serde::de::{MapAccess, Visitor, value::MapAccessDeserializer};
52use serde::{Deserialize, Deserializer, Serialize};
53
54/// The acting party (RFC 8693 §4.1), and — through [`Self::act`] — the
55/// delegation chain behind it.
56///
57/// Wire shape is the RFC's: `{"sub": "…", "act": {"sub": "…"}}`. The
58/// outermost value is the *current* actor; each nested `act` is the party
59/// that authorized the one enclosing it.
60#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
61pub struct Act {
62 /// Identifier of the acting party. PAS stamps the actor's `ppnum_id`
63 /// (ULID); the engine does not validate the format, because a future
64 /// Token Exchange phase may carry non-ppoppo principals here.
65 pub sub: String,
66
67 /// The prior link in the delegation chain, if any. `Box` because the
68 /// type is self-referential; `None` for the common single-hop case.
69 #[serde(default, skip_serializing_if = "Option::is_none")]
70 pub act: Option<Box<Act>>,
71}
72
73/// The map-form fields, derived so `deny_unknown_fields` does the interior
74/// allowlisting. Kept private: [`Act`]'s own `Deserialize` is the only way
75/// in, and it refuses every wire form but a JSON object.
76#[derive(Deserialize)]
77#[serde(deny_unknown_fields)]
78struct ActFields {
79 sub: String,
80 #[serde(default)]
81 act: Option<Box<Act>>,
82}
83
84impl<'de> Deserialize<'de> for Act {
85 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
86 struct MapOnly;
87
88 impl<'de> Visitor<'de> for MapOnly {
89 type Value = Act;
90
91 fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
92 f.write_str("an RFC 8693 `act` object")
93 }
94
95 fn visit_map<A: MapAccess<'de>>(self, map: A) -> Result<Act, A::Error> {
96 let fields = ActFields::deserialize(MapAccessDeserializer::new(map))?;
97 Ok(Act {
98 sub: fields.sub,
99 act: fields.act,
100 })
101 }
102 }
103
104 // `deserialize_map`, not `deserialize_struct`: the latter also
105 // admits the sequence form (see the module docs).
106 deserializer.deserialize_map(MapOnly)
107 }
108}
109
110impl Act {
111 /// A single-hop actor — the shape both PAS agent-flow mint sites emit.
112 ///
113 /// There is deliberately no chain builder: no mint site nests today
114 /// (the retired flat `delegator` claim could not express a chain
115 /// either, so nothing regresses). The engine still enforces
116 /// [`Self::depth`] on *inbound* tokens regardless, because a nested
117 /// `act` arriving at verify is either another issuer's or a forgery.
118 #[must_use]
119 pub fn new(sub: impl Into<String>) -> Self {
120 Self {
121 sub: sub.into(),
122 act: None,
123 }
124 }
125
126 /// Delegation depth — `1` for a single actor, `+1` per nested link.
127 ///
128 /// Iterative rather than recursive: the payload is attacker-supplied,
129 /// and a bound that could blow the stack while measuring it would be
130 /// no bound at all.
131 #[must_use]
132 pub fn depth(&self) -> usize {
133 let mut depth = 1;
134 let mut link = self.act.as_deref();
135 while let Some(next) = link {
136 depth += 1;
137 link = next.act.as_deref();
138 }
139 depth
140 }
141}
142
143#[cfg(test)]
144mod tests {
145 #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
146 use super::*;
147
148 #[test]
149 fn single_actor_is_depth_one() {
150 assert_eq!(Act::new("01HSAB00000000000000000000").depth(), 1);
151 }
152
153 #[test]
154 fn depth_counts_every_nested_link() {
155 let chain = Act {
156 sub: "a".into(),
157 act: Some(Box::new(Act {
158 sub: "b".into(),
159 act: Some(Box::new(Act::new("c"))),
160 })),
161 };
162 assert_eq!(chain.depth(), 3);
163 }
164
165 /// The wire shape is the RFC's, and a single-hop actor must not emit a
166 /// `"act": null` key — absent means absent.
167 #[test]
168 fn single_hop_serializes_to_the_rfc_shape() {
169 let json = serde_json::to_value(Act::new("actor")).expect("serialize");
170 assert_eq!(json, serde_json::json!({"sub": "actor"}));
171 }
172
173 #[test]
174 fn nested_shape_round_trips() {
175 let chain = Act {
176 sub: "outer".into(),
177 act: Some(Box::new(Act::new("inner"))),
178 };
179 let json = serde_json::to_value(&chain).expect("serialize");
180 assert_eq!(
181 json,
182 serde_json::json!({"sub":"outer","act":{"sub":"inner"}})
183 );
184 assert_eq!(serde_json::from_value::<Act>(json).expect("parse"), chain);
185 }
186
187 /// **The M45 blind spot this type closes.** The PII allowlist scans
188 /// top-level keys; without `deny_unknown_fields` an interior `email`
189 /// would never be looked at by anything.
190 #[test]
191 fn interior_pii_is_rejected_at_every_level() {
192 for smuggled in [
193 serde_json::json!({"sub": "actor", "email": "a@b.c"}),
194 serde_json::json!({"sub": "outer", "act": {"sub": "inner", "email": "a@b.c"}}),
195 ] {
196 assert!(
197 serde_json::from_value::<Act>(smuggled.clone()).is_err(),
198 "{smuggled} smuggles a claim past M45's top-level-only scan",
199 );
200 }
201 }
202
203 #[test]
204 fn sub_is_mandatory() {
205 assert!(serde_json::from_value::<Act>(serde_json::json!({})).is_err());
206 }
207
208 /// **The reason `Deserialize` is hand-written.** serde's derive also
209 /// accepts a sequence of the fields in declaration order *and ignores
210 /// trailing elements* — so this array would otherwise parse into a
211 /// valid `Act` while carrying an unnamed payload that neither M45 nor
212 /// `deny_unknown_fields` can see. Map form only, at every depth.
213 #[test]
214 fn sequence_form_is_not_an_actor_object() {
215 for seq in [
216 serde_json::json!(["actor"]),
217 serde_json::json!(["actor", null, "smuggled"]),
218 serde_json::json!({"sub": "outer", "act": ["inner", null, "smuggled"]}),
219 ] {
220 assert!(
221 serde_json::from_value::<Act>(seq.clone()).is_err(),
222 "{seq} is not the RFC 8693 object form",
223 );
224 }
225 }
226}