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 SCOPE_SERVED_BY_CAPABILITY: &str = "scope-served-by/v1";
197
198#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
204#[serde(deny_unknown_fields)]
205#[non_exhaustive]
206pub struct ScopeAttributes {
207 #[serde(default, skip_serializing_if = "Option::is_none")]
209 pub agent_id: Option<String>,
210 #[serde(default, skip_serializing_if = "Option::is_none")]
224 pub on_behalf_of_agent: Option<String>,
225 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
227 pub delegates: bool,
228 #[serde(default, skip_serializing_if = "Option::is_none")]
244 pub flow_id: Option<String>,
245 #[serde(default, skip_serializing_if = "Option::is_none")]
250 pub flow_version: Option<u64>,
251 #[serde(default, skip_serializing_if = "Option::is_none")]
255 pub flow_code_hash: Option<String>,
256 #[serde(default, skip_serializing_if = "Option::is_none")]
260 pub flow_install_id: Option<String>,
261 #[serde(default, skip_serializing_if = "Option::is_none")]
271 pub run_id: Option<String>,
272}
273
274impl ScopeAttributes {
275 pub fn new() -> Self {
276 Self::default()
277 }
278
279 #[must_use]
280 pub fn with_agent_id(mut self, agent_id: Option<String>) -> Self {
281 self.agent_id = agent_id;
282 self
283 }
284
285 #[must_use]
286 pub fn with_on_behalf_of_agent(mut self, on_behalf_of_agent: Option<String>) -> Self {
287 self.on_behalf_of_agent = on_behalf_of_agent;
288 self
289 }
290
291 #[must_use]
292 pub fn with_delegates(mut self, delegates: bool) -> Self {
293 self.delegates = delegates;
294 self
295 }
296
297 #[must_use]
298 pub fn with_flow_id(mut self, flow_id: Option<String>) -> Self {
299 self.flow_id = flow_id;
300 self
301 }
302
303 #[must_use]
304 pub fn with_flow_version(mut self, flow_version: Option<u64>) -> Self {
305 self.flow_version = flow_version;
306 self
307 }
308
309 #[must_use]
310 pub fn with_flow_code_hash(mut self, flow_code_hash: Option<String>) -> Self {
311 self.flow_code_hash = flow_code_hash;
312 self
313 }
314
315 #[must_use]
316 pub fn with_flow_install_id(mut self, flow_install_id: Option<String>) -> Self {
317 self.flow_install_id = flow_install_id;
318 self
319 }
320
321 #[must_use]
322 pub fn with_run_id(mut self, run_id: Option<String>) -> Self {
323 self.run_id = run_id;
324 self
325 }
326
327 pub fn is_empty(&self) -> bool {
328 self.agent_id.is_none()
329 && self.on_behalf_of_agent.is_none()
330 && !self.delegates
331 && self.flow_id.is_none()
332 && self.flow_version.is_none()
333 && self.flow_code_hash.is_none()
334 && self.flow_install_id.is_none()
335 && self.run_id.is_none()
336 }
337}
338
339pub fn validate_flow_id(flow_id: &str) -> Result<(), crate::tool_call::OpaqueFieldError> {
343 crate::tool_call::validate_opaque_field("flow_id", flow_id)
344}
345
346pub fn validate_flow_version(flow_version: u64) -> Result<(), &'static str> {
349 if !(1..=9_007_199_254_740_991).contains(&flow_version) {
350 return Err("flow_version must be from 1 to 9007199254740991");
351 }
352 Ok(())
353}
354
355pub fn validate_flow_code_hash(flow_code_hash: &str) -> Result<(), &'static str> {
357 if flow_code_hash.len() != 64
358 || !flow_code_hash
359 .bytes()
360 .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
361 {
362 return Err("flow_code_hash must contain exactly 64 lowercase hex characters");
363 }
364 Ok(())
365}
366
367pub fn validate_flow_install_id(
370 flow_install_id: &str,
371) -> Result<(), crate::tool_call::OpaqueFieldError> {
372 crate::tool_call::validate_opaque_field("flow_install_id", flow_install_id)
373}
374
375pub fn validate_run_id(run_id: &str) -> Result<(), crate::tool_call::OpaqueFieldError> {
378 crate::tool_call::validate_opaque_field("run_id", run_id)
379}
380
381pub fn validate_on_behalf_of_agent(agent: &str) -> Result<(), crate::tool_call::OpaqueFieldError> {
384 crate::tool_call::validate_opaque_field("on_behalf_of_agent", agent)
385}
386
387pub const SCOPE_WORKDIR_CAPABILITY: &str = "scope-workdir/v1";
389
390pub fn validate_project_id(value: &str) -> Result<(), &'static str> {
392 if value.is_empty() || value.len() > 128 {
393 return Err("project_id must contain 1 to 128 bytes");
394 }
395 if !value.bytes().all(|byte| (0x21..=0x7e).contains(&byte)) {
396 return Err("project_id must be printable ASCII without whitespace");
397 }
398 Ok(())
399}
400
401#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
403#[serde(deny_unknown_fields)]
404#[non_exhaustive]
405pub struct ScopeRecord {
406 #[serde(rename = "ref")]
407 pub scope_ref: String,
408 pub scope_epoch: u64,
412 pub kind: ScopeKind,
413 #[serde(default, skip_serializing_if = "Option::is_none")]
416 pub workdir: Option<String>,
417 #[serde(default, skip_serializing_if = "Option::is_none")]
419 pub project_id: Option<String>,
420 #[serde(
423 default,
424 skip_serializing_if = "Option::is_none",
425 deserialize_with = "deserialize_bind_proof_sha256"
426 )]
427 pub bind_proof_sha256: Option<String>,
428 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
433 pub replace_only_if_idle: bool,
434 #[serde(default, skip_serializing_if = "Option::is_none")]
438 pub expires_at_ms: Option<u64>,
439 #[serde(default, skip_serializing_if = "Option::is_none")]
440 pub parent: Option<ScopeParent>,
441 #[serde(
444 default,
445 skip_serializing_if = "Vec::is_empty",
446 deserialize_with = "deserialize_scope_principals"
447 )]
448 pub child_owners: Vec<Principal>,
449 #[serde(default, skip_serializing_if = "Vec::is_empty")]
450 pub carriers: Vec<ScopeCarrier>,
451 #[serde(default, skip_serializing_if = "ScopeAttributes::is_empty")]
452 pub attributes: ScopeAttributes,
453}
454
455impl ScopeRecord {
456 pub fn new(scope_ref: impl Into<String>, scope_epoch: u64, kind: ScopeKind) -> Self {
457 Self {
458 scope_ref: scope_ref.into(),
459 scope_epoch,
460 kind,
461 workdir: None,
462 project_id: None,
463 bind_proof_sha256: None,
464 replace_only_if_idle: false,
465 expires_at_ms: None,
466 parent: None,
467 child_owners: Vec::new(),
468 carriers: Vec::new(),
469 attributes: ScopeAttributes::default(),
470 }
471 }
472
473 #[must_use]
474 pub fn with_workdir(mut self, workdir: Option<String>) -> Self {
475 self.workdir = workdir;
476 self
477 }
478
479 #[must_use]
480 pub fn with_project_id(mut self, project_id: Option<String>) -> Self {
481 self.project_id = project_id;
482 self
483 }
484
485 #[must_use]
486 pub fn with_bind_proof_sha256(mut self, hash: Option<String>) -> Self {
487 self.bind_proof_sha256 = hash;
488 self
489 }
490
491 #[must_use]
492 pub fn with_replace_only_if_idle(mut self, replace_only_if_idle: bool) -> Self {
493 self.replace_only_if_idle = replace_only_if_idle;
494 self
495 }
496
497 #[must_use]
498 pub fn with_expires_at_ms(mut self, expires_at_ms: Option<u64>) -> Self {
499 self.expires_at_ms = expires_at_ms;
500 self
501 }
502
503 #[must_use]
504 pub fn with_parent(mut self, parent: Option<ScopeParent>) -> Self {
505 self.parent = parent;
506 self
507 }
508
509 #[must_use]
510 pub fn with_child_owners(mut self, child_owners: Vec<Principal>) -> Self {
511 self.child_owners = child_owners;
512 self
513 }
514
515 #[must_use]
516 pub fn with_carriers(mut self, carriers: Vec<ScopeCarrier>) -> Self {
517 self.carriers = carriers;
518 self
519 }
520
521 #[must_use]
522 pub fn with_attributes(mut self, attributes: ScopeAttributes) -> Self {
523 self.attributes = attributes;
524 self
525 }
526}
527
528#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
530#[serde(deny_unknown_fields)]
531#[non_exhaustive]
532pub struct ScopeEnd {
533 #[serde(rename = "ref")]
534 pub scope_ref: String,
535 pub scope_epoch: u64,
536}
537
538impl ScopeEnd {
539 pub fn new(scope_ref: impl Into<String>, scope_epoch: u64) -> Self {
540 Self {
541 scope_ref: scope_ref.into(),
542 scope_epoch,
543 }
544 }
545}
546
547#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
549#[serde(rename_all = "snake_case")]
550pub enum ScopeEndOutcome {
551 Ended,
553 NotLive,
556}
557
558#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
560#[serde(deny_unknown_fields)]
561#[non_exhaustive]
562pub struct ScopeEndResult {
563 #[serde(rename = "ref")]
564 pub scope_ref: String,
565 pub scope_epoch: u64,
566 pub outcome: ScopeEndOutcome,
567}
568
569impl ScopeEndResult {
570 pub fn new(scope_ref: impl Into<String>, scope_epoch: u64, outcome: ScopeEndOutcome) -> Self {
571 Self {
572 scope_ref: scope_ref.into(),
573 scope_epoch,
574 outcome,
575 }
576 }
577}
578
579#[derive(Clone, Serialize, Deserialize, PartialEq, Eq)]
585#[serde(deny_unknown_fields)]
586#[non_exhaustive]
587pub struct ScopeSelector {
588 #[serde(deserialize_with = "deserialize_scope_principal")]
589 pub owner: Principal,
590 #[serde(rename = "ref")]
591 pub scope_ref: String,
592 #[serde(default, skip_serializing_if = "Option::is_none")]
593 pub scope_epoch: Option<u64>,
594 #[serde(default, skip_serializing_if = "Option::is_none")]
597 pub bind_proof: Option<String>,
598 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
601 pub hold_presence: bool,
602}
603
604impl ScopeSelector {
605 pub fn new(owner: Principal, scope_ref: impl Into<String>, scope_epoch: Option<u64>) -> Self {
606 Self {
607 owner,
608 scope_ref: scope_ref.into(),
609 scope_epoch,
610 bind_proof: None,
611 hold_presence: false,
612 }
613 }
614
615 #[must_use]
616 pub fn with_bind_proof(mut self, proof: Option<String>) -> Self {
617 self.bind_proof = proof;
618 self
619 }
620
621 #[must_use]
622 pub fn with_hold_presence(mut self, hold_presence: bool) -> Self {
623 self.hold_presence = hold_presence;
624 self
625 }
626}
627
628impl std::fmt::Debug for ScopeSelector {
629 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
630 f.debug_struct("ScopeSelector")
631 .field("owner", &self.owner)
632 .field("scope_ref", &self.scope_ref)
633 .field("scope_epoch", &self.scope_epoch)
634 .field(
635 "bind_proof",
636 &self.bind_proof.as_ref().map(|_| "<redacted>"),
637 )
638 .finish()
639 }
640}
641
642impl std::fmt::Display for ScopeSelector {
643 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
644 std::fmt::Debug::fmt(self, f)
645 }
646}
647
648#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
650#[serde(rename_all = "snake_case")]
651pub enum ParentState {
652 Linked,
654 Pending,
657 Ended,
660}
661
662#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
664#[serde(rename_all = "snake_case")]
665pub enum ScopeRecordOutcome {
666 Created,
668 Replaced,
670 Updated,
672 Unchanged,
675 Refused,
678}
679
680#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
682pub struct ScopeRecordResult {
683 #[serde(rename = "ref")]
684 pub scope_ref: String,
685 pub scope_epoch: u64,
688 pub outcome: ScopeRecordOutcome,
689 #[serde(default, skip_serializing_if = "Option::is_none")]
691 pub code: Option<String>,
692 #[serde(default, skip_serializing_if = "Option::is_none")]
693 pub message: Option<String>,
694 #[serde(default, skip_serializing_if = "Option::is_none")]
697 pub version: Option<u64>,
698 #[serde(default, skip_serializing_if = "Option::is_none")]
700 pub parent_state: Option<ParentState>,
701}
702
703#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
707pub struct ScopeEnded {
708 #[serde(rename = "ref")]
709 pub scope_ref: String,
710 pub scope_epoch: u64,
711}
712
713#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
715#[serde(rename_all = "snake_case")]
716pub enum ScopeStatus {
717 Live,
718 Ended,
720 NotLive,
726}
727
728#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
731#[non_exhaustive]
732pub struct ScopeStamp {
733 pub owner: Principal,
734 #[serde(rename = "ref")]
735 pub scope_ref: String,
736 pub scope_epoch: u64,
737 pub kind: ScopeKind,
738 #[serde(default, skip_serializing_if = "Option::is_none")]
741 pub workdir: Option<String>,
742 #[serde(default, skip_serializing_if = "Option::is_none")]
744 pub project_id: Option<String>,
745 #[serde(default, skip_serializing_if = "Option::is_none")]
746 pub parent: Option<ScopeParent>,
747 #[serde(default, skip_serializing_if = "Option::is_none")]
748 pub parent_state: Option<ParentState>,
749 #[serde(default, skip_serializing_if = "ScopeAttributes::is_empty")]
750 pub attributes: ScopeAttributes,
751 pub owner_authorized: bool,
754 #[serde(default, skip_serializing_if = "Option::is_none")]
759 pub expires_at_ms: Option<u64>,
760}
761
762impl ScopeStamp {
763 pub fn new(
765 owner: Principal,
766 scope_ref: impl Into<String>,
767 scope_epoch: u64,
768 kind: ScopeKind,
769 ) -> Self {
770 Self {
771 owner,
772 scope_ref: scope_ref.into(),
773 scope_epoch,
774 kind,
775 workdir: None,
776 project_id: None,
777 parent: None,
778 parent_state: None,
779 attributes: ScopeAttributes::new(),
780 owner_authorized: false,
781 expires_at_ms: None,
782 }
783 }
784
785 #[must_use]
786 pub fn with_workdir(mut self, workdir: Option<String>) -> Self {
787 self.workdir = workdir;
788 self
789 }
790
791 #[must_use]
792 pub fn with_project_id(mut self, project_id: Option<String>) -> Self {
793 self.project_id = project_id;
794 self
795 }
796
797 #[must_use]
798 pub fn with_parent(mut self, parent: Option<ScopeParent>) -> Self {
799 self.parent = parent;
800 self
801 }
802
803 #[must_use]
804 pub fn with_parent_state(mut self, parent_state: Option<ParentState>) -> Self {
805 self.parent_state = parent_state;
806 self
807 }
808
809 #[must_use]
810 pub fn with_attributes(mut self, attributes: ScopeAttributes) -> Self {
811 self.attributes = attributes;
812 self
813 }
814
815 #[must_use]
816 pub fn with_owner_authorized(mut self, owner_authorized: bool) -> Self {
817 self.owner_authorized = owner_authorized;
818 self
819 }
820
821 #[must_use]
822 pub fn with_expires_at_ms(mut self, expires_at_ms: Option<u64>) -> Self {
823 self.expires_at_ms = expires_at_ms;
824 self
825 }
826}
827
828#[cfg(test)]
829mod tests {
830 use super::*;
831 use crate::tool_call::OpaqueFieldError;
832
833 #[test]
834 fn project_id_is_an_opaque_non_space_ascii_token_of_at_most_128_bytes() {
835 for valid in ["p", "!~Project:7/path", &"p".repeat(128)] {
836 assert_eq!(validate_project_id(valid), Ok(()));
837 }
838 for invalid in ["", "p p", "p\t", "pé", "p\u{7f}", &"p".repeat(129)] {
839 assert!(validate_project_id(invalid).is_err(), "{invalid:?}");
840 }
841 }
842
843 #[test]
844 fn scope_project_fields_round_trip_and_absence_keeps_exact_bytes() {
845 let record = ScopeRecord::new("session", 1, ScopeKind::Head);
846 assert_eq!(
847 serde_json::to_string(&record).unwrap(),
848 r#"{"ref":"session","scope_epoch":1,"kind":"head"}"#
849 );
850 let record = record
851 .with_workdir(Some("/folder".into()))
852 .with_project_id(Some("project:1".into()));
853 let encoded = serde_json::to_string(&record).unwrap();
854 assert_eq!(
855 serde_json::from_str::<ScopeRecord>(&encoded).unwrap(),
856 record
857 );
858 let stamp = ScopeStamp::new(Principal::Direct, "session", 1, ScopeKind::Head);
859 assert_eq!(
860 serde_json::to_string(&stamp).unwrap(),
861 r#"{"owner":{"kind":"direct"},"ref":"session","scope_epoch":1,"kind":"head","owner_authorized":false}"#
862 );
863 let stamp = stamp
864 .with_workdir(record.workdir)
865 .with_project_id(record.project_id);
866 let encoded = serde_json::to_string(&stamp).unwrap();
867 assert_eq!(serde_json::from_str::<ScopeStamp>(&encoded).unwrap(), stamp);
868 }
869
870 #[test]
871 fn flow_id_uses_the_shared_opaque_token_bounds_and_names_its_field() {
872 let field = "flow_id";
873 assert_eq!(validate_flow_id(""), Err(OpaqueFieldError::Empty { field }));
874 assert_eq!(validate_flow_id("f"), Ok(()));
875 assert_eq!(validate_flow_id(&"f".repeat(256)), Ok(()));
876 assert_eq!(
877 validate_flow_id(&"f".repeat(257)),
878 Err(OpaqueFieldError::TooLong { field, length: 257 })
879 );
880 assert_eq!(validate_flow_id("!~Flow:7/step"), Ok(()));
881 for bad in ["f é", "f\t", "fé", "f\u{7f}"] {
882 let error = validate_flow_id(bad).unwrap_err();
883 assert_eq!(
884 error,
885 OpaqueFieldError::InvalidCharacter { field, index: 1 }
886 );
887 assert_eq!(error.field(), "flow_id");
888 }
889 }
890
891 #[test]
892 fn flow_identity_validators_enforce_boundaries_and_name_fields() {
893 for valid in [1, 9_007_199_254_740_991] {
894 assert_eq!(validate_flow_version(valid), Ok(()));
895 }
896 for invalid in [0, 9_007_199_254_740_992, u64::MAX] {
897 assert!(validate_flow_version(invalid)
898 .unwrap_err()
899 .contains("flow_version"));
900 }
901 assert_eq!(
902 validate_flow_code_hash(&"0123456789abcdef".repeat(4)),
903 Ok(())
904 );
905 for invalid in [
906 "a".repeat(63),
907 "a".repeat(65),
908 "A".repeat(64),
909 "g".repeat(64),
910 ] {
911 assert!(validate_flow_code_hash(&invalid)
912 .unwrap_err()
913 .contains("flow_code_hash"));
914 }
915 for valid in ["i", "!~Install:7/path", &"i".repeat(256)] {
916 assert_eq!(validate_flow_install_id(valid), Ok(()));
917 }
918 for invalid in ["", "i i", "i\t", "ié", "i\u{7f}", &"i".repeat(257)] {
919 assert_eq!(
920 validate_flow_install_id(invalid).unwrap_err().field(),
921 "flow_install_id"
922 );
923 }
924 }
925
926 #[test]
927 fn flow_identity_round_trips_and_legacy_stamp_keeps_exact_bytes() {
928 let attributes = ScopeAttributes::new().with_flow_id(Some("flow:7".into()));
929 let stamp = ScopeStamp::new(Principal::Direct, "session", 1, ScopeKind::Head)
930 .with_attributes(attributes.clone());
931 assert_eq!(
932 serde_json::to_string(&stamp).unwrap(),
933 r#"{"owner":{"kind":"direct"},"ref":"session","scope_epoch":1,"kind":"head","attributes":{"flow_id":"flow:7"},"owner_authorized":false}"#
934 );
935 let attributes = attributes
936 .with_flow_version(Some(9_007_199_254_740_991))
937 .with_flow_code_hash(Some("a".repeat(64)))
938 .with_flow_install_id(Some("install:7".into()));
939 let stamp = stamp.with_attributes(attributes.clone());
940 let encoded = serde_json::to_string(&stamp).unwrap();
941 assert_eq!(serde_json::from_str::<ScopeStamp>(&encoded).unwrap(), stamp);
942 assert_eq!(
943 serde_json::from_str::<ScopeAttributes>(&serde_json::to_string(&attributes).unwrap())
944 .unwrap(),
945 attributes
946 );
947 assert!(
948 serde_json::from_str::<ScopeAttributes>(r#"{"flow_version":1,"unknown":true}"#)
949 .is_err()
950 );
951 assert!(!ScopeAttributes::new().with_flow_version(Some(1)).is_empty());
952 assert!(!ScopeAttributes::new()
953 .with_flow_code_hash(Some("a".repeat(64)))
954 .is_empty());
955 assert!(!ScopeAttributes::new()
956 .with_flow_install_id(Some("i".into()))
957 .is_empty());
958 }
959
960 #[test]
961 fn flow_only_attributes_round_trip_and_absence_keeps_the_bytes() {
962 let attributes = ScopeAttributes::default();
963 assert!(attributes.is_empty());
964 assert_eq!(serde_json::to_string(&attributes).unwrap(), "{}");
965 assert_eq!(
966 serde_json::from_str::<ScopeAttributes>("{}").unwrap(),
967 attributes
968 );
969 let attributes = ScopeAttributes {
970 flow_id: Some("flow:7".to_string()),
971 ..ScopeAttributes::default()
972 };
973 assert!(!attributes.is_empty());
974 let encoded = serde_json::to_string(&attributes).unwrap();
975 assert_eq!(encoded, r#"{"flow_id":"flow:7"}"#);
976 assert_eq!(
977 serde_json::from_str::<ScopeAttributes>(&encoded).unwrap(),
978 attributes
979 );
980 assert!(
981 serde_json::from_str::<ScopeAttributes>(r#"{"flow_id":"flow:7","unknown":true}"#)
982 .is_err()
983 );
984 }
985}