1use serde::{Deserialize, Serialize};
15
16use crate::Principal;
17
18mod federated;
19pub use federated::{FederatedAttributes, FederatedPeerClass, RemoteClaim};
20mod authorize;
21pub use authorize::{
22 RouteAuthorizeExpected, RouteAuthorizeOutcome, RouteAuthorizeResponse, RouteAuthorizeScope,
23 ROUTE_AUTHORIZE_CAPABILITY, ROUTE_AUTHORIZE_OP,
24};
25
26pub const SCOPE_FEDERATED_CAPABILITY: &str = "scope-federated/v1";
28
29#[derive(Deserialize)]
33#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
34enum ScopePrincipal {
35 Reserved { module_id: String },
36 Direct {},
37 Unverified {},
38}
39
40impl From<ScopePrincipal> for Principal {
41 fn from(value: ScopePrincipal) -> Self {
42 match value {
43 ScopePrincipal::Reserved { module_id } => Self::Reserved { module_id },
44 ScopePrincipal::Direct {} => Self::Direct,
45 ScopePrincipal::Unverified {} => Self::Unverified,
46 }
47 }
48}
49
50fn deserialize_scope_principal<'de, D: serde::Deserializer<'de>>(
51 deserializer: D,
52) -> Result<Principal, D::Error> {
53 ScopePrincipal::deserialize(deserializer).map(Into::into)
54}
55
56fn deserialize_scope_principals<'de, D: serde::Deserializer<'de>>(
57 deserializer: D,
58) -> Result<Vec<Principal>, D::Error> {
59 Vec::<ScopePrincipal>::deserialize(deserializer)
60 .map(|principals| principals.into_iter().map(Into::into).collect())
61}
62
63pub fn validate_bind_proof_sha256(hash: &str) -> Result<(), &'static str> {
65 if hash.len() == 64
66 && hash
67 .bytes()
68 .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
69 {
70 Ok(())
71 } else {
72 Err("bind_proof_sha256 must be exactly 64 lowercase hexadecimal characters")
73 }
74}
75
76fn deserialize_bind_proof_sha256<'de, D: serde::Deserializer<'de>>(
77 deserializer: D,
78) -> Result<Option<String>, D::Error> {
79 let hash = Option::<String>::deserialize(deserializer)?;
80 if let Some(hash) = &hash {
81 validate_bind_proof_sha256(hash).map_err(serde::de::Error::custom)?;
82 }
83 Ok(hash)
84}
85
86pub const CAP_SCOPES_V1: &str = "scopes/v1";
90
91pub const CAP_ROUTE_ROLE_VERSIONS_V1: &str = "route-role-versions/v1";
96
97pub const BIND_NO_PROJECT_CAPABILITY: &str = "bind-no-project/v1";
102
103pub const SCOPE_SYNC_OP: &str = "scope.sync";
105pub const SCOPE_APPLY_OP: &str = "scope.apply";
108pub const SCOPE_DESCRIBE_OP: &str = "scope.describe";
110
111pub const MAX_LIVE_SCOPES_PER_OWNER: usize = 10_000;
113pub const MAX_SCOPE_ATTRIBUTE_BYTES: usize = 4 * 1024;
116pub const MAX_SCOPE_TOMBSTONES_PER_OWNER: usize = 1_000;
119pub const MAX_CARRIER_TARGETS: usize = 16;
121pub const MAX_SCOPE_EXPIRY_AHEAD_MS: u64 = 86_400_000;
124
125#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
128#[serde(rename_all = "snake_case")]
129#[non_exhaustive]
130pub enum ScopeKind {
131 Head,
132 Worker,
133 Ephemeral,
134 Federated,
135}
136
137#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
140#[serde(deny_unknown_fields)]
141#[non_exhaustive]
142pub struct ScopeParent {
143 #[serde(deserialize_with = "deserialize_scope_principal")]
144 pub owner: Principal,
145 #[serde(rename = "ref")]
146 pub scope_ref: String,
147 pub scope_epoch: u64,
148}
149
150impl ScopeParent {
151 pub fn new(owner: Principal, scope_ref: impl Into<String>, scope_epoch: u64) -> Self {
152 Self {
153 owner,
154 scope_ref: scope_ref.into(),
155 scope_epoch,
156 }
157 }
158}
159
160#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
167#[serde(deny_unknown_fields)]
168#[non_exhaustive]
169pub struct ScopeCarrier {
170 #[serde(deserialize_with = "deserialize_scope_principal")]
171 pub principal: Principal,
172 #[serde(default, skip_serializing_if = "Option::is_none")]
173 pub targets: Option<Vec<String>>,
174}
175
176impl ScopeCarrier {
177 pub fn new(principal: Principal) -> Self {
178 Self {
179 principal,
180 targets: None,
181 }
182 }
183
184 #[must_use]
185 pub fn with_targets(mut self, targets: Option<Vec<String>>) -> Self {
186 self.targets = targets;
187 self
188 }
189}
190
191pub const FLOW_SCOPES_CAPABILITY: &str = "flow-scopes/v1";
197
198pub const FLOW_IDENTITY_SCOPES_CAPABILITY: &str = "flow-identity-scopes/v1";
201
202pub const AGENT_RUN_SCOPES_CAPABILITY: &str = "agent-run-scopes/v1";
208
209pub const SCOPE_ON_BEHALF_OF_CAPABILITY: &str = "scope-on-behalf-of/v1";
213
214pub const WORKER_RUNS_CAPABILITY: &str = "worker-runs/v1";
227
228pub const SCOPE_SERVED_BY_CAPABILITY: &str = "scope-served-by/v1";
230
231#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
239#[serde(deny_unknown_fields)]
240#[non_exhaustive]
241pub struct ScopeAttributes {
242 #[serde(default, skip_serializing_if = "Option::is_none")]
244 pub federated: Option<FederatedAttributes>,
245 #[serde(default, skip_serializing_if = "Option::is_none")]
247 pub agent_id: Option<String>,
248 #[serde(default, skip_serializing_if = "Option::is_none")]
265 pub on_behalf_of_agent: Option<String>,
266 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
268 pub delegates: bool,
269 #[serde(default, skip_serializing_if = "Option::is_none")]
285 pub flow_id: Option<String>,
286 #[serde(default, skip_serializing_if = "Option::is_none")]
291 pub flow_version: Option<u64>,
292 #[serde(default, skip_serializing_if = "Option::is_none")]
296 pub flow_code_hash: Option<String>,
297 #[serde(default, skip_serializing_if = "Option::is_none")]
301 pub flow_install_id: Option<String>,
302 #[serde(default, skip_serializing_if = "Option::is_none")]
314 pub run_id: Option<String>,
315}
316
317impl ScopeAttributes {
318 pub fn new() -> Self {
319 Self::default()
320 }
321
322 #[must_use]
323 pub fn with_federated(mut self, federated: Option<FederatedAttributes>) -> Self {
324 self.federated = federated;
325 self
326 }
327
328 #[must_use]
329 pub fn with_agent_id(mut self, agent_id: Option<String>) -> Self {
330 self.agent_id = agent_id;
331 self
332 }
333
334 #[must_use]
335 pub fn with_on_behalf_of_agent(mut self, on_behalf_of_agent: Option<String>) -> Self {
336 self.on_behalf_of_agent = on_behalf_of_agent;
337 self
338 }
339
340 #[must_use]
341 pub fn with_delegates(mut self, delegates: bool) -> Self {
342 self.delegates = delegates;
343 self
344 }
345
346 #[must_use]
347 pub fn with_flow_id(mut self, flow_id: Option<String>) -> Self {
348 self.flow_id = flow_id;
349 self
350 }
351
352 #[must_use]
353 pub fn with_flow_version(mut self, flow_version: Option<u64>) -> Self {
354 self.flow_version = flow_version;
355 self
356 }
357
358 #[must_use]
359 pub fn with_flow_code_hash(mut self, flow_code_hash: Option<String>) -> Self {
360 self.flow_code_hash = flow_code_hash;
361 self
362 }
363
364 #[must_use]
365 pub fn with_flow_install_id(mut self, flow_install_id: Option<String>) -> Self {
366 self.flow_install_id = flow_install_id;
367 self
368 }
369
370 #[must_use]
371 pub fn with_run_id(mut self, run_id: Option<String>) -> Self {
372 self.run_id = run_id;
373 self
374 }
375
376 pub fn is_empty(&self) -> bool {
377 self.federated.is_none()
378 && self.agent_id.is_none()
379 && self.on_behalf_of_agent.is_none()
380 && !self.delegates
381 && self.flow_id.is_none()
382 && self.flow_version.is_none()
383 && self.flow_code_hash.is_none()
384 && self.flow_install_id.is_none()
385 && self.run_id.is_none()
386 }
387}
388
389pub fn validate_flow_id(flow_id: &str) -> Result<(), crate::tool_call::OpaqueFieldError> {
393 crate::tool_call::validate_opaque_field("flow_id", flow_id)
394}
395
396pub fn validate_flow_version(flow_version: u64) -> Result<(), &'static str> {
399 if !(1..=9_007_199_254_740_991).contains(&flow_version) {
400 return Err("flow_version must be from 1 to 9007199254740991");
401 }
402 Ok(())
403}
404
405pub fn validate_flow_code_hash(flow_code_hash: &str) -> Result<(), &'static str> {
407 if flow_code_hash.len() != 64
408 || !flow_code_hash
409 .bytes()
410 .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
411 {
412 return Err("flow_code_hash must contain exactly 64 lowercase hex characters");
413 }
414 Ok(())
415}
416
417pub fn validate_flow_install_id(
420 flow_install_id: &str,
421) -> Result<(), crate::tool_call::OpaqueFieldError> {
422 crate::tool_call::validate_opaque_field("flow_install_id", flow_install_id)
423}
424
425pub fn validate_run_id(run_id: &str) -> Result<(), crate::tool_call::OpaqueFieldError> {
428 crate::tool_call::validate_opaque_field("run_id", run_id)
429}
430
431pub fn validate_on_behalf_of_agent(agent: &str) -> Result<(), crate::tool_call::OpaqueFieldError> {
434 crate::tool_call::validate_opaque_field("on_behalf_of_agent", agent)
435}
436
437pub const SCOPE_WORKDIR_CAPABILITY: &str = "scope-workdir/v1";
439
440pub fn validate_project_id(value: &str) -> Result<(), &'static str> {
442 if value.is_empty() || value.len() > 128 {
443 return Err("project_id must contain 1 to 128 bytes");
444 }
445 if !value.bytes().all(|byte| (0x21..=0x7e).contains(&byte)) {
446 return Err("project_id must be printable ASCII without whitespace");
447 }
448 Ok(())
449}
450
451#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
453#[serde(deny_unknown_fields)]
454#[non_exhaustive]
455pub struct ScopeRecord {
456 #[serde(rename = "ref")]
457 pub scope_ref: String,
458 pub scope_epoch: u64,
462 pub kind: ScopeKind,
463 #[serde(default, skip_serializing_if = "Option::is_none")]
466 pub workdir: Option<String>,
467 #[serde(default, skip_serializing_if = "Option::is_none")]
469 pub project_id: Option<String>,
470 #[serde(
473 default,
474 skip_serializing_if = "Option::is_none",
475 deserialize_with = "deserialize_bind_proof_sha256"
476 )]
477 pub bind_proof_sha256: Option<String>,
478 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
483 pub replace_only_if_idle: bool,
484 #[serde(default, skip_serializing_if = "Option::is_none")]
488 pub expires_at_ms: Option<u64>,
489 #[serde(default, skip_serializing_if = "Option::is_none")]
490 pub parent: Option<ScopeParent>,
491 #[serde(
494 default,
495 skip_serializing_if = "Vec::is_empty",
496 deserialize_with = "deserialize_scope_principals"
497 )]
498 pub child_owners: Vec<Principal>,
499 #[serde(default, skip_serializing_if = "Vec::is_empty")]
500 pub carriers: Vec<ScopeCarrier>,
501 #[serde(default, skip_serializing_if = "ScopeAttributes::is_empty")]
502 pub attributes: ScopeAttributes,
503}
504
505impl ScopeRecord {
506 pub fn new(scope_ref: impl Into<String>, scope_epoch: u64, kind: ScopeKind) -> Self {
507 Self {
508 scope_ref: scope_ref.into(),
509 scope_epoch,
510 kind,
511 workdir: None,
512 project_id: None,
513 bind_proof_sha256: None,
514 replace_only_if_idle: false,
515 expires_at_ms: None,
516 parent: None,
517 child_owners: Vec::new(),
518 carriers: Vec::new(),
519 attributes: ScopeAttributes::default(),
520 }
521 }
522
523 #[must_use]
524 pub fn with_workdir(mut self, workdir: Option<String>) -> Self {
525 self.workdir = workdir;
526 self
527 }
528
529 #[must_use]
530 pub fn with_project_id(mut self, project_id: Option<String>) -> Self {
531 self.project_id = project_id;
532 self
533 }
534
535 #[must_use]
536 pub fn with_bind_proof_sha256(mut self, hash: Option<String>) -> Self {
537 self.bind_proof_sha256 = hash;
538 self
539 }
540
541 #[must_use]
542 pub fn with_replace_only_if_idle(mut self, replace_only_if_idle: bool) -> Self {
543 self.replace_only_if_idle = replace_only_if_idle;
544 self
545 }
546
547 #[must_use]
548 pub fn with_expires_at_ms(mut self, expires_at_ms: Option<u64>) -> Self {
549 self.expires_at_ms = expires_at_ms;
550 self
551 }
552
553 #[must_use]
554 pub fn with_parent(mut self, parent: Option<ScopeParent>) -> Self {
555 self.parent = parent;
556 self
557 }
558
559 #[must_use]
560 pub fn with_child_owners(mut self, child_owners: Vec<Principal>) -> Self {
561 self.child_owners = child_owners;
562 self
563 }
564
565 #[must_use]
566 pub fn with_carriers(mut self, carriers: Vec<ScopeCarrier>) -> Self {
567 self.carriers = carriers;
568 self
569 }
570
571 #[must_use]
572 pub fn with_attributes(mut self, attributes: ScopeAttributes) -> Self {
573 self.attributes = attributes;
574 self
575 }
576}
577
578#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
580#[serde(deny_unknown_fields)]
581#[non_exhaustive]
582pub struct ScopeEnd {
583 #[serde(rename = "ref")]
584 pub scope_ref: String,
585 pub scope_epoch: u64,
586}
587
588impl ScopeEnd {
589 pub fn new(scope_ref: impl Into<String>, scope_epoch: u64) -> Self {
590 Self {
591 scope_ref: scope_ref.into(),
592 scope_epoch,
593 }
594 }
595}
596
597#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
599#[serde(rename_all = "snake_case")]
600pub enum ScopeEndOutcome {
601 Ended,
603 NotLive,
606}
607
608#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
610#[serde(deny_unknown_fields)]
611#[non_exhaustive]
612pub struct ScopeEndResult {
613 #[serde(rename = "ref")]
614 pub scope_ref: String,
615 pub scope_epoch: u64,
616 pub outcome: ScopeEndOutcome,
617}
618
619impl ScopeEndResult {
620 pub fn new(scope_ref: impl Into<String>, scope_epoch: u64, outcome: ScopeEndOutcome) -> Self {
621 Self {
622 scope_ref: scope_ref.into(),
623 scope_epoch,
624 outcome,
625 }
626 }
627}
628
629#[derive(Clone, Serialize, Deserialize, PartialEq, Eq)]
635#[serde(deny_unknown_fields)]
636#[non_exhaustive]
637pub struct ScopeSelector {
638 #[serde(deserialize_with = "deserialize_scope_principal")]
639 pub owner: Principal,
640 #[serde(rename = "ref")]
641 pub scope_ref: String,
642 #[serde(default, skip_serializing_if = "Option::is_none")]
643 pub scope_epoch: Option<u64>,
644 #[serde(default, skip_serializing_if = "Option::is_none")]
647 pub bind_proof: Option<String>,
648 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
651 pub hold_presence: bool,
652}
653
654impl ScopeSelector {
655 pub fn new(owner: Principal, scope_ref: impl Into<String>, scope_epoch: Option<u64>) -> Self {
656 Self {
657 owner,
658 scope_ref: scope_ref.into(),
659 scope_epoch,
660 bind_proof: None,
661 hold_presence: false,
662 }
663 }
664
665 #[must_use]
666 pub fn with_bind_proof(mut self, proof: Option<String>) -> Self {
667 self.bind_proof = proof;
668 self
669 }
670
671 #[must_use]
672 pub fn with_hold_presence(mut self, hold_presence: bool) -> Self {
673 self.hold_presence = hold_presence;
674 self
675 }
676}
677
678impl std::fmt::Debug for ScopeSelector {
679 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
680 f.debug_struct("ScopeSelector")
681 .field("owner", &self.owner)
682 .field("scope_ref", &self.scope_ref)
683 .field("scope_epoch", &self.scope_epoch)
684 .field(
685 "bind_proof",
686 &self.bind_proof.as_ref().map(|_| "<redacted>"),
687 )
688 .finish()
689 }
690}
691
692impl std::fmt::Display for ScopeSelector {
693 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
694 std::fmt::Debug::fmt(self, f)
695 }
696}
697
698#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
700#[serde(rename_all = "snake_case")]
701pub enum ParentState {
702 Linked,
704 Pending,
707 Ended,
710}
711
712#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
714#[serde(rename_all = "snake_case")]
715pub enum ScopeRecordOutcome {
716 Created,
718 Replaced,
720 Updated,
722 Unchanged,
725 Refused,
728}
729
730#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
732pub struct ScopeRecordResult {
733 #[serde(rename = "ref")]
734 pub scope_ref: String,
735 pub scope_epoch: u64,
738 pub outcome: ScopeRecordOutcome,
739 #[serde(default, skip_serializing_if = "Option::is_none")]
741 pub code: Option<String>,
742 #[serde(default, skip_serializing_if = "Option::is_none")]
743 pub message: Option<String>,
744 #[serde(default, skip_serializing_if = "Option::is_none")]
747 pub version: Option<u64>,
748 #[serde(default, skip_serializing_if = "Option::is_none")]
750 pub parent_state: Option<ParentState>,
751}
752
753#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
757pub struct ScopeEnded {
758 #[serde(rename = "ref")]
759 pub scope_ref: String,
760 pub scope_epoch: u64,
761}
762
763#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
765#[serde(rename_all = "snake_case")]
766pub enum ScopeStatus {
767 Live,
768 Ended,
770 NotLive,
776}
777
778#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
781#[non_exhaustive]
782pub struct ScopeStamp {
783 pub owner: Principal,
784 #[serde(rename = "ref")]
785 pub scope_ref: String,
786 pub scope_epoch: u64,
787 pub kind: ScopeKind,
788 #[serde(default, skip_serializing_if = "Option::is_none")]
791 pub workdir: Option<String>,
792 #[serde(default, skip_serializing_if = "Option::is_none")]
794 pub project_id: Option<String>,
795 #[serde(default, skip_serializing_if = "Option::is_none")]
796 pub parent: Option<ScopeParent>,
797 #[serde(default, skip_serializing_if = "Option::is_none")]
798 pub parent_state: Option<ParentState>,
799 #[serde(default, skip_serializing_if = "ScopeAttributes::is_empty")]
800 pub attributes: ScopeAttributes,
801 pub owner_authorized: bool,
805 #[serde(default, skip_serializing_if = "Option::is_none")]
810 pub expires_at_ms: Option<u64>,
811}
812
813impl ScopeStamp {
814 pub fn new(
816 owner: Principal,
817 scope_ref: impl Into<String>,
818 scope_epoch: u64,
819 kind: ScopeKind,
820 ) -> Self {
821 Self {
822 owner,
823 scope_ref: scope_ref.into(),
824 scope_epoch,
825 kind,
826 workdir: None,
827 project_id: None,
828 parent: None,
829 parent_state: None,
830 attributes: ScopeAttributes::new(),
831 owner_authorized: false,
832 expires_at_ms: None,
833 }
834 }
835
836 #[must_use]
837 pub fn with_workdir(mut self, workdir: Option<String>) -> Self {
838 self.workdir = workdir;
839 self
840 }
841
842 #[must_use]
843 pub fn with_project_id(mut self, project_id: Option<String>) -> Self {
844 self.project_id = project_id;
845 self
846 }
847
848 #[must_use]
849 pub fn with_parent(mut self, parent: Option<ScopeParent>) -> Self {
850 self.parent = parent;
851 self
852 }
853
854 #[must_use]
855 pub fn with_parent_state(mut self, parent_state: Option<ParentState>) -> Self {
856 self.parent_state = parent_state;
857 self
858 }
859
860 #[must_use]
861 pub fn with_attributes(mut self, attributes: ScopeAttributes) -> Self {
862 self.attributes = attributes;
863 self
864 }
865
866 #[must_use]
867 pub fn with_owner_authorized(mut self, owner_authorized: bool) -> Self {
868 self.owner_authorized = owner_authorized;
869 self
870 }
871
872 #[must_use]
873 pub fn with_expires_at_ms(mut self, expires_at_ms: Option<u64>) -> Self {
874 self.expires_at_ms = expires_at_ms;
875 self
876 }
877}
878
879#[cfg(test)]
880mod tests {
881 use super::*;
882 use crate::tool_call::OpaqueFieldError;
883
884 #[test]
885 fn project_id_is_an_opaque_non_space_ascii_token_of_at_most_128_bytes() {
886 for valid in ["p", "!~Project:7/path", &"p".repeat(128)] {
887 assert_eq!(validate_project_id(valid), Ok(()));
888 }
889 for invalid in ["", "p p", "p\t", "pé", "p\u{7f}", &"p".repeat(129)] {
890 assert!(validate_project_id(invalid).is_err(), "{invalid:?}");
891 }
892 }
893
894 #[test]
895 fn scope_project_fields_round_trip_and_absence_keeps_exact_bytes() {
896 let record = ScopeRecord::new("session", 1, ScopeKind::Head);
897 assert_eq!(
898 serde_json::to_string(&record).unwrap(),
899 r#"{"ref":"session","scope_epoch":1,"kind":"head"}"#
900 );
901 let record = record
902 .with_workdir(Some("/folder".into()))
903 .with_project_id(Some("project:1".into()));
904 let encoded = serde_json::to_string(&record).unwrap();
905 assert_eq!(
906 serde_json::from_str::<ScopeRecord>(&encoded).unwrap(),
907 record
908 );
909 let stamp = ScopeStamp::new(Principal::Direct, "session", 1, ScopeKind::Head);
910 assert_eq!(
911 serde_json::to_string(&stamp).unwrap(),
912 r#"{"owner":{"kind":"direct"},"ref":"session","scope_epoch":1,"kind":"head","owner_authorized":false}"#
913 );
914 let stamp = stamp
915 .with_workdir(record.workdir)
916 .with_project_id(record.project_id);
917 let encoded = serde_json::to_string(&stamp).unwrap();
918 assert_eq!(serde_json::from_str::<ScopeStamp>(&encoded).unwrap(), stamp);
919 }
920
921 #[test]
922 fn flow_id_uses_the_shared_opaque_token_bounds_and_names_its_field() {
923 let field = "flow_id";
924 assert_eq!(validate_flow_id(""), Err(OpaqueFieldError::Empty { field }));
925 assert_eq!(validate_flow_id("f"), Ok(()));
926 assert_eq!(validate_flow_id(&"f".repeat(256)), Ok(()));
927 assert_eq!(
928 validate_flow_id(&"f".repeat(257)),
929 Err(OpaqueFieldError::TooLong { field, length: 257 })
930 );
931 assert_eq!(validate_flow_id("!~Flow:7/step"), Ok(()));
932 for bad in ["f é", "f\t", "fé", "f\u{7f}"] {
933 let error = validate_flow_id(bad).unwrap_err();
934 assert_eq!(
935 error,
936 OpaqueFieldError::InvalidCharacter { field, index: 1 }
937 );
938 assert_eq!(error.field(), "flow_id");
939 }
940 }
941
942 #[test]
943 fn flow_identity_validators_enforce_boundaries_and_name_fields() {
944 for valid in [1, 9_007_199_254_740_991] {
945 assert_eq!(validate_flow_version(valid), Ok(()));
946 }
947 for invalid in [0, 9_007_199_254_740_992, u64::MAX] {
948 assert!(validate_flow_version(invalid)
949 .unwrap_err()
950 .contains("flow_version"));
951 }
952 assert_eq!(
953 validate_flow_code_hash(&"0123456789abcdef".repeat(4)),
954 Ok(())
955 );
956 for invalid in [
957 "a".repeat(63),
958 "a".repeat(65),
959 "A".repeat(64),
960 "g".repeat(64),
961 ] {
962 assert!(validate_flow_code_hash(&invalid)
963 .unwrap_err()
964 .contains("flow_code_hash"));
965 }
966 for valid in ["i", "!~Install:7/path", &"i".repeat(256)] {
967 assert_eq!(validate_flow_install_id(valid), Ok(()));
968 }
969 for invalid in ["", "i i", "i\t", "ié", "i\u{7f}", &"i".repeat(257)] {
970 assert_eq!(
971 validate_flow_install_id(invalid).unwrap_err().field(),
972 "flow_install_id"
973 );
974 }
975 }
976
977 #[test]
978 fn flow_identity_round_trips_and_legacy_stamp_keeps_exact_bytes() {
979 let attributes = ScopeAttributes::new().with_flow_id(Some("flow:7".into()));
980 let stamp = ScopeStamp::new(Principal::Direct, "session", 1, ScopeKind::Head)
981 .with_attributes(attributes.clone());
982 assert_eq!(
983 serde_json::to_string(&stamp).unwrap(),
984 r#"{"owner":{"kind":"direct"},"ref":"session","scope_epoch":1,"kind":"head","attributes":{"flow_id":"flow:7"},"owner_authorized":false}"#
985 );
986 let attributes = attributes
987 .with_flow_version(Some(9_007_199_254_740_991))
988 .with_flow_code_hash(Some("a".repeat(64)))
989 .with_flow_install_id(Some("install:7".into()));
990 let stamp = stamp.with_attributes(attributes.clone());
991 let encoded = serde_json::to_string(&stamp).unwrap();
992 assert_eq!(serde_json::from_str::<ScopeStamp>(&encoded).unwrap(), stamp);
993 assert_eq!(
994 serde_json::from_str::<ScopeAttributes>(&serde_json::to_string(&attributes).unwrap())
995 .unwrap(),
996 attributes
997 );
998 assert!(
999 serde_json::from_str::<ScopeAttributes>(r#"{"flow_version":1,"unknown":true}"#)
1000 .is_err()
1001 );
1002 assert!(!ScopeAttributes::new().with_flow_version(Some(1)).is_empty());
1003 assert!(!ScopeAttributes::new()
1004 .with_flow_code_hash(Some("a".repeat(64)))
1005 .is_empty());
1006 assert!(!ScopeAttributes::new()
1007 .with_flow_install_id(Some("i".into()))
1008 .is_empty());
1009 }
1010
1011 #[test]
1012 fn flow_only_attributes_round_trip_and_absence_keeps_the_bytes() {
1013 let attributes = ScopeAttributes::default();
1014 assert!(attributes.is_empty());
1015 assert_eq!(serde_json::to_string(&attributes).unwrap(), "{}");
1016 assert_eq!(
1017 serde_json::from_str::<ScopeAttributes>("{}").unwrap(),
1018 attributes
1019 );
1020 let attributes = ScopeAttributes {
1021 flow_id: Some("flow:7".to_string()),
1022 ..ScopeAttributes::default()
1023 };
1024 assert!(!attributes.is_empty());
1025 let encoded = serde_json::to_string(&attributes).unwrap();
1026 assert_eq!(encoded, r#"{"flow_id":"flow:7"}"#);
1027 assert_eq!(
1028 serde_json::from_str::<ScopeAttributes>(&encoded).unwrap(),
1029 attributes
1030 );
1031 assert!(
1032 serde_json::from_str::<ScopeAttributes>(r#"{"flow_id":"flow:7","unknown":true}"#)
1033 .is_err()
1034 );
1035 }
1036}