1use serde::{Deserialize, Serialize};
15
16use crate::Principal;
17
18mod federated;
19pub use federated::{FederatedAttributes, FederatedPeerClass, FederatedProject, 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
29pub const SCOPE_FEDERATED_V2_CAPABILITY: &str = "scope-federated/v2";
35
36#[derive(Deserialize)]
40#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
41enum ScopePrincipal {
42 Reserved { module_id: String },
43 Direct {},
44 Unverified {},
45}
46
47impl From<ScopePrincipal> for Principal {
48 fn from(value: ScopePrincipal) -> Self {
49 match value {
50 ScopePrincipal::Reserved { module_id } => Self::Reserved { module_id },
51 ScopePrincipal::Direct {} => Self::Direct,
52 ScopePrincipal::Unverified {} => Self::Unverified,
53 }
54 }
55}
56
57fn deserialize_scope_principal<'de, D: serde::Deserializer<'de>>(
58 deserializer: D,
59) -> Result<Principal, D::Error> {
60 ScopePrincipal::deserialize(deserializer).map(Into::into)
61}
62
63fn deserialize_scope_principals<'de, D: serde::Deserializer<'de>>(
64 deserializer: D,
65) -> Result<Vec<Principal>, D::Error> {
66 Vec::<ScopePrincipal>::deserialize(deserializer)
67 .map(|principals| principals.into_iter().map(Into::into).collect())
68}
69
70pub fn validate_bind_proof_sha256(hash: &str) -> Result<(), &'static str> {
72 if hash.len() == 64
73 && hash
74 .bytes()
75 .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
76 {
77 Ok(())
78 } else {
79 Err("bind_proof_sha256 must be exactly 64 lowercase hexadecimal characters")
80 }
81}
82
83fn deserialize_bind_proof_sha256<'de, D: serde::Deserializer<'de>>(
84 deserializer: D,
85) -> Result<Option<String>, D::Error> {
86 let hash = Option::<String>::deserialize(deserializer)?;
87 if let Some(hash) = &hash {
88 validate_bind_proof_sha256(hash).map_err(serde::de::Error::custom)?;
89 }
90 Ok(hash)
91}
92
93pub const CAP_SCOPES_V1: &str = "scopes/v1";
97
98pub const CAP_ROUTE_ROLE_VERSIONS_V1: &str = "route-role-versions/v1";
103
104pub const BIND_NO_PROJECT_CAPABILITY: &str = "bind-no-project/v1";
109
110pub const SCOPE_SYNC_OP: &str = "scope.sync";
112pub const SCOPE_APPLY_OP: &str = "scope.apply";
115pub const SCOPE_DESCRIBE_OP: &str = "scope.describe";
117
118pub const MAX_LIVE_SCOPES_PER_OWNER: usize = 10_000;
120pub const MAX_SCOPE_ATTRIBUTE_BYTES: usize = 4 * 1024;
123pub const MAX_SCOPE_TOMBSTONES_PER_OWNER: usize = 1_000;
126pub const MAX_CARRIER_TARGETS: usize = 16;
128pub const MAX_SCOPE_EXPIRY_AHEAD_MS: u64 = 86_400_000;
131
132#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
135#[serde(rename_all = "snake_case")]
136#[non_exhaustive]
137pub enum ScopeKind {
138 Head,
139 Worker,
140 Ephemeral,
141 Federated,
142}
143
144#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
147#[serde(deny_unknown_fields)]
148#[non_exhaustive]
149pub struct ScopeParent {
150 #[serde(deserialize_with = "deserialize_scope_principal")]
151 pub owner: Principal,
152 #[serde(rename = "ref")]
153 pub scope_ref: String,
154 pub scope_epoch: u64,
155}
156
157impl ScopeParent {
158 pub fn new(owner: Principal, scope_ref: impl Into<String>, scope_epoch: u64) -> Self {
159 Self {
160 owner,
161 scope_ref: scope_ref.into(),
162 scope_epoch,
163 }
164 }
165}
166
167#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
174#[serde(deny_unknown_fields)]
175#[non_exhaustive]
176pub struct ScopeCarrier {
177 #[serde(deserialize_with = "deserialize_scope_principal")]
178 pub principal: Principal,
179 #[serde(default, skip_serializing_if = "Option::is_none")]
180 pub targets: Option<Vec<String>>,
181}
182
183impl ScopeCarrier {
184 pub fn new(principal: Principal) -> Self {
185 Self {
186 principal,
187 targets: None,
188 }
189 }
190
191 #[must_use]
192 pub fn with_targets(mut self, targets: Option<Vec<String>>) -> Self {
193 self.targets = targets;
194 self
195 }
196}
197
198pub const FLOW_SCOPES_CAPABILITY: &str = "flow-scopes/v1";
204
205pub const FLOW_IDENTITY_SCOPES_CAPABILITY: &str = "flow-identity-scopes/v1";
208
209pub const AGENT_RUN_SCOPES_CAPABILITY: &str = "agent-run-scopes/v1";
215
216pub const SCOPE_ON_BEHALF_OF_CAPABILITY: &str = "scope-on-behalf-of/v1";
220
221pub const WORKER_RUNS_CAPABILITY: &str = "worker-runs/v1";
234
235pub const SCOPE_SERVED_BY_CAPABILITY: &str = "scope-served-by/v1";
237
238#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
246#[serde(deny_unknown_fields)]
247#[non_exhaustive]
248pub struct ScopeAttributes {
249 #[serde(default, skip_serializing_if = "Option::is_none")]
251 pub federated: Option<FederatedAttributes>,
252 #[serde(default, skip_serializing_if = "Option::is_none")]
254 pub agent_id: Option<String>,
255 #[serde(default, skip_serializing_if = "Option::is_none")]
272 pub on_behalf_of_agent: Option<String>,
273 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
275 pub delegates: bool,
276 #[serde(default, skip_serializing_if = "Option::is_none")]
292 pub flow_id: Option<String>,
293 #[serde(default, skip_serializing_if = "Option::is_none")]
298 pub flow_version: Option<u64>,
299 #[serde(default, skip_serializing_if = "Option::is_none")]
303 pub flow_code_hash: Option<String>,
304 #[serde(default, skip_serializing_if = "Option::is_none")]
308 pub flow_install_id: Option<String>,
309 #[serde(default, skip_serializing_if = "Option::is_none")]
321 pub run_id: Option<String>,
322}
323
324impl ScopeAttributes {
325 pub fn new() -> Self {
326 Self::default()
327 }
328
329 #[must_use]
330 pub fn with_federated(mut self, federated: Option<FederatedAttributes>) -> Self {
331 self.federated = federated;
332 self
333 }
334
335 #[must_use]
336 pub fn with_agent_id(mut self, agent_id: Option<String>) -> Self {
337 self.agent_id = agent_id;
338 self
339 }
340
341 #[must_use]
342 pub fn with_on_behalf_of_agent(mut self, on_behalf_of_agent: Option<String>) -> Self {
343 self.on_behalf_of_agent = on_behalf_of_agent;
344 self
345 }
346
347 #[must_use]
348 pub fn with_delegates(mut self, delegates: bool) -> Self {
349 self.delegates = delegates;
350 self
351 }
352
353 #[must_use]
354 pub fn with_flow_id(mut self, flow_id: Option<String>) -> Self {
355 self.flow_id = flow_id;
356 self
357 }
358
359 #[must_use]
360 pub fn with_flow_version(mut self, flow_version: Option<u64>) -> Self {
361 self.flow_version = flow_version;
362 self
363 }
364
365 #[must_use]
366 pub fn with_flow_code_hash(mut self, flow_code_hash: Option<String>) -> Self {
367 self.flow_code_hash = flow_code_hash;
368 self
369 }
370
371 #[must_use]
372 pub fn with_flow_install_id(mut self, flow_install_id: Option<String>) -> Self {
373 self.flow_install_id = flow_install_id;
374 self
375 }
376
377 #[must_use]
378 pub fn with_run_id(mut self, run_id: Option<String>) -> Self {
379 self.run_id = run_id;
380 self
381 }
382
383 pub fn is_empty(&self) -> bool {
384 self.federated.is_none()
385 && self.agent_id.is_none()
386 && self.on_behalf_of_agent.is_none()
387 && !self.delegates
388 && self.flow_id.is_none()
389 && self.flow_version.is_none()
390 && self.flow_code_hash.is_none()
391 && self.flow_install_id.is_none()
392 && self.run_id.is_none()
393 }
394}
395
396pub fn validate_flow_id(flow_id: &str) -> Result<(), crate::tool_call::OpaqueFieldError> {
400 crate::tool_call::validate_opaque_field("flow_id", flow_id)
401}
402
403pub fn validate_flow_version(flow_version: u64) -> Result<(), &'static str> {
406 if !(1..=9_007_199_254_740_991).contains(&flow_version) {
407 return Err("flow_version must be from 1 to 9007199254740991");
408 }
409 Ok(())
410}
411
412pub fn validate_flow_code_hash(flow_code_hash: &str) -> Result<(), &'static str> {
414 if flow_code_hash.len() != 64
415 || !flow_code_hash
416 .bytes()
417 .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
418 {
419 return Err("flow_code_hash must contain exactly 64 lowercase hex characters");
420 }
421 Ok(())
422}
423
424pub fn validate_flow_install_id(
427 flow_install_id: &str,
428) -> Result<(), crate::tool_call::OpaqueFieldError> {
429 crate::tool_call::validate_opaque_field("flow_install_id", flow_install_id)
430}
431
432pub fn validate_run_id(run_id: &str) -> Result<(), crate::tool_call::OpaqueFieldError> {
435 crate::tool_call::validate_opaque_field("run_id", run_id)
436}
437
438pub fn validate_on_behalf_of_agent(agent: &str) -> Result<(), crate::tool_call::OpaqueFieldError> {
441 crate::tool_call::validate_opaque_field("on_behalf_of_agent", agent)
442}
443
444pub const SCOPE_WORKDIR_CAPABILITY: &str = "scope-workdir/v1";
446
447pub fn validate_project_id(value: &str) -> Result<(), &'static str> {
449 if value.is_empty() || value.len() > 128 {
450 return Err("project_id must contain 1 to 128 bytes");
451 }
452 if !value.bytes().all(|byte| (0x21..=0x7e).contains(&byte)) {
453 return Err("project_id must be printable ASCII without whitespace");
454 }
455 Ok(())
456}
457
458#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
460#[serde(rename_all = "snake_case")]
461pub enum RootKeyKind {
462 Remote,
463 Label,
464}
465
466#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
470#[serde(deny_unknown_fields)]
471#[non_exhaustive]
472pub struct RootKey {
473 pub kind: RootKeyKind,
474 pub key: String,
475}
476
477impl RootKey {
478 pub fn new(kind: RootKeyKind, key: impl Into<String>) -> Self {
479 Self {
480 kind,
481 key: key.into(),
482 }
483 }
484
485 pub fn validate(&self) -> Result<(), &'static str> {
486 validate_root_key(&self.key)
487 }
488}
489
490pub fn validate_root_key(value: &str) -> Result<(), &'static str> {
492 validate_project_id(value).map_err(|error| match error {
493 "project_id must contain 1 to 128 bytes" => "root_key must contain 1 to 128 bytes",
494 _ => "root_key must be printable ASCII without whitespace",
495 })
496}
497
498#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
500#[serde(deny_unknown_fields)]
501#[non_exhaustive]
502pub struct ScopeRecord {
503 #[serde(rename = "ref")]
504 pub scope_ref: String,
505 pub scope_epoch: u64,
509 pub kind: ScopeKind,
510 #[serde(default, skip_serializing_if = "Option::is_none")]
513 pub workdir: Option<String>,
514 #[serde(default, skip_serializing_if = "Option::is_none")]
516 pub project_id: Option<String>,
517 #[serde(default, skip_serializing_if = "Option::is_none")]
521 pub root_key: Option<RootKey>,
522 #[serde(
525 default,
526 skip_serializing_if = "Option::is_none",
527 deserialize_with = "deserialize_bind_proof_sha256"
528 )]
529 pub bind_proof_sha256: Option<String>,
530 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
535 pub replace_only_if_idle: bool,
536 #[serde(default, skip_serializing_if = "Option::is_none")]
540 pub expires_at_ms: Option<u64>,
541 #[serde(default, skip_serializing_if = "Option::is_none")]
542 pub parent: Option<ScopeParent>,
543 #[serde(
546 default,
547 skip_serializing_if = "Vec::is_empty",
548 deserialize_with = "deserialize_scope_principals"
549 )]
550 pub child_owners: Vec<Principal>,
551 #[serde(default, skip_serializing_if = "Vec::is_empty")]
552 pub carriers: Vec<ScopeCarrier>,
553 #[serde(default, skip_serializing_if = "ScopeAttributes::is_empty")]
554 pub attributes: ScopeAttributes,
555}
556
557impl ScopeRecord {
558 pub fn new(scope_ref: impl Into<String>, scope_epoch: u64, kind: ScopeKind) -> Self {
559 Self {
560 scope_ref: scope_ref.into(),
561 scope_epoch,
562 kind,
563 workdir: None,
564 project_id: None,
565 root_key: None,
566 bind_proof_sha256: None,
567 replace_only_if_idle: false,
568 expires_at_ms: None,
569 parent: None,
570 child_owners: Vec::new(),
571 carriers: Vec::new(),
572 attributes: ScopeAttributes::default(),
573 }
574 }
575
576 #[must_use]
577 pub fn with_workdir(mut self, workdir: Option<String>) -> Self {
578 self.workdir = workdir;
579 self
580 }
581
582 #[must_use]
583 pub fn with_project_id(mut self, project_id: Option<String>) -> Self {
584 self.project_id = project_id;
585 self
586 }
587
588 #[must_use]
589 pub fn with_root_key(mut self, root_key: Option<RootKey>) -> Self {
590 self.root_key = root_key;
591 self
592 }
593
594 #[must_use]
595 pub fn with_bind_proof_sha256(mut self, hash: Option<String>) -> Self {
596 self.bind_proof_sha256 = hash;
597 self
598 }
599
600 #[must_use]
601 pub fn with_replace_only_if_idle(mut self, replace_only_if_idle: bool) -> Self {
602 self.replace_only_if_idle = replace_only_if_idle;
603 self
604 }
605
606 #[must_use]
607 pub fn with_expires_at_ms(mut self, expires_at_ms: Option<u64>) -> Self {
608 self.expires_at_ms = expires_at_ms;
609 self
610 }
611
612 #[must_use]
613 pub fn with_parent(mut self, parent: Option<ScopeParent>) -> Self {
614 self.parent = parent;
615 self
616 }
617
618 #[must_use]
619 pub fn with_child_owners(mut self, child_owners: Vec<Principal>) -> Self {
620 self.child_owners = child_owners;
621 self
622 }
623
624 #[must_use]
625 pub fn with_carriers(mut self, carriers: Vec<ScopeCarrier>) -> Self {
626 self.carriers = carriers;
627 self
628 }
629
630 #[must_use]
631 pub fn with_attributes(mut self, attributes: ScopeAttributes) -> Self {
632 self.attributes = attributes;
633 self
634 }
635}
636
637#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
639#[serde(deny_unknown_fields)]
640#[non_exhaustive]
641pub struct ScopeEnd {
642 #[serde(rename = "ref")]
643 pub scope_ref: String,
644 pub scope_epoch: u64,
645}
646
647impl ScopeEnd {
648 pub fn new(scope_ref: impl Into<String>, scope_epoch: u64) -> Self {
649 Self {
650 scope_ref: scope_ref.into(),
651 scope_epoch,
652 }
653 }
654}
655
656#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
658#[serde(rename_all = "snake_case")]
659pub enum ScopeEndOutcome {
660 Ended,
662 NotLive,
665}
666
667#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
669#[serde(deny_unknown_fields)]
670#[non_exhaustive]
671pub struct ScopeEndResult {
672 #[serde(rename = "ref")]
673 pub scope_ref: String,
674 pub scope_epoch: u64,
675 pub outcome: ScopeEndOutcome,
676}
677
678impl ScopeEndResult {
679 pub fn new(scope_ref: impl Into<String>, scope_epoch: u64, outcome: ScopeEndOutcome) -> Self {
680 Self {
681 scope_ref: scope_ref.into(),
682 scope_epoch,
683 outcome,
684 }
685 }
686}
687
688#[derive(Clone, Serialize, Deserialize, PartialEq, Eq)]
694#[serde(deny_unknown_fields)]
695#[non_exhaustive]
696pub struct ScopeSelector {
697 #[serde(deserialize_with = "deserialize_scope_principal")]
698 pub owner: Principal,
699 #[serde(rename = "ref")]
700 pub scope_ref: String,
701 #[serde(default, skip_serializing_if = "Option::is_none")]
702 pub scope_epoch: Option<u64>,
703 #[serde(default, skip_serializing_if = "Option::is_none")]
706 pub bind_proof: Option<String>,
707 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
710 pub hold_presence: bool,
711}
712
713impl ScopeSelector {
714 pub fn new(owner: Principal, scope_ref: impl Into<String>, scope_epoch: Option<u64>) -> Self {
715 Self {
716 owner,
717 scope_ref: scope_ref.into(),
718 scope_epoch,
719 bind_proof: None,
720 hold_presence: false,
721 }
722 }
723
724 #[must_use]
725 pub fn with_bind_proof(mut self, proof: Option<String>) -> Self {
726 self.bind_proof = proof;
727 self
728 }
729
730 #[must_use]
731 pub fn with_hold_presence(mut self, hold_presence: bool) -> Self {
732 self.hold_presence = hold_presence;
733 self
734 }
735}
736
737impl std::fmt::Debug for ScopeSelector {
738 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
739 f.debug_struct("ScopeSelector")
740 .field("owner", &self.owner)
741 .field("scope_ref", &self.scope_ref)
742 .field("scope_epoch", &self.scope_epoch)
743 .field(
744 "bind_proof",
745 &self.bind_proof.as_ref().map(|_| "<redacted>"),
746 )
747 .finish()
748 }
749}
750
751impl std::fmt::Display for ScopeSelector {
752 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
753 std::fmt::Debug::fmt(self, f)
754 }
755}
756
757#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
759#[serde(rename_all = "snake_case")]
760pub enum ParentState {
761 Linked,
763 Pending,
766 Ended,
769}
770
771#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
773#[serde(rename_all = "snake_case")]
774pub enum ScopeRecordOutcome {
775 Created,
777 Replaced,
779 Updated,
781 Unchanged,
784 Refused,
787}
788
789#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
791pub struct ScopeRecordResult {
792 #[serde(rename = "ref")]
793 pub scope_ref: String,
794 pub scope_epoch: u64,
797 pub outcome: ScopeRecordOutcome,
798 #[serde(default, skip_serializing_if = "Option::is_none")]
800 pub code: Option<String>,
801 #[serde(default, skip_serializing_if = "Option::is_none")]
802 pub message: Option<String>,
803 #[serde(default, skip_serializing_if = "Option::is_none")]
806 pub version: Option<u64>,
807 #[serde(default, skip_serializing_if = "Option::is_none")]
809 pub parent_state: Option<ParentState>,
810}
811
812#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
816pub struct ScopeEnded {
817 #[serde(rename = "ref")]
818 pub scope_ref: String,
819 pub scope_epoch: u64,
820}
821
822#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
824#[serde(rename_all = "snake_case")]
825pub enum ScopeStatus {
826 Live,
827 Ended,
829 NotLive,
835}
836
837#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
840#[non_exhaustive]
841pub struct ScopeStamp {
842 pub owner: Principal,
843 #[serde(rename = "ref")]
844 pub scope_ref: String,
845 pub scope_epoch: u64,
846 pub kind: ScopeKind,
847 #[serde(default, skip_serializing_if = "Option::is_none")]
850 pub workdir: Option<String>,
851 #[serde(default, skip_serializing_if = "Option::is_none")]
853 pub project_id: Option<String>,
854 #[serde(default, skip_serializing_if = "Option::is_none")]
858 pub root_key: Option<RootKey>,
859 #[serde(default, skip_serializing_if = "Option::is_none")]
860 pub parent: Option<ScopeParent>,
861 #[serde(default, skip_serializing_if = "Option::is_none")]
862 pub parent_state: Option<ParentState>,
863 #[serde(default, skip_serializing_if = "ScopeAttributes::is_empty")]
864 pub attributes: ScopeAttributes,
865 pub owner_authorized: bool,
869 #[serde(default, skip_serializing_if = "Option::is_none")]
874 pub expires_at_ms: Option<u64>,
875}
876
877impl ScopeStamp {
878 pub fn new(
880 owner: Principal,
881 scope_ref: impl Into<String>,
882 scope_epoch: u64,
883 kind: ScopeKind,
884 ) -> Self {
885 Self {
886 owner,
887 scope_ref: scope_ref.into(),
888 scope_epoch,
889 kind,
890 workdir: None,
891 project_id: None,
892 root_key: None,
893 parent: None,
894 parent_state: None,
895 attributes: ScopeAttributes::new(),
896 owner_authorized: false,
897 expires_at_ms: None,
898 }
899 }
900
901 #[must_use]
902 pub fn with_workdir(mut self, workdir: Option<String>) -> Self {
903 self.workdir = workdir;
904 self
905 }
906
907 #[must_use]
908 pub fn with_project_id(mut self, project_id: Option<String>) -> Self {
909 self.project_id = project_id;
910 self
911 }
912
913 #[must_use]
914 pub fn with_root_key(mut self, root_key: Option<RootKey>) -> Self {
915 self.root_key = root_key;
916 self
917 }
918
919 #[must_use]
920 pub fn with_parent(mut self, parent: Option<ScopeParent>) -> Self {
921 self.parent = parent;
922 self
923 }
924
925 #[must_use]
926 pub fn with_parent_state(mut self, parent_state: Option<ParentState>) -> Self {
927 self.parent_state = parent_state;
928 self
929 }
930
931 #[must_use]
932 pub fn with_attributes(mut self, attributes: ScopeAttributes) -> Self {
933 self.attributes = attributes;
934 self
935 }
936
937 #[must_use]
938 pub fn with_owner_authorized(mut self, owner_authorized: bool) -> Self {
939 self.owner_authorized = owner_authorized;
940 self
941 }
942
943 #[must_use]
944 pub fn with_expires_at_ms(mut self, expires_at_ms: Option<u64>) -> Self {
945 self.expires_at_ms = expires_at_ms;
946 self
947 }
948}
949
950#[cfg(test)]
951mod tests {
952 use super::*;
953 use crate::tool_call::OpaqueFieldError;
954
955 #[test]
956 fn scope_root_key_roundtrips_namespaces_and_enforces_key_bounds() {
957 for kind in [RootKeyKind::Remote, RootKeyKind::Label] {
958 for key in ["p", "!~owner/repo", &"p".repeat(128)] {
959 let root = RootKey::new(kind, key);
960 root.validate().unwrap();
961 let wire = serde_json::to_value(&root).unwrap();
962 assert_eq!(serde_json::from_value::<RootKey>(wire).unwrap(), root);
963 }
964 }
965 assert_ne!(
966 RootKey::new(RootKeyKind::Remote, "owner/repo"),
967 RootKey::new(RootKeyKind::Label, "owner/repo")
968 );
969 for key in ["", "has space", "a\n", "é", "\u{007f}", &"a".repeat(129)] {
970 let error = RootKey::new(RootKeyKind::Remote, key)
971 .validate()
972 .unwrap_err();
973 assert!(error.starts_with("root_key"));
974 assert_eq!(validate_root_key(key), Err(error));
975 }
976 for wire in [
977 serde_json::json!({"kind":"future", "key":"owner/repo"}),
978 serde_json::json!({"kind":"remote", "key":"owner/repo", "extra":true}),
979 serde_json::json!({"key":"owner/repo"}),
980 serde_json::json!({"kind":"label"}),
981 serde_json::json!("owner/repo"),
982 ] {
983 assert!(serde_json::from_value::<RootKey>(wire).is_err());
984 }
985 }
986
987 #[test]
988 fn scope_root_key_is_optional_on_records_and_stamps_and_old_stamp_readers_ignore_it() {
989 let record = ScopeRecord::new("session", 1, ScopeKind::Head);
990 assert!(serde_json::to_value(&record)
991 .unwrap()
992 .get("root_key")
993 .is_none());
994 let record = record
995 .with_project_id(Some("project".into()))
996 .with_root_key(Some(RootKey::new(RootKeyKind::Remote, "owner/repo")));
997 let wire = serde_json::to_value(&record).unwrap();
998 assert_eq!(
999 wire["root_key"],
1000 serde_json::json!({"kind":"remote", "key":"owner/repo"})
1001 );
1002 assert_eq!(serde_json::from_value::<ScopeRecord>(wire).unwrap(), record);
1003 let stamp = ScopeStamp::new(Principal::Direct, "session", 1, ScopeKind::Head);
1004 assert!(serde_json::to_value(&stamp)
1005 .unwrap()
1006 .get("root_key")
1007 .is_none());
1008 let stamp = stamp
1009 .with_project_id(record.project_id)
1010 .with_root_key(record.root_key);
1011 let wire = serde_json::to_value(&stamp).unwrap();
1012 assert_eq!(
1013 serde_json::from_value::<ScopeStamp>(wire.clone()).unwrap(),
1014 stamp
1015 );
1016 #[derive(Deserialize)]
1017 struct OldStamp {
1018 project_id: Option<String>,
1019 }
1020 let old: OldStamp = serde_json::from_value(wire).unwrap();
1021 assert_eq!(old.project_id.as_deref(), Some("project"));
1022 }
1023
1024 #[test]
1025 fn project_id_is_an_opaque_non_space_ascii_token_of_at_most_128_bytes() {
1026 for valid in ["p", "!~Project:7/path", &"p".repeat(128)] {
1027 assert_eq!(validate_project_id(valid), Ok(()));
1028 }
1029 for invalid in ["", "p p", "p\t", "pé", "p\u{7f}", &"p".repeat(129)] {
1030 assert!(validate_project_id(invalid).is_err(), "{invalid:?}");
1031 }
1032 }
1033
1034 #[test]
1035 fn scope_project_fields_round_trip_and_absence_keeps_exact_bytes() {
1036 let record = ScopeRecord::new("session", 1, ScopeKind::Head);
1037 assert_eq!(
1038 serde_json::to_string(&record).unwrap(),
1039 r#"{"ref":"session","scope_epoch":1,"kind":"head"}"#
1040 );
1041 let record = record
1042 .with_workdir(Some("/folder".into()))
1043 .with_project_id(Some("project:1".into()));
1044 let encoded = serde_json::to_string(&record).unwrap();
1045 assert_eq!(
1046 serde_json::from_str::<ScopeRecord>(&encoded).unwrap(),
1047 record
1048 );
1049 let stamp = ScopeStamp::new(Principal::Direct, "session", 1, ScopeKind::Head);
1050 assert_eq!(
1051 serde_json::to_string(&stamp).unwrap(),
1052 r#"{"owner":{"kind":"direct"},"ref":"session","scope_epoch":1,"kind":"head","owner_authorized":false}"#
1053 );
1054 let stamp = stamp
1055 .with_workdir(record.workdir)
1056 .with_project_id(record.project_id);
1057 let encoded = serde_json::to_string(&stamp).unwrap();
1058 assert_eq!(serde_json::from_str::<ScopeStamp>(&encoded).unwrap(), stamp);
1059 }
1060
1061 #[test]
1062 fn flow_id_uses_the_shared_opaque_token_bounds_and_names_its_field() {
1063 let field = "flow_id";
1064 assert_eq!(validate_flow_id(""), Err(OpaqueFieldError::Empty { field }));
1065 assert_eq!(validate_flow_id("f"), Ok(()));
1066 assert_eq!(validate_flow_id(&"f".repeat(256)), Ok(()));
1067 assert_eq!(
1068 validate_flow_id(&"f".repeat(257)),
1069 Err(OpaqueFieldError::TooLong { field, length: 257 })
1070 );
1071 assert_eq!(validate_flow_id("!~Flow:7/step"), Ok(()));
1072 for bad in ["f é", "f\t", "fé", "f\u{7f}"] {
1073 let error = validate_flow_id(bad).unwrap_err();
1074 assert_eq!(
1075 error,
1076 OpaqueFieldError::InvalidCharacter { field, index: 1 }
1077 );
1078 assert_eq!(error.field(), "flow_id");
1079 }
1080 }
1081
1082 #[test]
1083 fn flow_identity_validators_enforce_boundaries_and_name_fields() {
1084 for valid in [1, 9_007_199_254_740_991] {
1085 assert_eq!(validate_flow_version(valid), Ok(()));
1086 }
1087 for invalid in [0, 9_007_199_254_740_992, u64::MAX] {
1088 assert!(validate_flow_version(invalid)
1089 .unwrap_err()
1090 .contains("flow_version"));
1091 }
1092 assert_eq!(
1093 validate_flow_code_hash(&"0123456789abcdef".repeat(4)),
1094 Ok(())
1095 );
1096 for invalid in [
1097 "a".repeat(63),
1098 "a".repeat(65),
1099 "A".repeat(64),
1100 "g".repeat(64),
1101 ] {
1102 assert!(validate_flow_code_hash(&invalid)
1103 .unwrap_err()
1104 .contains("flow_code_hash"));
1105 }
1106 for valid in ["i", "!~Install:7/path", &"i".repeat(256)] {
1107 assert_eq!(validate_flow_install_id(valid), Ok(()));
1108 }
1109 for invalid in ["", "i i", "i\t", "ié", "i\u{7f}", &"i".repeat(257)] {
1110 assert_eq!(
1111 validate_flow_install_id(invalid).unwrap_err().field(),
1112 "flow_install_id"
1113 );
1114 }
1115 }
1116
1117 #[test]
1118 fn flow_identity_round_trips_and_legacy_stamp_keeps_exact_bytes() {
1119 let attributes = ScopeAttributes::new().with_flow_id(Some("flow:7".into()));
1120 let stamp = ScopeStamp::new(Principal::Direct, "session", 1, ScopeKind::Head)
1121 .with_attributes(attributes.clone());
1122 assert_eq!(
1123 serde_json::to_string(&stamp).unwrap(),
1124 r#"{"owner":{"kind":"direct"},"ref":"session","scope_epoch":1,"kind":"head","attributes":{"flow_id":"flow:7"},"owner_authorized":false}"#
1125 );
1126 let attributes = attributes
1127 .with_flow_version(Some(9_007_199_254_740_991))
1128 .with_flow_code_hash(Some("a".repeat(64)))
1129 .with_flow_install_id(Some("install:7".into()));
1130 let stamp = stamp.with_attributes(attributes.clone());
1131 let encoded = serde_json::to_string(&stamp).unwrap();
1132 assert_eq!(serde_json::from_str::<ScopeStamp>(&encoded).unwrap(), stamp);
1133 assert_eq!(
1134 serde_json::from_str::<ScopeAttributes>(&serde_json::to_string(&attributes).unwrap())
1135 .unwrap(),
1136 attributes
1137 );
1138 assert!(
1139 serde_json::from_str::<ScopeAttributes>(r#"{"flow_version":1,"unknown":true}"#)
1140 .is_err()
1141 );
1142 assert!(!ScopeAttributes::new().with_flow_version(Some(1)).is_empty());
1143 assert!(!ScopeAttributes::new()
1144 .with_flow_code_hash(Some("a".repeat(64)))
1145 .is_empty());
1146 assert!(!ScopeAttributes::new()
1147 .with_flow_install_id(Some("i".into()))
1148 .is_empty());
1149 }
1150
1151 #[test]
1152 fn flow_only_attributes_round_trip_and_absence_keeps_the_bytes() {
1153 let attributes = ScopeAttributes::default();
1154 assert!(attributes.is_empty());
1155 assert_eq!(serde_json::to_string(&attributes).unwrap(), "{}");
1156 assert_eq!(
1157 serde_json::from_str::<ScopeAttributes>("{}").unwrap(),
1158 attributes
1159 );
1160 let attributes = ScopeAttributes {
1161 flow_id: Some("flow:7".to_string()),
1162 ..ScopeAttributes::default()
1163 };
1164 assert!(!attributes.is_empty());
1165 let encoded = serde_json::to_string(&attributes).unwrap();
1166 assert_eq!(encoded, r#"{"flow_id":"flow:7"}"#);
1167 assert_eq!(
1168 serde_json::from_str::<ScopeAttributes>(&encoded).unwrap(),
1169 attributes
1170 );
1171 assert!(
1172 serde_json::from_str::<ScopeAttributes>(r#"{"flow_id":"flow:7","unknown":true}"#)
1173 .is_err()
1174 );
1175 }
1176}