context.rs (22601B)
1 //! Exact captured-context descriptors. These values authenticate no principal 2 //! and grant no command permission, approval or stock authority. 3 4 use crate::{ 5 ApprovalIntentDigest, CheckpointDigest, ExecutorId, GrantId, OperationId, OrderId, RecordId, 6 RouteDigest, SourceId, WorkspaceId, 7 }; 8 use alloc::{boxed::Box, string::String, vec::Vec}; 9 use core::{fmt, str::FromStr}; 10 use radroots_identity::PublicKey; 11 12 /// Maximum sequence or authority generation supported by every governed host. 13 const MAX_SEQUENCE: u64 = i64::MAX as u64; 14 const MAX_UNIX_SECONDS: u64 = 253_402_300_799; 15 const MAX_MISSING: usize = 128; 16 17 /// A fixed descriptor failure with no retained caller input. 18 #[derive(Clone, Copy, Debug, Eq, PartialEq)] 19 #[non_exhaustive] 20 pub enum ContextError { 21 /// An integer has a noncanonical decimal representation. 22 InvalidInteger, 23 /// A value exceeds the shared bound or requires a positive value. 24 OutOfRange, 25 /// Bounded diagnostic or scope text is invalid. 26 InvalidText, 27 /// A checkpoint has more missing references than supported. 28 TooManyReferences, 29 /// Satisfied coverage cannot retain missing references. 30 InconsistentCoverage, 31 } 32 impl fmt::Display for ContextError { 33 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 34 f.write_str(match self { 35 Self::InvalidInteger => "context integer is not canonical", 36 Self::OutOfRange => "context value is out of range", 37 Self::InvalidText => "context text is invalid", 38 Self::TooManyReferences => "checkpoint reference limit exceeded", 39 Self::InconsistentCoverage => "checkpoint coverage is inconsistent", 40 }) 41 } 42 } 43 impl core::error::Error for ContextError {} 44 45 fn integer(value: &str, max: u64, positive: bool) -> Result<u64, ContextError> { 46 if value.is_empty() 47 || value.len() > 20 48 || (value.len() > 1 && value.starts_with('0')) 49 || !value.bytes().all(|b| b.is_ascii_digit()) 50 { 51 return Err(ContextError::InvalidInteger); 52 } 53 let number = value.parse::<u64>().map_err(|_| ContextError::OutOfRange)?; 54 if number > max || (positive && number == 0) { 55 return Err(ContextError::OutOfRange); 56 } 57 Ok(number) 58 } 59 macro_rules! exact_integer { 60 ($name:ident,$doc:literal,$max:expr,$positive:expr) => { 61 #[doc=$doc] 62 #[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)] 63 pub struct $name(u64); 64 impl $name { 65 /// Checks the cross-host range without coercing or rounding. 66 pub const fn new(value: u64) -> Result<Self, ContextError> { 67 if value > $max || ($positive && value == 0) { 68 Err(ContextError::OutOfRange) 69 } else { 70 Ok(Self(value)) 71 } 72 } 73 /// Returns the exact integer for checked host operations. 74 pub const fn get(self) -> u64 { 75 self.0 76 } 77 } 78 impl FromStr for $name { 79 type Err = ContextError; 80 fn from_str(value: &str) -> Result<Self, Self::Err> { 81 integer(value, $max, $positive).map(Self) 82 } 83 } 84 impl fmt::Display for $name { 85 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 86 write!(f, "{}", self.0) 87 } 88 } 89 #[cfg(feature = "serde")] 90 impl serde::Serialize for $name { 91 fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> { 92 s.collect_str(self) 93 } 94 } 95 #[cfg(feature = "serde")] 96 impl<'de> serde::Deserialize<'de> for $name { 97 fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> { 98 struct Visitor; 99 impl serde::de::Visitor<'_> for Visitor { 100 type Value = $name; 101 fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 102 f.write_str("a bounded canonical decimal string") 103 } 104 fn visit_str<E: serde::de::Error>(self, value: &str) -> Result<$name, E> { 105 value.parse().map_err(E::custom) 106 } 107 } 108 d.deserialize_str(Visitor) 109 } 110 } 111 }; 112 } 113 exact_integer!( 114 Sequence, 115 "A canonical sequence, including an explicit genesis zero.", 116 MAX_SEQUENCE, 117 false 118 ); 119 exact_integer!( 120 Generation, 121 "A positive authority generation, independent of cache cursors.", 122 MAX_SEQUENCE, 123 true 124 ); 125 exact_integer!( 126 UnixSeconds, 127 "Exact bounded Unix seconds serialized as a decimal string.", 128 MAX_UNIX_SECONDS, 129 false 130 ); 131 132 /// A participant's requested business role; this is not permission evidence. 133 #[derive(Clone, Copy, Debug, Eq, PartialEq)] 134 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] 135 #[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))] 136 #[non_exhaustive] 137 pub enum ActorRole { 138 /// The seller participant. 139 Seller, 140 /// The buyer participant. 141 Buyer, 142 /// A separately granted logistics coordinator. 143 Coordinator, 144 } 145 /// An untrusted actor descriptor. Grant origin and scope require authentication. 146 #[derive(Clone, Copy, Debug, Eq, PartialEq)] 147 #[cfg_attr(feature = "serde", derive(serde::Serialize))] 148 pub struct ActorRef { 149 participant: PublicKey, 150 role: ActorRole, 151 organization: Option<PublicKey>, 152 grant_id: Option<GrantId>, 153 } 154 impl ActorRef { 155 /// Captures validated values without authenticating their relationship. 156 pub const fn new( 157 participant: PublicKey, 158 role: ActorRole, 159 organization: Option<PublicKey>, 160 grant_id: Option<GrantId>, 161 ) -> Self { 162 Self { 163 participant, 164 role, 165 organization, 166 grant_id, 167 } 168 } 169 /// Returns the claimed participant. 170 pub const fn participant(self) -> PublicKey { 171 self.participant 172 } 173 /// Returns the requested role. 174 pub const fn role(self) -> ActorRole { 175 self.role 176 } 177 /// Returns the represented organization, if supplied. 178 pub const fn organization(self) -> Option<PublicKey> { 179 self.organization 180 } 181 /// Returns a grant selector, never its credential. 182 pub const fn grant_id(self) -> Option<GrantId> { 183 self.grant_id 184 } 185 } 186 /// Exact selected executor and authority epoch, without an authority certificate. 187 #[derive(Clone, Copy, Debug, Eq, PartialEq)] 188 #[cfg_attr(feature = "serde", derive(serde::Serialize))] 189 pub struct AuthorityRef { 190 executor_id: ExecutorId, 191 generation: Generation, 192 } 193 impl AuthorityRef { 194 /// Captures one exact selected executor/generation pair. 195 pub const fn new(executor_id: ExecutorId, generation: Generation) -> Self { 196 Self { 197 executor_id, 198 generation, 199 } 200 } 201 /// Returns the selected executor. 202 pub const fn executor_id(self) -> ExecutorId { 203 self.executor_id 204 } 205 /// Returns the authority generation. 206 pub const fn generation(self) -> Generation { 207 self.generation 208 } 209 } 210 /// Described checkpoint coverage, independently verified by the execution owner. 211 #[derive(Clone, Copy, Debug, Eq, PartialEq)] 212 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] 213 #[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))] 214 #[non_exhaustive] 215 pub enum Coverage { 216 /// Coverage is incomplete or unknown within its scope. 217 Partial, 218 /// The named scope has no reported missing references. 219 ScopeSatisfied, 220 } 221 /// A bounded checkpoint descriptor; it is neither a stock authority nor a proof. 222 #[derive(Clone, Debug, Eq, PartialEq)] 223 #[cfg_attr(feature = "serde", derive(serde::Serialize))] 224 pub struct CheckpointRef { 225 digest: CheckpointDigest, 226 sequence: Sequence, 227 coverage: Coverage, 228 missing: Box<[SourceId]>, 229 } 230 impl CheckpointRef { 231 /// Captures bounded, internally consistent coverage claims. 232 pub fn new( 233 digest: CheckpointDigest, 234 sequence: Sequence, 235 coverage: Coverage, 236 missing: Vec<SourceId>, 237 ) -> Result<Self, ContextError> { 238 if missing.len() > MAX_MISSING { 239 return Err(ContextError::TooManyReferences); 240 } 241 if coverage == Coverage::ScopeSatisfied && !missing.is_empty() { 242 return Err(ContextError::InconsistentCoverage); 243 } 244 Ok(Self { 245 digest, 246 sequence, 247 coverage, 248 missing: missing.into_boxed_slice(), 249 }) 250 } 251 /// Returns the claimed checkpoint digest. 252 pub const fn digest(&self) -> CheckpointDigest { 253 self.digest 254 } 255 /// Returns its exact sequence, including explicit genesis. 256 pub const fn sequence(&self) -> Sequence { 257 self.sequence 258 } 259 /// Returns the described coverage. 260 pub const fn coverage(&self) -> Coverage { 261 self.coverage 262 } 263 /// Borrows the bounded missing-source list. 264 pub fn missing(&self) -> &[SourceId] { 265 &self.missing 266 } 267 } 268 /// A bounded diagnostic reference excluded from semantic idempotency. 269 #[derive(Clone, Eq, PartialEq)] 270 pub struct CorrelationId(Box<str>); 271 impl CorrelationId { 272 /// Retains at most 128 UTF-8 bytes, with no terminal/control characters. 273 pub fn new(value: impl Into<String>) -> Result<Self, ContextError> { 274 let value = value.into(); 275 if value.len() > 128 || value.chars().any(char::is_control) { 276 return Err(ContextError::InvalidText); 277 } 278 Ok(Self(value.into_boxed_str())) 279 } 280 /// Borrows the explicit diagnostic value for an authorized presentation. 281 pub fn as_str(&self) -> &str { 282 &self.0 283 } 284 } 285 impl fmt::Debug for CorrelationId { 286 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 287 f.write_str("CorrelationId(<redacted>)") 288 } 289 } 290 /// Untrusted approval data. The descriptor alone proves no consent or grant. 291 #[derive(Clone, Eq, PartialEq)] 292 #[cfg_attr(feature = "serde", derive(serde::Serialize))] 293 pub struct Approval { 294 intent_digest: ApprovalIntentDigest, 295 scope: Box<str>, 296 expires_at: UnixSeconds, 297 } 298 impl Approval { 299 /// Checks representation only; the host must authenticate origin and scope. 300 pub fn new( 301 intent_digest: ApprovalIntentDigest, 302 scope: impl Into<String>, 303 expires_at: UnixSeconds, 304 ) -> Result<Self, ContextError> { 305 let scope = scope.into(); 306 if scope.is_empty() || scope.len() > 160 || scope.chars().any(char::is_control) { 307 return Err(ContextError::InvalidText); 308 } 309 if expires_at.get() == 0 { 310 return Err(ContextError::OutOfRange); 311 } 312 Ok(Self { 313 intent_digest, 314 scope: scope.into_boxed_str(), 315 expires_at, 316 }) 317 } 318 /// Returns the exact displayed-intent commitment. 319 pub const fn intent_digest(&self) -> ApprovalIntentDigest { 320 self.intent_digest 321 } 322 /// Borrows the bounded requested consent scope. 323 pub fn scope(&self) -> &str { 324 &self.scope 325 } 326 /// Returns the captured consent expiry. 327 pub const fn expires_at(&self) -> UnixSeconds { 328 self.expires_at 329 } 330 } 331 impl fmt::Debug for Approval { 332 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 333 f.write_str("Approval(<untrusted descriptor>)") 334 } 335 } 336 /// Captured order preconditions, independent of whether the history is present. 337 #[derive(Clone, Debug, Eq, PartialEq)] 338 #[cfg_attr(feature = "serde", derive(serde::Serialize))] 339 pub struct ExpectedOrder { 340 order_id: OrderId, 341 agreement: Option<RecordId>, 342 seller_sequence: Sequence, 343 buyer_head: Option<RecordId>, 344 checkpoint: CheckpointRef, 345 } 346 impl ExpectedOrder { 347 /// Captures exact expected values without querying or installing an order. 348 pub const fn new( 349 order_id: OrderId, 350 agreement: Option<RecordId>, 351 seller_sequence: Sequence, 352 buyer_head: Option<RecordId>, 353 checkpoint: CheckpointRef, 354 ) -> Self { 355 Self { 356 order_id, 357 agreement, 358 seller_sequence, 359 buyer_head, 360 checkpoint, 361 } 362 } 363 /// Returns the order identity. 364 pub const fn order_id(&self) -> OrderId { 365 self.order_id 366 } 367 /// Returns the expected installed agreement. 368 pub const fn agreement(&self) -> Option<RecordId> { 369 self.agreement 370 } 371 /// Returns the exact expected seller sequence. 372 pub const fn seller_sequence(&self) -> Sequence { 373 self.seller_sequence 374 } 375 /// Returns the expected buyer head. 376 pub const fn buyer_head(&self) -> Option<RecordId> { 377 self.buyer_head 378 } 379 /// Borrows the expected evidence checkpoint. 380 pub const fn checkpoint(&self) -> &CheckpointRef { 381 &self.checkpoint 382 } 383 } 384 /// Complete wire-shaped captured-context data. Deserializing it never constructs 385 /// an authenticated execution context or grants any permission. 386 #[derive(Clone, Eq, PartialEq)] 387 #[cfg_attr(feature = "serde", derive(serde::Serialize))] 388 pub struct CommandContextData { 389 operation_id: OperationId, 390 actor: ActorRef, 391 workspace_id: WorkspaceId, 392 authority: AuthorityRef, 393 route_digest: RouteDigest, 394 approval: Option<Approval>, 395 expected: Option<ExpectedOrder>, 396 not_after: UnixSeconds, 397 correlation_id: Option<CorrelationId>, 398 } 399 impl CommandContextData { 400 /// Captures every explicit descriptor field, with no ambient effects. 401 #[allow(clippy::too_many_arguments)] 402 pub fn new( 403 operation_id: OperationId, 404 actor: ActorRef, 405 workspace_id: WorkspaceId, 406 authority: AuthorityRef, 407 route_digest: RouteDigest, 408 approval: Option<Approval>, 409 expected: Option<ExpectedOrder>, 410 not_after: UnixSeconds, 411 correlation_id: Option<CorrelationId>, 412 ) -> Result<Self, ContextError> { 413 if not_after.get() == 0 { 414 return Err(ContextError::OutOfRange); 415 } 416 Ok(Self { 417 operation_id, 418 actor, 419 workspace_id, 420 authority, 421 route_digest, 422 approval, 423 expected, 424 not_after, 425 correlation_id, 426 }) 427 } 428 /// Returns the full caller-retained operation identity. 429 pub const fn operation_id(&self) -> OperationId { 430 self.operation_id 431 } 432 /// Returns claimed actor/grant data, without authenticating it. 433 pub const fn actor(&self) -> ActorRef { 434 self.actor 435 } 436 /// Returns the selected workspace. 437 pub const fn workspace_id(&self) -> WorkspaceId { 438 self.workspace_id 439 } 440 /// Returns the exact executor and epoch. 441 pub const fn authority(&self) -> AuthorityRef { 442 self.authority 443 } 444 /// Returns the immutable selected route commitment. 445 pub const fn route_digest(&self) -> RouteDigest { 446 self.route_digest 447 } 448 /// Borrows untrusted approval data. 449 pub const fn approval(&self) -> Option<&Approval> { 450 self.approval.as_ref() 451 } 452 /// Borrows captured expected order state. 453 pub const fn expected(&self) -> Option<&ExpectedOrder> { 454 self.expected.as_ref() 455 } 456 /// Returns the original admission deadline. 457 pub const fn not_after(&self) -> UnixSeconds { 458 self.not_after 459 } 460 /// Borrows the diagnostic reference, which is not idempotency. 461 pub const fn correlation_id(&self) -> Option<&CorrelationId> { 462 self.correlation_id.as_ref() 463 } 464 } 465 impl fmt::Debug for CommandContextData { 466 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 467 f.write_str("CommandContextData(<untrusted descriptor>)") 468 } 469 } 470 471 #[cfg(feature = "serde")] 472 mod serialization { 473 use super::*; 474 use serde::{Deserialize, Deserializer, Serializer, de::Error}; 475 476 fn canonical_key<'de, D: Deserializer<'de>>(d: D) -> Result<PublicKey, D::Error> { 477 struct KeyVisitor; 478 impl serde::de::Visitor<'_> for KeyVisitor { 479 type Value = PublicKey; 480 fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 481 f.write_str("a canonical public key") 482 } 483 fn visit_str<E: serde::de::Error>(self, value: &str) -> Result<PublicKey, E> { 484 let key = 485 PublicKey::from_hex(value).map_err(|_| E::custom("invalid public key"))?; 486 if key.to_hex() != value { 487 return Err(E::custom("noncanonical public key")); 488 } 489 Ok(key) 490 } 491 } 492 d.deserialize_str(KeyVisitor) 493 } 494 fn nullable_key<'de, D: Deserializer<'de>>(d: D) -> Result<Option<PublicKey>, D::Error> { 495 #[derive(Deserialize)] 496 struct Key(#[serde(deserialize_with = "canonical_key")] PublicKey); 497 Option::<Key>::deserialize(d).map(|value| value.map(|key| key.0)) 498 } 499 500 fn object<'de, D: Deserializer<'de>, T: Deserialize<'de>>(d: D) -> Result<T, D::Error> { 501 struct ObjectVisitor<T>(core::marker::PhantomData<T>); 502 impl<'de, T: Deserialize<'de>> serde::de::Visitor<'de> for ObjectVisitor<T> { 503 type Value = T; 504 fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 505 f.write_str("an object") 506 } 507 fn visit_map<M: serde::de::MapAccess<'de>>(self, map: M) -> Result<T, M::Error> { 508 T::deserialize(serde::de::value::MapAccessDeserializer::new(map)) 509 } 510 } 511 d.deserialize_map(ObjectVisitor::<T>(core::marker::PhantomData)) 512 } 513 514 fn nullable<'de, D: Deserializer<'de>, T: Deserialize<'de>>( 515 d: D, 516 ) -> Result<Option<T>, D::Error> { 517 Option::<T>::deserialize(d) 518 } 519 impl serde::Serialize for CorrelationId { 520 fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> { 521 s.serialize_str(&self.0) 522 } 523 } 524 impl<'de> Deserialize<'de> for CorrelationId { 525 fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> { 526 Self::new(String::deserialize(d)?).map_err(D::Error::custom) 527 } 528 } 529 impl<'de> Deserialize<'de> for AuthorityRef { 530 fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> { 531 #[derive(Deserialize)] 532 #[serde(deny_unknown_fields)] 533 struct Raw { 534 executor_id: ExecutorId, 535 generation: Generation, 536 } 537 let raw: Raw = object(d)?; 538 Ok(Self::new(raw.executor_id, raw.generation)) 539 } 540 } 541 impl<'de> Deserialize<'de> for ActorRef { 542 fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> { 543 #[derive(Deserialize)] 544 #[serde(deny_unknown_fields)] 545 struct Raw { 546 #[serde(deserialize_with = "canonical_key")] 547 participant: PublicKey, 548 role: ActorRole, 549 #[serde(deserialize_with = "nullable_key")] 550 organization: Option<PublicKey>, 551 #[serde(deserialize_with = "nullable")] 552 grant_id: Option<GrantId>, 553 } 554 let raw: Raw = object(d)?; 555 Ok(Self::new( 556 raw.participant, 557 raw.role, 558 raw.organization, 559 raw.grant_id, 560 )) 561 } 562 } 563 impl<'de> Deserialize<'de> for CheckpointRef { 564 fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> { 565 #[derive(Deserialize)] 566 #[serde(deny_unknown_fields)] 567 struct Raw { 568 digest: CheckpointDigest, 569 sequence: Sequence, 570 coverage: Coverage, 571 missing: Vec<SourceId>, 572 } 573 let raw: Raw = object(d)?; 574 Self::new(raw.digest, raw.sequence, raw.coverage, raw.missing).map_err(D::Error::custom) 575 } 576 } 577 impl<'de> Deserialize<'de> for Approval { 578 fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> { 579 #[derive(Deserialize)] 580 #[serde(deny_unknown_fields)] 581 struct Raw { 582 intent_digest: ApprovalIntentDigest, 583 scope: String, 584 expires_at: UnixSeconds, 585 } 586 let raw: Raw = object(d)?; 587 Self::new(raw.intent_digest, raw.scope, raw.expires_at).map_err(D::Error::custom) 588 } 589 } 590 impl<'de> Deserialize<'de> for ExpectedOrder { 591 fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> { 592 #[derive(Deserialize)] 593 #[serde(deny_unknown_fields)] 594 struct Raw { 595 order_id: OrderId, 596 #[serde(deserialize_with = "nullable")] 597 agreement: Option<RecordId>, 598 seller_sequence: Sequence, 599 #[serde(deserialize_with = "nullable")] 600 buyer_head: Option<RecordId>, 601 checkpoint: CheckpointRef, 602 } 603 let raw: Raw = object(d)?; 604 Ok(Self::new( 605 raw.order_id, 606 raw.agreement, 607 raw.seller_sequence, 608 raw.buyer_head, 609 raw.checkpoint, 610 )) 611 } 612 } 613 impl<'de> Deserialize<'de> for CommandContextData { 614 fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> { 615 #[derive(Deserialize)] 616 #[serde(deny_unknown_fields)] 617 struct Raw { 618 operation_id: OperationId, 619 actor: ActorRef, 620 workspace_id: WorkspaceId, 621 authority: AuthorityRef, 622 route_digest: RouteDigest, 623 #[serde(deserialize_with = "nullable")] 624 approval: Option<Approval>, 625 #[serde(deserialize_with = "nullable")] 626 expected: Option<ExpectedOrder>, 627 not_after: UnixSeconds, 628 #[serde(deserialize_with = "nullable")] 629 correlation_id: Option<CorrelationId>, 630 } 631 let raw: Raw = object(d)?; 632 Self::new( 633 raw.operation_id, 634 raw.actor, 635 raw.workspace_id, 636 raw.authority, 637 raw.route_digest, 638 raw.approval, 639 raw.expected, 640 raw.not_after, 641 raw.correlation_id, 642 ) 643 .map_err(D::Error::custom) 644 } 645 } 646 }