installation.rs (24837B)
1 //! Protected logical chat installation and original recipient publication links. 2 //! Bodies remain in the authenticated captured command; no private text is 3 //! duplicated or reserialized into these fixed bounded transaction records. 4 use super::{ 5 AttachmentInput, AttachmentProof, 6 admission::{Journal, recheck}, 7 crypto::{IssuancePayload, IssuanceScope, WorkspaceCrypto}, 8 snapshot::RetainedGraph, 9 }; 10 use core::num::NonZeroU64; 11 use radroots_domain::{ 12 CommandDigest, EnvelopeEventId, MessageId, OperationId, PublicKey, SigningAttemptId, ThreadId, 13 TransactionId, UnixSeconds, WorkspaceId, 14 }; 15 use radroots_storage::command::{ 16 BoundSigningPlan, ChatInstallation, CommitAttempt, EvidenceReceipt, InstallationOutcome, 17 InstallationRequest, OperationError, PublicationWork, 18 }; 19 use serde::{Deserialize, Serialize}; 20 use sqlx::{Connection, Row, SqliteConnection}; 21 use zeroize::Zeroizing; 22 23 pub(super) const TABLE: &str = "CREATE TABLE chat_messages (workspace BLOB NOT NULL, message_id BLOB NOT NULL CHECK(length(message_id)=32), operation_id BLOB NOT NULL, thread_id BLOB NOT NULL CHECK(length(thread_id)=32), plan_digest BLOB NOT NULL CHECK(length(plan_digest)=32), transaction_id BLOB NOT NULL CHECK(length(transaction_id)=32), protected BLOB NOT NULL CHECK(length(protected)>0 AND length(protected)<=262144), PRIMARY KEY(workspace,message_id), FOREIGN KEY(workspace,operation_id) REFERENCES signing_plans(workspace,operation_id)) STRICT, WITHOUT ROWID"; 24 pub(super) const OP_INDEX: &str = 25 "CREATE UNIQUE INDEX chat_message_operation_identity ON chat_messages(workspace,operation_id)"; 26 pub(super) const TX_INDEX: &str = "CREATE UNIQUE INDEX chat_message_transaction_identity ON chat_messages(workspace,transaction_id)"; 27 pub(super) const THREAD_INDEX: &str = 28 "CREATE INDEX chat_message_thread ON chat_messages(workspace,thread_id,message_id)"; 29 pub(super) const WORK: &str = "CREATE TABLE chat_publication_work (workspace BLOB NOT NULL, operation_id BLOB NOT NULL, recipient BLOB NOT NULL CHECK(length(recipient)=32), installation_transaction BLOB NOT NULL CHECK(length(installation_transaction)=32), capture_transaction BLOB NOT NULL CHECK(length(capture_transaction)=32), event_id BLOB NOT NULL CHECK(length(event_id)=32), evidence_digest BLOB NOT NULL CHECK(length(evidence_digest)=32), transaction_id BLOB NOT NULL CHECK(length(transaction_id)=32), protected BLOB NOT NULL CHECK(length(protected)>0 AND length(protected)<=262144), PRIMARY KEY(workspace,operation_id,recipient), FOREIGN KEY(workspace,operation_id) REFERENCES chat_messages(workspace,operation_id), FOREIGN KEY(workspace,operation_id,recipient) REFERENCES artifact_evidence(workspace,operation_id,artifact_key)) STRICT, WITHOUT ROWID"; 30 pub(super) const WORK_V8: &str = "CREATE TABLE chat_publication_work (workspace BLOB NOT NULL, operation_id BLOB NOT NULL, recipient BLOB NOT NULL CHECK(length(recipient)=32), installation_transaction BLOB NOT NULL CHECK(length(installation_transaction)=32), capture_transaction BLOB NOT NULL CHECK(length(capture_transaction)=32), event_id BLOB NOT NULL CHECK(length(event_id)=32), evidence_digest BLOB NOT NULL CHECK(length(evidence_digest)=32), transaction_id BLOB NOT NULL CHECK(length(transaction_id)=32), protected BLOB NOT NULL CHECK(length(protected)>0 AND length(protected)<=262144), PRIMARY KEY(workspace,operation_id,recipient), FOREIGN KEY(workspace,operation_id) REFERENCES chat_messages(workspace,operation_id), FOREIGN KEY(workspace,operation_id,recipient) REFERENCES seal_evidence(workspace,operation_id,recipient)) STRICT, WITHOUT ROWID"; 31 32 #[derive(Serialize, Deserialize, Eq, PartialEq)] 33 #[serde(deny_unknown_fields)] 34 pub(super) struct EvidenceRef { 35 workspace: WorkspaceId, 36 operation: OperationId, 37 command: CommandDigest, 38 recipient: PublicKey, 39 attempt: SigningAttemptId, 40 event: EnvelopeEventId, 41 digest: [u8; 32], 42 transaction: TransactionId, 43 observed_at: Option<u64>, 44 } 45 impl EvidenceRef { 46 pub(super) fn new(value: EvidenceReceipt, recipient: PublicKey) -> Self { 47 Self { 48 workspace: value.workspace_id(), 49 operation: value.operation_id(), 50 command: value.command_digest(), 51 recipient, 52 attempt: value.attempt_id(), 53 event: value.event_id(), 54 digest: *value.digest(), 55 transaction: value.transaction_id(), 56 observed_at: value.observed_at_unix_ms().map(NonZeroU64::get), 57 } 58 } 59 } 60 #[derive(Serialize, Deserialize, Eq, PartialEq)] 61 #[serde(deny_unknown_fields)] 62 struct MessageRecord { 63 version: u8, 64 plan_digest: [u8; 32], 65 message: MessageId, 66 thread: ThreadId, 67 preparation_transaction: TransactionId, 68 plan_transaction: TransactionId, 69 transaction: TransactionId, 70 installed_at: UnixSeconds, 71 basis: EvidenceRef, 72 } 73 impl MessageRecord { 74 fn new(bound: &BoundSigningPlan, value: ChatInstallation) -> Result<Self, OperationError> { 75 Ok(Self { 76 version: 1, 77 plan_digest: *value.plan_digest(), 78 message: value.message_id(), 79 thread: bound.prepared().request().chat_command()?.thread_id(), 80 preparation_transaction: value.preparation_transaction_id(), 81 plan_transaction: value.plan_transaction_id(), 82 transaction: value.transaction_id(), 83 installed_at: value.installed_at(), 84 basis: EvidenceRef::new(value.basis(), value.basis().recipient()?), 85 }) 86 } 87 } 88 #[derive(Serialize, Deserialize, Eq, PartialEq)] 89 #[serde(deny_unknown_fields)] 90 struct WorkRecord { 91 version: u8, 92 plan_digest: [u8; 32], 93 message: MessageId, 94 installation_transaction: TransactionId, 95 preparation_transaction: TransactionId, 96 plan_transaction: TransactionId, 97 transaction: TransactionId, 98 queued_at: UnixSeconds, 99 evidence: EvidenceRef, 100 } 101 impl WorkRecord { 102 fn new(installed: ChatInstallation, value: PublicationWork) -> Self { 103 Self { 104 version: 1, 105 plan_digest: *value.plan_digest(), 106 message: installed.message_id(), 107 installation_transaction: value.installation_transaction_id(), 108 preparation_transaction: installed.preparation_transaction_id(), 109 plan_transaction: installed.plan_transaction_id(), 110 transaction: value.transaction_id(), 111 queued_at: value.queued_at(), 112 evidence: EvidenceRef::new(value.evidence(), value.recipient()), 113 } 114 } 115 } 116 pub(super) struct ProtectedMessage { 117 pub report: ChatInstallation, 118 pub thread: ThreadId, 119 pub protected: Vec<u8>, 120 } 121 pub(super) struct ProtectedWork { 122 pub report: PublicationWork, 123 pub protected: Vec<u8>, 124 } 125 pub(super) struct Records { 126 pub message: Option<ProtectedMessage>, 127 pub work: Vec<ProtectedWork>, 128 } 129 fn scope(bound: &BoundSigningPlan, receipt: EvidenceReceipt) -> IssuanceScope { 130 IssuanceScope { 131 workspace: receipt.workspace_id(), 132 operation: receipt.operation_id(), 133 plan_digest: *bound.plan().digest(), 134 attempt: receipt.attempt_id(), 135 target: receipt.target(), 136 } 137 } 138 fn bytes(row: &sqlx::sqlite::SqliteRow, index: usize) -> Result<Vec<u8>, OperationError> { 139 row.try_get::<Option<Vec<u8>>, _>(index) 140 .map_err(|_| OperationError::RecoveryRequired)? 141 .ok_or(OperationError::RecoveryRequired) 142 } 143 fn obtained( 144 graph: &RetainedGraph, 145 recipient: PublicKey, 146 ) -> Result<EvidenceReceipt, OperationError> { 147 graph 148 .reports() 149 .find(|value| value.target().recipient() == Some(recipient)) 150 .and_then(|value| value.obtained()) 151 .ok_or(OperationError::RecoveryRequired) 152 } 153 impl Records { 154 pub(super) async fn read( 155 connection: &mut SqliteConnection, 156 selected: &AttachmentInput, 157 operation: OperationId, 158 graph: &RetainedGraph, 159 crypto: &WorkspaceCrypto, 160 ) -> Result<Self, OperationError> { 161 // At most one message and two recipient work rows can be materialized; 162 // fixed 262144-byte protected bounds cap their total below 1 MiB. 163 // Excess or orphan rows are rejected by bounded transaction sentinels. 164 let row=sqlx::query("SELECT CASE WHEN length(message_id)=32 THEN message_id END,CASE WHEN length(thread_id)=32 THEN thread_id END,CASE WHEN length(plan_digest)=32 THEN plan_digest END,CASE WHEN length(transaction_id)=32 THEN transaction_id END,CASE WHEN length(protected)>0 AND length(protected)<=262144 THEN protected END FROM chat_messages WHERE workspace=? AND operation_id=? LIMIT 1") 165 .bind(selected.workspace_id().as_bytes().as_slice()).bind(operation.as_bytes().as_slice()).fetch_optional(&mut *connection).await.map_err(|_|OperationError::RecoveryRequired)?; 166 let message = if let Some(row) = row { 167 let bound = graph.bound_plan().ok_or(OperationError::RecoveryRequired)?; 168 let protected = bytes(&row, 4)?; 169 let plaintext = crypto 170 .open_message( 171 selected.workspace_id(), 172 operation, 173 bound.plan().digest(), 174 &protected, 175 ) 176 .await?; 177 let encoded: MessageRecord = plaintext 178 .expose_secret(|raw| serde_json::from_slice(raw)) 179 .map_err(|_| OperationError::RecoveryRequired)?; 180 let basis = obtained(graph, encoded.basis.recipient)?; 181 let report = ChatInstallation::from_committed_store( 182 bound, 183 basis, 184 encoded.transaction, 185 encoded.installed_at, 186 )?; 187 if encoded != MessageRecord::new(bound, report)? 188 || bytes(&row, 0)? != report.message_id().as_bytes() 189 || bytes(&row, 1)? 190 != bound 191 .prepared() 192 .request() 193 .chat_command()? 194 .thread_id() 195 .as_bytes() 196 || bytes(&row, 2)? != report.plan_digest() 197 || bytes(&row, 3)? != report.transaction_id().as_bytes() 198 { 199 return Err(OperationError::RecoveryRequired); 200 } 201 Some(ProtectedMessage { 202 report, 203 thread: encoded.thread, 204 protected, 205 }) 206 } else { 207 None 208 }; 209 let mut work = Vec::new(); 210 if let Some(bound) = graph.bound_plan() { 211 for recipient in graph 212 .reports() 213 .filter_map(|value| value.target().recipient()) 214 { 215 let row=sqlx::query("SELECT CASE WHEN length(installation_transaction)=32 THEN installation_transaction END,CASE WHEN length(capture_transaction)=32 THEN capture_transaction END,CASE WHEN length(event_id)=32 THEN event_id END,CASE WHEN length(evidence_digest)=32 THEN evidence_digest END,CASE WHEN length(transaction_id)=32 THEN transaction_id END,CASE WHEN length(protected)>0 AND length(protected)<=262144 THEN protected END FROM chat_publication_work WHERE workspace=? AND operation_id=? AND recipient=?") 216 .bind(selected.workspace_id().as_bytes().as_slice()).bind(operation.as_bytes().as_slice()).bind(recipient.as_bytes().as_slice()).fetch_optional(&mut *connection).await.map_err(|_|OperationError::RecoveryRequired)?; 217 if let Some(row) = row { 218 let installed = message 219 .as_ref() 220 .ok_or(OperationError::RecoveryRequired)? 221 .report; 222 let evidence = obtained(graph, recipient)?; 223 let protected = bytes(&row, 5)?; 224 let plaintext = crypto 225 .open_issuance( 226 scope(bound, evidence), 227 IssuancePayload::Publication, 228 0, 229 &protected, 230 ) 231 .await?; 232 let encoded: WorkRecord = plaintext 233 .expose_secret(|raw| serde_json::from_slice(raw)) 234 .map_err(|_| OperationError::RecoveryRequired)?; 235 let report = PublicationWork::from_committed_store( 236 bound, 237 installed, 238 evidence, 239 encoded.transaction, 240 encoded.queued_at, 241 )?; 242 if encoded != WorkRecord::new(installed, report) 243 || bytes(&row, 0)? != installed.transaction_id().as_bytes() 244 || bytes(&row, 1)? != evidence.transaction_id().as_bytes() 245 || bytes(&row, 2)? != evidence.event_id().as_bytes() 246 || bytes(&row, 3)? != evidence.digest() 247 || bytes(&row, 4)? != report.transaction_id().as_bytes() 248 { 249 return Err(OperationError::RecoveryRequired); 250 } 251 work.push(ProtectedWork { report, protected }); 252 } 253 } 254 } 255 if let Some(message) = &message 256 && !work 257 .iter() 258 .any(|value| value.report.evidence() == message.report.basis()) 259 { 260 return Err(OperationError::RecoveryRequired); 261 } 262 Ok(Self { message, work }) 263 } 264 pub(super) async fn unchanged( 265 &self, 266 connection: &mut SqliteConnection, 267 selected: &AttachmentInput, 268 operation: OperationId, 269 ) -> Result<(), OperationError> { 270 let counts:(i64,i64)=sqlx::query_as("SELECT (SELECT count(*) FROM (SELECT 1 FROM chat_messages WHERE workspace=?1 AND operation_id=?2 LIMIT 2)),(SELECT count(*) FROM (SELECT 1 FROM chat_publication_work WHERE workspace=?1 AND operation_id=?2 LIMIT 3))") 271 .bind(selected.workspace_id().as_bytes().as_slice()).bind(operation.as_bytes().as_slice()).fetch_one(&mut *connection).await.map_err(|_|OperationError::RecoveryRequired)?; 272 if counts != (i64::from(self.message.is_some()), self.work.len() as i64) { 273 return Err(OperationError::RecoveryRequired); 274 } 275 if let Some(message) = &self.message { 276 let installed = message.report; 277 let count:i64=sqlx::query_scalar("SELECT count(*) FROM chat_messages WHERE workspace=? AND operation_id=? AND message_id=? AND thread_id=? AND plan_digest=? AND transaction_id=? AND protected=?") 278 .bind(selected.workspace_id().as_bytes().as_slice()).bind(operation.as_bytes().as_slice()).bind(installed.message_id().as_bytes().as_slice()).bind(message.thread.as_bytes().as_slice()).bind(installed.plan_digest().as_slice()).bind(installed.transaction_id().as_bytes().as_slice()).bind(&message.protected).fetch_one(&mut *connection).await.map_err(|_|OperationError::RecoveryRequired)?; 279 if count != 1 { 280 return Err(OperationError::RecoveryRequired); 281 } 282 } 283 for value in &self.work { 284 let work = value.report; 285 let evidence = work.evidence(); 286 let count:i64=sqlx::query_scalar("SELECT count(*) FROM chat_publication_work WHERE workspace=? AND operation_id=? AND recipient=? AND installation_transaction=? AND capture_transaction=? AND event_id=? AND evidence_digest=? AND transaction_id=? AND protected=?") 287 .bind(selected.workspace_id().as_bytes().as_slice()).bind(operation.as_bytes().as_slice()).bind(evidence.recipient()?.as_bytes().as_slice()).bind(work.installation_transaction_id().as_bytes().as_slice()).bind(evidence.transaction_id().as_bytes().as_slice()).bind(evidence.event_id().as_bytes().as_slice()).bind(evidence.digest().as_slice()).bind(work.transaction_id().as_bytes().as_slice()).bind(&value.protected).fetch_one(&mut *connection).await.map_err(|_|OperationError::RecoveryRequired)?; 288 if count != 1 { 289 return Err(OperationError::RecoveryRequired); 290 } 291 } 292 Ok(()) 293 } 294 } 295 pub(super) async fn protect_message( 296 bound: &BoundSigningPlan, 297 report: ChatInstallation, 298 crypto: &WorkspaceCrypto, 299 ) -> Result<ProtectedMessage, OperationError> { 300 let plaintext = Zeroizing::new( 301 serde_json::to_vec(&MessageRecord::new(bound, report)?) 302 .map_err(|_| OperationError::InvalidCommand)?, 303 ); 304 let protected = crypto 305 .seal_message( 306 report.workspace_id(), 307 report.operation_id(), 308 report.plan_digest(), 309 &plaintext, 310 ) 311 .await?; 312 Ok(ProtectedMessage { 313 report, 314 thread: bound.prepared().request().chat_command()?.thread_id(), 315 protected, 316 }) 317 } 318 pub(super) async fn protect_work( 319 bound: &BoundSigningPlan, 320 installed: ChatInstallation, 321 report: PublicationWork, 322 crypto: &WorkspaceCrypto, 323 ) -> Result<ProtectedWork, OperationError> { 324 let plaintext = Zeroizing::new( 325 serde_json::to_vec(&WorkRecord::new(installed, report)) 326 .map_err(|_| OperationError::InvalidCommand)?, 327 ); 328 let protected = crypto 329 .seal_issuance( 330 scope(bound, report.evidence()), 331 IssuancePayload::Publication, 332 0, 333 &plaintext, 334 ) 335 .await?; 336 Ok(ProtectedWork { report, protected }) 337 } 338 pub(super) async fn insert_message( 339 connection: &mut SqliteConnection, 340 bound: &BoundSigningPlan, 341 value: &ProtectedMessage, 342 ) -> Result<(), OperationError> { 343 let report = value.report; 344 sqlx::query("INSERT INTO chat_messages(workspace,message_id,operation_id,thread_id,plan_digest,transaction_id,protected) VALUES(?,?,?,?,?,?,?)") 345 .bind(report.workspace_id().as_bytes().as_slice()).bind(report.message_id().as_bytes().as_slice()).bind(report.operation_id().as_bytes().as_slice()).bind(bound.prepared().request().chat_command()?.thread_id().as_bytes().as_slice()).bind(report.plan_digest().as_slice()).bind(report.transaction_id().as_bytes().as_slice()).bind(&value.protected).execute(connection).await.map_err(write_error)?; 346 Ok(()) 347 } 348 pub(super) async fn insert_work( 349 connection: &mut SqliteConnection, 350 value: &ProtectedWork, 351 ) -> Result<(), OperationError> { 352 let work = value.report; 353 let evidence = work.evidence(); 354 sqlx::query("INSERT INTO chat_publication_work(workspace,operation_id,recipient,installation_transaction,capture_transaction,event_id,evidence_digest,transaction_id,protected) VALUES(?,?,?,?,?,?,?,?,?)") 355 .bind(evidence.workspace_id().as_bytes().as_slice()).bind(evidence.operation_id().as_bytes().as_slice()).bind(evidence.recipient()?.as_bytes().as_slice()).bind(work.installation_transaction_id().as_bytes().as_slice()).bind(evidence.transaction_id().as_bytes().as_slice()).bind(evidence.event_id().as_bytes().as_slice()).bind(evidence.digest().as_slice()).bind(work.transaction_id().as_bytes().as_slice()).bind(&value.protected).execute(connection).await.map_err(write_error)?; 356 Ok(()) 357 } 358 fn write_error(error: sqlx::Error) -> OperationError { 359 if error 360 .as_database_error() 361 .is_some_and(|value| value.is_unique_violation()) 362 { 363 OperationError::IdempotencyConflict 364 } else { 365 OperationError::StorageFailure 366 } 367 } 368 369 impl Journal<'_> { 370 pub(super) async fn install_chat( 371 &mut self, 372 request: InstallationRequest, 373 proof: AttachmentProof, 374 ) -> Result<InstallationOutcome, OperationError> { 375 let (record, grant, current) = self.access(request.binding(), &proof).await?; 376 let graph = RetainedGraph::read( 377 self.connection, 378 self.selected, 379 request.binding(), 380 request.operation_id(), 381 Some(request.command_digest()), 382 self.crypto, 383 ) 384 .await?; 385 if graph 386 .bound_plan() 387 .is_some_and(|bound| bound.plan().listing().is_some()) 388 { 389 return self 390 .install_listing(request, proof, record, grant, current, graph) 391 .await; 392 } 393 let bound = graph.bound_plan().ok_or(OperationError::RecoveryRequired)?; 394 if bound.plan().digest() != request.plan_digest() { 395 return Err(OperationError::IdempotencyConflict); 396 } 397 let records = Records::read( 398 self.connection, 399 self.selected, 400 request.operation_id(), 401 &graph, 402 self.crypto, 403 ) 404 .await?; 405 let missing: Vec<EvidenceReceipt> = graph 406 .reports() 407 .filter_map(|value| value.obtained()) 408 .filter(|evidence| { 409 !records 410 .work 411 .iter() 412 .any(|value| value.report.evidence().target() == evidence.target()) 413 }) 414 .collect(); 415 let fresh = records.message.is_none() || !missing.is_empty(); 416 if records.message.is_none() && missing.is_empty() { 417 return Err(OperationError::InvalidEvidence); 418 } 419 // Exact replay never replaces the installation, reruns allocation, 420 // re-signs, consumes new entropy or prepares replacement ciphertext. 421 let transaction_id = if fresh { 422 TransactionId::from_bytes(super::random()?) 423 } else { 424 records 425 .message 426 .as_ref() 427 .ok_or(OperationError::RecoveryRequired)? 428 .report 429 .transaction_id() 430 }; 431 let installed = match &records.message { 432 Some(value) => value.report, 433 None => ChatInstallation::from_committed_store( 434 bound, 435 *missing.first().ok_or(OperationError::InvalidEvidence)?, 436 transaction_id, 437 current.observed_at(), 438 )?, 439 }; 440 let prepared_message = if records.message.is_none() { 441 Some(protect_message(bound, installed, self.crypto).await?) 442 } else { 443 None 444 }; 445 let mut prepared_work = Vec::with_capacity(missing.len()); 446 for evidence in missing { 447 let work = PublicationWork::from_committed_store( 448 bound, 449 installed, 450 evidence, 451 transaction_id, 452 current.observed_at(), 453 )?; 454 prepared_work.push(protect_work(bound, installed, work, self.crypto).await?); 455 } 456 let anchor = CommitAttempt::new( 457 installed.workspace_id(), 458 installed.operation_id(), 459 installed.command_digest(), 460 Some(transaction_id), 461 ); 462 let mut transaction = self 463 .connection 464 .begin_with("BEGIN IMMEDIATE") 465 .await 466 .map_err(|_| OperationError::StorageFailure)?; 467 let changed = async { 468 let now = recheck( 469 &mut transaction, 470 self.namespace, 471 self.selected, 472 &grant, 473 &record, 474 request.binding(), 475 &proof, 476 self.clock, 477 ) 478 .await?; 479 graph 480 .unchanged(&mut transaction, self.selected, request.operation_id()) 481 .await?; 482 records 483 .unchanged(&mut transaction, self.selected, request.operation_id()) 484 .await?; 485 if fresh && now.observed_at() < current.observed_at() { 486 return Err(super::WorkspaceError::Unavailable.into()); 487 } 488 // The original window constrains first issuance, not installation 489 // of independently authenticated already obtained original bytes. 490 if let Some(message) = &prepared_message { 491 insert_message(&mut transaction, bound, message).await?; 492 } 493 for work in &prepared_work { 494 insert_work(&mut transaction, work).await?; 495 } 496 Ok::<_, OperationError>(()) 497 } 498 .await; 499 if let Err(error) = changed { 500 if transaction.rollback().await.is_err() { 501 *self.uncertain = true; 502 return Ok(InstallationOutcome::Unknown(anchor)); 503 } 504 return Err(error); 505 } 506 let completed = if fresh { 507 transaction.commit().await 508 } else { 509 transaction.rollback().await 510 }; 511 if completed.is_err() { 512 *self.uncertain = true; 513 return Ok(InstallationOutcome::Unknown(anchor)); 514 } 515 Ok(InstallationOutcome::Committed(Box::new(installed))) 516 } 517 }