admission.rs (16785B)
1 use super::{ 2 AttachmentInput, AttachmentProof, WorkspaceBinding, WorkspaceClock, WorkspaceCrypto, 3 fs::Namespace, operation, plan, record::GrantRecord, worker, 4 }; 5 use radroots_domain::{CommandDigest, IssuanceWindow, OperationId, TransactionId}; 6 use radroots_storage::command::{ 7 AdmissionOutcome, AdmissionRequest, BoundSigningPlan, CapturedSigningPlan, CommitAttempt, 8 OperationError, PlanBindingOutcome, PreparedOperation, 9 }; 10 use sqlx::{Connection, Sqlite, SqliteConnection, Transaction}; 11 12 /// One borrowed turn on the existing connection owner, never a second runtime. 13 pub(super) struct Journal<'a> { 14 pub connection: &'a mut SqliteConnection, 15 pub namespace: &'a Namespace, 16 pub selected: &'a AttachmentInput, 17 pub crypto: &'a WorkspaceCrypto, 18 pub clock: &'a dyn WorkspaceClock, 19 pub uncertain: &'a mut bool, 20 } 21 impl Journal<'_> { 22 pub(super) async fn access( 23 &mut self, 24 binding: &WorkspaceBinding, 25 proof: &AttachmentProof, 26 ) -> Result<(GrantRecord, Vec<u8>, WorkspaceBinding), OperationError> { 27 if *self.uncertain { 28 return Err(OperationError::RecoveryRequired); 29 } 30 self.namespace.validate()?; 31 let protected = worker::read(self.connection, self.selected).await?; 32 let plaintext = self 33 .crypto 34 .open( 35 self.selected.workspace_id(), 36 self.selected.grant_id(), 37 &protected, 38 ) 39 .await?; 40 let record = plaintext.expose_secret(GrantRecord::decode_outbox)?; 41 let current = record.authenticate(binding.input(), proof, self.clock.now()?)?; 42 same_binding(binding, ¤t)?; 43 self.namespace.validate()?; 44 Ok((record, protected, current)) 45 } 46 47 pub(super) async fn bind_plan( 48 &mut self, 49 binding: WorkspaceBinding, 50 supplied: CapturedSigningPlan, 51 proof: AttachmentProof, 52 ) -> Result<PlanBindingOutcome, OperationError> { 53 let (record, grant, current) = self.access(&binding, &proof).await?; 54 let (prepared, operation_protected) = operation::read( 55 self.connection, 56 self.selected, 57 supplied.operation_id(), 58 self.crypto, 59 ) 60 .await? 61 .ok_or(OperationError::RecoveryRequired)?; 62 operation::check_digest(&prepared, binding.actor(), Some(supplied.command_digest()))?; 63 same_binding(prepared.request().binding(), &binding)?; 64 let anchor = prepared.identity(); 65 let (prepared, existing) = 66 plan::read(self.connection, self.selected, prepared, self.crypto).await?; 67 let (plan, transaction_id, bound_at, protected, fresh) = 68 if let Some((plan, transaction, bound_at, protected)) = existing { 69 if plan.protected_wire() != supplied.protected_wire() { 70 return Err(OperationError::IdempotencyConflict); 71 } 72 (plan, transaction, bound_at, protected, false) 73 } else { 74 if supplied.listing().is_some() && !super::listing::current(self.connection).await? 75 { 76 return Err(OperationError::UnsupportedOperation); 77 } 78 let window = prepared.issuance_window(); 79 if current.observed_at() < window.prepared_at() { 80 return Err(super::WorkspaceError::Unavailable.into()); 81 } 82 if current.observed_at() >= window.first_issue_not_after() { 83 return Err(OperationError::DeadlineExceeded); 84 } 85 let supplied = CapturedSigningPlan::parse( 86 prepared.request().command(), 87 supplied.protected_wire(), 88 ) 89 .map_err(|_| OperationError::InvalidCommand)?; 90 if supplied.created_at() < window.prepared_at() 91 || supplied.created_at() > current.observed_at() 92 { 93 return Err(OperationError::InvalidCommand); 94 } 95 let transaction = TransactionId::from_bytes(super::random()?); 96 let protected = plan::protect( 97 &prepared, 98 &supplied, 99 transaction, 100 current.observed_at(), 101 self.crypto, 102 ) 103 .await?; 104 ( 105 supplied, 106 transaction, 107 current.observed_at(), 108 protected, 109 true, 110 ) 111 }; 112 let attempt = CommitAttempt::new( 113 anchor.workspace_id(), 114 anchor.operation_id(), 115 anchor.command_digest(), 116 Some(transaction_id), 117 ); 118 let mut transaction = self 119 .connection 120 .begin_with("BEGIN IMMEDIATE") 121 .await 122 .map_err(|_| OperationError::StorageFailure)?; 123 let changed = async { 124 let now = recheck( 125 &mut transaction, 126 self.namespace, 127 self.selected, 128 &grant, 129 &record, 130 &binding, 131 &proof, 132 self.clock, 133 ) 134 .await?; 135 operation::unchanged(&mut transaction, &prepared, &operation_protected).await?; 136 if fresh { 137 if now.observed_at() < bound_at { 138 return Err(super::WorkspaceError::Unavailable.into()); 139 } 140 if now.observed_at() >= prepared.issuance_window().first_issue_not_after() { 141 return Err(OperationError::DeadlineExceeded); 142 } 143 plan::unchanged(&mut transaction, &prepared, None).await?; 144 plan::insert(&mut transaction, &prepared, &protected).await?; 145 } else { 146 plan::unchanged(&mut transaction, &prepared, Some(&protected)).await?; 147 } 148 Ok(()) 149 } 150 .await; 151 if let Err(error) = changed { 152 if transaction.rollback().await.is_err() { 153 *self.uncertain = true; 154 return Ok(PlanBindingOutcome::Unknown(attempt)); 155 } 156 return Err(error); 157 } 158 let finished = if fresh { 159 transaction.commit().await 160 } else { 161 transaction.rollback().await 162 }; 163 if finished.is_err() { 164 *self.uncertain = true; 165 return Ok(PlanBindingOutcome::Unknown(attempt)); 166 } 167 Ok(PlanBindingOutcome::Committed( 168 BoundSigningPlan::from_committed_store(prepared, plan, transaction_id, bound_at)?, 169 )) 170 } 171 172 pub(super) async fn query_plan( 173 &mut self, 174 binding: WorkspaceBinding, 175 operation_id: OperationId, 176 digest: CommandDigest, 177 proof: AttachmentProof, 178 ) -> Result<Option<BoundSigningPlan>, OperationError> { 179 let (record, grant, _) = self.access(&binding, &proof).await?; 180 let operation = 181 operation::read(self.connection, self.selected, operation_id, self.crypto).await?; 182 let retained = if let Some((prepared, ciphertext)) = operation { 183 operation::check_digest(&prepared, binding.actor(), Some(digest))?; 184 same_binding(prepared.request().binding(), &binding)?; 185 let (prepared, plan) = 186 plan::read(self.connection, self.selected, prepared, self.crypto).await?; 187 Some((prepared, ciphertext, plan)) 188 } else { 189 None 190 }; 191 let mut transaction = self 192 .connection 193 .begin_with("BEGIN IMMEDIATE") 194 .await 195 .map_err(|_| OperationError::StorageFailure)?; 196 let checked: Result<(), OperationError> = async { 197 recheck( 198 &mut transaction, 199 self.namespace, 200 self.selected, 201 &grant, 202 &record, 203 &binding, 204 &proof, 205 self.clock, 206 ) 207 .await?; 208 if let Some((prepared, ciphertext, plan)) = &retained { 209 operation::unchanged(&mut transaction, prepared, ciphertext).await?; 210 plan::unchanged( 211 &mut transaction, 212 prepared, 213 plan.as_ref().map(|entry| &entry.3), 214 ) 215 .await?; 216 } else { 217 operation::absent(&mut transaction, self.selected, operation_id).await?; 218 } 219 Ok(()) 220 } 221 .await; 222 if transaction.rollback().await.is_err() { 223 *self.uncertain = true; 224 return Err(OperationError::RecoveryRequired); 225 } 226 checked?; 227 match retained { 228 Some((prepared, _, Some((plan, transaction, bound_at, _)))) => Ok(Some( 229 BoundSigningPlan::from_committed_store(prepared, plan, transaction, bound_at)?, 230 )), 231 _ => Ok(None), 232 } 233 } 234 235 pub(super) async fn admit( 236 &mut self, 237 request: AdmissionRequest, 238 proof: AttachmentProof, 239 ) -> Result<AdmissionOutcome, OperationError> { 240 let (record, grant, observed) = self.access(request.binding(), &proof).await?; 241 let context = request.command().context(); 242 let workspace = context.workspace_id(); 243 let operation_id = context.operation_id(); 244 let digest = request.command().digest(); 245 // Exact replay precedes fresh deadline, allocation, entropy and encoding. 246 let existing = 247 operation::read(self.connection, self.selected, operation_id, self.crypto).await?; 248 if let Some((snapshot, protected)) = existing { 249 operation::check_digest(&snapshot, context.actor(), Some(digest))?; 250 same_binding(snapshot.request().binding(), request.binding())?; 251 let anchor = snapshot.identity(); 252 let mut transaction = self 253 .connection 254 .begin_with("BEGIN IMMEDIATE") 255 .await 256 .map_err(|_| OperationError::StorageFailure)?; 257 let checked: Result<(), OperationError> = async { 258 recheck( 259 &mut transaction, 260 self.namespace, 261 self.selected, 262 &grant, 263 &record, 264 request.binding(), 265 &proof, 266 self.clock, 267 ) 268 .await?; 269 operation::unchanged(&mut transaction, &snapshot, &protected).await 270 } 271 .await; 272 if transaction.rollback().await.is_err() { 273 *self.uncertain = true; 274 return Ok(AdmissionOutcome::Unknown(anchor)); 275 } 276 checked?; 277 return Ok(AdmissionOutcome::Committed(snapshot)); 278 } 279 280 if request.command().listing().is_some() 281 && !super::listing::current(self.connection).await? 282 { 283 return Err(OperationError::UnsupportedOperation); 284 } 285 286 // This fresh local outbox has no authenticated parent/order 287 // history or protected approval origin. Selectors cannot create either. 288 request.validate_fresh(observed.observed_at())?; 289 if observed.observed_at() < request.binding().observed_at() { 290 return Err(super::WorkspaceError::Unavailable.into()); 291 } 292 let window = IssuanceWindow::capture(observed.observed_at(), context.not_after()) 293 .map_err(|_| OperationError::DeadlineExceeded)?; 294 let transaction_id = TransactionId::from_bytes(super::random()?); 295 let anchor = CommitAttempt::new(workspace, operation_id, digest, Some(transaction_id)); 296 // Encryption/provider work finishes before opening the write transaction. 297 let protected = operation::protect(&request, transaction_id, window, self.crypto).await?; 298 let creation = 299 super::listing::Creation::protect(&request, transaction_id, self.crypto).await?; 300 let mut transaction = self 301 .connection 302 .begin_with("BEGIN IMMEDIATE") 303 .await 304 .map_err(|_| OperationError::StorageFailure)?; 305 let inserted = async { 306 let current = recheck( 307 &mut transaction, 308 self.namespace, 309 self.selected, 310 &grant, 311 &record, 312 request.binding(), 313 &proof, 314 self.clock, 315 ) 316 .await?; 317 if current.observed_at() < window.prepared_at() { 318 return Err(super::WorkspaceError::Unavailable.into()); 319 } 320 if window.first_issue_not_after() <= current.observed_at() 321 || context.not_after() > current.expires_at() 322 { 323 return Err(OperationError::DeadlineExceeded); 324 } 325 operation::absent(&mut transaction, self.selected, operation_id).await?; 326 operation::insert(&mut transaction, &request, transaction_id, &protected).await?; 327 if let Some(creation) = &creation { 328 creation.insert(&mut transaction).await?; 329 } 330 Ok(()) 331 } 332 .await; 333 if let Err(error) = inserted { 334 if transaction.rollback().await.is_err() { 335 *self.uncertain = true; 336 return Ok(AdmissionOutcome::Unknown(anchor)); 337 } 338 return Err(error); 339 } 340 if transaction.commit().await.is_err() { 341 *self.uncertain = true; 342 return Ok(AdmissionOutcome::Unknown(anchor)); 343 } 344 Ok(AdmissionOutcome::Committed( 345 PreparedOperation::from_committed_store( 346 request, 347 transaction_id, 348 radroots_domain::Sequence::new(1).map_err(|_| OperationError::RecoveryRequired)?, 349 window, 350 )?, 351 )) 352 } 353 354 pub(super) async fn query( 355 &mut self, 356 binding: WorkspaceBinding, 357 operation_id: OperationId, 358 digest: Option<CommandDigest>, 359 proof: AttachmentProof, 360 ) -> Result<Option<PreparedOperation>, OperationError> { 361 let (record, grant, _) = self.access(&binding, &proof).await?; 362 let result = 363 operation::read(self.connection, self.selected, operation_id, self.crypto).await?; 364 if let Some((snapshot, _)) = &result { 365 operation::check_digest(snapshot, binding.actor(), digest)?; 366 same_binding(snapshot.request().binding(), &binding)?; 367 } 368 let mut transaction = self 369 .connection 370 .begin_with("BEGIN IMMEDIATE") 371 .await 372 .map_err(|_| OperationError::StorageFailure)?; 373 let checked: Result<(), OperationError> = async { 374 recheck( 375 &mut transaction, 376 self.namespace, 377 self.selected, 378 &grant, 379 &record, 380 &binding, 381 &proof, 382 self.clock, 383 ) 384 .await?; 385 if let Some((snapshot, protected)) = &result { 386 operation::unchanged(&mut transaction, snapshot, protected).await?; 387 } else { 388 operation::absent(&mut transaction, self.selected, operation_id).await?; 389 } 390 Ok(()) 391 } 392 .await; 393 if transaction.rollback().await.is_err() { 394 *self.uncertain = true; 395 return Err(OperationError::RecoveryRequired); 396 } 397 checked?; 398 Ok(result.map(|(snapshot, _)| snapshot)) 399 } 400 } 401 402 pub(super) use radroots_storage::command::protected::same_binding; 403 404 #[expect( 405 clippy::too_many_arguments, 406 reason = "Private transaction recheck borrows only the existing owner inputs" 407 )] 408 pub(super) async fn recheck( 409 transaction: &mut Transaction<'_, Sqlite>, 410 namespace: &Namespace, 411 selected: &AttachmentInput, 412 protected: &[u8], 413 record: &GrantRecord, 414 binding: &WorkspaceBinding, 415 proof: &AttachmentProof, 416 clock: &dyn WorkspaceClock, 417 ) -> Result<WorkspaceBinding, OperationError> { 418 namespace.validate()?; 419 if worker::read(transaction, selected).await? != protected { 420 return Err(OperationError::RecoveryRequired); 421 } 422 // No provider await occurs under this transaction: the exact protected row 423 // has just matched the authenticated pre-transaction plaintext. 424 let current = record.authenticate(binding.input(), proof, clock.now()?)?; 425 same_binding(binding, ¤t)?; 426 Ok(current) 427 }