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    /// Require a federated stamp instead of falling back to a legacy bind.
232    /// This daemon instruction is removed from provider-facing stamps.
233    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
234    pub stamp_required: bool,
235    pub peer_class: FederatedPeerClass,
236    pub peer_fingerprint: String,
237    pub pairing_id: String,
238    pub peer_name: String,
239    #[serde(default, skip_serializing_if = "Option::is_none")]
240    pub remote_claim: Option<RemoteClaim>,
241}
242
243impl FederatedAttributes {
244    /// Compare the facts fixed for an epoch, ignoring only the remote claim's
245    /// display names. Every other field counts, including any added later;
246    /// `peer_name` is a fixed pairing-roster fact, not a display name here.
247    pub fn same_identity(&self, other: &Self) -> bool {
248        let without_names = |facts: &Self| {
249            let mut facts = facts.clone();
250            facts.remote_claim = facts.remote_claim.as_ref().map(RemoteClaim::without_names);
251            facts
252        };
253        without_names(self) == without_names(other)
254    }
255
256    pub fn new(
257        peer_class: FederatedPeerClass,
258        peer_fingerprint: String,
259        pairing_id: String,
260        peer_name: String,
261    ) -> Self {
262        Self {
263            peer_class,
264            stamp_required: false,
265            peer_fingerprint,
266            pairing_id,
267            peer_name,
268            remote_claim: None,
269        }
270    }
271
272    #[must_use]
273    pub fn with_remote_claim(mut self, claim: Option<RemoteClaim>) -> Self {
274        self.remote_claim = claim;
275        self
276    }
277
278    /// Validate both decoded and programmatically constructed attributes.
279    pub fn validate(&self) -> Result<(), String> {
280        hex("peer_fingerprint", &self.peer_fingerprint, 32)?;
281        crate::tool_call::validate_opaque_field("pairing_id", &self.pairing_id)
282            .map_err(|e| e.to_string())?;
283        crate::manifest::validate_plain_text(&self.peer_name, 80)
284            .map_err(|e| format!("peer_name {e}"))?;
285        if let Some(claim) = &self.remote_claim {
286            claim.validate()?;
287        }
288        Ok(())
289    }
290}
291
292fn hex(name: &str, value: &str, length: usize) -> Result<(), String> {
293    if value.len() != length
294        || !value
295            .bytes()
296            .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
297    {
298        return Err(format!(
299            "{name} must contain exactly {length} lowercase hex characters"
300        ));
301    }
302    Ok(())
303}
304
305#[cfg(test)]
306mod tests {
307    use super::*;
308    use serde_json::json;
309
310    fn attributes() -> FederatedAttributes {
311        FederatedAttributes::new(
312            FederatedPeerClass::Computer,
313            "a".repeat(32),
314            "pairing".into(),
315            "Peer".into(),
316        )
317    }
318
319    #[test]
320    fn federated_claim_names_are_optional_lossy_display_only() {
321        for (claim, field) in [
322            (RemoteClaim::agent("agent"), "agent_name"),
323            (RemoteClaim::run("agent"), "agent_name"),
324            (
325                RemoteClaim::worker("mcp:module", "a".repeat(64), Some("agent".into())),
326                "agent_name",
327            ),
328            (
329                RemoteClaim::flow("flow", 1, "install", "a".repeat(64)),
330                "flow_name",
331            ),
332        ] {
333            let original = serde_json::to_value(&claim).unwrap();
334            assert!(original.get(field).is_none());
335            let built = if field == "flow_name" {
336                claim.clone().with_flow_name("Name")
337            } else {
338                claim.clone().with_agent_name("Name")
339            };
340            assert_eq!(serde_json::to_value(built).unwrap()[field], "Name");
341            let invalid_built = if field == "flow_name" {
342                claim.clone().with_flow_name("\n")
343            } else {
344                claim.clone().with_agent_name("\n")
345            };
346            assert_eq!(serde_json::to_value(invalid_built).unwrap(), original);
347            for name in ["Agent".to_string(), "é".repeat(80), "🦀".repeat(80)] {
348                let mut wire = original.clone();
349                wire[field] = json!(name);
350                let decoded: RemoteClaim = serde_json::from_value(wire.clone()).unwrap();
351                decoded.validate().unwrap();
352                assert_eq!(serde_json::to_value(&decoded).unwrap(), wire);
353                assert_ne!(
354                    decoded, claim,
355                    "structural equality must detect display changes"
356                );
357                assert!(decoded.same_identity(&claim));
358            }
359            for invalid in [
360                json!(""),
361                json!("x".repeat(81)),
362                json!("\n"),
363                json!("\u{007f}"),
364                json!("\u{0085}"),
365                json!("\u{061c}"),
366                json!("\u{202e}"),
367                json!("\u{2069}"),
368                json!(null),
369                json!(7),
370                json!({"name": "Agent"}),
371            ] {
372                let mut wire = original.clone();
373                wire[field] = invalid;
374                let decoded: RemoteClaim = serde_json::from_value(wire).unwrap();
375                decoded.validate().unwrap();
376                assert_eq!(serde_json::to_value(&decoded).unwrap(), original);
377                assert_eq!(decoded, claim);
378            }
379            for (key, value) in original.as_object().unwrap() {
380                if key == "kind" {
381                    continue;
382                }
383                let mut changed = original.clone();
384                changed[key] = if let Some(n) = value.as_u64() {
385                    json!(n + 1)
386                } else {
387                    json!(format!("other{}", value.as_str().unwrap()))
388                };
389                let changed: RemoteClaim = serde_json::from_value(changed).unwrap();
390                assert!(
391                    !claim.same_identity(&changed),
392                    "{key} must remain identity-bearing"
393                );
394            }
395        }
396        assert!(!RemoteClaim::agent("agent").same_identity(&RemoteClaim::run("agent")));
397    }
398
399    #[test]
400    fn federated_stamp_required_defaults_false_and_is_omitted_unless_required() {
401        let mut facts = attributes();
402        let value = serde_json::to_value(&facts).unwrap();
403        assert!(value.get("stamp_required").is_none());
404        assert!(
405            !serde_json::from_value::<FederatedAttributes>(value)
406                .unwrap()
407                .stamp_required
408        );
409        facts.stamp_required = true;
410        let value = serde_json::to_value(&facts).unwrap();
411        assert_eq!(value["stamp_required"], true);
412        assert!(
413            serde_json::from_value::<FederatedAttributes>(value)
414                .unwrap()
415                .stamp_required
416        );
417    }
418
419    #[test]
420    fn federated_claim_roundtrips_and_enforces_every_field_bound() {
421        for claim in [
422            RemoteClaim::Agent {
423                agent_id: "a".repeat(256),
424                agent_name: None,
425            },
426            RemoteClaim::Run {
427                agent_id: "a".repeat(256),
428                agent_name: None,
429            },
430            RemoteClaim::Worker {
431                owner_module_id: "mcp:module".into(),
432                worker_ref: "a".repeat(64),
433                on_behalf_of: Some("a".repeat(256)),
434                agent_name: None,
435            },
436            RemoteClaim::Flow {
437                flow_id: "a".repeat(256),
438                flow_version: 9_007_199_254_740_991,
439                flow_install_id: "b".repeat(256),
440                flow_code_hash: "f".repeat(64),
441                flow_name: None,
442            },
443        ] {
444            claim.validate().unwrap();
445            let value = serde_json::to_value(&claim).unwrap();
446            assert_eq!(
447                serde_json::from_value::<RemoteClaim>(value.clone()).unwrap(),
448                claim
449            );
450            let mut unknown = value.clone();
451            unknown["unexpected"] = json!(true);
452            assert!(serde_json::from_value::<RemoteClaim>(unknown).is_err());
453            for key in ["agent_id", "flow_id", "flow_install_id", "on_behalf_of"] {
454                if value.get(key).is_some() {
455                    for bad in [
456                        "".to_string(),
457                        "x".repeat(257),
458                        "with space".into(),
459                        "\n".into(),
460                        "é".into(),
461                    ] {
462                        let mut invalid = value.clone();
463                        invalid[key] = json!(bad);
464                        assert!(
465                            serde_json::from_value::<RemoteClaim>(invalid)
466                                .unwrap()
467                                .validate()
468                                .is_err(),
469                            "{key}"
470                        );
471                    }
472                }
473            }
474            for key in ["worker_ref", "flow_code_hash"] {
475                if value.get(key).is_some() {
476                    for bad in [
477                        "a".repeat(63),
478                        "A".repeat(64),
479                        "g".repeat(64),
480                        "a".repeat(65),
481                    ] {
482                        let mut invalid = value.clone();
483                        invalid[key] = json!(bad);
484                        assert!(serde_json::from_value::<RemoteClaim>(invalid)
485                            .unwrap()
486                            .validate()
487                            .is_err());
488                    }
489                }
490            }
491            if value.get("flow_version").is_some() {
492                for bad in [0u64, 9_007_199_254_740_992] {
493                    let mut invalid = value.clone();
494                    invalid["flow_version"] = json!(bad);
495                    assert!(serde_json::from_value::<RemoteClaim>(invalid)
496                        .unwrap()
497                        .validate()
498                        .is_err());
499                }
500            }
501            if value.get("owner_module_id").is_some() {
502                for bad in ["", "..", "a/b", "a\\b", "\n"] {
503                    let mut invalid = value.clone();
504                    invalid["owner_module_id"] = json!(bad);
505                    assert!(serde_json::from_value::<RemoteClaim>(invalid)
506                        .unwrap()
507                        .validate()
508                        .is_err());
509                }
510            }
511        }
512        assert!(serde_json::from_value::<RemoteClaim>(json!({"kind":"future"})).is_err());
513    }
514
515    #[test]
516    fn federated_attributes_roundtrip_classes_and_enforce_limits_and_unknown_members() {
517        for class in [
518            FederatedPeerClass::Computer,
519            FederatedPeerClass::Phone,
520            FederatedPeerClass::Sim,
521            FederatedPeerClass::Unknown,
522        ] {
523            let mut facts = attributes();
524            facts.peer_class = class;
525            facts.peer_name = "界".repeat(80);
526            facts.validate().unwrap();
527            let value = serde_json::to_value(&facts).unwrap();
528            assert_eq!(
529                serde_json::from_value::<FederatedAttributes>(value.clone()).unwrap(),
530                facts
531            );
532            let mut unknown = value;
533            unknown["unexpected"] = json!(true);
534            assert!(serde_json::from_value::<FederatedAttributes>(unknown).is_err());
535        }
536        for bad in [
537            "",
538            "a\n",
539            "a\u{061c}",
540            "a\u{200e}",
541            "a\u{202e}",
542            "a\u{2069}",
543            &"a".repeat(81),
544        ] {
545            let mut facts = attributes();
546            facts.peer_name = bad.into();
547            assert!(facts.validate().is_err());
548        }
549        for bad in [
550            "A".repeat(32),
551            "a".repeat(31),
552            "a".repeat(33),
553            "g".repeat(32),
554        ] {
555            let mut facts = attributes();
556            facts.peer_fingerprint = bad;
557            assert!(facts.validate().is_err());
558        }
559        for bad in ["".to_string(), "x".repeat(257), "space here".into()] {
560            let mut facts = attributes();
561            facts.pairing_id = bad;
562            assert!(facts.validate().is_err());
563        }
564        let mut facts = attributes();
565        facts.pairing_id = "x".repeat(256);
566        facts.validate().unwrap();
567    }
568
569    #[test]
570    fn federated_absent_keeps_nonfederated_stamps_readable_by_the_strict_034_attributes_decoder() {
571        // Freeze the 0.34 nested schema rather than decoding with today's types.
572        #[derive(Default, Deserialize)]
573        #[serde(default, deny_unknown_fields)]
574        #[allow(dead_code)]
575        struct Attributes034 {
576            agent_id: Option<String>,
577            delegates: bool,
578            on_behalf_of_agent: Option<String>,
579            flow_id: Option<String>,
580            flow_version: Option<u64>,
581            flow_code_hash: Option<String>,
582            flow_install_id: Option<String>,
583            run_id: Option<String>,
584        }
585        #[derive(Deserialize)]
586        #[serde(rename_all = "snake_case")]
587        enum Kind034 {
588            Head,
589            Worker,
590            Ephemeral,
591        }
592        #[derive(Deserialize)]
593        struct Stamp034 {
594            kind: Kind034,
595            #[serde(default)]
596            attributes: Attributes034,
597        }
598        for (kind, wire_kind) in [
599            (crate::scope::ScopeKind::Head, "head"),
600            (crate::scope::ScopeKind::Worker, "worker"),
601            (crate::scope::ScopeKind::Ephemeral, "ephemeral"),
602        ] {
603            let stamp = crate::scope::ScopeStamp::new(crate::Principal::Direct, "legacy", 1, kind)
604                .with_attributes(
605                    crate::scope::ScopeAttributes::new()
606                        .with_agent_id(Some("agent".into()))
607                        .with_delegates(true),
608                );
609            let value = serde_json::to_value(stamp).unwrap();
610            assert!(value["attributes"].get("federated").is_none());
611            assert_eq!(value["kind"], wire_kind);
612            let old: Stamp034 = serde_json::from_value(value.clone()).unwrap();
613            assert!(matches!(
614                old.kind,
615                Kind034::Head | Kind034::Worker | Kind034::Ephemeral
616            ));
617            assert_eq!(old.attributes.agent_id.as_deref(), Some("agent"));
618            assert!(old.attributes.delegates);
619            let mut bad = value["attributes"].clone();
620            bad["federated"] = serde_json::to_value(attributes()).unwrap();
621            assert!(serde_json::from_value::<Attributes034>(bad).is_err());
622        }
623    }
624}