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
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, Copy, Serialize, Deserialize, PartialEq, Eq)]
453#[serde(rename_all = "snake_case")]
454pub enum RootKeyKind {
455 Remote,
456 Label,
457}
458
459#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
463#[serde(deny_unknown_fields)]
464#[non_exhaustive]
465pub struct RootKey {
466 pub kind: RootKeyKind,
467 pub key: String,
468}
469
470impl RootKey {
471 pub fn new(kind: RootKeyKind, key: impl Into<String>) -> Self {
472 Self {
473 kind,
474 key: key.into(),
475 }
476 }
477
478 pub fn validate(&self) -> Result<(), &'static str> {
479 validate_root_key(&self.key)
480 }
481}
482
483pub fn validate_root_key(value: &str) -> Result<(), &'static str> {
485 validate_project_id(value).map_err(|error| match error {
486 "project_id must contain 1 to 128 bytes" => "root_key must contain 1 to 128 bytes",
487 _ => "root_key must be printable ASCII without whitespace",
488 })
489}
490
491#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
493#[serde(deny_unknown_fields)]
494#[non_exhaustive]
495pub struct ScopeRecord {
496 #[serde(rename = "ref")]
497 pub scope_ref: String,
498 pub scope_epoch: u64,
502 pub kind: ScopeKind,
503 #[serde(default, skip_serializing_if = "Option::is_none")]
506 pub workdir: Option<String>,
507 #[serde(default, skip_serializing_if = "Option::is_none")]
509 pub project_id: Option<String>,
510 #[serde(default, skip_serializing_if = "Option::is_none")]
514 pub root_key: Option<RootKey>,
515 #[serde(
518 default,
519 skip_serializing_if = "Option::is_none",
520 deserialize_with = "deserialize_bind_proof_sha256"
521 )]
522 pub bind_proof_sha256: Option<String>,
523 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
528 pub replace_only_if_idle: bool,
529 #[serde(default, skip_serializing_if = "Option::is_none")]
533 pub expires_at_ms: Option<u64>,
534 #[serde(default, skip_serializing_if = "Option::is_none")]
535 pub parent: Option<ScopeParent>,
536 #[serde(
539 default,
540 skip_serializing_if = "Vec::is_empty",
541 deserialize_with = "deserialize_scope_principals"
542 )]
543 pub child_owners: Vec<Principal>,
544 #[serde(default, skip_serializing_if = "Vec::is_empty")]
545 pub carriers: Vec<ScopeCarrier>,
546 #[serde(default, skip_serializing_if = "ScopeAttributes::is_empty")]
547 pub attributes: ScopeAttributes,
548}
549
550impl ScopeRecord {
551 pub fn new(scope_ref: impl Into<String>, scope_epoch: u64, kind: ScopeKind) -> Self {
552 Self {
553 scope_ref: scope_ref.into(),
554 scope_epoch,
555 kind,
556 workdir: None,
557 project_id: None,
558 root_key: None,
559 bind_proof_sha256: None,
560 replace_only_if_idle: false,
561 expires_at_ms: None,
562 parent: None,
563 child_owners: Vec::new(),
564 carriers: Vec::new(),
565 attributes: ScopeAttributes::default(),
566 }
567 }
568
569 #[must_use]
570 pub fn with_workdir(mut self, workdir: Option<String>) -> Self {
571 self.workdir = workdir;
572 self
573 }
574
575 #[must_use]
576 pub fn with_project_id(mut self, project_id: Option<String>) -> Self {
577 self.project_id = project_id;
578 self
579 }
580
581 #[must_use]
582 pub fn with_root_key(mut self, root_key: Option<RootKey>) -> Self {
583 self.root_key = root_key;
584 self
585 }
586
587 #[must_use]
588 pub fn with_bind_proof_sha256(mut self, hash: Option<String>) -> Self {
589 self.bind_proof_sha256 = hash;
590 self
591 }
592
593 #[must_use]
594 pub fn with_replace_only_if_idle(mut self, replace_only_if_idle: bool) -> Self {
595 self.replace_only_if_idle = replace_only_if_idle;
596 self
597 }
598
599 #[must_use]
600 pub fn with_expires_at_ms(mut self, expires_at_ms: Option<u64>) -> Self {
601 self.expires_at_ms = expires_at_ms;
602 self
603 }
604
605 #[must_use]
606 pub fn with_parent(mut self, parent: Option<ScopeParent>) -> Self {
607 self.parent = parent;
608 self
609 }
610
611 #[must_use]
612 pub fn with_child_owners(mut self, child_owners: Vec<Principal>) -> Self {
613 self.child_owners = child_owners;
614 self
615 }
616
617 #[must_use]
618 pub fn with_carriers(mut self, carriers: Vec<ScopeCarrier>) -> Self {
619 self.carriers = carriers;
620 self
621 }
622
623 #[must_use]
624 pub fn with_attributes(mut self, attributes: ScopeAttributes) -> Self {
625 self.attributes = attributes;
626 self
627 }
628}
629
630#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
632#[serde(deny_unknown_fields)]
633#[non_exhaustive]
634pub struct ScopeEnd {
635 #[serde(rename = "ref")]
636 pub scope_ref: String,
637 pub scope_epoch: u64,
638}
639
640impl ScopeEnd {
641 pub fn new(scope_ref: impl Into<String>, scope_epoch: u64) -> Self {
642 Self {
643 scope_ref: scope_ref.into(),
644 scope_epoch,
645 }
646 }
647}
648
649#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
651#[serde(rename_all = "snake_case")]
652pub enum ScopeEndOutcome {
653 Ended,
655 NotLive,
658}
659
660#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
662#[serde(deny_unknown_fields)]
663#[non_exhaustive]
664pub struct ScopeEndResult {
665 #[serde(rename = "ref")]
666 pub scope_ref: String,
667 pub scope_epoch: u64,
668 pub outcome: ScopeEndOutcome,
669}
670
671impl ScopeEndResult {
672 pub fn new(scope_ref: impl Into<String>, scope_epoch: u64, outcome: ScopeEndOutcome) -> Self {
673 Self {
674 scope_ref: scope_ref.into(),
675 scope_epoch,
676 outcome,
677 }
678 }
679}
680
681#[derive(Clone, Serialize, Deserialize, PartialEq, Eq)]
687#[serde(deny_unknown_fields)]
688#[non_exhaustive]
689pub struct ScopeSelector {
690 #[serde(deserialize_with = "deserialize_scope_principal")]
691 pub owner: Principal,
692 #[serde(rename = "ref")]
693 pub scope_ref: String,
694 #[serde(default, skip_serializing_if = "Option::is_none")]
695 pub scope_epoch: Option<u64>,
696 #[serde(default, skip_serializing_if = "Option::is_none")]
699 pub bind_proof: Option<String>,
700 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
703 pub hold_presence: bool,
704}
705
706impl ScopeSelector {
707 pub fn new(owner: Principal, scope_ref: impl Into<String>, scope_epoch: Option<u64>) -> Self {
708 Self {
709 owner,
710 scope_ref: scope_ref.into(),
711 scope_epoch,
712 bind_proof: None,
713 hold_presence: false,
714 }
715 }
716
717 #[must_use]
718 pub fn with_bind_proof(mut self, proof: Option<String>) -> Self {
719 self.bind_proof = proof;
720 self
721 }
722
723 #[must_use]
724 pub fn with_hold_presence(mut self, hold_presence: bool) -> Self {
725 self.hold_presence = hold_presence;
726 self
727 }
728}
729
730impl std::fmt::Debug for ScopeSelector {
731 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
732 f.debug_struct("ScopeSelector")
733 .field("owner", &self.owner)
734 .field("scope_ref", &self.scope_ref)
735 .field("scope_epoch", &self.scope_epoch)
736 .field(
737 "bind_proof",
738 &self.bind_proof.as_ref().map(|_| "<redacted>"),
739 )
740 .finish()
741 }
742}
743
744impl std::fmt::Display for ScopeSelector {
745 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
746 std::fmt::Debug::fmt(self, f)
747 }
748}
749
750#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
752#[serde(rename_all = "snake_case")]
753pub enum ParentState {
754 Linked,
756 Pending,
759 Ended,
762}
763
764#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
766#[serde(rename_all = "snake_case")]
767pub enum ScopeRecordOutcome {
768 Created,
770 Replaced,
772 Updated,
774 Unchanged,
777 Refused,
780}
781
782#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
784pub struct ScopeRecordResult {
785 #[serde(rename = "ref")]
786 pub scope_ref: String,
787 pub scope_epoch: u64,
790 pub outcome: ScopeRecordOutcome,
791 #[serde(default, skip_serializing_if = "Option::is_none")]
793 pub code: Option<String>,
794 #[serde(default, skip_serializing_if = "Option::is_none")]
795 pub message: Option<String>,
796 #[serde(default, skip_serializing_if = "Option::is_none")]
799 pub version: Option<u64>,
800 #[serde(default, skip_serializing_if = "Option::is_none")]
802 pub parent_state: Option<ParentState>,
803}
804
805#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
809pub struct ScopeEnded {
810 #[serde(rename = "ref")]
811 pub scope_ref: String,
812 pub scope_epoch: u64,
813}
814
815#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
817#[serde(rename_all = "snake_case")]
818pub enum ScopeStatus {
819 Live,
820 Ended,
822 NotLive,
828}
829
830#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
833#[non_exhaustive]
834pub struct ScopeStamp {
835 pub owner: Principal,
836 #[serde(rename = "ref")]
837 pub scope_ref: String,
838 pub scope_epoch: u64,
839 pub kind: ScopeKind,
840 #[serde(default, skip_serializing_if = "Option::is_none")]
843 pub workdir: Option<String>,
844 #[serde(default, skip_serializing_if = "Option::is_none")]
846 pub project_id: Option<String>,
847 #[serde(default, skip_serializing_if = "Option::is_none")]
851 pub root_key: Option<RootKey>,
852 #[serde(default, skip_serializing_if = "Option::is_none")]
853 pub parent: Option<ScopeParent>,
854 #[serde(default, skip_serializing_if = "Option::is_none")]
855 pub parent_state: Option<ParentState>,
856 #[serde(default, skip_serializing_if = "ScopeAttributes::is_empty")]
857 pub attributes: ScopeAttributes,
858 pub owner_authorized: bool,
862 #[serde(default, skip_serializing_if = "Option::is_none")]
867 pub expires_at_ms: Option<u64>,
868}
869
870impl ScopeStamp {
871 pub fn new(
873 owner: Principal,
874 scope_ref: impl Into<String>,
875 scope_epoch: u64,
876 kind: ScopeKind,
877 ) -> Self {
878 Self {
879 owner,
880 scope_ref: scope_ref.into(),
881 scope_epoch,
882 kind,
883 workdir: None,
884 project_id: None,
885 root_key: None,
886 parent: None,
887 parent_state: None,
888 attributes: ScopeAttributes::new(),
889 owner_authorized: false,
890 expires_at_ms: None,
891 }
892 }
893
894 #[must_use]
895 pub fn with_workdir(mut self, workdir: Option<String>) -> Self {
896 self.workdir = workdir;
897 self
898 }
899
900 #[must_use]
901 pub fn with_project_id(mut self, project_id: Option<String>) -> Self {
902 self.project_id = project_id;
903 self
904 }
905
906 #[must_use]
907 pub fn with_root_key(mut self, root_key: Option<RootKey>) -> Self {
908 self.root_key = root_key;
909 self
910 }
911
912 #[must_use]
913 pub fn with_parent(mut self, parent: Option<ScopeParent>) -> Self {
914 self.parent = parent;
915 self
916 }
917
918 #[must_use]
919 pub fn with_parent_state(mut self, parent_state: Option<ParentState>) -> Self {
920 self.parent_state = parent_state;
921 self
922 }
923
924 #[must_use]
925 pub fn with_attributes(mut self, attributes: ScopeAttributes) -> Self {
926 self.attributes = attributes;
927 self
928 }
929
930 #[must_use]
931 pub fn with_owner_authorized(mut self, owner_authorized: bool) -> Self {
932 self.owner_authorized = owner_authorized;
933 self
934 }
935
936 #[must_use]
937 pub fn with_expires_at_ms(mut self, expires_at_ms: Option<u64>) -> Self {
938 self.expires_at_ms = expires_at_ms;
939 self
940 }
941}
942
943#[cfg(test)]
944mod tests {
945 use super::*;
946 use crate::tool_call::OpaqueFieldError;
947
948 #[test]
949 fn scope_root_key_roundtrips_namespaces_and_enforces_key_bounds() {
950 for kind in [RootKeyKind::Remote, RootKeyKind::Label] {
951 for key in ["p", "!~owner/repo", &"p".repeat(128)] {
952 let root = RootKey::new(kind, key);
953 root.validate().unwrap();
954 let wire = serde_json::to_value(&root).unwrap();
955 assert_eq!(serde_json::from_value::<RootKey>(wire).unwrap(), root);
956 }
957 }
958 assert_ne!(
959 RootKey::new(RootKeyKind::Remote, "owner/repo"),
960 RootKey::new(RootKeyKind::Label, "owner/repo")
961 );
962 for key in ["", "has space", "a\n", "é", "\u{007f}", &"a".repeat(129)] {
963 let error = RootKey::new(RootKeyKind::Remote, key)
964 .validate()
965 .unwrap_err();
966 assert!(error.starts_with("root_key"));
967 assert_eq!(validate_root_key(key), Err(error));
968 }
969 for wire in [
970 serde_json::json!({"kind":"future", "key":"owner/repo"}),
971 serde_json::json!({"kind":"remote", "key":"owner/repo", "extra":true}),
972 serde_json::json!({"key":"owner/repo"}),
973 serde_json::json!({"kind":"label"}),
974 serde_json::json!("owner/repo"),
975 ] {
976 assert!(serde_json::from_value::<RootKey>(wire).is_err());
977 }
978 }
979
980 #[test]
981 fn scope_root_key_is_optional_on_records_and_stamps_and_old_stamp_readers_ignore_it() {
982 let record = ScopeRecord::new("session", 1, ScopeKind::Head);
983 assert!(serde_json::to_value(&record)
984 .unwrap()
985 .get("root_key")
986 .is_none());
987 let record = record
988 .with_project_id(Some("project".into()))
989 .with_root_key(Some(RootKey::new(RootKeyKind::Remote, "owner/repo")));
990 let wire = serde_json::to_value(&record).unwrap();
991 assert_eq!(
992 wire["root_key"],
993 serde_json::json!({"kind":"remote", "key":"owner/repo"})
994 );
995 assert_eq!(serde_json::from_value::<ScopeRecord>(wire).unwrap(), record);
996 let stamp = ScopeStamp::new(Principal::Direct, "session", 1, ScopeKind::Head);
997 assert!(serde_json::to_value(&stamp)
998 .unwrap()
999 .get("root_key")
1000 .is_none());
1001 let stamp = stamp
1002 .with_project_id(record.project_id)
1003 .with_root_key(record.root_key);
1004 let wire = serde_json::to_value(&stamp).unwrap();
1005 assert_eq!(
1006 serde_json::from_value::<ScopeStamp>(wire.clone()).unwrap(),
1007 stamp
1008 );
1009 #[derive(Deserialize)]
1010 struct OldStamp {
1011 project_id: Option<String>,
1012 }
1013 let old: OldStamp = serde_json::from_value(wire).unwrap();
1014 assert_eq!(old.project_id.as_deref(), Some("project"));
1015 }
1016
1017 #[test]
1018 fn project_id_is_an_opaque_non_space_ascii_token_of_at_most_128_bytes() {
1019 for valid in ["p", "!~Project:7/path", &"p".repeat(128)] {
1020 assert_eq!(validate_project_id(valid), Ok(()));
1021 }
1022 for invalid in ["", "p p", "p\t", "pé", "p\u{7f}", &"p".repeat(129)] {
1023 assert!(validate_project_id(invalid).is_err(), "{invalid:?}");
1024 }
1025 }
1026
1027 #[test]
1028 fn scope_project_fields_round_trip_and_absence_keeps_exact_bytes() {
1029 let record = ScopeRecord::new("session", 1, ScopeKind::Head);
1030 assert_eq!(
1031 serde_json::to_string(&record).unwrap(),
1032 r#"{"ref":"session","scope_epoch":1,"kind":"head"}"#
1033 );
1034 let record = record
1035 .with_workdir(Some("/folder".into()))
1036 .with_project_id(Some("project:1".into()));
1037 let encoded = serde_json::to_string(&record).unwrap();
1038 assert_eq!(
1039 serde_json::from_str::<ScopeRecord>(&encoded).unwrap(),
1040 record
1041 );
1042 let stamp = ScopeStamp::new(Principal::Direct, "session", 1, ScopeKind::Head);
1043 assert_eq!(
1044 serde_json::to_string(&stamp).unwrap(),
1045 r#"{"owner":{"kind":"direct"},"ref":"session","scope_epoch":1,"kind":"head","owner_authorized":false}"#
1046 );
1047 let stamp = stamp
1048 .with_workdir(record.workdir)
1049 .with_project_id(record.project_id);
1050 let encoded = serde_json::to_string(&stamp).unwrap();
1051 assert_eq!(serde_json::from_str::<ScopeStamp>(&encoded).unwrap(), stamp);
1052 }
1053
1054 #[test]
1055 fn flow_id_uses_the_shared_opaque_token_bounds_and_names_its_field() {
1056 let field = "flow_id";
1057 assert_eq!(validate_flow_id(""), Err(OpaqueFieldError::Empty { field }));
1058 assert_eq!(validate_flow_id("f"), Ok(()));
1059 assert_eq!(validate_flow_id(&"f".repeat(256)), Ok(()));
1060 assert_eq!(
1061 validate_flow_id(&"f".repeat(257)),
1062 Err(OpaqueFieldError::TooLong { field, length: 257 })
1063 );
1064 assert_eq!(validate_flow_id("!~Flow:7/step"), Ok(()));
1065 for bad in ["f é", "f\t", "fé", "f\u{7f}"] {
1066 let error = validate_flow_id(bad).unwrap_err();
1067 assert_eq!(
1068 error,
1069 OpaqueFieldError::InvalidCharacter { field, index: 1 }
1070 );
1071 assert_eq!(error.field(), "flow_id");
1072 }
1073 }
1074
1075 #[test]
1076 fn flow_identity_validators_enforce_boundaries_and_name_fields() {
1077 for valid in [1, 9_007_199_254_740_991] {
1078 assert_eq!(validate_flow_version(valid), Ok(()));
1079 }
1080 for invalid in [0, 9_007_199_254_740_992, u64::MAX] {
1081 assert!(validate_flow_version(invalid)
1082 .unwrap_err()
1083 .contains("flow_version"));
1084 }
1085 assert_eq!(
1086 validate_flow_code_hash(&"0123456789abcdef".repeat(4)),
1087 Ok(())
1088 );
1089 for invalid in [
1090 "a".repeat(63),
1091 "a".repeat(65),
1092 "A".repeat(64),
1093 "g".repeat(64),
1094 ] {
1095 assert!(validate_flow_code_hash(&invalid)
1096 .unwrap_err()
1097 .contains("flow_code_hash"));
1098 }
1099 for valid in ["i", "!~Install:7/path", &"i".repeat(256)] {
1100 assert_eq!(validate_flow_install_id(valid), Ok(()));
1101 }
1102 for invalid in ["", "i i", "i\t", "ié", "i\u{7f}", &"i".repeat(257)] {
1103 assert_eq!(
1104 validate_flow_install_id(invalid).unwrap_err().field(),
1105 "flow_install_id"
1106 );
1107 }
1108 }
1109
1110 #[test]
1111 fn flow_identity_round_trips_and_legacy_stamp_keeps_exact_bytes() {
1112 let attributes = ScopeAttributes::new().with_flow_id(Some("flow:7".into()));
1113 let stamp = ScopeStamp::new(Principal::Direct, "session", 1, ScopeKind::Head)
1114 .with_attributes(attributes.clone());
1115 assert_eq!(
1116 serde_json::to_string(&stamp).unwrap(),
1117 r#"{"owner":{"kind":"direct"},"ref":"session","scope_epoch":1,"kind":"head","attributes":{"flow_id":"flow:7"},"owner_authorized":false}"#
1118 );
1119 let attributes = attributes
1120 .with_flow_version(Some(9_007_199_254_740_991))
1121 .with_flow_code_hash(Some("a".repeat(64)))
1122 .with_flow_install_id(Some("install:7".into()));
1123 let stamp = stamp.with_attributes(attributes.clone());
1124 let encoded = serde_json::to_string(&stamp).unwrap();
1125 assert_eq!(serde_json::from_str::<ScopeStamp>(&encoded).unwrap(), stamp);
1126 assert_eq!(
1127 serde_json::from_str::<ScopeAttributes>(&serde_json::to_string(&attributes).unwrap())
1128 .unwrap(),
1129 attributes
1130 );
1131 assert!(
1132 serde_json::from_str::<ScopeAttributes>(r#"{"flow_version":1,"unknown":true}"#)
1133 .is_err()
1134 );
1135 assert!(!ScopeAttributes::new().with_flow_version(Some(1)).is_empty());
1136 assert!(!ScopeAttributes::new()
1137 .with_flow_code_hash(Some("a".repeat(64)))
1138 .is_empty());
1139 assert!(!ScopeAttributes::new()
1140 .with_flow_install_id(Some("i".into()))
1141 .is_empty());
1142 }
1143
1144 #[test]
1145 fn flow_only_attributes_round_trip_and_absence_keeps_the_bytes() {
1146 let attributes = ScopeAttributes::default();
1147 assert!(attributes.is_empty());
1148 assert_eq!(serde_json::to_string(&attributes).unwrap(), "{}");
1149 assert_eq!(
1150 serde_json::from_str::<ScopeAttributes>("{}").unwrap(),
1151 attributes
1152 );
1153 let attributes = ScopeAttributes {
1154 flow_id: Some("flow:7".to_string()),
1155 ..ScopeAttributes::default()
1156 };
1157 assert!(!attributes.is_empty());
1158 let encoded = serde_json::to_string(&attributes).unwrap();
1159 assert_eq!(encoded, r#"{"flow_id":"flow:7"}"#);
1160 assert_eq!(
1161 serde_json::from_str::<ScopeAttributes>(&encoded).unwrap(),
1162 attributes
1163 );
1164 assert!(
1165 serde_json::from_str::<ScopeAttributes>(r#"{"flow_id":"flow:7","unknown":true}"#)
1166 .is_err()
1167 );
1168 }
1169}