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 BIND_NO_PROJECT_CAPABILITY: &str = "bind-no-project/v1";
91
92pub const SCOPE_SYNC_OP: &str = "scope.sync";
94pub const SCOPE_APPLY_OP: &str = "scope.apply";
97pub const SCOPE_DESCRIBE_OP: &str = "scope.describe";
99
100pub const MAX_LIVE_SCOPES_PER_OWNER: usize = 10_000;
102pub const MAX_SCOPE_ATTRIBUTE_BYTES: usize = 4 * 1024;
105pub const MAX_SCOPE_TOMBSTONES_PER_OWNER: usize = 1_000;
108pub const MAX_CARRIER_TARGETS: usize = 16;
110pub const MAX_SCOPE_EXPIRY_AHEAD_MS: u64 = 86_400_000;
113
114#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
117#[serde(rename_all = "snake_case")]
118pub enum ScopeKind {
119 Head,
120 Worker,
121 Ephemeral,
122}
123
124#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
127#[serde(deny_unknown_fields)]
128#[non_exhaustive]
129pub struct ScopeParent {
130 #[serde(deserialize_with = "deserialize_scope_principal")]
131 pub owner: Principal,
132 #[serde(rename = "ref")]
133 pub scope_ref: String,
134 pub scope_epoch: u64,
135}
136
137impl ScopeParent {
138 pub fn new(owner: Principal, scope_ref: impl Into<String>, scope_epoch: u64) -> Self {
139 Self {
140 owner,
141 scope_ref: scope_ref.into(),
142 scope_epoch,
143 }
144 }
145}
146
147#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
154#[serde(deny_unknown_fields)]
155#[non_exhaustive]
156pub struct ScopeCarrier {
157 #[serde(deserialize_with = "deserialize_scope_principal")]
158 pub principal: Principal,
159 #[serde(default, skip_serializing_if = "Option::is_none")]
160 pub targets: Option<Vec<String>>,
161}
162
163impl ScopeCarrier {
164 pub fn new(principal: Principal) -> Self {
165 Self {
166 principal,
167 targets: None,
168 }
169 }
170
171 #[must_use]
172 pub fn with_targets(mut self, targets: Option<Vec<String>>) -> Self {
173 self.targets = targets;
174 self
175 }
176}
177
178pub const FLOW_SCOPES_CAPABILITY: &str = "flow-scopes/v1";
184
185pub const FLOW_IDENTITY_SCOPES_CAPABILITY: &str = "flow-identity-scopes/v1";
188
189pub const AGENT_RUN_SCOPES_CAPABILITY: &str = "agent-run-scopes/v1";
195
196pub const SCOPE_ON_BEHALF_OF_CAPABILITY: &str = "scope-on-behalf-of/v1";
200
201pub const WORKER_RUNS_CAPABILITY: &str = "worker-runs/v1";
214
215pub const SCOPE_SERVED_BY_CAPABILITY: &str = "scope-served-by/v1";
217
218#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
224#[serde(deny_unknown_fields)]
225#[non_exhaustive]
226pub struct ScopeAttributes {
227 #[serde(default, skip_serializing_if = "Option::is_none")]
229 pub agent_id: Option<String>,
230 #[serde(default, skip_serializing_if = "Option::is_none")]
247 pub on_behalf_of_agent: Option<String>,
248 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
250 pub delegates: bool,
251 #[serde(default, skip_serializing_if = "Option::is_none")]
267 pub flow_id: Option<String>,
268 #[serde(default, skip_serializing_if = "Option::is_none")]
273 pub flow_version: Option<u64>,
274 #[serde(default, skip_serializing_if = "Option::is_none")]
278 pub flow_code_hash: Option<String>,
279 #[serde(default, skip_serializing_if = "Option::is_none")]
283 pub flow_install_id: Option<String>,
284 #[serde(default, skip_serializing_if = "Option::is_none")]
296 pub run_id: Option<String>,
297}
298
299impl ScopeAttributes {
300 pub fn new() -> Self {
301 Self::default()
302 }
303
304 #[must_use]
305 pub fn with_agent_id(mut self, agent_id: Option<String>) -> Self {
306 self.agent_id = agent_id;
307 self
308 }
309
310 #[must_use]
311 pub fn with_on_behalf_of_agent(mut self, on_behalf_of_agent: Option<String>) -> Self {
312 self.on_behalf_of_agent = on_behalf_of_agent;
313 self
314 }
315
316 #[must_use]
317 pub fn with_delegates(mut self, delegates: bool) -> Self {
318 self.delegates = delegates;
319 self
320 }
321
322 #[must_use]
323 pub fn with_flow_id(mut self, flow_id: Option<String>) -> Self {
324 self.flow_id = flow_id;
325 self
326 }
327
328 #[must_use]
329 pub fn with_flow_version(mut self, flow_version: Option<u64>) -> Self {
330 self.flow_version = flow_version;
331 self
332 }
333
334 #[must_use]
335 pub fn with_flow_code_hash(mut self, flow_code_hash: Option<String>) -> Self {
336 self.flow_code_hash = flow_code_hash;
337 self
338 }
339
340 #[must_use]
341 pub fn with_flow_install_id(mut self, flow_install_id: Option<String>) -> Self {
342 self.flow_install_id = flow_install_id;
343 self
344 }
345
346 #[must_use]
347 pub fn with_run_id(mut self, run_id: Option<String>) -> Self {
348 self.run_id = run_id;
349 self
350 }
351
352 pub fn is_empty(&self) -> bool {
353 self.agent_id.is_none()
354 && self.on_behalf_of_agent.is_none()
355 && !self.delegates
356 && self.flow_id.is_none()
357 && self.flow_version.is_none()
358 && self.flow_code_hash.is_none()
359 && self.flow_install_id.is_none()
360 && self.run_id.is_none()
361 }
362}
363
364pub fn validate_flow_id(flow_id: &str) -> Result<(), crate::tool_call::OpaqueFieldError> {
368 crate::tool_call::validate_opaque_field("flow_id", flow_id)
369}
370
371pub fn validate_flow_version(flow_version: u64) -> Result<(), &'static str> {
374 if !(1..=9_007_199_254_740_991).contains(&flow_version) {
375 return Err("flow_version must be from 1 to 9007199254740991");
376 }
377 Ok(())
378}
379
380pub fn validate_flow_code_hash(flow_code_hash: &str) -> Result<(), &'static str> {
382 if flow_code_hash.len() != 64
383 || !flow_code_hash
384 .bytes()
385 .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
386 {
387 return Err("flow_code_hash must contain exactly 64 lowercase hex characters");
388 }
389 Ok(())
390}
391
392pub fn validate_flow_install_id(
395 flow_install_id: &str,
396) -> Result<(), crate::tool_call::OpaqueFieldError> {
397 crate::tool_call::validate_opaque_field("flow_install_id", flow_install_id)
398}
399
400pub fn validate_run_id(run_id: &str) -> Result<(), crate::tool_call::OpaqueFieldError> {
403 crate::tool_call::validate_opaque_field("run_id", run_id)
404}
405
406pub fn validate_on_behalf_of_agent(agent: &str) -> Result<(), crate::tool_call::OpaqueFieldError> {
409 crate::tool_call::validate_opaque_field("on_behalf_of_agent", agent)
410}
411
412pub const SCOPE_WORKDIR_CAPABILITY: &str = "scope-workdir/v1";
414
415pub fn validate_project_id(value: &str) -> Result<(), &'static str> {
417 if value.is_empty() || value.len() > 128 {
418 return Err("project_id must contain 1 to 128 bytes");
419 }
420 if !value.bytes().all(|byte| (0x21..=0x7e).contains(&byte)) {
421 return Err("project_id must be printable ASCII without whitespace");
422 }
423 Ok(())
424}
425
426#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
428#[serde(deny_unknown_fields)]
429#[non_exhaustive]
430pub struct ScopeRecord {
431 #[serde(rename = "ref")]
432 pub scope_ref: String,
433 pub scope_epoch: u64,
437 pub kind: ScopeKind,
438 #[serde(default, skip_serializing_if = "Option::is_none")]
441 pub workdir: Option<String>,
442 #[serde(default, skip_serializing_if = "Option::is_none")]
444 pub project_id: Option<String>,
445 #[serde(
448 default,
449 skip_serializing_if = "Option::is_none",
450 deserialize_with = "deserialize_bind_proof_sha256"
451 )]
452 pub bind_proof_sha256: Option<String>,
453 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
458 pub replace_only_if_idle: bool,
459 #[serde(default, skip_serializing_if = "Option::is_none")]
463 pub expires_at_ms: Option<u64>,
464 #[serde(default, skip_serializing_if = "Option::is_none")]
465 pub parent: Option<ScopeParent>,
466 #[serde(
469 default,
470 skip_serializing_if = "Vec::is_empty",
471 deserialize_with = "deserialize_scope_principals"
472 )]
473 pub child_owners: Vec<Principal>,
474 #[serde(default, skip_serializing_if = "Vec::is_empty")]
475 pub carriers: Vec<ScopeCarrier>,
476 #[serde(default, skip_serializing_if = "ScopeAttributes::is_empty")]
477 pub attributes: ScopeAttributes,
478}
479
480impl ScopeRecord {
481 pub fn new(scope_ref: impl Into<String>, scope_epoch: u64, kind: ScopeKind) -> Self {
482 Self {
483 scope_ref: scope_ref.into(),
484 scope_epoch,
485 kind,
486 workdir: None,
487 project_id: None,
488 bind_proof_sha256: None,
489 replace_only_if_idle: false,
490 expires_at_ms: None,
491 parent: None,
492 child_owners: Vec::new(),
493 carriers: Vec::new(),
494 attributes: ScopeAttributes::default(),
495 }
496 }
497
498 #[must_use]
499 pub fn with_workdir(mut self, workdir: Option<String>) -> Self {
500 self.workdir = workdir;
501 self
502 }
503
504 #[must_use]
505 pub fn with_project_id(mut self, project_id: Option<String>) -> Self {
506 self.project_id = project_id;
507 self
508 }
509
510 #[must_use]
511 pub fn with_bind_proof_sha256(mut self, hash: Option<String>) -> Self {
512 self.bind_proof_sha256 = hash;
513 self
514 }
515
516 #[must_use]
517 pub fn with_replace_only_if_idle(mut self, replace_only_if_idle: bool) -> Self {
518 self.replace_only_if_idle = replace_only_if_idle;
519 self
520 }
521
522 #[must_use]
523 pub fn with_expires_at_ms(mut self, expires_at_ms: Option<u64>) -> Self {
524 self.expires_at_ms = expires_at_ms;
525 self
526 }
527
528 #[must_use]
529 pub fn with_parent(mut self, parent: Option<ScopeParent>) -> Self {
530 self.parent = parent;
531 self
532 }
533
534 #[must_use]
535 pub fn with_child_owners(mut self, child_owners: Vec<Principal>) -> Self {
536 self.child_owners = child_owners;
537 self
538 }
539
540 #[must_use]
541 pub fn with_carriers(mut self, carriers: Vec<ScopeCarrier>) -> Self {
542 self.carriers = carriers;
543 self
544 }
545
546 #[must_use]
547 pub fn with_attributes(mut self, attributes: ScopeAttributes) -> Self {
548 self.attributes = attributes;
549 self
550 }
551}
552
553#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
555#[serde(deny_unknown_fields)]
556#[non_exhaustive]
557pub struct ScopeEnd {
558 #[serde(rename = "ref")]
559 pub scope_ref: String,
560 pub scope_epoch: u64,
561}
562
563impl ScopeEnd {
564 pub fn new(scope_ref: impl Into<String>, scope_epoch: u64) -> Self {
565 Self {
566 scope_ref: scope_ref.into(),
567 scope_epoch,
568 }
569 }
570}
571
572#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
574#[serde(rename_all = "snake_case")]
575pub enum ScopeEndOutcome {
576 Ended,
578 NotLive,
581}
582
583#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
585#[serde(deny_unknown_fields)]
586#[non_exhaustive]
587pub struct ScopeEndResult {
588 #[serde(rename = "ref")]
589 pub scope_ref: String,
590 pub scope_epoch: u64,
591 pub outcome: ScopeEndOutcome,
592}
593
594impl ScopeEndResult {
595 pub fn new(scope_ref: impl Into<String>, scope_epoch: u64, outcome: ScopeEndOutcome) -> Self {
596 Self {
597 scope_ref: scope_ref.into(),
598 scope_epoch,
599 outcome,
600 }
601 }
602}
603
604#[derive(Clone, Serialize, Deserialize, PartialEq, Eq)]
610#[serde(deny_unknown_fields)]
611#[non_exhaustive]
612pub struct ScopeSelector {
613 #[serde(deserialize_with = "deserialize_scope_principal")]
614 pub owner: Principal,
615 #[serde(rename = "ref")]
616 pub scope_ref: String,
617 #[serde(default, skip_serializing_if = "Option::is_none")]
618 pub scope_epoch: Option<u64>,
619 #[serde(default, skip_serializing_if = "Option::is_none")]
622 pub bind_proof: Option<String>,
623 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
626 pub hold_presence: bool,
627}
628
629impl ScopeSelector {
630 pub fn new(owner: Principal, scope_ref: impl Into<String>, scope_epoch: Option<u64>) -> Self {
631 Self {
632 owner,
633 scope_ref: scope_ref.into(),
634 scope_epoch,
635 bind_proof: None,
636 hold_presence: false,
637 }
638 }
639
640 #[must_use]
641 pub fn with_bind_proof(mut self, proof: Option<String>) -> Self {
642 self.bind_proof = proof;
643 self
644 }
645
646 #[must_use]
647 pub fn with_hold_presence(mut self, hold_presence: bool) -> Self {
648 self.hold_presence = hold_presence;
649 self
650 }
651}
652
653impl std::fmt::Debug for ScopeSelector {
654 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
655 f.debug_struct("ScopeSelector")
656 .field("owner", &self.owner)
657 .field("scope_ref", &self.scope_ref)
658 .field("scope_epoch", &self.scope_epoch)
659 .field(
660 "bind_proof",
661 &self.bind_proof.as_ref().map(|_| "<redacted>"),
662 )
663 .finish()
664 }
665}
666
667impl std::fmt::Display for ScopeSelector {
668 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
669 std::fmt::Debug::fmt(self, f)
670 }
671}
672
673#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
675#[serde(rename_all = "snake_case")]
676pub enum ParentState {
677 Linked,
679 Pending,
682 Ended,
685}
686
687#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
689#[serde(rename_all = "snake_case")]
690pub enum ScopeRecordOutcome {
691 Created,
693 Replaced,
695 Updated,
697 Unchanged,
700 Refused,
703}
704
705#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
707pub struct ScopeRecordResult {
708 #[serde(rename = "ref")]
709 pub scope_ref: String,
710 pub scope_epoch: u64,
713 pub outcome: ScopeRecordOutcome,
714 #[serde(default, skip_serializing_if = "Option::is_none")]
716 pub code: Option<String>,
717 #[serde(default, skip_serializing_if = "Option::is_none")]
718 pub message: Option<String>,
719 #[serde(default, skip_serializing_if = "Option::is_none")]
722 pub version: Option<u64>,
723 #[serde(default, skip_serializing_if = "Option::is_none")]
725 pub parent_state: Option<ParentState>,
726}
727
728#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
732pub struct ScopeEnded {
733 #[serde(rename = "ref")]
734 pub scope_ref: String,
735 pub scope_epoch: u64,
736}
737
738#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
740#[serde(rename_all = "snake_case")]
741pub enum ScopeStatus {
742 Live,
743 Ended,
745 NotLive,
751}
752
753#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
756#[non_exhaustive]
757pub struct ScopeStamp {
758 pub owner: Principal,
759 #[serde(rename = "ref")]
760 pub scope_ref: String,
761 pub scope_epoch: u64,
762 pub kind: ScopeKind,
763 #[serde(default, skip_serializing_if = "Option::is_none")]
766 pub workdir: Option<String>,
767 #[serde(default, skip_serializing_if = "Option::is_none")]
769 pub project_id: Option<String>,
770 #[serde(default, skip_serializing_if = "Option::is_none")]
771 pub parent: Option<ScopeParent>,
772 #[serde(default, skip_serializing_if = "Option::is_none")]
773 pub parent_state: Option<ParentState>,
774 #[serde(default, skip_serializing_if = "ScopeAttributes::is_empty")]
775 pub attributes: ScopeAttributes,
776 pub owner_authorized: bool,
779 #[serde(default, skip_serializing_if = "Option::is_none")]
784 pub expires_at_ms: Option<u64>,
785}
786
787impl ScopeStamp {
788 pub fn new(
790 owner: Principal,
791 scope_ref: impl Into<String>,
792 scope_epoch: u64,
793 kind: ScopeKind,
794 ) -> Self {
795 Self {
796 owner,
797 scope_ref: scope_ref.into(),
798 scope_epoch,
799 kind,
800 workdir: None,
801 project_id: None,
802 parent: None,
803 parent_state: None,
804 attributes: ScopeAttributes::new(),
805 owner_authorized: false,
806 expires_at_ms: None,
807 }
808 }
809
810 #[must_use]
811 pub fn with_workdir(mut self, workdir: Option<String>) -> Self {
812 self.workdir = workdir;
813 self
814 }
815
816 #[must_use]
817 pub fn with_project_id(mut self, project_id: Option<String>) -> Self {
818 self.project_id = project_id;
819 self
820 }
821
822 #[must_use]
823 pub fn with_parent(mut self, parent: Option<ScopeParent>) -> Self {
824 self.parent = parent;
825 self
826 }
827
828 #[must_use]
829 pub fn with_parent_state(mut self, parent_state: Option<ParentState>) -> Self {
830 self.parent_state = parent_state;
831 self
832 }
833
834 #[must_use]
835 pub fn with_attributes(mut self, attributes: ScopeAttributes) -> Self {
836 self.attributes = attributes;
837 self
838 }
839
840 #[must_use]
841 pub fn with_owner_authorized(mut self, owner_authorized: bool) -> Self {
842 self.owner_authorized = owner_authorized;
843 self
844 }
845
846 #[must_use]
847 pub fn with_expires_at_ms(mut self, expires_at_ms: Option<u64>) -> Self {
848 self.expires_at_ms = expires_at_ms;
849 self
850 }
851}
852
853#[cfg(test)]
854mod tests {
855 use super::*;
856 use crate::tool_call::OpaqueFieldError;
857
858 #[test]
859 fn project_id_is_an_opaque_non_space_ascii_token_of_at_most_128_bytes() {
860 for valid in ["p", "!~Project:7/path", &"p".repeat(128)] {
861 assert_eq!(validate_project_id(valid), Ok(()));
862 }
863 for invalid in ["", "p p", "p\t", "pé", "p\u{7f}", &"p".repeat(129)] {
864 assert!(validate_project_id(invalid).is_err(), "{invalid:?}");
865 }
866 }
867
868 #[test]
869 fn scope_project_fields_round_trip_and_absence_keeps_exact_bytes() {
870 let record = ScopeRecord::new("session", 1, ScopeKind::Head);
871 assert_eq!(
872 serde_json::to_string(&record).unwrap(),
873 r#"{"ref":"session","scope_epoch":1,"kind":"head"}"#
874 );
875 let record = record
876 .with_workdir(Some("/folder".into()))
877 .with_project_id(Some("project:1".into()));
878 let encoded = serde_json::to_string(&record).unwrap();
879 assert_eq!(
880 serde_json::from_str::<ScopeRecord>(&encoded).unwrap(),
881 record
882 );
883 let stamp = ScopeStamp::new(Principal::Direct, "session", 1, ScopeKind::Head);
884 assert_eq!(
885 serde_json::to_string(&stamp).unwrap(),
886 r#"{"owner":{"kind":"direct"},"ref":"session","scope_epoch":1,"kind":"head","owner_authorized":false}"#
887 );
888 let stamp = stamp
889 .with_workdir(record.workdir)
890 .with_project_id(record.project_id);
891 let encoded = serde_json::to_string(&stamp).unwrap();
892 assert_eq!(serde_json::from_str::<ScopeStamp>(&encoded).unwrap(), stamp);
893 }
894
895 #[test]
896 fn flow_id_uses_the_shared_opaque_token_bounds_and_names_its_field() {
897 let field = "flow_id";
898 assert_eq!(validate_flow_id(""), Err(OpaqueFieldError::Empty { field }));
899 assert_eq!(validate_flow_id("f"), Ok(()));
900 assert_eq!(validate_flow_id(&"f".repeat(256)), Ok(()));
901 assert_eq!(
902 validate_flow_id(&"f".repeat(257)),
903 Err(OpaqueFieldError::TooLong { field, length: 257 })
904 );
905 assert_eq!(validate_flow_id("!~Flow:7/step"), Ok(()));
906 for bad in ["f é", "f\t", "fé", "f\u{7f}"] {
907 let error = validate_flow_id(bad).unwrap_err();
908 assert_eq!(
909 error,
910 OpaqueFieldError::InvalidCharacter { field, index: 1 }
911 );
912 assert_eq!(error.field(), "flow_id");
913 }
914 }
915
916 #[test]
917 fn flow_identity_validators_enforce_boundaries_and_name_fields() {
918 for valid in [1, 9_007_199_254_740_991] {
919 assert_eq!(validate_flow_version(valid), Ok(()));
920 }
921 for invalid in [0, 9_007_199_254_740_992, u64::MAX] {
922 assert!(validate_flow_version(invalid)
923 .unwrap_err()
924 .contains("flow_version"));
925 }
926 assert_eq!(
927 validate_flow_code_hash(&"0123456789abcdef".repeat(4)),
928 Ok(())
929 );
930 for invalid in [
931 "a".repeat(63),
932 "a".repeat(65),
933 "A".repeat(64),
934 "g".repeat(64),
935 ] {
936 assert!(validate_flow_code_hash(&invalid)
937 .unwrap_err()
938 .contains("flow_code_hash"));
939 }
940 for valid in ["i", "!~Install:7/path", &"i".repeat(256)] {
941 assert_eq!(validate_flow_install_id(valid), Ok(()));
942 }
943 for invalid in ["", "i i", "i\t", "ié", "i\u{7f}", &"i".repeat(257)] {
944 assert_eq!(
945 validate_flow_install_id(invalid).unwrap_err().field(),
946 "flow_install_id"
947 );
948 }
949 }
950
951 #[test]
952 fn flow_identity_round_trips_and_legacy_stamp_keeps_exact_bytes() {
953 let attributes = ScopeAttributes::new().with_flow_id(Some("flow:7".into()));
954 let stamp = ScopeStamp::new(Principal::Direct, "session", 1, ScopeKind::Head)
955 .with_attributes(attributes.clone());
956 assert_eq!(
957 serde_json::to_string(&stamp).unwrap(),
958 r#"{"owner":{"kind":"direct"},"ref":"session","scope_epoch":1,"kind":"head","attributes":{"flow_id":"flow:7"},"owner_authorized":false}"#
959 );
960 let attributes = attributes
961 .with_flow_version(Some(9_007_199_254_740_991))
962 .with_flow_code_hash(Some("a".repeat(64)))
963 .with_flow_install_id(Some("install:7".into()));
964 let stamp = stamp.with_attributes(attributes.clone());
965 let encoded = serde_json::to_string(&stamp).unwrap();
966 assert_eq!(serde_json::from_str::<ScopeStamp>(&encoded).unwrap(), stamp);
967 assert_eq!(
968 serde_json::from_str::<ScopeAttributes>(&serde_json::to_string(&attributes).unwrap())
969 .unwrap(),
970 attributes
971 );
972 assert!(
973 serde_json::from_str::<ScopeAttributes>(r#"{"flow_version":1,"unknown":true}"#)
974 .is_err()
975 );
976 assert!(!ScopeAttributes::new().with_flow_version(Some(1)).is_empty());
977 assert!(!ScopeAttributes::new()
978 .with_flow_code_hash(Some("a".repeat(64)))
979 .is_empty());
980 assert!(!ScopeAttributes::new()
981 .with_flow_install_id(Some("i".into()))
982 .is_empty());
983 }
984
985 #[test]
986 fn flow_only_attributes_round_trip_and_absence_keeps_the_bytes() {
987 let attributes = ScopeAttributes::default();
988 assert!(attributes.is_empty());
989 assert_eq!(serde_json::to_string(&attributes).unwrap(), "{}");
990 assert_eq!(
991 serde_json::from_str::<ScopeAttributes>("{}").unwrap(),
992 attributes
993 );
994 let attributes = ScopeAttributes {
995 flow_id: Some("flow:7".to_string()),
996 ..ScopeAttributes::default()
997 };
998 assert!(!attributes.is_empty());
999 let encoded = serde_json::to_string(&attributes).unwrap();
1000 assert_eq!(encoded, r#"{"flow_id":"flow:7"}"#);
1001 assert_eq!(
1002 serde_json::from_str::<ScopeAttributes>(&encoded).unwrap(),
1003 attributes
1004 );
1005 assert!(
1006 serde_json::from_str::<ScopeAttributes>(r#"{"flow_id":"flow:7","unknown":true}"#)
1007 .is_err()
1008 );
1009 }
1010}