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/// Optional names are display-only. Use [`RemoteClaim::same_identity`] to compare
16/// callers without treating a display rename as a change of identity.
17#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
18#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
19#[non_exhaustive]
20pub enum RemoteClaim {
21    /// Construct with [`RemoteClaim::agent`] so future fields can be added.
22    /// ```compile_fail
23    /// use subc_protocol::scope::RemoteClaim;
24    /// let _ = RemoteClaim::Agent { agent_id: "agent".into() };
25    /// ```
26    #[non_exhaustive]
27    Agent {
28        agent_id: String,
29        #[serde(
30            default,
31            deserialize_with = "deserialize_name",
32            skip_serializing_if = "Option::is_none"
33        )]
34        agent_name: Option<String>,
35    },
36    /// Construct with [`RemoteClaim::worker`] so future fields can be added.
37    /// ```compile_fail
38    /// use subc_protocol::scope::RemoteClaim;
39    /// let _ = RemoteClaim::Worker { owner_module_id: "owner".into(), worker_ref: "a".repeat(64), on_behalf_of: None };
40    /// ```
41    #[non_exhaustive]
42    Worker {
43        owner_module_id: String,
44        worker_ref: String,
45        #[serde(default, skip_serializing_if = "Option::is_none")]
46        on_behalf_of: Option<String>,
47        /// Display name of the agent identified by `on_behalf_of`, not the worker.
48        #[serde(
49            default,
50            deserialize_with = "deserialize_name",
51            skip_serializing_if = "Option::is_none"
52        )]
53        agent_name: Option<String>,
54    },
55    /// Construct with [`RemoteClaim::run`] so future fields can be added.
56    /// ```compile_fail
57    /// use subc_protocol::scope::RemoteClaim;
58    /// let _ = RemoteClaim::Run { agent_id: "agent".into() };
59    /// ```
60    #[non_exhaustive]
61    Run {
62        agent_id: String,
63        #[serde(
64            default,
65            deserialize_with = "deserialize_name",
66            skip_serializing_if = "Option::is_none"
67        )]
68        agent_name: Option<String>,
69    },
70    /// Construct with [`RemoteClaim::flow`] so future fields can be added.
71    /// ```compile_fail
72    /// use subc_protocol::scope::RemoteClaim;
73    /// let _ = RemoteClaim::Flow { flow_id: "flow".into(), flow_version: 1, flow_install_id: "install".into(), flow_code_hash: "a".repeat(64) };
74    /// ```
75    #[non_exhaustive]
76    Flow {
77        flow_id: String,
78        flow_version: u64,
79        flow_install_id: String,
80        flow_code_hash: String,
81        #[serde(
82            default,
83            deserialize_with = "deserialize_name",
84            skip_serializing_if = "Option::is_none"
85        )]
86        flow_name: Option<String>,
87    },
88}
89
90impl RemoteClaim {
91    /// Whether these claims identify the same caller. Compares every field except
92    /// the display names, so a field added later counts as identity unless it is
93    /// cleared here too. Ordinary equality remains structural.
94    pub fn same_identity(&self, other: &Self) -> bool {
95        self.without_names() == other.without_names()
96    }
97
98    fn without_names(&self) -> Self {
99        let mut claim = self.clone();
100        match &mut claim {
101            Self::Agent { agent_name, .. }
102            | Self::Run { agent_name, .. }
103            | Self::Worker { agent_name, .. } => *agent_name = None,
104            Self::Flow { flow_name, .. } => *flow_name = None,
105        }
106        claim
107    }
108
109    pub fn agent(agent_id: impl Into<String>) -> Self {
110        Self::Agent {
111            agent_id: agent_id.into(),
112            agent_name: None,
113        }
114    }
115
116    pub fn worker(
117        owner_module_id: impl Into<String>,
118        worker_ref: impl Into<String>,
119        on_behalf_of: Option<String>,
120    ) -> Self {
121        Self::Worker {
122            owner_module_id: owner_module_id.into(),
123            worker_ref: worker_ref.into(),
124            on_behalf_of,
125            agent_name: None,
126        }
127    }
128
129    pub fn run(agent_id: impl Into<String>) -> Self {
130        Self::Run {
131            agent_id: agent_id.into(),
132            agent_name: None,
133        }
134    }
135
136    pub fn flow(
137        flow_id: impl Into<String>,
138        flow_version: u64,
139        flow_install_id: impl Into<String>,
140        flow_code_hash: impl Into<String>,
141    ) -> Self {
142        Self::Flow {
143            flow_id: flow_id.into(),
144            flow_version,
145            flow_install_id: flow_install_id.into(),
146            flow_code_hash: flow_code_hash.into(),
147            flow_name: None,
148        }
149    }
150
151    /// Set the claimed agent's display name (or the worker's `on_behalf_of` agent).
152    /// Invalid names are dropped. Has no effect on flow claims.
153    #[must_use]
154    pub fn with_agent_name(mut self, name: impl Into<String>) -> Self {
155        match &mut self {
156            Self::Agent { agent_name, .. }
157            | Self::Run { agent_name, .. }
158            | Self::Worker { agent_name, .. } => *agent_name = valid_name(name.into()),
159            Self::Flow { .. } => {}
160        }
161        self
162    }
163
164    /// Set the flow's display name. Invalid names are dropped.
165    /// Has no effect on agent, run or worker claims.
166    #[must_use]
167    pub fn with_flow_name(mut self, name: impl Into<String>) -> Self {
168        if let Self::Flow { flow_name, .. } = &mut self {
169            *flow_name = valid_name(name.into());
170        }
171        self
172    }
173
174    /// Check identity fields, including the shared opaque-token bounds.
175    /// Display names never invalidate a claim; decoders drop invalid names.
176    pub fn validate(&self) -> Result<(), String> {
177        let token = |name, value: &str| {
178            crate::tool_call::validate_opaque_field(name, value).map_err(|e| e.to_string())
179        };
180        match self {
181            Self::Agent { agent_id, .. } | Self::Run { agent_id, .. } => {
182                token("agent_id", agent_id)
183            }
184            Self::Worker {
185                owner_module_id,
186                worker_ref,
187                on_behalf_of,
188                ..
189            } => {
190                crate::manifest::validate_module_id(owner_module_id).map_err(|e| e.to_string())?;
191                hex("worker_ref", worker_ref, 64)?;
192                if let Some(agent) = on_behalf_of {
193                    token("on_behalf_of", agent)?;
194                }
195                Ok(())
196            }
197            Self::Flow {
198                flow_id,
199                flow_version,
200                flow_install_id,
201                flow_code_hash,
202                ..
203            } => {
204                token("flow_id", flow_id)?;
205                super::validate_flow_version(*flow_version).map_err(str::to_string)?;
206                token("flow_install_id", flow_install_id)?;
207                hex("flow_code_hash", flow_code_hash, 64)
208            }
209        }
210    }
211}
212
213fn valid_name(name: String) -> Option<String> {
214    crate::manifest::validate_plain_text(&name, 80)
215        .ok()
216        .map(|()| name)
217}
218
219fn deserialize_name<'de, D: serde::Deserializer<'de>>(
220    deserializer: D,
221) -> Result<Option<String>, D::Error> {
222    let value = serde_json::Value::deserialize(deserializer)?;
223    Ok(value.as_str().and_then(|name| valid_name(name.to_owned())))
224}
225
226/// Facts from the local pairing roster. Fixed for the scope's epoch.
227#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
228#[serde(deny_unknown_fields)]
229#[non_exhaustive]
230pub struct FederatedAttributes {
231    pub peer_class: FederatedPeerClass,
232    pub peer_fingerprint: String,
233    pub pairing_id: String,
234    pub peer_name: String,
235    #[serde(default, skip_serializing_if = "Option::is_none")]
236    pub remote_claim: Option<RemoteClaim>,
237}
238
239impl FederatedAttributes {
240    /// Compare the facts fixed for an epoch, ignoring only the remote claim's
241    /// display names. Every other field counts, including any added later;
242    /// `peer_name` is a fixed pairing-roster fact, not a display name here.
243    pub fn same_identity(&self, other: &Self) -> bool {
244        let without_names = |facts: &Self| {
245            let mut facts = facts.clone();
246            facts.remote_claim = facts.remote_claim.as_ref().map(RemoteClaim::without_names);
247            facts
248        };
249        without_names(self) == without_names(other)
250    }
251
252    pub fn new(
253        peer_class: FederatedPeerClass,
254        peer_fingerprint: String,
255        pairing_id: String,
256        peer_name: String,
257    ) -> Self {
258        Self {
259            peer_class,
260            peer_fingerprint,
261            pairing_id,
262            peer_name,
263            remote_claim: None,
264        }
265    }
266
267    #[must_use]
268    pub fn with_remote_claim(mut self, claim: Option<RemoteClaim>) -> Self {
269        self.remote_claim = claim;
270        self
271    }
272
273    /// Validate both decoded and programmatically constructed attributes.
274    pub fn validate(&self) -> Result<(), String> {
275        hex("peer_fingerprint", &self.peer_fingerprint, 32)?;
276        crate::tool_call::validate_opaque_field("pairing_id", &self.pairing_id)
277            .map_err(|e| e.to_string())?;
278        crate::manifest::validate_plain_text(&self.peer_name, 80)
279            .map_err(|e| format!("peer_name {e}"))?;
280        if let Some(claim) = &self.remote_claim {
281            claim.validate()?;
282        }
283        Ok(())
284    }
285}
286
287fn hex(name: &str, value: &str, length: usize) -> Result<(), String> {
288    if value.len() != length
289        || !value
290            .bytes()
291            .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
292    {
293        return Err(format!(
294            "{name} must contain exactly {length} lowercase hex characters"
295        ));
296    }
297    Ok(())
298}
299
300#[cfg(test)]
301mod tests {
302    use super::*;
303    use serde_json::json;
304
305    fn attributes() -> FederatedAttributes {
306        FederatedAttributes::new(
307            FederatedPeerClass::Computer,
308            "a".repeat(32),
309            "pairing".into(),
310            "Peer".into(),
311        )
312    }
313
314    #[test]
315    fn federated_claim_names_are_optional_lossy_display_only() {
316        for (claim, field) in [
317            (RemoteClaim::agent("agent"), "agent_name"),
318            (RemoteClaim::run("agent"), "agent_name"),
319            (
320                RemoteClaim::worker("mcp:module", "a".repeat(64), Some("agent".into())),
321                "agent_name",
322            ),
323            (
324                RemoteClaim::flow("flow", 1, "install", "a".repeat(64)),
325                "flow_name",
326            ),
327        ] {
328            let original = serde_json::to_value(&claim).unwrap();
329            assert!(original.get(field).is_none());
330            let built = if field == "flow_name" {
331                claim.clone().with_flow_name("Name")
332            } else {
333                claim.clone().with_agent_name("Name")
334            };
335            assert_eq!(serde_json::to_value(built).unwrap()[field], "Name");
336            let invalid_built = if field == "flow_name" {
337                claim.clone().with_flow_name("\n")
338            } else {
339                claim.clone().with_agent_name("\n")
340            };
341            assert_eq!(serde_json::to_value(invalid_built).unwrap(), original);
342            for name in ["Agent".to_string(), "é".repeat(80), "🦀".repeat(80)] {
343                let mut wire = original.clone();
344                wire[field] = json!(name);
345                let decoded: RemoteClaim = serde_json::from_value(wire.clone()).unwrap();
346                decoded.validate().unwrap();
347                assert_eq!(serde_json::to_value(&decoded).unwrap(), wire);
348                assert_ne!(
349                    decoded, claim,
350                    "structural equality must detect display changes"
351                );
352                assert!(decoded.same_identity(&claim));
353            }
354            for invalid in [
355                json!(""),
356                json!("x".repeat(81)),
357                json!("\n"),
358                json!("\u{007f}"),
359                json!("\u{0085}"),
360                json!("\u{061c}"),
361                json!("\u{202e}"),
362                json!("\u{2069}"),
363                json!(null),
364                json!(7),
365                json!({"name": "Agent"}),
366            ] {
367                let mut wire = original.clone();
368                wire[field] = invalid;
369                let decoded: RemoteClaim = serde_json::from_value(wire).unwrap();
370                decoded.validate().unwrap();
371                assert_eq!(serde_json::to_value(&decoded).unwrap(), original);
372                assert_eq!(decoded, claim);
373            }
374            for (key, value) in original.as_object().unwrap() {
375                if key == "kind" {
376                    continue;
377                }
378                let mut changed = original.clone();
379                changed[key] = if let Some(n) = value.as_u64() {
380                    json!(n + 1)
381                } else {
382                    json!(format!("other{}", value.as_str().unwrap()))
383                };
384                let changed: RemoteClaim = serde_json::from_value(changed).unwrap();
385                assert!(
386                    !claim.same_identity(&changed),
387                    "{key} must remain identity-bearing"
388                );
389            }
390        }
391        assert!(!RemoteClaim::agent("agent").same_identity(&RemoteClaim::run("agent")));
392    }
393
394    #[test]
395    fn federated_claim_roundtrips_and_enforces_every_field_bound() {
396        for claim in [
397            RemoteClaim::Agent {
398                agent_id: "a".repeat(256),
399                agent_name: None,
400            },
401            RemoteClaim::Run {
402                agent_id: "a".repeat(256),
403                agent_name: None,
404            },
405            RemoteClaim::Worker {
406                owner_module_id: "mcp:module".into(),
407                worker_ref: "a".repeat(64),
408                on_behalf_of: Some("a".repeat(256)),
409                agent_name: None,
410            },
411            RemoteClaim::Flow {
412                flow_id: "a".repeat(256),
413                flow_version: 9_007_199_254_740_991,
414                flow_install_id: "b".repeat(256),
415                flow_code_hash: "f".repeat(64),
416                flow_name: None,
417            },
418        ] {
419            claim.validate().unwrap();
420            let value = serde_json::to_value(&claim).unwrap();
421            assert_eq!(
422                serde_json::from_value::<RemoteClaim>(value.clone()).unwrap(),
423                claim
424            );
425            let mut unknown = value.clone();
426            unknown["unexpected"] = json!(true);
427            assert!(serde_json::from_value::<RemoteClaim>(unknown).is_err());
428            for key in ["agent_id", "flow_id", "flow_install_id", "on_behalf_of"] {
429                if value.get(key).is_some() {
430                    for bad in [
431                        "".to_string(),
432                        "x".repeat(257),
433                        "with space".into(),
434                        "\n".into(),
435                        "é".into(),
436                    ] {
437                        let mut invalid = value.clone();
438                        invalid[key] = json!(bad);
439                        assert!(
440                            serde_json::from_value::<RemoteClaim>(invalid)
441                                .unwrap()
442                                .validate()
443                                .is_err(),
444                            "{key}"
445                        );
446                    }
447                }
448            }
449            for key in ["worker_ref", "flow_code_hash"] {
450                if value.get(key).is_some() {
451                    for bad in [
452                        "a".repeat(63),
453                        "A".repeat(64),
454                        "g".repeat(64),
455                        "a".repeat(65),
456                    ] {
457                        let mut invalid = value.clone();
458                        invalid[key] = json!(bad);
459                        assert!(serde_json::from_value::<RemoteClaim>(invalid)
460                            .unwrap()
461                            .validate()
462                            .is_err());
463                    }
464                }
465            }
466            if value.get("flow_version").is_some() {
467                for bad in [0u64, 9_007_199_254_740_992] {
468                    let mut invalid = value.clone();
469                    invalid["flow_version"] = json!(bad);
470                    assert!(serde_json::from_value::<RemoteClaim>(invalid)
471                        .unwrap()
472                        .validate()
473                        .is_err());
474                }
475            }
476            if value.get("owner_module_id").is_some() {
477                for bad in ["", "..", "a/b", "a\\b", "\n"] {
478                    let mut invalid = value.clone();
479                    invalid["owner_module_id"] = json!(bad);
480                    assert!(serde_json::from_value::<RemoteClaim>(invalid)
481                        .unwrap()
482                        .validate()
483                        .is_err());
484                }
485            }
486        }
487        assert!(serde_json::from_value::<RemoteClaim>(json!({"kind":"future"})).is_err());
488    }
489
490    #[test]
491    fn federated_attributes_roundtrip_classes_and_enforce_limits_and_unknown_members() {
492        for class in [
493            FederatedPeerClass::Computer,
494            FederatedPeerClass::Phone,
495            FederatedPeerClass::Sim,
496            FederatedPeerClass::Unknown,
497        ] {
498            let mut facts = attributes();
499            facts.peer_class = class;
500            facts.peer_name = "界".repeat(80);
501            facts.validate().unwrap();
502            let value = serde_json::to_value(&facts).unwrap();
503            assert_eq!(
504                serde_json::from_value::<FederatedAttributes>(value.clone()).unwrap(),
505                facts
506            );
507            let mut unknown = value;
508            unknown["unexpected"] = json!(true);
509            assert!(serde_json::from_value::<FederatedAttributes>(unknown).is_err());
510        }
511        for bad in [
512            "",
513            "a\n",
514            "a\u{061c}",
515            "a\u{200e}",
516            "a\u{202e}",
517            "a\u{2069}",
518            &"a".repeat(81),
519        ] {
520            let mut facts = attributes();
521            facts.peer_name = bad.into();
522            assert!(facts.validate().is_err());
523        }
524        for bad in [
525            "A".repeat(32),
526            "a".repeat(31),
527            "a".repeat(33),
528            "g".repeat(32),
529        ] {
530            let mut facts = attributes();
531            facts.peer_fingerprint = bad;
532            assert!(facts.validate().is_err());
533        }
534        for bad in ["".to_string(), "x".repeat(257), "space here".into()] {
535            let mut facts = attributes();
536            facts.pairing_id = bad;
537            assert!(facts.validate().is_err());
538        }
539        let mut facts = attributes();
540        facts.pairing_id = "x".repeat(256);
541        facts.validate().unwrap();
542    }
543
544    #[test]
545    fn federated_absent_keeps_nonfederated_stamps_readable_by_the_strict_034_attributes_decoder() {
546        // Freeze the 0.34 nested schema rather than decoding with today's types.
547        #[derive(Default, Deserialize)]
548        #[serde(default, deny_unknown_fields)]
549        #[allow(dead_code)]
550        struct Attributes034 {
551            agent_id: Option<String>,
552            delegates: bool,
553            on_behalf_of_agent: Option<String>,
554            flow_id: Option<String>,
555            flow_version: Option<u64>,
556            flow_code_hash: Option<String>,
557            flow_install_id: Option<String>,
558            run_id: Option<String>,
559        }
560        #[derive(Deserialize)]
561        #[serde(rename_all = "snake_case")]
562        enum Kind034 {
563            Head,
564            Worker,
565            Ephemeral,
566        }
567        #[derive(Deserialize)]
568        struct Stamp034 {
569            kind: Kind034,
570            #[serde(default)]
571            attributes: Attributes034,
572        }
573        for (kind, wire_kind) in [
574            (crate::scope::ScopeKind::Head, "head"),
575            (crate::scope::ScopeKind::Worker, "worker"),
576            (crate::scope::ScopeKind::Ephemeral, "ephemeral"),
577        ] {
578            let stamp = crate::scope::ScopeStamp::new(crate::Principal::Direct, "legacy", 1, kind)
579                .with_attributes(
580                    crate::scope::ScopeAttributes::new()
581                        .with_agent_id(Some("agent".into()))
582                        .with_delegates(true),
583                );
584            let value = serde_json::to_value(stamp).unwrap();
585            assert!(value["attributes"].get("federated").is_none());
586            assert_eq!(value["kind"], wire_kind);
587            let old: Stamp034 = serde_json::from_value(value.clone()).unwrap();
588            assert!(matches!(
589                old.kind,
590                Kind034::Head | Kind034::Worker | Kind034::Ephemeral
591            ));
592            assert_eq!(old.attributes.agent_id.as_deref(), Some("agent"));
593            assert!(old.attributes.delegates);
594            let mut bad = value["attributes"].clone();
595            bad["federated"] = serde_json::to_value(attributes()).unwrap();
596            assert!(serde_json::from_value::<Attributes034>(bad).is_err());
597        }
598    }
599}