consent.rs (30050B)
1 //! Explicit per-operation business scopes. Preparation is untrusted data; 2 //! only an authenticated administrative transaction can issue these scopes. 3 #[cfg(test)] 4 mod tests; 5 use super::*; 6 use radroots_domain::{ActorRole, CommandDigest, OperationId, OrderId, UnixSeconds}; 7 use radroots_protocol::command::CapturedStockCommitment; 8 use radroots_storage::{ 9 command::OperationError, inventory::InventoryCheckpointRef, 10 workspace::seller_stock::StockResources, 11 }; 12 use sha2::{Digest, Sha256}; 13 use zeroize::Zeroizing; 14 15 #[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)] 16 #[serde(rename_all = "snake_case")] 17 pub enum StockConsentMode { 18 /// Explicit consent to this exact acceptance and access to its retained 19 /// operation. This supplies no signer or publication capability. 20 ExecuteAndRecover, 21 /// Access to an existing original operation under the named current grant; 22 /// it can never admit a missing operation or acquire fresh stock. 23 RecoverOnly, 24 } 25 26 /// Prepared before store IO. No constructor verifies consent or issues rights. 27 pub struct StockConsentCapture { 28 namespace: SellerAuthoritySelection, 29 operation: OperationId, 30 transaction: TransactionId, 31 subject: GrantId, 32 mode: StockConsentMode, 33 resources: StockResources, 34 expires: UnixSeconds, 35 command: CapturedStockCommitment, 36 digest: CommandDigest, 37 } 38 impl StockConsentCapture { 39 pub fn prepare( 40 namespace: SellerAuthoritySelection, 41 subject: GrantId, 42 mode: StockConsentMode, 43 resources: StockResources, 44 expires: UnixSeconds, 45 command: impl Into<CapturedStockCommitment>, 46 ) -> Result<Self, OperationError> { 47 let command = command.into(); 48 validate_capture(&namespace, subject, mode, expires, &command)?; 49 let digest = scope_digest( 50 &namespace, 51 subject, 52 mode, 53 &resources, 54 expires, 55 command.digest(), 56 )?; 57 let operation = OperationId::from_bytes(super::super::random()?); 58 if operation == command.context().operation_id() { 59 return Err(WorkspaceError::Unavailable.into()); 60 } 61 Ok(Self { 62 namespace, 63 operation, 64 transaction: TransactionId::from_bytes(super::super::random()?), 65 subject, 66 mode, 67 resources, 68 expires, 69 command, 70 digest, 71 }) 72 } 73 pub const fn control_operation_id(&self) -> OperationId { 74 self.operation 75 } 76 pub const fn transaction_id(&self) -> TransactionId { 77 self.transaction 78 } 79 pub const fn subject_grant(&self) -> GrantId { 80 self.subject 81 } 82 pub const fn mode(&self) -> StockConsentMode { 83 self.mode 84 } 85 pub const fn expires_at(&self) -> UnixSeconds { 86 self.expires 87 } 88 pub fn command(&self) -> &CapturedStockCommitment { 89 &self.command 90 } 91 pub fn resources(&self) -> &StockResources { 92 &self.resources 93 } 94 pub(super) fn retained_copy(&self) -> Result<Self, OperationError> { 95 Ok(Self { 96 namespace: self.namespace.clone(), 97 operation: self.operation, 98 transaction: self.transaction, 99 subject: self.subject, 100 mode: self.mode, 101 resources: self.resources.clone(), 102 expires: self.expires, 103 command: CapturedStockCommitment::parse(self.command.protected_wire()) 104 .map_err(|_| OperationError::InvalidCommand)?, 105 digest: self.digest, 106 }) 107 } 108 } 109 impl std::fmt::Debug for StockConsentCapture { 110 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 111 f.write_str("StockConsentCapture(<unissued scope>)") 112 } 113 } 114 fn validate_capture( 115 namespace: &SellerAuthoritySelection, 116 subject: GrantId, 117 mode: StockConsentMode, 118 expires: UnixSeconds, 119 command: &CapturedStockCommitment, 120 ) -> Result<(), OperationError> { 121 let context = command.context(); 122 let approval = context 123 .approval() 124 .ok_or(OperationError::UnverifiedApproval)?; 125 if context.actor().participant() != namespace.participant() 126 || context.actor().role() != ActorRole::Seller 127 || context.actor().organization().is_some() 128 || context.actor().grant_id().is_none() 129 || context.workspace_id() != namespace.workspace_id() 130 || context.authority() != namespace.authority() 131 || context.route_digest() != namespace.route_digest() 132 || context.expected().is_none() 133 || expires.get() == 0 134 || approval.scope() != command.command_name() 135 || approval.intent_digest() != command.approval_intent_digest() 136 || (mode == StockConsentMode::ExecuteAndRecover 137 && (context.actor().grant_id() != Some(subject) 138 || expires > context.not_after() 139 || expires > approval.expires_at())) 140 { 141 return Err(OperationError::InvalidCommand); 142 } 143 Ok(()) 144 } 145 fn scope_digest( 146 namespace: &SellerAuthoritySelection, 147 subject: GrantId, 148 mode: StockConsentMode, 149 resources: &StockResources, 150 expires: UnixSeconds, 151 command: CommandDigest, 152 ) -> Result<CommandDigest, OperationError> { 153 #[derive(Serialize)] 154 struct Scope<'a> { 155 version: u8, 156 namespace: &'a SellerAuthoritySelection, 157 subject: GrantId, 158 mode: StockConsentMode, 159 resources: &'a StockResources, 160 expires: UnixSeconds, 161 command: CommandDigest, 162 } 163 let bytes = Zeroizing::new( 164 serde_json::to_vec(&Scope { 165 version: 1, 166 namespace, 167 subject, 168 mode, 169 resources, 170 expires, 171 command, 172 }) 173 .map_err(|_| OperationError::InvalidCommand)?, 174 ); 175 if bytes.len() > 16 * 1024 { 176 return Err(WorkspaceError::Capacity.into()); 177 } 178 let mut hash = Sha256::new(); 179 hash.update(b"radroots.seller_stock.consent_scope.v1\0"); 180 hash.update(bytes.as_slice()); 181 Ok(CommandDigest::from_bytes(hash.finalize().into())) 182 } 183 184 #[derive(Clone, Debug, Eq, PartialEq)] 185 pub struct StockConsentReceipt { 186 operation: OperationId, 187 transaction: TransactionId, 188 subject: GrantId, 189 command_operation: OperationId, 190 command_digest: CommandDigest, 191 order: OrderId, 192 mode: StockConsentMode, 193 expires: UnixSeconds, 194 resources: StockResources, 195 checkpoint: InventoryCheckpointRef, 196 } 197 impl StockConsentReceipt { 198 /// The exact resource claim at issuance, without current execution authority. 199 pub fn resources(&self) -> &StockResources { 200 &self.resources 201 } 202 pub const fn control_operation_id(&self) -> OperationId { 203 self.operation 204 } 205 pub const fn transaction_id(&self) -> TransactionId { 206 self.transaction 207 } 208 pub const fn subject_grant(&self) -> GrantId { 209 self.subject 210 } 211 pub const fn command_operation_id(&self) -> OperationId { 212 self.command_operation 213 } 214 pub const fn command_digest(&self) -> CommandDigest { 215 self.command_digest 216 } 217 pub const fn order_id(&self) -> OrderId { 218 self.order 219 } 220 pub const fn mode(&self) -> StockConsentMode { 221 self.mode 222 } 223 pub const fn expires_at(&self) -> UnixSeconds { 224 self.expires 225 } 226 pub const fn checkpoint(&self) -> InventoryCheckpointRef { 227 self.checkpoint 228 } 229 } 230 #[derive(Clone, Debug, Eq, PartialEq)] 231 pub enum StockConsentOutcome { 232 Committed(Box<StockConsentReceipt>), 233 Unknown { 234 control_operation: OperationId, 235 transaction: TransactionId, 236 command_operation: OperationId, 237 subject: GrantId, 238 }, 239 } 240 241 #[derive(Serialize, Deserialize)] 242 #[serde(deny_unknown_fields)] 243 struct Body<'a> { 244 version: u8, 245 selection: AttachmentInput, 246 principal: String, 247 grant_revision: Sequence, 248 grant_expires: UnixSeconds, 249 observed_at: UnixSeconds, 250 authorization: StockAuthorizationRef, 251 minimum_revision: Sequence, 252 #[serde(deserialize_with = "super::required_nullable")] 253 minimum_head: Option<radroots_domain::CheckpointDigest>, 254 subject: GrantId, 255 subject_digest: [u8; 32], 256 mode: StockConsentMode, 257 resources: StockResources, 258 expires: UnixSeconds, 259 #[serde(borrow)] 260 command: &'a serde_json::value::RawValue, 261 } 262 pub(super) struct Retained { 263 pub frame: ledger::Retained, 264 pub observed_at: UnixSeconds, 265 pub command: CapturedStockCommitment, 266 pub mode: StockConsentMode, 267 pub resources: StockResources, 268 pub subject: GrantId, 269 pub expires: UnixSeconds, 270 pub authorization: StockAuthorizationRef, 271 pub subject_digest: [u8; 32], 272 } 273 impl Retained { 274 pub(super) fn identity(&self) -> inventory::checkpoint::EntryIdentity { 275 inventory::checkpoint::EntryIdentity { 276 operation: self.frame.header.operation, 277 revision: self.frame.header.revision, 278 head: self.frame.header.head, 279 protected_digest: Sha256::digest(&self.frame.protected).into(), 280 } 281 } 282 pub fn receipt(&self) -> Result<StockConsentReceipt, OperationError> { 283 let header = &self.frame.header; 284 Ok(StockConsentReceipt { 285 operation: header.operation, 286 transaction: header.transaction, 287 subject: self.subject, 288 command_operation: self.command.context().operation_id(), 289 command_digest: self.command.digest(), 290 order: header.order.ok_or(OperationError::RecoveryRequired)?, 291 mode: self.mode, 292 expires: self.expires, 293 resources: self.resources.clone(), 294 checkpoint: InventoryCheckpointRef::from_host_metadata( 295 self.command.context().authority(), 296 header.revision, 297 Some(header.head), 298 )? 299 .with_authorization(self.authorization), 300 }) 301 } 302 } 303 fn chain_head( 304 namespace: &SellerAuthoritySelection, 305 header: &ledger::Header, 306 subject_digest: [u8; 32], 307 ) -> Result<radroots_domain::CheckpointDigest, OperationError> { 308 let mut hash = Sha256::new(); 309 hash.update(b"radroots.seller_stock.consent_chain.v1\0"); 310 hash.update(namespace.workspace_id().as_bytes()); 311 hash.update(namespace.authority().executor_id().as_bytes()); 312 hash.update(namespace.authority().generation().get().to_be_bytes()); 313 hash.update(namespace.route_digest().as_bytes()); 314 hash.update([u8::from(header.previous.is_some())]); 315 hash.update(header.previous.map(|v| *v.as_bytes()).unwrap_or([0; 32])); 316 hash.update(header.revision.get().to_be_bytes()); 317 hash.update(header.actor.participant().as_bytes()); 318 hash.update( 319 header 320 .actor 321 .grant_id() 322 .ok_or(OperationError::RecoveryRequired)? 323 .as_bytes(), 324 ); 325 hash.update(header.operation.as_bytes()); 326 hash.update(header.transaction.as_bytes()); 327 hash.update(header.digest.as_bytes()); 328 hash.update(subject_digest); 329 Ok(radroots_domain::CheckpointDigest::from_bytes( 330 hash.finalize().into(), 331 )) 332 } 333 pub(super) async fn read( 334 connection: &mut SqliteConnection, 335 input: &AttachmentInput, 336 crypto: &WorkspaceCrypto, 337 administrator: GrantId, 338 operation: OperationId, 339 ) -> Result<Option<Retained>, OperationError> { 340 let Some(frame) = ledger::read(connection, input, crypto, operation).await? else { 341 return Ok(None); 342 }; 343 let mut parser = serde_json::Deserializer::from_slice(frame.body.as_slice()); 344 let body: Body<'_> = 345 super::object(&mut parser).map_err(|_| OperationError::RecoveryRequired)?; 346 parser.end().map_err(|_| OperationError::RecoveryRequired)?; 347 let command = CapturedStockCommitment::parse(body.command.get().as_bytes()) 348 .map_err(|_| OperationError::RecoveryRequired)?; 349 let namespace = SellerAuthoritySelection::from_attachment(input); 350 validate_capture(&namespace, body.subject, body.mode, body.expires, &command) 351 .map_err(|_| OperationError::RecoveryRequired)?; 352 let header = &frame.header; 353 if header.family != ledger::Family::Consent 354 || header.actor.grant_id() != Some(administrator) 355 || body.version != 1 356 || (command.proposal().is_some() 357 && sqlx::query_scalar::<_, i64>("PRAGMA user_version") 358 .fetch_one(&mut *connection) 359 .await 360 .map_err(|_| OperationError::RecoveryRequired)? 361 < 20) 362 || !namespace.matches_attachment(&body.selection) 363 || body.selection.grant_id() != administrator 364 || header.subject_grant != Some(body.subject) 365 || header.related_operation != Some(command.context().operation_id()) 366 || header.order != command.context().expected().map(|v| v.order_id()) 367 || body.principal.is_empty() 368 || body.principal.len() > 128 369 || body.principal.chars().any(char::is_control) 370 || body.grant_revision.get() == 0 371 || body.observed_at.get() == 0 372 || body.grant_expires <= body.observed_at 373 || body.expires <= body.observed_at 374 || body.expires > body.grant_expires 375 || body.minimum_revision.get() >= header.revision.get() 376 || (body.minimum_revision.get() == 0) != body.minimum_head.is_none() 377 || header.digest 378 != scope_digest( 379 &namespace, 380 body.subject, 381 body.mode, 382 &body.resources, 383 body.expires, 384 command.digest(), 385 )? 386 || header.head != chain_head(&namespace, header, body.subject_digest)? 387 { 388 return Err(OperationError::RecoveryRequired); 389 } 390 let mode = body.mode; 391 let resources = body.resources; 392 let subject = body.subject; 393 let expires = body.expires; 394 let authorization = body.authorization; 395 let subject_digest = body.subject_digest; 396 Ok(Some(Retained { 397 observed_at: body.observed_at, 398 frame, 399 command, 400 mode, 401 resources, 402 subject, 403 expires, 404 authorization, 405 subject_digest, 406 })) 407 } 408 409 pub(super) async fn natural( 410 connection: &mut SqliteConnection, 411 participant: radroots_domain::PublicKey, 412 operation: OperationId, 413 subject: GrantId, 414 ) -> Result<Option<OperationId>, OperationError> { 415 let id:Option<Vec<u8>>=sqlx::query_scalar("SELECT operation_id FROM stock_operations WHERE actor=? AND family=1 AND related_operation=? AND subject_grant=?") 416 .bind(participant.as_bytes().as_slice()).bind(operation.as_bytes().as_slice()).bind(subject.as_bytes().as_slice()) 417 .fetch_optional(connection).await.map_err(|_|OperationError::RecoveryRequired)?; 418 id.map(|bytes| { 419 bytes 420 .try_into() 421 .map(OperationId::from_bytes) 422 .map_err(|_| OperationError::RecoveryRequired) 423 }) 424 .transpose() 425 } 426 pub(in crate::workspace) async fn issue( 427 turn: &mut inventory::Turn<'_>, 428 binding: WorkspaceBinding, 429 minimum: InventoryCheckpointRef, 430 capture: StockConsentCapture, 431 proof: AttachmentProof, 432 ) -> Result<StockConsentOutcome, OperationError> { 433 let access = turn.access(&binding, minimum, &proof).await?; 434 if !matches!(access.authority.catalog, 7..=20) 435 || (capture.command.proposal().is_some() && access.authority.catalog < 20) 436 { 437 return Err(OperationError::UnsupportedOperation); 438 } 439 if !access.record.administrator() 440 || capture.namespace != SellerAuthoritySelection::from_attachment(turn.selected) 441 { 442 return Err(OperationError::Unauthorized); 443 } 444 let command_operation = capture.command.context().operation_id(); 445 if let Some(operation) = natural( 446 turn.connection, 447 turn.selected.participant(), 448 command_operation, 449 capture.subject, 450 ) 451 .await? 452 { 453 let original = read( 454 turn.connection, 455 turn.selected, 456 turn.crypto, 457 access.authority.input.grant_id(), 458 operation, 459 ) 460 .await? 461 .ok_or(OperationError::RecoveryRequired)?; 462 let identity = inventory::checkpoint::authenticate_identity( 463 turn.connection, 464 turn.selected, 465 turn.crypto, 466 &access.current, 467 &access.authority, 468 inventory::checkpoint::IdentityTarget::Consent { 469 operation: command_operation, 470 subject: capture.subject, 471 expected: Some(original.identity()), 472 }, 473 ) 474 .await?; 475 if original.frame.header.digest != capture.digest { 476 return Err(OperationError::IdempotencyConflict); 477 } 478 let receipt = original.receipt()?; 479 let mut tx = turn 480 .connection 481 .begin_with("BEGIN IMMEDIATE") 482 .await 483 .map_err(|_| OperationError::StorageFailure)?; 484 let checked: Result<(), OperationError> = async { 485 access 486 .confirm(&mut tx, turn.namespace, turn.clock, &proof) 487 .await?; 488 identity.confirm(&mut tx).await?; 489 ledger::confirm_header(&mut tx, &original.frame.header, &original.frame.protected) 490 .await?; 491 ledger::confirm_parts( 492 &mut tx, 493 original.frame.header.actor, 494 operation, 495 original.frame.parts_witness, 496 original.frame.header.parts, 497 ) 498 .await?; 499 Ok(()) 500 } 501 .await; 502 if tx.rollback().await.is_err() { 503 *turn.uncertain = true; 504 return Err(OperationError::RecoveryRequired); 505 } 506 checked?; 507 return Ok(StockConsentOutcome::Committed(Box::new(receipt))); 508 } 509 let identity = inventory::checkpoint::authenticate_identity( 510 turn.connection, 511 turn.selected, 512 turn.crypto, 513 &access.current, 514 &access.authority, 515 inventory::checkpoint::IdentityTarget::Consent { 516 operation: command_operation, 517 subject: capture.subject, 518 expected: None, 519 }, 520 ) 521 .await?; 522 if access.current.observed_at() >= capture.expires 523 || capture.expires > access.current.expires_at() 524 { 525 return Err(OperationError::DeadlineExceeded); 526 } 527 let target:Vec<u8>=sqlx::query_scalar("SELECT protected FROM stock_grants WHERE grant_id=? AND length(protected) BETWEEN 1 AND 262144") 528 .bind(capture.subject.as_bytes().as_slice()).fetch_optional(&mut *turn.connection).await.map_err(|_|OperationError::RecoveryRequired)?.ok_or(OperationError::Unauthorized)?; 529 let target_input = capture.namespace.attachment(capture.subject)?; 530 let clear = turn 531 .crypto 532 .open_stock_record(&target_input, "grant", capture.subject.as_bytes(), &target) 533 .await?; 534 let target_record = clear.expose_secret(StockGrantRecord::decode)?; 535 if target_record.input() != &target_input 536 || !target_record.belongs_to(&capture.namespace)? 537 || target_record.is_revoked() 538 || capture.expires > target_record.expires_at() 539 { 540 return Err(OperationError::Unauthorized); 541 } 542 let subject_digest: [u8; 32] = Sha256::digest(&target).into(); 543 let before = access 544 .authority 545 .inventory 546 .ok_or(OperationError::RecoveryRequired)?; 547 let revision = Sequence::new( 548 before 549 .revision 550 .get() 551 .checked_add(1) 552 .ok_or(WorkspaceError::Capacity)?, 553 ) 554 .map_err(|_| WorkspaceError::Capacity)?; 555 let authorization = access 556 .authority 557 .authorization 558 .ok_or(OperationError::RecoveryRequired)?; 559 let command: &serde_json::value::RawValue = 560 serde_json::from_slice(capture.command.protected_wire()) 561 .map_err(|_| OperationError::InvalidCommand)?; 562 let body = Body { 563 version: 1, 564 selection: access.current.input().clone(), 565 principal: access.current.principal_id().into(), 566 grant_revision: access.current.grant_revision(), 567 grant_expires: access.current.expires_at(), 568 observed_at: access.current.observed_at(), 569 authorization, 570 minimum_revision: minimum.revision(), 571 minimum_head: minimum.head(), 572 subject: capture.subject, 573 subject_digest, 574 mode: capture.mode, 575 resources: capture.resources.clone(), 576 expires: capture.expires, 577 command, 578 }; 579 let body = 580 Zeroizing::new(serde_json::to_vec(&body).map_err(|_| OperationError::StorageFailure)?); 581 let mut header = ledger::Header { 582 version: 5, 583 family: ledger::Family::Consent, 584 namespace: capture.namespace.clone(), 585 actor: access.current.actor(), 586 operation: capture.operation, 587 digest: capture.digest, 588 transaction: capture.transaction, 589 revision, 590 previous: before.head, 591 head: radroots_domain::CheckpointDigest::from_bytes([0; 32]), 592 pool: None, 593 order: capture 594 .command 595 .context() 596 .expected() 597 .map(|value| value.order_id()), 598 related_operation: Some(command_operation), 599 subject_grant: Some(capture.subject), 600 bytes: 0, 601 parts: 0, 602 body_digest: [0; 32], 603 }; 604 header.head = chain_head(&capture.namespace, &header, subject_digest)?; 605 let head = header.head; 606 let prepared = ledger::prepare(turn.crypto, turn.selected, header, &body).await?; 607 let mut next = access.authority.clone(); 608 next.inventory = Some(InventoryCheckpoint { 609 revision, 610 head: Some(head), 611 ..before 612 }); 613 let root = turn 614 .crypto 615 .seal_stock_root(turn.selected, access.authority.catalog, &next.encode()?) 616 .await?; 617 let receipt = StockConsentReceipt { 618 operation: capture.operation, 619 transaction: capture.transaction, 620 subject: capture.subject, 621 command_operation, 622 command_digest: capture.command.digest(), 623 order: capture 624 .command 625 .context() 626 .expected() 627 .ok_or(OperationError::InvalidCommand)? 628 .order_id(), 629 mode: capture.mode, 630 expires: capture.expires, 631 resources: capture.resources.clone(), 632 checkpoint: InventoryCheckpointRef::from_host_metadata( 633 turn.selected.authority(), 634 revision, 635 Some(head), 636 )? 637 .with_authorization(authorization), 638 }; 639 turn.namespace.validate()?; 640 let mut tx = turn 641 .connection 642 .begin_with("BEGIN IMMEDIATE") 643 .await 644 .map_err(|_| OperationError::StorageFailure)?; 645 let changed:Result<(),OperationError>=async { 646 let current=access.confirm(&mut tx,turn.namespace,turn.clock,&proof).await?; 647 identity.confirm(&mut tx).await?; 648 if !access.record.administrator() {return Err(OperationError::Unauthorized);} 649 if current.observed_at()>=capture.expires {return Err(OperationError::DeadlineExceeded);} 650 let target_matches:i64=sqlx::query_scalar("SELECT count(*) FROM stock_grants WHERE grant_id=? AND protected=?") 651 .bind(capture.subject.as_bytes().as_slice()).bind(&target).fetch_one(&mut *tx).await.map_err(|_|OperationError::RecoveryRequired)?; 652 if target_matches!=1 {return Err(OperationError::RecoveryRequired);} 653 if natural(&mut tx,turn.selected.participant(),command_operation,capture.subject).await?.is_some() {return Err(OperationError::StaleState);} 654 let absent:i64=sqlx::query_scalar("SELECT count(*) FROM stock_operations WHERE actor=? AND operation_id=?") 655 .bind(current.actor().participant().as_bytes().as_slice()).bind(capture.operation.as_bytes().as_slice()).fetch_one(&mut *tx).await.map_err(|_|OperationError::RecoveryRequired)?; 656 if absent!=0 {return Err(OperationError::IdempotencyConflict);} 657 sqlx::query("INSERT INTO stock_operations(actor,grant_id,operation_id,command_digest,transaction_id,pool_id,revision,chain_head,protected,family,order_id,related_operation,subject_grant) VALUES(?,?,?,?,?,NULL,?,?,?,1,?,?,?)") 658 .bind(current.actor().participant().as_bytes().as_slice()).bind(current.input().grant_id().as_bytes().as_slice()) 659 .bind(capture.operation.as_bytes().as_slice()).bind(capture.digest.as_bytes().as_slice()).bind(capture.transaction.as_bytes().as_slice()) 660 .bind(revision.get() as i64).bind(head.as_bytes().as_slice()).bind(&prepared.protected) 661 .bind(receipt.order.as_bytes().as_slice()).bind(command_operation.as_bytes().as_slice()).bind(capture.subject.as_bytes().as_slice()) 662 .execute(&mut *tx).await.map_err(|_|OperationError::StorageFailure)?; 663 prepared.insert_parts(&mut tx,current.actor(),capture.operation).await?; 664 let updated=sqlx::query("UPDATE stock_authority SET protected=? WHERE singleton=1 AND protected=?") 665 .bind(root).bind(&access.root).execute(&mut *tx).await.map_err(|_|OperationError::StorageFailure)?; 666 if updated.rows_affected()!=1 {return Err(OperationError::RecoveryRequired);}turn.namespace.validate()?;Ok(()) 667 }.await; 668 let unknown = || StockConsentOutcome::Unknown { 669 control_operation: capture.operation, 670 transaction: capture.transaction, 671 command_operation, 672 subject: capture.subject, 673 }; 674 if let Err(error) = changed { 675 if tx.rollback().await.is_err() { 676 *turn.uncertain = true; 677 return Ok(unknown()); 678 } 679 return Err(error); 680 } 681 if tx.commit().await.is_err() { 682 *turn.uncertain = true; 683 return Ok(unknown()); 684 } 685 Ok(StockConsentOutcome::Committed(Box::new(receipt))) 686 } 687 688 pub(in crate::workspace) async fn query( 689 turn: &mut inventory::Turn<'_>, 690 binding: WorkspaceBinding, 691 minimum: InventoryCheckpointRef, 692 command_operation: OperationId, 693 subject: GrantId, 694 proof: AttachmentProof, 695 ) -> Result<Option<StockConsentReceipt>, OperationError> { 696 let access = turn.access(&binding, minimum, &proof).await?; 697 if !matches!(access.authority.catalog, 7..=20) { 698 return Err(OperationError::UnsupportedOperation); 699 } 700 if !access.record.administrator() && access.current.input().grant_id() != subject { 701 return Err(OperationError::Unauthorized); 702 } 703 let original = if let Some(operation) = natural( 704 turn.connection, 705 turn.selected.participant(), 706 command_operation, 707 subject, 708 ) 709 .await? 710 { 711 Some( 712 read( 713 turn.connection, 714 turn.selected, 715 turn.crypto, 716 access.authority.input.grant_id(), 717 operation, 718 ) 719 .await? 720 .ok_or(OperationError::RecoveryRequired)?, 721 ) 722 } else { 723 None 724 }; 725 let identity = inventory::checkpoint::authenticate_identity( 726 turn.connection, 727 turn.selected, 728 turn.crypto, 729 &access.current, 730 &access.authority, 731 inventory::checkpoint::IdentityTarget::Consent { 732 operation: command_operation, 733 subject, 734 expected: original.as_ref().map(Retained::identity), 735 }, 736 ) 737 .await?; 738 let receipt = original.as_ref().map(Retained::receipt).transpose()?; 739 let mut tx = turn 740 .connection 741 .begin_with("BEGIN IMMEDIATE") 742 .await 743 .map_err(|_| OperationError::StorageFailure)?; 744 let checked: Result<(), OperationError> = async { 745 access 746 .confirm(&mut tx, turn.namespace, turn.clock, &proof) 747 .await?; 748 identity.confirm(&mut tx).await?; 749 if let Some(original) = &original { 750 ledger::confirm_header(&mut tx, &original.frame.header, &original.frame.protected) 751 .await?; 752 ledger::confirm_parts( 753 &mut tx, 754 original.frame.header.actor, 755 original.frame.header.operation, 756 original.frame.parts_witness, 757 original.frame.header.parts, 758 ) 759 .await?; 760 } 761 turn.namespace.validate()?; 762 Ok(()) 763 } 764 .await; 765 if tx.rollback().await.is_err() { 766 *turn.uncertain = true; 767 return Err(OperationError::RecoveryRequired); 768 } 769 checked?; 770 Ok(receipt) 771 } 772 773 impl NativeWorkspace { 774 /// Issues an explicit scope for one captured business command, using the 775 /// current administrative grant. The borrowed capture preserves its original 776 /// recovery identity if this observer is lost. Issuance performs no order, 777 /// stock, signing or publication effect. 778 pub async fn issue_stock_consent( 779 &self, 780 binding: WorkspaceBinding, 781 minimum: InventoryCheckpointRef, 782 capture: &StockConsentCapture, 783 proof: &AttachmentProof, 784 ) -> Result<StockConsentOutcome, OperationError> { 785 let proof = proof.with_secret(|bytes| AttachmentProof::from_protected_input(bytes))?; 786 self.worker 787 .issue_stock_consent(binding, minimum, capture.retained_copy()?, proof) 788 .await 789 } 790 791 /// Reads a retained issuance under current administrator or subject access. 792 /// A receipt describes its original issuance; it does not establish that its 793 /// expiry, target grant or business preconditions still permit execution. 794 pub async fn stock_consent( 795 &self, 796 binding: WorkspaceBinding, 797 minimum: InventoryCheckpointRef, 798 command_operation: OperationId, 799 subject: GrantId, 800 proof: &AttachmentProof, 801 ) -> Result<Option<StockConsentReceipt>, OperationError> { 802 let proof = proof.with_secret(|bytes| AttachmentProof::from_protected_input(bytes))?; 803 self.worker 804 .stock_consent(binding, minimum, command_operation, subject, proof) 805 .await 806 } 807 }