1use serde::{Deserialize, Serialize};
2
3use super::RootKey;
4use crate::Principal;
5
6#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
8#[serde(rename_all = "snake_case")]
9#[non_exhaustive]
10pub enum FederatedPeerClass {
11 Computer,
12 App,
13 Phone,
14 Sim,
15 Unknown,
16}
17
18#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
22#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
23#[non_exhaustive]
24pub enum RemoteClaim {
25 #[non_exhaustive]
31 Agent {
32 agent_id: String,
33 #[serde(
34 default,
35 deserialize_with = "deserialize_name",
36 skip_serializing_if = "Option::is_none"
37 )]
38 agent_name: Option<String>,
39 },
40 #[non_exhaustive]
46 Worker {
47 owner_module_id: String,
48 worker_ref: String,
49 #[serde(default, skip_serializing_if = "Option::is_none")]
50 on_behalf_of: Option<String>,
51 #[serde(
53 default,
54 deserialize_with = "deserialize_name",
55 skip_serializing_if = "Option::is_none"
56 )]
57 agent_name: Option<String>,
58 },
59 #[non_exhaustive]
65 Run {
66 agent_id: String,
67 #[serde(default, skip_serializing_if = "Option::is_none")]
68 run_id: Option<String>,
69 #[serde(
70 default,
71 deserialize_with = "deserialize_name",
72 skip_serializing_if = "Option::is_none"
73 )]
74 agent_name: Option<String>,
75 },
76 #[non_exhaustive]
82 Flow {
83 flow_id: String,
84 flow_version: u64,
85 flow_install_id: String,
86 flow_code_hash: String,
87 #[serde(default, skip_serializing_if = "Option::is_none")]
90 agent_id: Option<String>,
91 #[serde(
92 default,
93 deserialize_with = "deserialize_name",
94 skip_serializing_if = "Option::is_none"
95 )]
96 flow_name: Option<String>,
97 },
98}
99
100impl RemoteClaim {
101 pub fn same_identity(&self, other: &Self) -> bool {
105 self.without_names() == other.without_names()
106 }
107
108 fn without_names(&self) -> Self {
109 let mut claim = self.clone();
110 match &mut claim {
111 Self::Agent { agent_name, .. }
112 | Self::Run { agent_name, .. }
113 | Self::Worker { agent_name, .. } => *agent_name = None,
114 Self::Flow { flow_name, .. } => *flow_name = None,
115 }
116 claim
117 }
118
119 pub fn agent(agent_id: impl Into<String>) -> Self {
120 Self::Agent {
121 agent_id: agent_id.into(),
122 agent_name: None,
123 }
124 }
125
126 pub fn worker(
127 owner_module_id: impl Into<String>,
128 worker_ref: impl Into<String>,
129 on_behalf_of: Option<String>,
130 ) -> Self {
131 Self::Worker {
132 owner_module_id: owner_module_id.into(),
133 worker_ref: worker_ref.into(),
134 on_behalf_of,
135 agent_name: None,
136 }
137 }
138
139 pub fn run(agent_id: impl Into<String>) -> Self {
140 Self::Run {
141 agent_id: agent_id.into(),
142 run_id: None,
143 agent_name: None,
144 }
145 }
146
147 pub fn flow(
148 flow_id: impl Into<String>,
149 flow_version: u64,
150 flow_install_id: impl Into<String>,
151 flow_code_hash: impl Into<String>,
152 ) -> Self {
153 Self::Flow {
154 flow_id: flow_id.into(),
155 flow_version,
156 flow_install_id: flow_install_id.into(),
157 flow_code_hash: flow_code_hash.into(),
158 agent_id: None,
159 flow_name: None,
160 }
161 }
162
163 #[must_use]
166 pub fn with_agent_name(mut self, name: impl Into<String>) -> Self {
167 match &mut self {
168 Self::Agent { agent_name, .. }
169 | Self::Run { agent_name, .. }
170 | Self::Worker { agent_name, .. } => *agent_name = valid_name(name.into()),
171 Self::Flow { .. } => {}
172 }
173 self
174 }
175
176 #[must_use]
179 pub fn with_flow_name(mut self, name: impl Into<String>) -> Self {
180 if let Self::Flow { flow_name, .. } = &mut self {
181 *flow_name = valid_name(name.into());
182 }
183 self
184 }
185
186 #[must_use]
188 pub fn with_run_id(mut self, run_id: impl Into<String>) -> Self {
189 if let Self::Run { run_id: value, .. } = &mut self {
190 *value = Some(run_id.into());
191 }
192 self
193 }
194
195 #[must_use]
197 pub fn with_flow_agent(mut self, agent_id: impl Into<String>) -> Self {
198 if let Self::Flow {
199 agent_id: value, ..
200 } = &mut self
201 {
202 *value = Some(agent_id.into());
203 }
204 self
205 }
206
207 pub fn validate(&self) -> Result<(), String> {
210 let token = |name, value: &str| {
211 crate::tool_call::validate_opaque_field(name, value).map_err(|e| e.to_string())
212 };
213 match self {
214 Self::Agent { agent_id, .. } => token("agent_id", agent_id),
215 Self::Run {
216 agent_id, run_id, ..
217 } => {
218 token("agent_id", agent_id)?;
219 if let Some(run_id) = run_id {
220 super::validate_run_id(run_id).map_err(|e| e.to_string())?;
221 }
222 Ok(())
223 }
224 Self::Worker {
225 owner_module_id,
226 worker_ref,
227 on_behalf_of,
228 ..
229 } => {
230 crate::manifest::validate_module_id(owner_module_id).map_err(|e| e.to_string())?;
231 hex("worker_ref", worker_ref, 64)?;
232 if let Some(agent) = on_behalf_of {
233 token("on_behalf_of", agent)?;
234 }
235 Ok(())
236 }
237 Self::Flow {
238 flow_id,
239 flow_version,
240 flow_install_id,
241 flow_code_hash,
242 agent_id,
243 ..
244 } => {
245 token("flow_id", flow_id)?;
246 super::validate_flow_version(*flow_version).map_err(str::to_string)?;
247 token("flow_install_id", flow_install_id)?;
248 if let Some(agent_id) = agent_id {
249 token("agent_id", agent_id)?;
250 }
251 hex("flow_code_hash", flow_code_hash, 64)
252 }
253 }
254 }
255}
256
257fn valid_name(name: String) -> Option<String> {
258 crate::manifest::validate_plain_text(&name, 80)
259 .ok()
260 .map(|()| name)
261}
262
263fn deserialize_name<'de, D: serde::Deserializer<'de>>(
264 deserializer: D,
265) -> Result<Option<String>, D::Error> {
266 let value = serde_json::Value::deserialize(deserializer)?;
267 Ok(value.as_str().and_then(|name| valid_name(name.to_owned())))
268}
269
270#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
275#[serde(deny_unknown_fields)]
276#[non_exhaustive]
277pub struct FederatedProject {
278 pub project_id: String,
279 pub root_key: RootKey,
280}
281
282impl FederatedProject {
283 pub fn new(project_id: impl Into<String>, root_key: RootKey) -> Self {
284 Self {
285 project_id: project_id.into(),
286 root_key,
287 }
288 }
289
290 pub fn validate(&self) -> Result<(), String> {
291 crate::tool_call::validate_opaque_field("project_id", &self.project_id)
292 .map_err(|e| e.to_string())?;
293 self.root_key.validate().map_err(str::to_string)
294 }
295}
296
297#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
299#[serde(deny_unknown_fields)]
300#[non_exhaustive]
301pub struct FederatedAttributes {
302 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
305 pub stamp_required: bool,
306 pub peer_class: FederatedPeerClass,
307 pub peer_fingerprint: String,
308 #[serde(default, skip_serializing_if = "Option::is_none")]
313 pub peer_box_id: Option<String>,
314 pub pairing_id: String,
315 pub peer_name: String,
316 #[serde(
321 default,
322 deserialize_with = "deserialize_origin_principal",
323 skip_serializing_if = "Option::is_none"
324 )]
325 pub origin_principal: Option<Principal>,
326 #[serde(default, skip_serializing_if = "Option::is_none")]
328 pub project: Option<FederatedProject>,
329 #[serde(default, skip_serializing_if = "Option::is_none")]
330 pub remote_claim: Option<RemoteClaim>,
331}
332
333impl FederatedAttributes {
334 pub fn same_identity(&self, other: &Self) -> bool {
338 let without_names = |facts: &Self| {
339 let mut facts = facts.clone();
340 facts.remote_claim = facts.remote_claim.as_ref().map(RemoteClaim::without_names);
341 facts
342 };
343 without_names(self) == without_names(other)
344 }
345
346 pub fn new(
347 peer_class: FederatedPeerClass,
348 peer_fingerprint: String,
349 pairing_id: String,
350 peer_name: String,
351 ) -> Self {
352 Self {
353 peer_class,
354 stamp_required: false,
355 peer_fingerprint,
356 peer_box_id: None,
357 pairing_id,
358 peer_name,
359 origin_principal: None,
360 project: None,
361 remote_claim: None,
362 }
363 }
364
365 #[must_use]
366 pub fn with_remote_claim(mut self, claim: Option<RemoteClaim>) -> Self {
367 self.remote_claim = claim;
368 self
369 }
370
371 #[must_use]
372 pub fn with_origin_principal(mut self, principal: Option<Principal>) -> Self {
373 self.origin_principal = principal;
374 self
375 }
376
377 #[must_use]
378 pub fn with_project(mut self, project: Option<FederatedProject>) -> Self {
379 self.project = project;
380 self
381 }
382
383 pub fn validate(&self) -> Result<(), String> {
385 hex("peer_fingerprint", &self.peer_fingerprint, 32)?;
386 if let Some(peer_box_id) = &self.peer_box_id {
387 hex("peer_box_id", peer_box_id, 32)?;
388 }
389 match &self.origin_principal {
390 Some(Principal::Reserved { module_id }) => {
391 crate::manifest::validate_module_id(module_id).map_err(|e| e.to_string())?;
392 }
393 Some(Principal::Unverified) => return Err("origin_principal is unverified".into()),
394 Some(Principal::Direct) | None => {}
395 }
396 if let Some(project) = &self.project {
397 project.validate()?;
398 }
399 crate::tool_call::validate_opaque_field("pairing_id", &self.pairing_id)
400 .map_err(|e| e.to_string())?;
401 crate::manifest::validate_plain_text(&self.peer_name, 80)
402 .map_err(|e| format!("peer_name {e}"))?;
403 if let Some(claim) = &self.remote_claim {
404 claim.validate()?;
405 }
406 Ok(())
407 }
408}
409
410fn hex(name: &str, value: &str, length: usize) -> Result<(), String> {
411 if value.len() != length
412 || !value
413 .bytes()
414 .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
415 {
416 return Err(format!(
417 "{name} must contain exactly {length} lowercase hex characters"
418 ));
419 }
420 Ok(())
421}
422
423fn deserialize_origin_principal<'de, D: serde::Deserializer<'de>>(
424 deserializer: D,
425) -> Result<Option<Principal>, D::Error> {
426 Option::<super::ScopePrincipal>::deserialize(deserializer)
427 .map(|principal| principal.map(Into::into))
428}
429
430#[cfg(test)]
431mod tests {
432 use super::*;
433 use crate::scope::RootKeyKind;
434 use serde_json::json;
435
436 fn attributes() -> FederatedAttributes {
437 FederatedAttributes::new(
438 FederatedPeerClass::Computer,
439 "a".repeat(32),
440 "pairing".into(),
441 "Peer".into(),
442 )
443 }
444
445 #[test]
446 fn federated_claim_names_are_optional_lossy_display_only() {
447 for (claim, field) in [
448 (RemoteClaim::agent("agent"), "agent_name"),
449 (RemoteClaim::run("agent"), "agent_name"),
450 (
451 RemoteClaim::worker("mcp:module", "a".repeat(64), Some("agent".into())),
452 "agent_name",
453 ),
454 (
455 RemoteClaim::flow("flow", 1, "install", "a".repeat(64)),
456 "flow_name",
457 ),
458 ] {
459 let original = serde_json::to_value(&claim).unwrap();
460 assert!(original.get(field).is_none());
461 let built = if field == "flow_name" {
462 claim.clone().with_flow_name("Name")
463 } else {
464 claim.clone().with_agent_name("Name")
465 };
466 assert_eq!(serde_json::to_value(built).unwrap()[field], "Name");
467 let invalid_built = if field == "flow_name" {
468 claim.clone().with_flow_name("\n")
469 } else {
470 claim.clone().with_agent_name("\n")
471 };
472 assert_eq!(serde_json::to_value(invalid_built).unwrap(), original);
473 for name in ["Agent".to_string(), "é".repeat(80), "🦀".repeat(80)] {
474 let mut wire = original.clone();
475 wire[field] = json!(name);
476 let decoded: RemoteClaim = serde_json::from_value(wire.clone()).unwrap();
477 decoded.validate().unwrap();
478 assert_eq!(serde_json::to_value(&decoded).unwrap(), wire);
479 assert_ne!(
480 decoded, claim,
481 "structural equality must detect display changes"
482 );
483 assert!(decoded.same_identity(&claim));
484 }
485 for invalid in [
486 json!(""),
487 json!("x".repeat(81)),
488 json!("\n"),
489 json!("\u{007f}"),
490 json!("\u{0085}"),
491 json!("\u{061c}"),
492 json!("\u{202e}"),
493 json!("\u{2069}"),
494 json!(null),
495 json!(7),
496 json!({"name": "Agent"}),
497 ] {
498 let mut wire = original.clone();
499 wire[field] = invalid;
500 let decoded: RemoteClaim = serde_json::from_value(wire).unwrap();
501 decoded.validate().unwrap();
502 assert_eq!(serde_json::to_value(&decoded).unwrap(), original);
503 assert_eq!(decoded, claim);
504 }
505 for (key, value) in original.as_object().unwrap() {
506 if key == "kind" {
507 continue;
508 }
509 let mut changed = original.clone();
510 changed[key] = if let Some(n) = value.as_u64() {
511 json!(n + 1)
512 } else {
513 json!(format!("other{}", value.as_str().unwrap()))
514 };
515 let changed: RemoteClaim = serde_json::from_value(changed).unwrap();
516 assert!(
517 !claim.same_identity(&changed),
518 "{key} must remain identity-bearing"
519 );
520 }
521 }
522 assert!(!RemoteClaim::agent("agent").same_identity(&RemoteClaim::run("agent")));
523 }
524
525 #[test]
526 fn federated_stamp_required_defaults_false_and_is_omitted_unless_required() {
527 let mut facts = attributes();
528 let value = serde_json::to_value(&facts).unwrap();
529 assert!(value.get("stamp_required").is_none());
530 assert!(
531 !serde_json::from_value::<FederatedAttributes>(value)
532 .unwrap()
533 .stamp_required
534 );
535 facts.stamp_required = true;
536 let value = serde_json::to_value(&facts).unwrap();
537 assert_eq!(value["stamp_required"], true);
538 assert!(
539 serde_json::from_value::<FederatedAttributes>(value)
540 .unwrap()
541 .stamp_required
542 );
543 }
544
545 #[test]
546 fn federated_claim_roundtrips_and_enforces_every_field_bound() {
547 for claim in [
548 RemoteClaim::Agent {
549 agent_id: "a".repeat(256),
550 agent_name: None,
551 },
552 RemoteClaim::Run {
553 agent_id: "a".repeat(256),
554 run_id: None,
555 agent_name: None,
556 },
557 RemoteClaim::Worker {
558 owner_module_id: "mcp:module".into(),
559 worker_ref: "a".repeat(64),
560 on_behalf_of: Some("a".repeat(256)),
561 agent_name: None,
562 },
563 RemoteClaim::Flow {
564 flow_id: "a".repeat(256),
565 flow_version: 9_007_199_254_740_991,
566 flow_install_id: "b".repeat(256),
567 flow_code_hash: "f".repeat(64),
568 agent_id: None,
569 flow_name: None,
570 },
571 ] {
572 claim.validate().unwrap();
573 let value = serde_json::to_value(&claim).unwrap();
574 assert_eq!(
575 serde_json::from_value::<RemoteClaim>(value.clone()).unwrap(),
576 claim
577 );
578 let mut unknown = value.clone();
579 unknown["unexpected"] = json!(true);
580 assert!(serde_json::from_value::<RemoteClaim>(unknown).is_err());
581 for key in ["agent_id", "flow_id", "flow_install_id", "on_behalf_of"] {
582 if value.get(key).is_some() {
583 for bad in [
584 "".to_string(),
585 "x".repeat(257),
586 "with space".into(),
587 "\n".into(),
588 "é".into(),
589 ] {
590 let mut invalid = value.clone();
591 invalid[key] = json!(bad);
592 assert!(
593 serde_json::from_value::<RemoteClaim>(invalid)
594 .unwrap()
595 .validate()
596 .is_err(),
597 "{key}"
598 );
599 }
600 }
601 }
602 for key in ["worker_ref", "flow_code_hash"] {
603 if value.get(key).is_some() {
604 for bad in [
605 "a".repeat(63),
606 "A".repeat(64),
607 "g".repeat(64),
608 "a".repeat(65),
609 ] {
610 let mut invalid = value.clone();
611 invalid[key] = json!(bad);
612 assert!(serde_json::from_value::<RemoteClaim>(invalid)
613 .unwrap()
614 .validate()
615 .is_err());
616 }
617 }
618 }
619 if value.get("flow_version").is_some() {
620 for bad in [0u64, 9_007_199_254_740_992] {
621 let mut invalid = value.clone();
622 invalid["flow_version"] = json!(bad);
623 assert!(serde_json::from_value::<RemoteClaim>(invalid)
624 .unwrap()
625 .validate()
626 .is_err());
627 }
628 }
629 if value.get("owner_module_id").is_some() {
630 for bad in ["", "..", "a/b", "a\\b", "\n"] {
631 let mut invalid = value.clone();
632 invalid["owner_module_id"] = json!(bad);
633 assert!(serde_json::from_value::<RemoteClaim>(invalid)
634 .unwrap()
635 .validate()
636 .is_err());
637 }
638 }
639 }
640 assert!(serde_json::from_value::<RemoteClaim>(json!({"kind":"future"})).is_err());
641 }
642
643 #[test]
644 fn federated_attributes_roundtrip_classes_and_enforce_limits_and_unknown_members() {
645 for class in [
646 FederatedPeerClass::Computer,
647 FederatedPeerClass::App,
648 FederatedPeerClass::Phone,
649 FederatedPeerClass::Sim,
650 FederatedPeerClass::Unknown,
651 ] {
652 let mut facts = attributes();
653 facts.peer_class = class;
654 facts.peer_name = "界".repeat(80);
655 facts.validate().unwrap();
656 let value = serde_json::to_value(&facts).unwrap();
657 assert_eq!(
658 serde_json::from_value::<FederatedAttributes>(value.clone()).unwrap(),
659 facts
660 );
661 let mut unknown = value;
662 unknown["unexpected"] = json!(true);
663 assert!(serde_json::from_value::<FederatedAttributes>(unknown).is_err());
664 }
665 for bad in [
666 "",
667 "a\n",
668 "a\u{061c}",
669 "a\u{200e}",
670 "a\u{202e}",
671 "a\u{2069}",
672 &"a".repeat(81),
673 ] {
674 let mut facts = attributes();
675 facts.peer_name = bad.into();
676 assert!(facts.validate().is_err());
677 }
678 for bad in [
679 "A".repeat(32),
680 "a".repeat(31),
681 "a".repeat(33),
682 "g".repeat(32),
683 ] {
684 let mut facts = attributes();
685 facts.peer_fingerprint = bad;
686 assert!(facts.validate().is_err());
687 }
688 for bad in ["".to_string(), "x".repeat(257), "space here".into()] {
689 let mut facts = attributes();
690 facts.pairing_id = bad;
691 assert!(facts.validate().is_err());
692 }
693 let mut facts = attributes();
694 facts.pairing_id = "x".repeat(256);
695 facts.validate().unwrap();
696 }
697
698 #[test]
699 fn federated_new_members_roundtrip_and_old_senders_decode_unchanged() {
700 let old = json!({
701 "peer_class": "computer", "peer_fingerprint": "a".repeat(32),
702 "pairing_id": "pairing", "peer_name": "Peer"
703 });
704 let decoded: FederatedAttributes = serde_json::from_value(old.clone()).unwrap();
705 assert_eq!(decoded, attributes());
706 assert_eq!(serde_json::to_value(decoded).unwrap(), old);
707 for claim in [
708 RemoteClaim::run("agent"),
709 RemoteClaim::flow("flow", 1, "install", "b".repeat(64)),
710 ] {
711 let value = serde_json::to_value(&claim).unwrap();
712 assert!(value.get("run_id").is_none());
713 if matches!(claim, RemoteClaim::Flow { .. }) {
714 assert!(value.get("agent_id").is_none());
715 }
716 assert_eq!(serde_json::from_value::<RemoteClaim>(value).unwrap(), claim);
717 }
718 for principal in [
719 Principal::Direct,
720 Principal::Reserved {
721 module_id: "origin-module".into(),
722 },
723 ] {
724 for claim in [
725 RemoteClaim::run("agent").with_run_id("run-1"),
726 RemoteClaim::flow("flow", 1, "install", "b".repeat(64)).with_flow_agent("agent"),
727 ] {
728 let mut facts = attributes()
729 .with_origin_principal(Some(principal.clone()))
730 .with_remote_claim(Some(claim));
731 facts.peer_class = FederatedPeerClass::App;
732 facts.peer_box_id = Some("0123456789abcdef".repeat(2));
733 facts = facts.with_project(Some(FederatedProject::new(
734 "project",
735 RootKey::new(RootKeyKind::Remote, "owner/repo"),
736 )));
737 facts.validate().unwrap();
738 let wire = serde_json::to_value(&facts).unwrap();
739 assert_eq!(wire["peer_class"], "app");
740 assert_eq!(
741 wire["origin_principal"],
742 serde_json::to_value(&principal).unwrap()
743 );
744 assert_eq!(wire["peer_box_id"], "0123456789abcdef".repeat(2));
745 assert_eq!(
746 wire["project"],
747 json!({"project_id":"project", "root_key":{"kind":"remote", "key":"owner/repo"}})
748 );
749 assert_eq!(
750 serde_json::from_value::<FederatedAttributes>(wire).unwrap(),
751 facts
752 );
753 }
754 }
755 assert_eq!(
756 RemoteClaim::agent("agent")
757 .with_run_id("run")
758 .with_flow_agent("owner"),
759 RemoteClaim::agent("agent")
760 );
761 assert_eq!(
762 RemoteClaim::run("agent").with_flow_agent("owner"),
763 RemoteClaim::run("agent")
764 );
765 let flow = RemoteClaim::flow("flow", 1, "install", "b".repeat(64));
766 assert_eq!(flow.clone().with_run_id("run"), flow);
767 let worker = RemoteClaim::worker("owner", "b".repeat(64), None);
768 assert_eq!(
769 worker.clone().with_run_id("run").with_flow_agent("owner"),
770 worker
771 );
772 }
773
774 #[test]
775 fn federated_new_identity_members_enforce_bounds() {
776 for module_id in [
777 "".into(),
778 ".".into(),
779 "..".into(),
780 "a/b".into(),
781 "a\\b".into(),
782 "\n".into(),
783 "x".repeat(256),
784 ] {
785 assert!(attributes()
786 .with_origin_principal(Some(Principal::Reserved { module_id }))
787 .validate()
788 .is_err());
789 }
790 attributes()
791 .with_origin_principal(Some(Principal::Reserved {
792 module_id: "x".repeat(255),
793 }))
794 .validate()
795 .unwrap();
796 attributes()
797 .with_origin_principal(Some(Principal::Direct))
798 .validate()
799 .unwrap();
800 assert!(attributes()
801 .with_origin_principal(Some(Principal::Unverified))
802 .validate()
803 .is_err());
804 for value in [
805 "".into(),
806 "x".repeat(257),
807 "has space".into(),
808 "\n".into(),
809 "é".into(),
810 "\u{007f}".into(),
811 ] {
812 assert!(RemoteClaim::run("agent")
813 .with_run_id(&value)
814 .validate()
815 .is_err());
816 assert!(RemoteClaim::flow("flow", 1, "install", "b".repeat(64))
817 .with_flow_agent(&value)
818 .validate()
819 .is_err());
820 assert!(attributes()
821 .with_project(Some(FederatedProject::new(
822 &value,
823 RootKey::new(RootKeyKind::Remote, "owner/repo")
824 )))
825 .validate()
826 .is_err());
827 assert!(attributes()
828 .with_project(Some(FederatedProject::new(
829 "project",
830 RootKey::new(RootKeyKind::Label, &value)
831 )))
832 .validate()
833 .is_err());
834 }
835 for value in ["!".to_owned(), "~".repeat(256)] {
836 RemoteClaim::run("agent")
837 .with_run_id(&value)
838 .validate()
839 .unwrap();
840 RemoteClaim::flow("flow", 1, "install", "b".repeat(64))
841 .with_flow_agent(&value)
842 .validate()
843 .unwrap();
844 attributes()
845 .with_project(Some(FederatedProject::new(
846 &value,
847 RootKey::new(RootKeyKind::Label, "root"),
848 )))
849 .validate()
850 .unwrap();
851 }
852 for value in [
853 "".into(),
854 "a".repeat(31),
855 "a".repeat(33),
856 "A".repeat(32),
857 "g".repeat(32),
858 ] {
859 let mut facts = attributes();
860 facts.peer_box_id = Some(value);
861 assert!(facts.validate().is_err());
862 }
863 for principal in [
864 json!({"kind":"reserved", "module_id":"origin", "extra":true}),
865 json!({"kind":"direct", "extra":true}),
866 json!({"kind":"future"}),
867 ] {
868 let mut wire = serde_json::to_value(attributes()).unwrap();
869 wire["origin_principal"] = principal;
870 assert!(serde_json::from_value::<FederatedAttributes>(wire).is_err());
871 }
872 }
873
874 #[test]
875 fn federated_project_requires_both_keys_and_refuses_unknown_members() {
876 for kind in [RootKeyKind::Remote, RootKeyKind::Label] {
877 let project = FederatedProject::new("project", RootKey::new(kind, "~".repeat(128)));
878 project.validate().unwrap();
879 let wire = serde_json::to_value(&project).unwrap();
880 assert_eq!(
881 serde_json::from_value::<FederatedProject>(wire).unwrap(),
882 project
883 );
884 }
885 assert!(FederatedProject::new(
886 "project",
887 RootKey::new(RootKeyKind::Remote, "x".repeat(129))
888 )
889 .validate()
890 .is_err());
891 for project in [
892 json!({}),
893 json!({"project_id":"project"}),
894 json!({"root_key":{"kind":"remote", "key":"owner/repo"}}),
895 json!({"project_id":"project", "root_key":"owner/repo"}),
896 json!({"project_id":"project", "root_key":{"kind":"future", "key":"owner/repo"}}),
897 json!({"project_id":"project", "root_key":{"kind":"remote", "key":"owner/repo", "extra":true}}),
898 json!({"project_id":"project", "root_key":{"kind":"remote", "key":"owner/repo"}, "extra":true}),
899 ] {
900 let mut wire = serde_json::to_value(attributes()).unwrap();
901 wire["project"] = project;
902 assert!(serde_json::from_value::<FederatedAttributes>(wire).is_err());
903 }
904 }
905
906 #[test]
907 fn federated_same_identity_counts_every_new_member() {
908 let base = attributes();
909 let mut with_box = base.clone();
910 with_box.peer_box_id = Some("b".repeat(32));
911 let mut app = base.clone();
912 app.peer_class = FederatedPeerClass::App;
913 let project = base.clone().with_project(Some(FederatedProject::new(
914 "project-one",
915 RootKey::new(RootKeyKind::Remote, "owner/repo"),
916 )));
917 for changed in [
918 with_box.clone(),
919 project.clone(),
920 app,
921 base.clone().with_origin_principal(Some(Principal::Direct)),
922 ] {
923 assert!(!base.same_identity(&changed));
924 }
925 let mut other_box = with_box.clone();
926 other_box.peer_box_id = Some("c".repeat(32));
927 assert!(!with_box.same_identity(&other_box));
928 for other_project in [
929 FederatedProject::new(
930 "project-two",
931 RootKey::new(RootKeyKind::Remote, "owner/repo"),
932 ),
933 FederatedProject::new(
934 "project-one",
935 RootKey::new(RootKeyKind::Remote, "other/repo"),
936 ),
937 FederatedProject::new(
938 "project-one",
939 RootKey::new(RootKeyKind::Label, "owner/repo"),
940 ),
941 ] {
942 assert!(!project.same_identity(&base.clone().with_project(Some(other_project))));
943 }
944 assert!(!base
945 .clone()
946 .with_origin_principal(Some(Principal::Direct))
947 .same_identity(
948 &base
949 .clone()
950 .with_origin_principal(Some(Principal::Reserved {
951 module_id: "origin".into()
952 }))
953 ));
954 for (old, new, other) in [
955 (
956 RemoteClaim::run("agent"),
957 RemoteClaim::run("agent").with_run_id("one"),
958 RemoteClaim::run("agent").with_run_id("two"),
959 ),
960 (
961 RemoteClaim::flow("flow", 1, "install", "b".repeat(64)),
962 RemoteClaim::flow("flow", 1, "install", "b".repeat(64)).with_flow_agent("one"),
963 RemoteClaim::flow("flow", 1, "install", "b".repeat(64)).with_flow_agent("two"),
964 ),
965 ] {
966 assert!(!old.same_identity(&new));
967 assert!(!new.same_identity(&other));
968 assert!(!base
969 .clone()
970 .with_remote_claim(Some(old))
971 .same_identity(&base.clone().with_remote_claim(Some(new.clone()))));
972 assert!(new.same_identity(&new.clone().with_agent_name("Name").with_flow_name("Name")));
973 }
974 }
975
976 #[test]
977 fn federated_readers_first_rollout_new_members_are_refused_by_strict_0373_readers() {
978 #[derive(Deserialize)]
981 #[serde(rename_all = "snake_case")]
982 enum Peer0373 {
983 Computer,
984 Phone,
985 Sim,
986 Unknown,
987 }
988 #[derive(Deserialize)]
989 #[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
990 #[allow(dead_code)]
991 enum Claim0373 {
992 Agent {
993 agent_id: String,
994 #[serde(default, deserialize_with = "deserialize_name")]
995 agent_name: Option<String>,
996 },
997 Worker {
998 owner_module_id: String,
999 worker_ref: String,
1000 #[serde(default)]
1001 on_behalf_of: Option<String>,
1002 #[serde(default, deserialize_with = "deserialize_name")]
1003 agent_name: Option<String>,
1004 },
1005 Run {
1006 agent_id: String,
1007 #[serde(default, deserialize_with = "deserialize_name")]
1008 agent_name: Option<String>,
1009 },
1010 Flow {
1011 flow_id: String,
1012 flow_version: u64,
1013 flow_install_id: String,
1014 flow_code_hash: String,
1015 #[serde(default, deserialize_with = "deserialize_name")]
1016 flow_name: Option<String>,
1017 },
1018 }
1019 #[derive(Deserialize)]
1020 #[serde(deny_unknown_fields)]
1021 #[allow(dead_code)]
1022 struct Attributes0373 {
1023 #[serde(default)]
1024 stamp_required: bool,
1025 peer_class: Peer0373,
1026 peer_fingerprint: String,
1027 pairing_id: String,
1028 peer_name: String,
1029 #[serde(default)]
1030 remote_claim: Option<Claim0373>,
1031 }
1032 let base = serde_json::to_value(attributes()).unwrap();
1033 serde_json::from_value::<Attributes0373>(base.clone()).unwrap();
1034 for (field, value) in [
1035 ("peer_class", json!("app")),
1036 ("peer_box_id", json!("b".repeat(32))),
1037 (
1038 "project",
1039 json!({"project_id":"project", "root_key":{"kind":"remote", "key":"owner/repo"}}),
1040 ),
1041 ("origin_principal", json!({"kind":"direct"})),
1042 (
1043 "remote_claim",
1044 json!({"kind":"run", "agent_id":"agent", "run_id":"run"}),
1045 ),
1046 (
1047 "remote_claim",
1048 json!({"kind":"flow", "flow_id":"flow", "flow_version":1, "flow_install_id":"install", "flow_code_hash":"b".repeat(64), "agent_id":"agent"}),
1049 ),
1050 ] {
1051 let mut wire = base.clone();
1052 wire[field] = value;
1053 let new: FederatedAttributes = serde_json::from_value(wire.clone()).unwrap();
1054 new.validate().unwrap();
1055 assert!(
1056 serde_json::from_value::<Attributes0373>(wire).is_err(),
1057 "{field}"
1058 );
1059 }
1060 }
1061
1062 #[test]
1063 fn federated_absent_keeps_nonfederated_stamps_readable_by_the_strict_034_attributes_decoder() {
1064 #[derive(Default, Deserialize)]
1066 #[serde(default, deny_unknown_fields)]
1067 #[allow(dead_code)]
1068 struct Attributes034 {
1069 agent_id: Option<String>,
1070 delegates: bool,
1071 on_behalf_of_agent: Option<String>,
1072 flow_id: Option<String>,
1073 flow_version: Option<u64>,
1074 flow_code_hash: Option<String>,
1075 flow_install_id: Option<String>,
1076 run_id: Option<String>,
1077 }
1078 #[derive(Deserialize)]
1079 #[serde(rename_all = "snake_case")]
1080 enum Kind034 {
1081 Head,
1082 Worker,
1083 Ephemeral,
1084 }
1085 #[derive(Deserialize)]
1086 struct Stamp034 {
1087 kind: Kind034,
1088 #[serde(default)]
1089 attributes: Attributes034,
1090 }
1091 for (kind, wire_kind) in [
1092 (crate::scope::ScopeKind::Head, "head"),
1093 (crate::scope::ScopeKind::Worker, "worker"),
1094 (crate::scope::ScopeKind::Ephemeral, "ephemeral"),
1095 ] {
1096 let stamp = crate::scope::ScopeStamp::new(crate::Principal::Direct, "legacy", 1, kind)
1097 .with_attributes(
1098 crate::scope::ScopeAttributes::new()
1099 .with_agent_id(Some("agent".into()))
1100 .with_delegates(true),
1101 );
1102 let value = serde_json::to_value(stamp).unwrap();
1103 assert!(value["attributes"].get("federated").is_none());
1104 assert_eq!(value["kind"], wire_kind);
1105 let old: Stamp034 = serde_json::from_value(value.clone()).unwrap();
1106 assert!(matches!(
1107 old.kind,
1108 Kind034::Head | Kind034::Worker | Kind034::Ephemeral
1109 ));
1110 assert_eq!(old.attributes.agent_id.as_deref(), Some("agent"));
1111 assert!(old.attributes.delegates);
1112 let mut bad = value["attributes"].clone();
1113 bad["federated"] = serde_json::to_value(attributes()).unwrap();
1114 assert!(serde_json::from_value::<Attributes034>(bad).is_err());
1115 }
1116 }
1117}