attempt.rs (9318B)
1 //! Immutable backend-owned first-claim records; no signer is invoked here. 2 use super::{ 3 AttachmentInput, 4 crypto::{IssuancePayload, IssuanceScope, WorkspaceCrypto}, 5 }; 6 use radroots_domain::{SigningAttemptId, TransactionId, UnixSeconds}; 7 use radroots_storage::command::SigningTarget; 8 use radroots_storage::command::protected::issuance::ClaimRecord; 9 use radroots_storage::command::{BoundSigningPlan, ClaimSnapshot, OperationError, SigningAttempt}; 10 use sqlx::{Row, SqliteConnection}; 11 12 pub(super) const TABLE: &str = "CREATE TABLE signing_attempts (workspace BLOB NOT NULL, operation_id BLOB NOT NULL, artifact_key BLOB NOT NULL CHECK(length(artifact_key)=32 OR (length(artifact_key)=1 AND hex(artifact_key)='00')), attempt_id BLOB NOT NULL CHECK(length(attempt_id)=32), transaction_id BLOB NOT NULL CHECK(length(transaction_id)=32), plan_digest BLOB NOT NULL CHECK(length(plan_digest)=32), intent_digest BLOB NOT NULL CHECK(length(intent_digest)=32), protected BLOB NOT NULL CHECK(length(protected)>0 AND length(protected)<=262144), PRIMARY KEY(workspace,operation_id,artifact_key), FOREIGN KEY(workspace,operation_id) REFERENCES signing_plans(workspace,operation_id)) STRICT, WITHOUT ROWID"; 13 pub(super) const TABLE_V8: &str = "CREATE TABLE signing_attempts (workspace BLOB NOT NULL, operation_id BLOB NOT NULL, recipient BLOB NOT NULL CHECK(length(recipient)=32), attempt_id BLOB NOT NULL CHECK(length(attempt_id)=32), transaction_id BLOB NOT NULL CHECK(length(transaction_id)=32), plan_digest BLOB NOT NULL CHECK(length(plan_digest)=32), intent_digest BLOB NOT NULL CHECK(length(intent_digest)=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 signing_plans(workspace,operation_id)) STRICT, WITHOUT ROWID"; 14 pub(super) const ID_INDEX: &str = 15 "CREATE UNIQUE INDEX signing_attempt_identity ON signing_attempts(workspace,attempt_id)"; 16 pub(super) const TX_INDEX: &str = "CREATE UNIQUE INDEX signing_attempt_transaction_identity ON signing_attempts(workspace,transaction_id)"; 17 18 pub(super) fn scope(attempt: &SigningAttempt) -> Result<IssuanceScope, OperationError> { 19 let identity = attempt.bound_plan().prepared().identity(); 20 Ok(IssuanceScope { 21 workspace: identity.workspace_id(), 22 operation: identity.operation_id(), 23 plan_digest: *attempt.bound_plan().plan().digest(), 24 attempt: attempt.attempt_id(), 25 target: attempt.target(), 26 }) 27 } 28 pub(super) async fn protect( 29 attempt: &SigningAttempt, 30 crypto: &WorkspaceCrypto, 31 ) -> Result<Vec<u8>, OperationError> { 32 let bytes = ClaimRecord::capture(attempt)?.encode()?; 33 Ok(crypto 34 .seal_issuance(scope(attempt)?, IssuancePayload::Attempt, 0, &bytes) 35 .await?) 36 } 37 /// Returns the complete original plan on absence as well as a verified retained 38 /// claim on presence. Providers run before the caller's write transaction. 39 pub(super) async fn read( 40 connection: &mut SqliteConnection, 41 selected: &AttachmentInput, 42 bound: BoundSigningPlan, 43 target: impl Into<SigningTarget>, 44 crypto: &WorkspaceCrypto, 45 ) -> Result< 46 ( 47 BoundSigningPlan, 48 Option<(SigningAttemptId, TransactionId, UnixSeconds, Vec<u8>)>, 49 ), 50 OperationError, 51 > { 52 let target = target.into(); 53 let original = bound.prepared().identity(); 54 let row=sqlx::query(sql(connection, "SELECT CASE WHEN length(attempt_id)=32 THEN attempt_id END,CASE WHEN length(transaction_id)=32 THEN transaction_id END,CASE WHEN length(plan_digest)=32 THEN plan_digest END,CASE WHEN length(intent_digest)=32 THEN intent_digest END,CASE WHEN length(protected)>0 AND length(protected)<=262144 THEN protected END FROM signing_attempts WHERE workspace=? AND operation_id=? AND recipient=?").await?) 55 .bind(selected.workspace_id().as_bytes().as_slice()).bind(original.operation_id().as_bytes().as_slice()).bind(target.key().as_slice()).fetch_optional(&mut *connection).await.map_err(|_|OperationError::RecoveryRequired)?; 56 let Some(row) = row else { 57 return Ok((bound, None)); 58 }; 59 let bytes = |index| { 60 row.try_get::<Option<Vec<u8>>, _>(index) 61 .map_err(|_| OperationError::RecoveryRequired)? 62 .ok_or(OperationError::RecoveryRequired) 63 }; 64 let id = SigningAttemptId::from_bytes( 65 bytes(0)? 66 .try_into() 67 .map_err(|_| OperationError::RecoveryRequired)?, 68 ); 69 let transaction = TransactionId::from_bytes( 70 bytes(1)? 71 .try_into() 72 .map_err(|_| OperationError::RecoveryRequired)?, 73 ); 74 let plan_digest = bytes(2)?; 75 let intent_digest = bytes(3)?; 76 let protected = bytes(4)?; 77 if plan_digest.as_slice() != bound.plan().digest() { 78 return Err(OperationError::RecoveryRequired); 79 } 80 let issuance_scope = IssuanceScope { 81 workspace: selected.workspace_id(), 82 operation: original.operation_id(), 83 plan_digest: *bound.plan().digest(), 84 attempt: id, 85 target, 86 }; 87 let plaintext = crypto 88 .open_issuance(issuance_scope, IssuancePayload::Attempt, 0, &protected) 89 .await?; 90 let attempt = plaintext.expose_secret(|raw| ClaimRecord::decode(raw, bound, target))?; 91 if attempt.attempt_id() != id 92 || attempt.transaction_id() != transaction 93 || intent_digest.as_slice() != attempt.binding().digest() 94 { 95 return Err(OperationError::RecoveryRequired); 96 } 97 let time = attempt.claimed_at(); 98 Ok(( 99 attempt.into_bound_plan(), 100 Some((id, transaction, time, protected)), 101 )) 102 } 103 104 pub(super) async fn insert( 105 connection: &mut SqliteConnection, 106 attempt: &SigningAttempt, 107 protected: &[u8], 108 ) -> Result<(), OperationError> { 109 require_target(connection, attempt.target()).await?; 110 let identity = attempt.bound_plan().prepared().identity(); 111 sqlx::query(sql(connection, "INSERT INTO signing_attempts(workspace,operation_id,recipient,attempt_id,transaction_id,plan_digest,intent_digest,protected) VALUES(?,?,?,?,?,?,?,?)").await?) 112 .bind(identity.workspace_id().as_bytes().as_slice()).bind(identity.operation_id().as_bytes().as_slice()).bind(attempt.target().key().as_slice()).bind(attempt.attempt_id().as_bytes().as_slice()).bind(attempt.transaction_id().as_bytes().as_slice()).bind(attempt.bound_plan().plan().digest().as_slice()).bind(attempt.binding().digest().as_slice()).bind(protected).execute(connection).await.map_err(|_|OperationError::StorageFailure)?; 113 Ok(()) 114 } 115 pub(super) async fn unchanged( 116 connection: &mut SqliteConnection, 117 attempt: &SigningAttempt, 118 protected: &[u8], 119 ) -> Result<(), OperationError> { 120 unchanged_snapshot( 121 connection, 122 ClaimSnapshot::from_store_report(attempt)?, 123 protected, 124 ) 125 .await 126 } 127 pub(super) async fn unchanged_snapshot( 128 connection: &mut SqliteConnection, 129 snapshot: ClaimSnapshot, 130 protected: &[u8], 131 ) -> Result<(), OperationError> { 132 let count:i64=sqlx::query_scalar(sql(connection, "SELECT count(*) FROM signing_attempts WHERE workspace=? AND operation_id=? AND recipient=? AND attempt_id=? AND transaction_id=? AND plan_digest=? AND intent_digest=? AND protected=?").await?) 133 .bind(snapshot.workspace_id().as_bytes().as_slice()).bind(snapshot.operation_id().as_bytes().as_slice()).bind(snapshot.target().key().as_slice()).bind(snapshot.attempt_id().as_bytes().as_slice()).bind(snapshot.transaction_id().as_bytes().as_slice()).bind(snapshot.plan_digest().as_slice()).bind(snapshot.intent().digest().as_slice()).bind(protected).fetch_one(connection).await.map_err(|_|OperationError::RecoveryRequired)?; 134 if count != 1 { 135 return Err(OperationError::RecoveryRequired); 136 } 137 Ok(()) 138 } 139 140 /// Exact old catalogs retain their names and private bytes without migration. 141 /// This is identifier adaptation on the same transaction engine, not a fallback 142 /// schema or a second persistence implementation. 143 pub(super) async fn sql( 144 connection: &mut SqliteConnection, 145 legacy: &'static str, 146 ) -> Result<sqlx::AssertSqlSafe<String>, OperationError> { 147 let version: i64 = sqlx::query_scalar("PRAGMA user_version") 148 .fetch_one(connection) 149 .await 150 .map_err(|_| OperationError::RecoveryRequired)?; 151 match version { 152 7 | 8 => Ok(sqlx::AssertSqlSafe(legacy.to_owned())), 153 9..=11 => { 154 let query = legacy 155 .replace("seal_evidence", "artifact_evidence") 156 .replace("recipient", "artifact_key"); 157 Ok(sqlx::AssertSqlSafe(if version == 11 { 158 query.replace("chat_delivery", "artifact_delivery") 159 } else { 160 query 161 })) 162 } 163 _ => Err(OperationError::RecoveryRequired), 164 } 165 } 166 pub(super) async fn require_target( 167 connection: &mut SqliteConnection, 168 target: SigningTarget, 169 ) -> Result<(), OperationError> { 170 if target == SigningTarget::PublicEvent { 171 let version: i64 = sqlx::query_scalar("PRAGMA user_version") 172 .fetch_one(connection) 173 .await 174 .map_err(|_| OperationError::RecoveryRequired)?; 175 if !matches!(version, 9..=11) { 176 return Err(OperationError::UnsupportedOperation); 177 } 178 } 179 Ok(()) 180 }