Skip to main content

subc_protocol/scope/
federated.rs

1use serde::{Deserialize, Serialize};
2
3/// The paired peer's class, attested by the configured federated owner.
4#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
5#[serde(rename_all = "snake_case")]
6#[non_exhaustive]
7pub enum FederatedPeerClass {
8    Computer,
9    Phone,
10    Sim,
11    Unknown,
12}
13
14/// Identity asserted by the paired stack, not a local agent identity.
15#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
16#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
17#[non_exhaustive]
18pub enum RemoteClaim {
19    /// Construct with [`RemoteClaim::agent`] so future fields can be added.
20    /// ```compile_fail
21    /// use subc_protocol::scope::RemoteClaim;
22    /// let _ = RemoteClaim::Agent { agent_id: "agent".into() };
23    /// ```
24    #[non_exhaustive]
25    Agent { agent_id: String },
26    /// Construct with [`RemoteClaim::worker`] so future fields can be added.
27    /// ```compile_fail
28    /// use subc_protocol::scope::RemoteClaim;
29    /// let _ = RemoteClaim::Worker { owner_module_id: "owner".into(), worker_ref: "a".repeat(64), on_behalf_of: None };
30    /// ```
31    #[non_exhaustive]
32    Worker {
33        owner_module_id: String,
34        worker_ref: String,
35        #[serde(default, skip_serializing_if = "Option::is_none")]
36        on_behalf_of: Option<String>,
37    },
38    /// Construct with [`RemoteClaim::run`] so future fields can be added.
39    /// ```compile_fail
40    /// use subc_protocol::scope::RemoteClaim;
41    /// let _ = RemoteClaim::Run { agent_id: "agent".into() };
42    /// ```
43    #[non_exhaustive]
44    Run { agent_id: String },
45    /// Construct with [`RemoteClaim::flow`] so future fields can be added.
46    /// ```compile_fail
47    /// use subc_protocol::scope::RemoteClaim;
48    /// let _ = RemoteClaim::Flow { flow_id: "flow".into(), flow_version: 1, flow_install_id: "install".into(), flow_code_hash: "a".repeat(64) };
49    /// ```
50    #[non_exhaustive]
51    Flow {
52        flow_id: String,
53        flow_version: u64,
54        flow_install_id: String,
55        flow_code_hash: String,
56    },
57}
58
59impl RemoteClaim {
60    pub fn agent(agent_id: impl Into<String>) -> Self {
61        Self::Agent {
62            agent_id: agent_id.into(),
63        }
64    }
65
66    pub fn worker(
67        owner_module_id: impl Into<String>,
68        worker_ref: impl Into<String>,
69        on_behalf_of: Option<String>,
70    ) -> Self {
71        Self::Worker {
72            owner_module_id: owner_module_id.into(),
73            worker_ref: worker_ref.into(),
74            on_behalf_of,
75        }
76    }
77
78    pub fn run(agent_id: impl Into<String>) -> Self {
79        Self::Run {
80            agent_id: agent_id.into(),
81        }
82    }
83
84    pub fn flow(
85        flow_id: impl Into<String>,
86        flow_version: u64,
87        flow_install_id: impl Into<String>,
88        flow_code_hash: impl Into<String>,
89    ) -> Self {
90        Self::Flow {
91            flow_id: flow_id.into(),
92            flow_version,
93            flow_install_id: flow_install_id.into(),
94            flow_code_hash: flow_code_hash.into(),
95        }
96    }
97
98    /// Check canonical claim fields, including the shared opaque-token bounds.
99    pub fn validate(&self) -> Result<(), String> {
100        let token = |name, value: &str| {
101            crate::tool_call::validate_opaque_field(name, value).map_err(|e| e.to_string())
102        };
103        match self {
104            Self::Agent { agent_id } | Self::Run { agent_id } => token("agent_id", agent_id),
105            Self::Worker {
106                owner_module_id,
107                worker_ref,
108                on_behalf_of,
109            } => {
110                crate::manifest::validate_module_id(owner_module_id).map_err(|e| e.to_string())?;
111                hex("worker_ref", worker_ref, 64)?;
112                if let Some(agent) = on_behalf_of {
113                    token("on_behalf_of", agent)?;
114                }
115                Ok(())
116            }
117            Self::Flow {
118                flow_id,
119                flow_version,
120                flow_install_id,
121                flow_code_hash,
122            } => {
123                token("flow_id", flow_id)?;
124                super::validate_flow_version(*flow_version).map_err(str::to_string)?;
125                token("flow_install_id", flow_install_id)?;
126                hex("flow_code_hash", flow_code_hash, 64)
127            }
128        }
129    }
130}
131
132/// Facts from the local pairing roster. Fixed for the scope's epoch.
133#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
134#[serde(deny_unknown_fields)]
135#[non_exhaustive]
136pub struct FederatedAttributes {
137    pub peer_class: FederatedPeerClass,
138    pub peer_fingerprint: String,
139    pub pairing_id: String,
140    pub peer_name: String,
141    #[serde(default, skip_serializing_if = "Option::is_none")]
142    pub remote_claim: Option<RemoteClaim>,
143}
144
145impl FederatedAttributes {
146    pub fn new(
147        peer_class: FederatedPeerClass,
148        peer_fingerprint: String,
149        pairing_id: String,
150        peer_name: String,
151    ) -> Self {
152        Self {
153            peer_class,
154            peer_fingerprint,
155            pairing_id,
156            peer_name,
157            remote_claim: None,
158        }
159    }
160
161    #[must_use]
162    pub fn with_remote_claim(mut self, claim: Option<RemoteClaim>) -> Self {
163        self.remote_claim = claim;
164        self
165    }
166
167    /// Validate both decoded and programmatically constructed attributes.
168    pub fn validate(&self) -> Result<(), String> {
169        hex("peer_fingerprint", &self.peer_fingerprint, 32)?;
170        crate::tool_call::validate_opaque_field("pairing_id", &self.pairing_id)
171            .map_err(|e| e.to_string())?;
172        crate::manifest::validate_plain_text(&self.peer_name, 80)
173            .map_err(|e| format!("peer_name {e}"))?;
174        if let Some(claim) = &self.remote_claim {
175            claim.validate()?;
176        }
177        Ok(())
178    }
179}
180
181fn hex(name: &str, value: &str, length: usize) -> Result<(), String> {
182    if value.len() != length
183        || !value
184            .bytes()
185            .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
186    {
187        return Err(format!(
188            "{name} must contain exactly {length} lowercase hex characters"
189        ));
190    }
191    Ok(())
192}
193
194#[cfg(test)]
195mod tests {
196    use super::*;
197    use serde_json::json;
198
199    fn attributes() -> FederatedAttributes {
200        FederatedAttributes::new(
201            FederatedPeerClass::Computer,
202            "a".repeat(32),
203            "pairing".into(),
204            "Peer".into(),
205        )
206    }
207
208    #[test]
209    fn federated_claim_roundtrips_and_enforces_every_field_bound() {
210        for claim in [
211            RemoteClaim::Agent {
212                agent_id: "a".repeat(256),
213            },
214            RemoteClaim::Run {
215                agent_id: "a".repeat(256),
216            },
217            RemoteClaim::Worker {
218                owner_module_id: "mcp:module".into(),
219                worker_ref: "a".repeat(64),
220                on_behalf_of: Some("a".repeat(256)),
221            },
222            RemoteClaim::Flow {
223                flow_id: "a".repeat(256),
224                flow_version: 9_007_199_254_740_991,
225                flow_install_id: "b".repeat(256),
226                flow_code_hash: "f".repeat(64),
227            },
228        ] {
229            claim.validate().unwrap();
230            let value = serde_json::to_value(&claim).unwrap();
231            assert_eq!(
232                serde_json::from_value::<RemoteClaim>(value.clone()).unwrap(),
233                claim
234            );
235            let mut unknown = value.clone();
236            unknown["unexpected"] = json!(true);
237            assert!(serde_json::from_value::<RemoteClaim>(unknown).is_err());
238            for key in ["agent_id", "flow_id", "flow_install_id", "on_behalf_of"] {
239                if value.get(key).is_some() {
240                    for bad in [
241                        "".to_string(),
242                        "x".repeat(257),
243                        "with space".into(),
244                        "\n".into(),
245                        "é".into(),
246                    ] {
247                        let mut invalid = value.clone();
248                        invalid[key] = json!(bad);
249                        assert!(
250                            serde_json::from_value::<RemoteClaim>(invalid)
251                                .unwrap()
252                                .validate()
253                                .is_err(),
254                            "{key}"
255                        );
256                    }
257                }
258            }
259            for key in ["worker_ref", "flow_code_hash"] {
260                if value.get(key).is_some() {
261                    for bad in [
262                        "a".repeat(63),
263                        "A".repeat(64),
264                        "g".repeat(64),
265                        "a".repeat(65),
266                    ] {
267                        let mut invalid = value.clone();
268                        invalid[key] = json!(bad);
269                        assert!(serde_json::from_value::<RemoteClaim>(invalid)
270                            .unwrap()
271                            .validate()
272                            .is_err());
273                    }
274                }
275            }
276            if value.get("flow_version").is_some() {
277                for bad in [0u64, 9_007_199_254_740_992] {
278                    let mut invalid = value.clone();
279                    invalid["flow_version"] = json!(bad);
280                    assert!(serde_json::from_value::<RemoteClaim>(invalid)
281                        .unwrap()
282                        .validate()
283                        .is_err());
284                }
285            }
286            if value.get("owner_module_id").is_some() {
287                for bad in ["", "..", "a/b", "a\\b", "\n"] {
288                    let mut invalid = value.clone();
289                    invalid["owner_module_id"] = json!(bad);
290                    assert!(serde_json::from_value::<RemoteClaim>(invalid)
291                        .unwrap()
292                        .validate()
293                        .is_err());
294                }
295            }
296        }
297        assert!(serde_json::from_value::<RemoteClaim>(json!({"kind":"future"})).is_err());
298    }
299
300    #[test]
301    fn federated_attributes_roundtrip_classes_and_enforce_limits_and_unknown_members() {
302        for class in [
303            FederatedPeerClass::Computer,
304            FederatedPeerClass::Phone,
305            FederatedPeerClass::Sim,
306            FederatedPeerClass::Unknown,
307        ] {
308            let mut facts = attributes();
309            facts.peer_class = class;
310            facts.peer_name = "界".repeat(80);
311            facts.validate().unwrap();
312            let value = serde_json::to_value(&facts).unwrap();
313            assert_eq!(
314                serde_json::from_value::<FederatedAttributes>(value.clone()).unwrap(),
315                facts
316            );
317            let mut unknown = value;
318            unknown["unexpected"] = json!(true);
319            assert!(serde_json::from_value::<FederatedAttributes>(unknown).is_err());
320        }
321        for bad in [
322            "",
323            "a\n",
324            "a\u{061c}",
325            "a\u{200e}",
326            "a\u{202e}",
327            "a\u{2069}",
328            &"a".repeat(81),
329        ] {
330            let mut facts = attributes();
331            facts.peer_name = bad.into();
332            assert!(facts.validate().is_err());
333        }
334        for bad in [
335            "A".repeat(32),
336            "a".repeat(31),
337            "a".repeat(33),
338            "g".repeat(32),
339        ] {
340            let mut facts = attributes();
341            facts.peer_fingerprint = bad;
342            assert!(facts.validate().is_err());
343        }
344        for bad in ["".to_string(), "x".repeat(257), "space here".into()] {
345            let mut facts = attributes();
346            facts.pairing_id = bad;
347            assert!(facts.validate().is_err());
348        }
349        let mut facts = attributes();
350        facts.pairing_id = "x".repeat(256);
351        facts.validate().unwrap();
352    }
353
354    #[test]
355    fn federated_absent_keeps_nonfederated_stamps_readable_by_the_strict_034_attributes_decoder() {
356        // Freeze the 0.34 nested schema rather than decoding with today's types.
357        #[derive(Default, Deserialize)]
358        #[serde(default, deny_unknown_fields)]
359        #[allow(dead_code)]
360        struct Attributes034 {
361            agent_id: Option<String>,
362            delegates: bool,
363            on_behalf_of_agent: Option<String>,
364            flow_id: Option<String>,
365            flow_version: Option<u64>,
366            flow_code_hash: Option<String>,
367            flow_install_id: Option<String>,
368            run_id: Option<String>,
369        }
370        #[derive(Deserialize)]
371        #[serde(rename_all = "snake_case")]
372        enum Kind034 {
373            Head,
374            Worker,
375            Ephemeral,
376        }
377        #[derive(Deserialize)]
378        struct Stamp034 {
379            kind: Kind034,
380            #[serde(default)]
381            attributes: Attributes034,
382        }
383        for (kind, wire_kind) in [
384            (crate::scope::ScopeKind::Head, "head"),
385            (crate::scope::ScopeKind::Worker, "worker"),
386            (crate::scope::ScopeKind::Ephemeral, "ephemeral"),
387        ] {
388            let stamp = crate::scope::ScopeStamp::new(crate::Principal::Direct, "legacy", 1, kind)
389                .with_attributes(
390                    crate::scope::ScopeAttributes::new()
391                        .with_agent_id(Some("agent".into()))
392                        .with_delegates(true),
393                );
394            let value = serde_json::to_value(stamp).unwrap();
395            assert!(value["attributes"].get("federated").is_none());
396            assert_eq!(value["kind"], wire_kind);
397            let old: Stamp034 = serde_json::from_value(value.clone()).unwrap();
398            assert!(matches!(
399                old.kind,
400                Kind034::Head | Kind034::Worker | Kind034::Ephemeral
401            ));
402            assert_eq!(old.attributes.agent_id.as_deref(), Some("agent"));
403            assert!(old.attributes.delegates);
404            let mut bad = value["attributes"].clone();
405            bad["federated"] = serde_json::to_value(attributes()).unwrap();
406            assert!(serde_json::from_value::<Attributes034>(bad).is_err());
407        }
408    }
409}