journal.rs (17809B)
1 //! Protected immutable T0 records. No signer, network or business installation. 2 use super::{ 3 Batch, BrowserWorkspace, Error, Mutation, RecordKey, State, WorkspaceError, crypto, grant_key, 4 owned, 5 }; 6 use crate::ReadSnapshot; 7 use radroots_domain::{CommandDigest, IssuanceWindow, OperationId, Sequence, TransactionId}; 8 use radroots_secrets::context::{ 9 EnvelopeContext, EnvelopePurpose, EnvelopeSubject, PayloadSchemaId, 10 }; 11 use radroots_storage::{ 12 command::{ 13 AdmissionOutcome, AdmissionRequest, CommitAttempt, OperationError, PreparedOperation, 14 protected, 15 }, 16 workspace::{AttachmentProof, WorkspaceBinding, grant::WorkspaceGrant}, 17 }; 18 use sha2::{Digest, Sha256}; 19 use std::{cell::Cell, rc::Rc}; 20 use zeroize::Zeroizing; 21 22 const PART_BYTES: usize = 16 * 1024; 23 const PARTS: usize = protected::PREPARED_BYTES_MAX / PART_BYTES; 24 const SLOTS: usize = PARTS + 1; 25 pub(super) type Records = Vec<Option<Vec<u8>>>; 26 27 pub(super) struct OperationChange { 28 pub before: Records, 29 pub after: Option<Records>, 30 pub window: Option<IssuanceWindow>, 31 pub delivery_deadline: Option<core::num::NonZeroU64>, 32 pub extra: Vec<Mutation>, 33 } 34 impl OperationChange { 35 pub fn observe(before: Records) -> Self { 36 Self { 37 before, 38 after: None, 39 window: None, 40 delivery_deadline: None, 41 extra: Vec::new(), 42 } 43 } 44 } 45 46 pub(super) fn mutations( 47 grant: Vec<u8>, 48 operation: OperationId, 49 before: Records, 50 after: Option<Records>, 51 extra: Vec<Mutation>, 52 ) -> Result<Batch, OperationError> { 53 let mut mutations = Vec::with_capacity(SLOTS + 1 + extra.len()); 54 mutations 55 .push(Mutation::new(grant_key(), Some(grant.clone()), Some(grant)).map_err(storage_error)?); 56 for (slot, old) in before.into_iter().enumerate() { 57 let new = after 58 .as_ref() 59 .map_or_else(|| old.clone(), |r| r[slot].clone()); 60 mutations.push(Mutation::new(key(operation, slot), old, new).map_err(storage_error)?); 61 } 62 mutations.extend(extra); 63 Batch::new(mutations).map_err(storage_error) 64 } 65 66 fn key(operation: OperationId, slot: usize) -> RecordKey { 67 super::address::key(operation, super::address::PREPARED, 0, slot as u8) 68 } 69 70 fn context( 71 state: &State, 72 operation: OperationId, 73 part: Option<(usize, &[u8])>, 74 ) -> Result<EnvelopeContext, WorkspaceError> { 75 let mut h = Sha256::new(); 76 h.update(b"radroots.browser.local_outbox.prepared.context.v2\0"); 77 h.update(state.selected.workspace_id().as_bytes()); 78 h.update(operation.as_bytes()); 79 if let Some((index, digest)) = part { 80 h.update(b"part\0"); 81 h.update((index as u32).to_be_bytes()); 82 h.update(digest); 83 } else { 84 h.update(b"manifest\0"); 85 } 86 let subject = h 87 .finalize() 88 .iter() 89 .map(|b| format!("{b:02x}")) 90 .collect::<String>(); 91 Ok(EnvelopeContext::new( 92 EnvelopePurpose::parse("radroots.browser.workspace.prepared") 93 .map_err(|_| WorkspaceError::InvalidInput)?, 94 EnvelopeSubject::parse("workspace_prepared", subject) 95 .map_err(|_| WorkspaceError::InvalidInput)?, 96 PayloadSchemaId::parse("radroots.browser.workspace.prepared.v2") 97 .map_err(|_| WorkspaceError::InvalidInput)?, 98 )) 99 } 100 impl State { 101 pub(super) async fn operation_records( 102 &self, 103 view: &ReadSnapshot, 104 operation: OperationId, 105 ) -> Result<Records, OperationError> { 106 let mut records = Vec::with_capacity(SLOTS); 107 for slot in 0..SLOTS { 108 let value = self.read_view_key(view, key(operation, slot)).await?; 109 if value 110 .as_ref() 111 .is_some_and(|bytes| bytes.len() > crypto::PROTECTED_MAX) 112 { 113 return Err(OperationError::RecoveryRequired); 114 } 115 records.push(value); 116 } 117 Ok(records) 118 } 119 pub(super) async fn preparation( 120 &self, 121 operation: OperationId, 122 records: &Records, 123 ) -> Result<Option<PreparedOperation>, OperationError> { 124 let Some(manifest) = &records[0] else { 125 if records.iter().any(Option::is_some) { 126 return Err(OperationError::RecoveryRequired); 127 } 128 return Ok(None); 129 }; 130 let manifest = crypto::open_bound( 131 self.provider.as_ref(), 132 &self.reference, 133 context(self, operation, None)?, 134 manifest, 135 ) 136 .await?; 137 let (length, digest) = manifest.expose_secret(|bytes| { 138 if bytes.len() != 40 || &bytes[..4] != b"RRP1" { 139 return Err(OperationError::RecoveryRequired); 140 } 141 let length = u32::from_be_bytes( 142 bytes[4..8] 143 .try_into() 144 .map_err(|_| OperationError::RecoveryRequired)?, 145 ) as usize; 146 if length == 0 || length > protected::PREPARED_BYTES_MAX { 147 return Err(OperationError::RecoveryRequired); 148 } 149 let digest: [u8; 32] = bytes[8..] 150 .try_into() 151 .map_err(|_| OperationError::RecoveryRequired)?; 152 Ok((length, digest)) 153 })?; 154 let count = length.div_ceil(PART_BYTES); 155 let mut plaintext = Zeroizing::new(Vec::with_capacity(length)); 156 for index in 0..PARTS { 157 if index >= count { 158 if records[index + 1].is_some() { 159 return Err(OperationError::RecoveryRequired); 160 } 161 continue; 162 } 163 let part = records[index + 1] 164 .as_ref() 165 .ok_or(OperationError::RecoveryRequired)?; 166 let opened = crypto::open_bound( 167 self.provider.as_ref(), 168 &self.reference, 169 context(self, operation, Some((index, &digest)))?, 170 part, 171 ) 172 .await?; 173 let expected = (length - index * PART_BYTES).min(PART_BYTES); 174 opened.expose_secret(|bytes| { 175 if bytes.len() != expected { 176 return Err(OperationError::RecoveryRequired); 177 } 178 plaintext.extend_from_slice(bytes); 179 Ok(()) 180 })?; 181 } 182 if Sha256::digest(plaintext.as_slice()).as_slice() != digest { 183 return Err(OperationError::RecoveryRequired); 184 } 185 let prepared = protected::decode(&plaintext, &self.selected, operation)?; 186 self.coordinate_guard(&prepared).await?; 187 Ok(Some(prepared)) 188 } 189 async fn protect_preparation( 190 &self, 191 request: &AdmissionRequest, 192 transaction: TransactionId, 193 window: IssuanceWindow, 194 ) -> Result<Records, OperationError> { 195 let plaintext = protected::encode(request, transaction, window)?; 196 let digest = Sha256::digest(plaintext.as_slice()); 197 let mut manifest = Zeroizing::new(Vec::with_capacity(40)); 198 manifest.extend_from_slice(b"RRP1"); 199 manifest.extend_from_slice(&(plaintext.len() as u32).to_be_bytes()); 200 manifest.extend_from_slice(&digest); 201 let operation = request.command().context().operation_id(); 202 let mut records = Vec::with_capacity(SLOTS); 203 records.push(Some( 204 crypto::seal_bound( 205 self.provider.as_ref(), 206 &self.reference, 207 context(self, operation, None)?, 208 &manifest, 209 ) 210 .await?, 211 )); 212 for (index, bytes) in plaintext.chunks(PART_BYTES).enumerate() { 213 records.push(Some( 214 crypto::seal_bound( 215 self.provider.as_ref(), 216 &self.reference, 217 context(self, operation, Some((index, &digest)))?, 218 bytes, 219 ) 220 .await?, 221 )); 222 } 223 records.resize_with(SLOTS, || None); 224 Ok(records) 225 } 226 } 227 pub(super) fn storage_error(error: Error) -> OperationError { 228 match error { 229 Error::Capacity => WorkspaceError::Capacity.into(), 230 Error::Closed => WorkspaceError::Closed.into(), 231 Error::CommitUnknown => WorkspaceError::CommitUnknown.into(), 232 Error::Aborted | Error::Unavailable => OperationError::StorageFailure, 233 _ => OperationError::RecoveryRequired, 234 } 235 } 236 pub(super) struct Access { 237 grant: WorkspaceGrant, 238 protected: Vec<u8>, 239 pub binding: WorkspaceBinding, 240 proof: AttachmentProof, 241 } 242 impl State { 243 pub(super) async fn operation_access( 244 &self, 245 binding: &WorkspaceBinding, 246 proof: AttachmentProof, 247 ) -> Result<Access, OperationError> { 248 let (grant, protected, current) = self.access(binding.input(), &proof).await?; 249 protected::same_binding(binding, ¤t)?; 250 Ok(Access { 251 grant, 252 protected, 253 binding: current, 254 proof, 255 }) 256 } 257 pub(super) async fn check_operation( 258 &self, 259 access: Access, 260 operation: OperationId, 261 change: OperationChange, 262 view: ReadSnapshot, 263 ) -> Result<(), OperationError> { 264 let OperationChange { 265 before, 266 after, 267 window, 268 delivery_deadline, 269 mut extra, 270 } = change; 271 // The current authenticated buyer grant cannot admit public work, and 272 // preparation decoding refuses any such stored command. Preserve the 273 // original private path without another decryption of every T0 part. 274 if access.binding.scope() != radroots_storage::workspace::WorkspaceScope::NewBuyerOutbox 275 && let Some(prepared) = self.preparation(operation, &before).await? 276 { 277 extra.extend(self.coordinate_guard(&prepared).await?); 278 } 279 let batch = mutations(access.protected, operation, before, after, extra)?; 280 let active = self.active()?; 281 let clock = self.clock.clone(); 282 self.checked_batch(batch, view, move || { 283 if !active.get() { 284 return Err(WorkspaceError::Closed.into()); 285 } 286 let now = clock.now()?; 287 if now.get() == 0 || now < access.binding.observed_at() { 288 return Err(WorkspaceError::Unavailable.into()); 289 } 290 let current = access 291 .grant 292 .authenticate(access.binding.input(), &access.proof, now)?; 293 protected::same_binding(&access.binding, ¤t)?; 294 if let Some(window) = window { 295 if now < window.prepared_at() { 296 return Err(WorkspaceError::Unavailable.into()); 297 } 298 if now >= window.first_issue_not_after() { 299 return Err(OperationError::DeadlineExceeded); 300 } 301 } 302 if delivery_deadline.is_some_and(|deadline| { 303 now.get() 304 .checked_mul(1000) 305 .is_none_or(|time| time >= deadline.get()) 306 }) { 307 return Err(OperationError::DeadlineExceeded); 308 } 309 Ok(()) 310 }) 311 .await 312 } 313 pub(super) async fn checked_batch( 314 &self, 315 batch: Batch, 316 view: ReadSnapshot, 317 check: impl Fn() -> Result<(), OperationError> + 'static, 318 ) -> Result<(), OperationError> { 319 let failure = Rc::new(Cell::new(None)); 320 let refused = failure.clone(); 321 let result = self 322 .database() 323 .compare_exchange_snapshot_checked(batch, view, move || { 324 if let Err(error) = check() { 325 refused.set(Some(error)); 326 false 327 } else { 328 true 329 } 330 }) 331 .await; 332 if matches!(result, Err(Error::GuardRefused)) { 333 return Err(failure.get().unwrap_or(OperationError::RecoveryRequired)); 334 } 335 match result { 336 Ok(_) => Ok(()), 337 Err(Error::CommitUnknown) => Err(WorkspaceError::CommitUnknown.into()), 338 Err(error) => Err(storage_error(error)), 339 } 340 } 341 } 342 impl BrowserWorkspace { 343 /// Atomically retains an authenticated immutable local buyer preparation. 344 /// Only actual commit/re-read yields Prepared; no signing or delivery occurs. 345 pub async fn admit_command_and_hold( 346 &self, 347 request: AdmissionRequest, 348 proof: AttachmentProof, 349 ) -> Result<AdmissionOutcome, OperationError> { 350 let context = request.command().context(); 351 let fallback = CommitAttempt::new( 352 context.workspace_id(), 353 context.operation_id(), 354 request.command().digest(), 355 None, 356 ); 357 let work = self.state.admit()?; 358 let state = self.state.clone(); 359 let result = owned(work, async move { 360 let access = state.operation_access(request.binding(), proof).await?; 361 let context = request.command().context(); 362 let operation = context.operation_id(); 363 let view = state.read_view(operation).await?; 364 let before = state.operation_records(&view, operation).await?; 365 let mut extra = if before.iter().all(Option::is_none) { 366 state.absent_plans(&view, operation).await? 367 } else { 368 Vec::new() 369 }; 370 let (prepared, after, fresh) = 371 if let Some(existing) = state.preparation(operation, &before).await? { 372 protected::check_digest( 373 &existing, 374 context.actor(), 375 Some(request.command().digest()), 376 )?; 377 protected::same_binding(existing.request().binding(), request.binding())?; 378 (existing, None, false) 379 } else { 380 request.validate_fresh(access.binding.observed_at())?; 381 if access.binding.observed_at() < request.binding().observed_at() { 382 return Err(WorkspaceError::Unavailable.into()); 383 } 384 if context.not_after() > access.binding.expires_at() { 385 return Err(OperationError::DeadlineExceeded); 386 } 387 let window = 388 IssuanceWindow::capture(access.binding.observed_at(), context.not_after()) 389 .map_err(|_| OperationError::DeadlineExceeded)?; 390 let transaction = TransactionId::from_bytes(*crypto::random::<32>()?); 391 let records = state 392 .protect_preparation(&request, transaction, window) 393 .await?; 394 let prepared = PreparedOperation::from_committed_store( 395 request, 396 transaction, 397 Sequence::new(1).map_err(|_| OperationError::RecoveryRequired)?, 398 window, 399 )?; 400 extra.extend(state.coordinate_creation(&prepared).await?); 401 (prepared, Some(records), true) 402 }; 403 let attempt = prepared.identity(); 404 match state 405 .check_operation( 406 access, 407 operation, 408 OperationChange { 409 before, 410 after, 411 window: fresh.then(|| prepared.issuance_window()), 412 delivery_deadline: None, 413 extra, 414 }, 415 view, 416 ) 417 .await 418 { 419 Ok(()) => Ok(AdmissionOutcome::Committed(prepared)), 420 Err(OperationError::Workspace(WorkspaceError::CommitUnknown)) => { 421 state.mark_unknown(); 422 Ok(AdmissionOutcome::Unknown(attempt)) 423 } 424 Err(error) => Err(error), 425 } 426 }) 427 .await; 428 match result { 429 Err(OperationError::Workspace(WorkspaceError::CommitUnknown)) => { 430 self.state.mark_unknown(); 431 Ok(AdmissionOutcome::Unknown(fallback)) 432 } 433 other => other, 434 } 435 } 436 /// Reads the original preparation under current access without replaying it. 437 /// Absent results are confirmed atomically against every fixed record slot. 438 pub async fn operation( 439 &self, 440 binding: WorkspaceBinding, 441 operation: OperationId, 442 digest: Option<CommandDigest>, 443 proof: AttachmentProof, 444 ) -> Result<Option<PreparedOperation>, OperationError> { 445 let work = self.state.admit()?; 446 let state = self.state.clone(); 447 owned(work, async move { 448 let access = state.operation_access(&binding, proof).await?; 449 let view = state.read_view(operation).await?; 450 let records = state.operation_records(&view, operation).await?; 451 let result = state.preparation(operation, &records).await?; 452 if let Some(prepared) = &result { 453 protected::check_digest(prepared, binding.actor(), digest)?; 454 protected::same_binding(prepared.request().binding(), &binding)?; 455 } 456 let mut change = OperationChange::observe(records); 457 if result.is_none() { 458 change.extra = state.absent_plans(&view, operation).await?; 459 } 460 state 461 .check_operation(access, operation, change, view) 462 .await?; 463 Ok(result) 464 }) 465 .await 466 } 467 }