1use serde::{Deserialize, Serialize};
15
16use crate::Principal;
17
18#[derive(Deserialize)]
22#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
23enum ScopePrincipal {
24 Reserved { module_id: String },
25 Direct {},
26 Unverified {},
27}
28
29impl From<ScopePrincipal> for Principal {
30 fn from(value: ScopePrincipal) -> Self {
31 match value {
32 ScopePrincipal::Reserved { module_id } => Self::Reserved { module_id },
33 ScopePrincipal::Direct {} => Self::Direct,
34 ScopePrincipal::Unverified {} => Self::Unverified,
35 }
36 }
37}
38
39fn deserialize_scope_principal<'de, D: serde::Deserializer<'de>>(
40 deserializer: D,
41) -> Result<Principal, D::Error> {
42 ScopePrincipal::deserialize(deserializer).map(Into::into)
43}
44
45fn deserialize_scope_principals<'de, D: serde::Deserializer<'de>>(
46 deserializer: D,
47) -> Result<Vec<Principal>, D::Error> {
48 Vec::<ScopePrincipal>::deserialize(deserializer)
49 .map(|principals| principals.into_iter().map(Into::into).collect())
50}
51
52pub fn validate_bind_proof_sha256(hash: &str) -> Result<(), &'static str> {
54 if hash.len() == 64
55 && hash
56 .bytes()
57 .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
58 {
59 Ok(())
60 } else {
61 Err("bind_proof_sha256 must be exactly 64 lowercase hexadecimal characters")
62 }
63}
64
65fn deserialize_bind_proof_sha256<'de, D: serde::Deserializer<'de>>(
66 deserializer: D,
67) -> Result<Option<String>, D::Error> {
68 let hash = Option::<String>::deserialize(deserializer)?;
69 if let Some(hash) = &hash {
70 validate_bind_proof_sha256(hash).map_err(serde::de::Error::custom)?;
71 }
72 Ok(hash)
73}
74
75pub const CAP_SCOPES_V1: &str = "scopes/v1";
79
80pub const CAP_ROUTE_ROLE_VERSIONS_V1: &str = "route-role-versions/v1";
85
86pub const SCOPE_SYNC_OP: &str = "scope.sync";
88pub const SCOPE_APPLY_OP: &str = "scope.apply";
91pub const SCOPE_DESCRIBE_OP: &str = "scope.describe";
93
94pub const MAX_LIVE_SCOPES_PER_OWNER: usize = 10_000;
96pub const MAX_SCOPE_ATTRIBUTE_BYTES: usize = 4 * 1024;
99pub const MAX_SCOPE_TOMBSTONES_PER_OWNER: usize = 1_000;
102pub const MAX_CARRIER_TARGETS: usize = 16;
104pub const MAX_SCOPE_EXPIRY_AHEAD_MS: u64 = 86_400_000;
107
108#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
111#[serde(rename_all = "snake_case")]
112pub enum ScopeKind {
113 Head,
114 Worker,
115 Ephemeral,
116}
117
118#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
121#[serde(deny_unknown_fields)]
122#[non_exhaustive]
123pub struct ScopeParent {
124 #[serde(deserialize_with = "deserialize_scope_principal")]
125 pub owner: Principal,
126 #[serde(rename = "ref")]
127 pub scope_ref: String,
128 pub scope_epoch: u64,
129}
130
131impl ScopeParent {
132 pub fn new(owner: Principal, scope_ref: impl Into<String>, scope_epoch: u64) -> Self {
133 Self {
134 owner,
135 scope_ref: scope_ref.into(),
136 scope_epoch,
137 }
138 }
139}
140
141#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
148#[serde(deny_unknown_fields)]
149#[non_exhaustive]
150pub struct ScopeCarrier {
151 #[serde(deserialize_with = "deserialize_scope_principal")]
152 pub principal: Principal,
153 #[serde(default, skip_serializing_if = "Option::is_none")]
154 pub targets: Option<Vec<String>>,
155}
156
157impl ScopeCarrier {
158 pub fn new(principal: Principal) -> Self {
159 Self {
160 principal,
161 targets: None,
162 }
163 }
164
165 #[must_use]
166 pub fn with_targets(mut self, targets: Option<Vec<String>>) -> Self {
167 self.targets = targets;
168 self
169 }
170}
171
172pub const FLOW_SCOPES_CAPABILITY: &str = "flow-scopes/v1";
178
179pub const FLOW_IDENTITY_SCOPES_CAPABILITY: &str = "flow-identity-scopes/v1";
182
183pub const AGENT_RUN_SCOPES_CAPABILITY: &str = "agent-run-scopes/v1";
189
190pub const SCOPE_ON_BEHALF_OF_CAPABILITY: &str = "scope-on-behalf-of/v1";
194
195pub const WORKER_RUNS_CAPABILITY: &str = "worker-runs/v1";
208
209pub const SCOPE_SERVED_BY_CAPABILITY: &str = "scope-served-by/v1";
211
212#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
218#[serde(deny_unknown_fields)]
219#[non_exhaustive]
220pub struct ScopeAttributes {
221 #[serde(default, skip_serializing_if = "Option::is_none")]
223 pub agent_id: Option<String>,
224 #[serde(default, skip_serializing_if = "Option::is_none")]
241 pub on_behalf_of_agent: Option<String>,
242 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
244 pub delegates: bool,
245 #[serde(default, skip_serializing_if = "Option::is_none")]
261 pub flow_id: Option<String>,
262 #[serde(default, skip_serializing_if = "Option::is_none")]
267 pub flow_version: Option<u64>,
268 #[serde(default, skip_serializing_if = "Option::is_none")]
272 pub flow_code_hash: Option<String>,
273 #[serde(default, skip_serializing_if = "Option::is_none")]
277 pub flow_install_id: Option<String>,
278 #[serde(default, skip_serializing_if = "Option::is_none")]
290 pub run_id: Option<String>,
291}
292
293impl ScopeAttributes {
294 pub fn new() -> Self {
295 Self::default()
296 }
297
298 #[must_use]
299 pub fn with_agent_id(mut self, agent_id: Option<String>) -> Self {
300 self.agent_id = agent_id;
301 self
302 }
303
304 #[must_use]
305 pub fn with_on_behalf_of_agent(mut self, on_behalf_of_agent: Option<String>) -> Self {
306 self.on_behalf_of_agent = on_behalf_of_agent;
307 self
308 }
309
310 #[must_use]
311 pub fn with_delegates(mut self, delegates: bool) -> Self {
312 self.delegates = delegates;
313 self
314 }
315
316 #[must_use]
317 pub fn with_flow_id(mut self, flow_id: Option<String>) -> Self {
318 self.flow_id = flow_id;
319 self
320 }
321
322 #[must_use]
323 pub fn with_flow_version(mut self, flow_version: Option<u64>) -> Self {
324 self.flow_version = flow_version;
325 self
326 }
327
328 #[must_use]
329 pub fn with_flow_code_hash(mut self, flow_code_hash: Option<String>) -> Self {
330 self.flow_code_hash = flow_code_hash;
331 self
332 }
333
334 #[must_use]
335 pub fn with_flow_install_id(mut self, flow_install_id: Option<String>) -> Self {
336 self.flow_install_id = flow_install_id;
337 self
338 }
339
340 #[must_use]
341 pub fn with_run_id(mut self, run_id: Option<String>) -> Self {
342 self.run_id = run_id;
343 self
344 }
345
346 pub fn is_empty(&self) -> bool {
347 self.agent_id.is_none()
348 && self.on_behalf_of_agent.is_none()
349 && !self.delegates
350 && self.flow_id.is_none()
351 && self.flow_version.is_none()
352 && self.flow_code_hash.is_none()
353 && self.flow_install_id.is_none()
354 && self.run_id.is_none()
355 }
356}
357
358pub fn validate_flow_id(flow_id: &str) -> Result<(), crate::tool_call::OpaqueFieldError> {
362 crate::tool_call::validate_opaque_field("flow_id", flow_id)
363}
364
365pub fn validate_flow_version(flow_version: u64) -> Result<(), &'static str> {
368 if !(1..=9_007_199_254_740_991).contains(&flow_version) {
369 return Err("flow_version must be from 1 to 9007199254740991");
370 }
371 Ok(())
372}
373
374pub fn validate_flow_code_hash(flow_code_hash: &str) -> Result<(), &'static str> {
376 if flow_code_hash.len() != 64
377 || !flow_code_hash
378 .bytes()
379 .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
380 {
381 return Err("flow_code_hash must contain exactly 64 lowercase hex characters");
382 }
383 Ok(())
384}
385
386pub fn validate_flow_install_id(
389 flow_install_id: &str,
390) -> Result<(), crate::tool_call::OpaqueFieldError> {
391 crate::tool_call::validate_opaque_field("flow_install_id", flow_install_id)
392}
393
394pub fn validate_run_id(run_id: &str) -> Result<(), crate::tool_call::OpaqueFieldError> {
397 crate::tool_call::validate_opaque_field("run_id", run_id)
398}
399
400pub fn validate_on_behalf_of_agent(agent: &str) -> Result<(), crate::tool_call::OpaqueFieldError> {
403 crate::tool_call::validate_opaque_field("on_behalf_of_agent", agent)
404}
405
406pub const SCOPE_WORKDIR_CAPABILITY: &str = "scope-workdir/v1";
408
409pub fn validate_project_id(value: &str) -> Result<(), &'static str> {
411 if value.is_empty() || value.len() > 128 {
412 return Err("project_id must contain 1 to 128 bytes");
413 }
414 if !value.bytes().all(|byte| (0x21..=0x7e).contains(&byte)) {
415 return Err("project_id must be printable ASCII without whitespace");
416 }
417 Ok(())
418}
419
420#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
422#[serde(deny_unknown_fields)]
423#[non_exhaustive]
424pub struct ScopeRecord {
425 #[serde(rename = "ref")]
426 pub scope_ref: String,
427 pub scope_epoch: u64,
431 pub kind: ScopeKind,
432 #[serde(default, skip_serializing_if = "Option::is_none")]
435 pub workdir: Option<String>,
436 #[serde(default, skip_serializing_if = "Option::is_none")]
438 pub project_id: Option<String>,
439 #[serde(
442 default,
443 skip_serializing_if = "Option::is_none",
444 deserialize_with = "deserialize_bind_proof_sha256"
445 )]
446 pub bind_proof_sha256: Option<String>,
447 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
452 pub replace_only_if_idle: bool,
453 #[serde(default, skip_serializing_if = "Option::is_none")]
457 pub expires_at_ms: Option<u64>,
458 #[serde(default, skip_serializing_if = "Option::is_none")]
459 pub parent: Option<ScopeParent>,
460 #[serde(
463 default,
464 skip_serializing_if = "Vec::is_empty",
465 deserialize_with = "deserialize_scope_principals"
466 )]
467 pub child_owners: Vec<Principal>,
468 #[serde(default, skip_serializing_if = "Vec::is_empty")]
469 pub carriers: Vec<ScopeCarrier>,
470 #[serde(default, skip_serializing_if = "ScopeAttributes::is_empty")]
471 pub attributes: ScopeAttributes,
472}
473
474impl ScopeRecord {
475 pub fn new(scope_ref: impl Into<String>, scope_epoch: u64, kind: ScopeKind) -> Self {
476 Self {
477 scope_ref: scope_ref.into(),
478 scope_epoch,
479 kind,
480 workdir: None,
481 project_id: None,
482 bind_proof_sha256: None,
483 replace_only_if_idle: false,
484 expires_at_ms: None,
485 parent: None,
486 child_owners: Vec::new(),
487 carriers: Vec::new(),
488 attributes: ScopeAttributes::default(),
489 }
490 }
491
492 #[must_use]
493 pub fn with_workdir(mut self, workdir: Option<String>) -> Self {
494 self.workdir = workdir;
495 self
496 }
497
498 #[must_use]
499 pub fn with_project_id(mut self, project_id: Option<String>) -> Self {
500 self.project_id = project_id;
501 self
502 }
503
504 #[must_use]
505 pub fn with_bind_proof_sha256(mut self, hash: Option<String>) -> Self {
506 self.bind_proof_sha256 = hash;
507 self
508 }
509
510 #[must_use]
511 pub fn with_replace_only_if_idle(mut self, replace_only_if_idle: bool) -> Self {
512 self.replace_only_if_idle = replace_only_if_idle;
513 self
514 }
515
516 #[must_use]
517 pub fn with_expires_at_ms(mut self, expires_at_ms: Option<u64>) -> Self {
518 self.expires_at_ms = expires_at_ms;
519 self
520 }
521
522 #[must_use]
523 pub fn with_parent(mut self, parent: Option<ScopeParent>) -> Self {
524 self.parent = parent;
525 self
526 }
527
528 #[must_use]
529 pub fn with_child_owners(mut self, child_owners: Vec<Principal>) -> Self {
530 self.child_owners = child_owners;
531 self
532 }
533
534 #[must_use]
535 pub fn with_carriers(mut self, carriers: Vec<ScopeCarrier>) -> Self {
536 self.carriers = carriers;
537 self
538 }
539
540 #[must_use]
541 pub fn with_attributes(mut self, attributes: ScopeAttributes) -> Self {
542 self.attributes = attributes;
543 self
544 }
545}
546
547#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
549#[serde(deny_unknown_fields)]
550#[non_exhaustive]
551pub struct ScopeEnd {
552 #[serde(rename = "ref")]
553 pub scope_ref: String,
554 pub scope_epoch: u64,
555}
556
557impl ScopeEnd {
558 pub fn new(scope_ref: impl Into<String>, scope_epoch: u64) -> Self {
559 Self {
560 scope_ref: scope_ref.into(),
561 scope_epoch,
562 }
563 }
564}
565
566#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
568#[serde(rename_all = "snake_case")]
569pub enum ScopeEndOutcome {
570 Ended,
572 NotLive,
575}
576
577#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
579#[serde(deny_unknown_fields)]
580#[non_exhaustive]
581pub struct ScopeEndResult {
582 #[serde(rename = "ref")]
583 pub scope_ref: String,
584 pub scope_epoch: u64,
585 pub outcome: ScopeEndOutcome,
586}
587
588impl ScopeEndResult {
589 pub fn new(scope_ref: impl Into<String>, scope_epoch: u64, outcome: ScopeEndOutcome) -> Self {
590 Self {
591 scope_ref: scope_ref.into(),
592 scope_epoch,
593 outcome,
594 }
595 }
596}
597
598#[derive(Clone, Serialize, Deserialize, PartialEq, Eq)]
604#[serde(deny_unknown_fields)]
605#[non_exhaustive]
606pub struct ScopeSelector {
607 #[serde(deserialize_with = "deserialize_scope_principal")]
608 pub owner: Principal,
609 #[serde(rename = "ref")]
610 pub scope_ref: String,
611 #[serde(default, skip_serializing_if = "Option::is_none")]
612 pub scope_epoch: Option<u64>,
613 #[serde(default, skip_serializing_if = "Option::is_none")]
616 pub bind_proof: Option<String>,
617 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
620 pub hold_presence: bool,
621}
622
623impl ScopeSelector {
624 pub fn new(owner: Principal, scope_ref: impl Into<String>, scope_epoch: Option<u64>) -> Self {
625 Self {
626 owner,
627 scope_ref: scope_ref.into(),
628 scope_epoch,
629 bind_proof: None,
630 hold_presence: false,
631 }
632 }
633
634 #[must_use]
635 pub fn with_bind_proof(mut self, proof: Option<String>) -> Self {
636 self.bind_proof = proof;
637 self
638 }
639
640 #[must_use]
641 pub fn with_hold_presence(mut self, hold_presence: bool) -> Self {
642 self.hold_presence = hold_presence;
643 self
644 }
645}
646
647impl std::fmt::Debug for ScopeSelector {
648 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
649 f.debug_struct("ScopeSelector")
650 .field("owner", &self.owner)
651 .field("scope_ref", &self.scope_ref)
652 .field("scope_epoch", &self.scope_epoch)
653 .field(
654 "bind_proof",
655 &self.bind_proof.as_ref().map(|_| "<redacted>"),
656 )
657 .finish()
658 }
659}
660
661impl std::fmt::Display for ScopeSelector {
662 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
663 std::fmt::Debug::fmt(self, f)
664 }
665}
666
667#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
669#[serde(rename_all = "snake_case")]
670pub enum ParentState {
671 Linked,
673 Pending,
676 Ended,
679}
680
681#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
683#[serde(rename_all = "snake_case")]
684pub enum ScopeRecordOutcome {
685 Created,
687 Replaced,
689 Updated,
691 Unchanged,
694 Refused,
697}
698
699#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
701pub struct ScopeRecordResult {
702 #[serde(rename = "ref")]
703 pub scope_ref: String,
704 pub scope_epoch: u64,
707 pub outcome: ScopeRecordOutcome,
708 #[serde(default, skip_serializing_if = "Option::is_none")]
710 pub code: Option<String>,
711 #[serde(default, skip_serializing_if = "Option::is_none")]
712 pub message: Option<String>,
713 #[serde(default, skip_serializing_if = "Option::is_none")]
716 pub version: Option<u64>,
717 #[serde(default, skip_serializing_if = "Option::is_none")]
719 pub parent_state: Option<ParentState>,
720}
721
722#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
726pub struct ScopeEnded {
727 #[serde(rename = "ref")]
728 pub scope_ref: String,
729 pub scope_epoch: u64,
730}
731
732#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
734#[serde(rename_all = "snake_case")]
735pub enum ScopeStatus {
736 Live,
737 Ended,
739 NotLive,
745}
746
747#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
750#[non_exhaustive]
751pub struct ScopeStamp {
752 pub owner: Principal,
753 #[serde(rename = "ref")]
754 pub scope_ref: String,
755 pub scope_epoch: u64,
756 pub kind: ScopeKind,
757 #[serde(default, skip_serializing_if = "Option::is_none")]
760 pub workdir: Option<String>,
761 #[serde(default, skip_serializing_if = "Option::is_none")]
763 pub project_id: Option<String>,
764 #[serde(default, skip_serializing_if = "Option::is_none")]
765 pub parent: Option<ScopeParent>,
766 #[serde(default, skip_serializing_if = "Option::is_none")]
767 pub parent_state: Option<ParentState>,
768 #[serde(default, skip_serializing_if = "ScopeAttributes::is_empty")]
769 pub attributes: ScopeAttributes,
770 pub owner_authorized: bool,
773 #[serde(default, skip_serializing_if = "Option::is_none")]
778 pub expires_at_ms: Option<u64>,
779}
780
781impl ScopeStamp {
782 pub fn new(
784 owner: Principal,
785 scope_ref: impl Into<String>,
786 scope_epoch: u64,
787 kind: ScopeKind,
788 ) -> Self {
789 Self {
790 owner,
791 scope_ref: scope_ref.into(),
792 scope_epoch,
793 kind,
794 workdir: None,
795 project_id: None,
796 parent: None,
797 parent_state: None,
798 attributes: ScopeAttributes::new(),
799 owner_authorized: false,
800 expires_at_ms: None,
801 }
802 }
803
804 #[must_use]
805 pub fn with_workdir(mut self, workdir: Option<String>) -> Self {
806 self.workdir = workdir;
807 self
808 }
809
810 #[must_use]
811 pub fn with_project_id(mut self, project_id: Option<String>) -> Self {
812 self.project_id = project_id;
813 self
814 }
815
816 #[must_use]
817 pub fn with_parent(mut self, parent: Option<ScopeParent>) -> Self {
818 self.parent = parent;
819 self
820 }
821
822 #[must_use]
823 pub fn with_parent_state(mut self, parent_state: Option<ParentState>) -> Self {
824 self.parent_state = parent_state;
825 self
826 }
827
828 #[must_use]
829 pub fn with_attributes(mut self, attributes: ScopeAttributes) -> Self {
830 self.attributes = attributes;
831 self
832 }
833
834 #[must_use]
835 pub fn with_owner_authorized(mut self, owner_authorized: bool) -> Self {
836 self.owner_authorized = owner_authorized;
837 self
838 }
839
840 #[must_use]
841 pub fn with_expires_at_ms(mut self, expires_at_ms: Option<u64>) -> Self {
842 self.expires_at_ms = expires_at_ms;
843 self
844 }
845}
846
847#[cfg(test)]
848mod tests {
849 use super::*;
850 use crate::tool_call::OpaqueFieldError;
851
852 #[test]
853 fn project_id_is_an_opaque_non_space_ascii_token_of_at_most_128_bytes() {
854 for valid in ["p", "!~Project:7/path", &"p".repeat(128)] {
855 assert_eq!(validate_project_id(valid), Ok(()));
856 }
857 for invalid in ["", "p p", "p\t", "pé", "p\u{7f}", &"p".repeat(129)] {
858 assert!(validate_project_id(invalid).is_err(), "{invalid:?}");
859 }
860 }
861
862 #[test]
863 fn scope_project_fields_round_trip_and_absence_keeps_exact_bytes() {
864 let record = ScopeRecord::new("session", 1, ScopeKind::Head);
865 assert_eq!(
866 serde_json::to_string(&record).unwrap(),
867 r#"{"ref":"session","scope_epoch":1,"kind":"head"}"#
868 );
869 let record = record
870 .with_workdir(Some("/folder".into()))
871 .with_project_id(Some("project:1".into()));
872 let encoded = serde_json::to_string(&record).unwrap();
873 assert_eq!(
874 serde_json::from_str::<ScopeRecord>(&encoded).unwrap(),
875 record
876 );
877 let stamp = ScopeStamp::new(Principal::Direct, "session", 1, ScopeKind::Head);
878 assert_eq!(
879 serde_json::to_string(&stamp).unwrap(),
880 r#"{"owner":{"kind":"direct"},"ref":"session","scope_epoch":1,"kind":"head","owner_authorized":false}"#
881 );
882 let stamp = stamp
883 .with_workdir(record.workdir)
884 .with_project_id(record.project_id);
885 let encoded = serde_json::to_string(&stamp).unwrap();
886 assert_eq!(serde_json::from_str::<ScopeStamp>(&encoded).unwrap(), stamp);
887 }
888
889 #[test]
890 fn flow_id_uses_the_shared_opaque_token_bounds_and_names_its_field() {
891 let field = "flow_id";
892 assert_eq!(validate_flow_id(""), Err(OpaqueFieldError::Empty { field }));
893 assert_eq!(validate_flow_id("f"), Ok(()));
894 assert_eq!(validate_flow_id(&"f".repeat(256)), Ok(()));
895 assert_eq!(
896 validate_flow_id(&"f".repeat(257)),
897 Err(OpaqueFieldError::TooLong { field, length: 257 })
898 );
899 assert_eq!(validate_flow_id("!~Flow:7/step"), Ok(()));
900 for bad in ["f é", "f\t", "fé", "f\u{7f}"] {
901 let error = validate_flow_id(bad).unwrap_err();
902 assert_eq!(
903 error,
904 OpaqueFieldError::InvalidCharacter { field, index: 1 }
905 );
906 assert_eq!(error.field(), "flow_id");
907 }
908 }
909
910 #[test]
911 fn flow_identity_validators_enforce_boundaries_and_name_fields() {
912 for valid in [1, 9_007_199_254_740_991] {
913 assert_eq!(validate_flow_version(valid), Ok(()));
914 }
915 for invalid in [0, 9_007_199_254_740_992, u64::MAX] {
916 assert!(validate_flow_version(invalid)
917 .unwrap_err()
918 .contains("flow_version"));
919 }
920 assert_eq!(
921 validate_flow_code_hash(&"0123456789abcdef".repeat(4)),
922 Ok(())
923 );
924 for invalid in [
925 "a".repeat(63),
926 "a".repeat(65),
927 "A".repeat(64),
928 "g".repeat(64),
929 ] {
930 assert!(validate_flow_code_hash(&invalid)
931 .unwrap_err()
932 .contains("flow_code_hash"));
933 }
934 for valid in ["i", "!~Install:7/path", &"i".repeat(256)] {
935 assert_eq!(validate_flow_install_id(valid), Ok(()));
936 }
937 for invalid in ["", "i i", "i\t", "ié", "i\u{7f}", &"i".repeat(257)] {
938 assert_eq!(
939 validate_flow_install_id(invalid).unwrap_err().field(),
940 "flow_install_id"
941 );
942 }
943 }
944
945 #[test]
946 fn flow_identity_round_trips_and_legacy_stamp_keeps_exact_bytes() {
947 let attributes = ScopeAttributes::new().with_flow_id(Some("flow:7".into()));
948 let stamp = ScopeStamp::new(Principal::Direct, "session", 1, ScopeKind::Head)
949 .with_attributes(attributes.clone());
950 assert_eq!(
951 serde_json::to_string(&stamp).unwrap(),
952 r#"{"owner":{"kind":"direct"},"ref":"session","scope_epoch":1,"kind":"head","attributes":{"flow_id":"flow:7"},"owner_authorized":false}"#
953 );
954 let attributes = attributes
955 .with_flow_version(Some(9_007_199_254_740_991))
956 .with_flow_code_hash(Some("a".repeat(64)))
957 .with_flow_install_id(Some("install:7".into()));
958 let stamp = stamp.with_attributes(attributes.clone());
959 let encoded = serde_json::to_string(&stamp).unwrap();
960 assert_eq!(serde_json::from_str::<ScopeStamp>(&encoded).unwrap(), stamp);
961 assert_eq!(
962 serde_json::from_str::<ScopeAttributes>(&serde_json::to_string(&attributes).unwrap())
963 .unwrap(),
964 attributes
965 );
966 assert!(
967 serde_json::from_str::<ScopeAttributes>(r#"{"flow_version":1,"unknown":true}"#)
968 .is_err()
969 );
970 assert!(!ScopeAttributes::new().with_flow_version(Some(1)).is_empty());
971 assert!(!ScopeAttributes::new()
972 .with_flow_code_hash(Some("a".repeat(64)))
973 .is_empty());
974 assert!(!ScopeAttributes::new()
975 .with_flow_install_id(Some("i".into()))
976 .is_empty());
977 }
978
979 #[test]
980 fn flow_only_attributes_round_trip_and_absence_keeps_the_bytes() {
981 let attributes = ScopeAttributes::default();
982 assert!(attributes.is_empty());
983 assert_eq!(serde_json::to_string(&attributes).unwrap(), "{}");
984 assert_eq!(
985 serde_json::from_str::<ScopeAttributes>("{}").unwrap(),
986 attributes
987 );
988 let attributes = ScopeAttributes {
989 flow_id: Some("flow:7".to_string()),
990 ..ScopeAttributes::default()
991 };
992 assert!(!attributes.is_empty());
993 let encoded = serde_json::to_string(&attributes).unwrap();
994 assert_eq!(encoded, r#"{"flow_id":"flow:7"}"#);
995 assert_eq!(
996 serde_json::from_str::<ScopeAttributes>(&encoded).unwrap(),
997 attributes
998 );
999 assert!(
1000 serde_json::from_str::<ScopeAttributes>(r#"{"flow_id":"flow:7","unknown":true}"#)
1001 .is_err()
1002 );
1003 }
1004}