a2a_protocol_server/auth/
actors.rs1use super::caller_id;
16
17pub const MAX_ACTORS: usize = 16;
19
20pub fn actors_of(
30 act: Option<&serde_json::Value>,
31 token_issuer: Option<&str>,
32) -> Result<Vec<String>, ()> {
33 let mut actors = Vec::new();
34 let mut next = act;
35 while let Some(value) = next {
36 if actors.len() == MAX_ACTORS {
37 return Err(());
38 }
39 let object = value.as_object().ok_or(())?;
40 let sub = object
41 .get("sub")
42 .and_then(serde_json::Value::as_str)
43 .ok_or(())?;
44 let iss = match object.get("iss") {
45 None => token_issuer,
46 Some(iss) => Some(iss.as_str().ok_or(())?),
47 };
48 actors.push(caller_id::jwt(iss, sub));
49 next = object.get("act");
50 }
51 Ok(actors)
52}
53
54#[cfg(test)]
55mod tests {
56 use super::*;
57 use serde_json::json;
58
59 #[test]
60 fn no_act_is_no_actors() {
61 assert_eq!(actors_of(None, Some("i")), Ok(vec![]));
62 }
63
64 #[test]
66 fn a_nested_chain_is_read_nearest_first() {
67 let act = json!({
68 "sub": "https://service16.example.com",
69 "act": {"sub": "https://service77.example.com", "iss": "https://other.example"}
70 });
71 assert_eq!(
72 actors_of(Some(&act), Some("https://as.example.com")),
73 Ok(vec![
74 caller_id::jwt(
75 Some("https://as.example.com"),
76 "https://service16.example.com"
77 ),
78 caller_id::jwt(
79 Some("https://other.example"),
80 "https://service77.example.com"
81 ),
82 ])
83 );
84 assert_eq!(
85 actors_of(Some(&json!({"sub": "a"})), None),
86 Ok(vec![caller_id::jwt(None, "a")])
87 );
88 }
89
90 #[test]
91 fn an_unreadable_chain_is_refused() {
92 for act in [
93 json!("agent"),
94 json!({}),
95 json!({"sub": 7}),
96 json!({"sub": "a", "iss": 7}),
97 json!({"sub": "a", "act": "b"}),
98 ] {
99 assert_eq!(actors_of(Some(&act), Some("i")), Err(()), "{act}");
100 }
101 }
102
103 #[test]
104 fn a_chain_is_capped() {
105 let mut act = json!({"sub": "last"});
106 for i in 1..MAX_ACTORS {
107 act = json!({"sub": format!("a{i}"), "act": act});
108 }
109 assert_eq!(actors_of(Some(&act), None).map(|a| a.len()), Ok(MAX_ACTORS));
110 let longer = json!({"sub": "one-more", "act": act});
111 assert_eq!(actors_of(Some(&longer), None), Err(()));
112 }
113}