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