plan.rs (13033B)
1 //! Protected complete plan storage; all crypto runs outside write transactions. 2 use super::{ 3 AttachmentInput, 4 crypto::{PRIVATE_PAYLOAD_MAX_BYTES, WorkspaceCrypto}, 5 }; 6 use radroots_domain::{TransactionId, UnixSeconds}; 7 use radroots_storage::command::protected::plan::PlanManifest; 8 use radroots_storage::command::{CapturedSigningPlan, OperationError, PreparedOperation}; 9 use sqlx::{Row, SqliteConnection}; 10 use zeroize::Zeroizing; 11 12 pub(super) const TABLE: &str = "CREATE TABLE signing_plans (workspace BLOB NOT NULL, operation_id BLOB NOT NULL, plan_digest BLOB NOT NULL CHECK(length(plan_digest)=32), transaction_id BLOB NOT NULL CHECK(length(transaction_id)=32), part_count INTEGER NOT NULL CHECK(part_count BETWEEN 1 AND 24), byte_count INTEGER NOT NULL CHECK(byte_count BETWEEN 1 AND 393216), protected BLOB NOT NULL CHECK(length(protected)>0 AND length(protected)<=262144), PRIMARY KEY(workspace,operation_id), FOREIGN KEY(workspace,operation_id) REFERENCES operations(workspace,operation_id)) STRICT, WITHOUT ROWID"; 13 pub(super) const PARTS: &str = "CREATE TABLE signing_plan_parts (workspace BLOB NOT NULL, operation_id BLOB NOT NULL, part INTEGER NOT NULL CHECK(part BETWEEN 1 AND 24), protected BLOB NOT NULL CHECK(length(protected)>0 AND length(protected)<=262144), PRIMARY KEY(workspace,operation_id,part), FOREIGN KEY(workspace,operation_id) REFERENCES signing_plans(workspace,operation_id)) STRICT, WITHOUT ROWID"; 14 const MAX_PROTECTED_TOTAL: usize = 2 * 1024 * 1024; 15 pub(super) struct ProtectedPlan { 16 pub digest: [u8; 32], 17 pub transaction: TransactionId, 18 pub manifest: Vec<u8>, 19 pub parts: Vec<Vec<u8>>, 20 pub bytes: usize, 21 } 22 pub(super) async fn protect( 23 prepared: &PreparedOperation, 24 plan: &CapturedSigningPlan, 25 transaction: TransactionId, 26 bound_at: UnixSeconds, 27 crypto: &WorkspaceCrypto, 28 ) -> Result<ProtectedPlan, OperationError> { 29 let anchor = prepared.identity(); 30 let chunks = plan.protected_wire().chunks(PRIVATE_PAYLOAD_MAX_BYTES); 31 let manifest = PlanManifest::capture(prepared, plan, transaction, bound_at)?; 32 let plaintext = manifest.encode()?; 33 let protected = crypto 34 .seal_plan_part( 35 anchor.workspace_id(), 36 anchor.operation_id(), 37 plan.digest(), 38 0, 39 &plaintext, 40 ) 41 .await?; 42 let mut total = protected.len(); 43 let mut parts = Vec::new(); 44 for (index, chunk) in chunks.enumerate() { 45 let part = crypto 46 .seal_plan_part( 47 anchor.workspace_id(), 48 anchor.operation_id(), 49 plan.digest(), 50 (index + 1) as u8, 51 chunk, 52 ) 53 .await?; 54 total = total 55 .checked_add(part.len()) 56 .filter(|size| *size <= MAX_PROTECTED_TOTAL) 57 .ok_or(OperationError::InvalidCommand)?; 58 parts.push(part); 59 } 60 Ok(ProtectedPlan { 61 digest: *plan.digest(), 62 transaction, 63 manifest: protected, 64 parts, 65 bytes: manifest.byte_count(), 66 }) 67 } 68 69 pub(super) async fn read( 70 connection: &mut SqliteConnection, 71 selected: &AttachmentInput, 72 prepared: PreparedOperation, 73 crypto: &WorkspaceCrypto, 74 ) -> Result< 75 ( 76 PreparedOperation, 77 Option<( 78 CapturedSigningPlan, 79 TransactionId, 80 UnixSeconds, 81 ProtectedPlan, 82 )>, 83 ), 84 OperationError, 85 > { 86 let anchor = prepared.identity(); 87 let row = sqlx::query("SELECT CASE WHEN length(plan_digest)=32 THEN plan_digest END,CASE WHEN length(transaction_id)=32 THEN transaction_id END,part_count,byte_count,CASE WHEN length(protected)>0 AND length(protected)<=262144 THEN protected END FROM signing_plans WHERE workspace=? AND operation_id=?") 88 .bind(selected.workspace_id().as_bytes().as_slice()).bind(anchor.operation_id().as_bytes().as_slice()).fetch_optional(&mut *connection).await.map_err(|_| OperationError::RecoveryRequired)?; 89 let Some(row) = row else { 90 return Ok((prepared, None)); 91 }; 92 let digest: Vec<u8> = row 93 .try_get::<Option<Vec<u8>>, _>(0) 94 .map_err(|_| OperationError::RecoveryRequired)? 95 .ok_or(OperationError::RecoveryRequired)?; 96 let digest: [u8; 32] = digest 97 .try_into() 98 .map_err(|_| OperationError::RecoveryRequired)?; 99 let transaction: Vec<u8> = row 100 .try_get::<Option<Vec<u8>>, _>(1) 101 .map_err(|_| OperationError::RecoveryRequired)? 102 .ok_or(OperationError::RecoveryRequired)?; 103 let transaction = TransactionId::from_bytes( 104 transaction 105 .try_into() 106 .map_err(|_| OperationError::RecoveryRequired)?, 107 ); 108 let part_count: i64 = row 109 .try_get(2) 110 .map_err(|_| OperationError::RecoveryRequired)?; 111 let byte_count: i64 = row 112 .try_get(3) 113 .map_err(|_| OperationError::RecoveryRequired)?; 114 if !(1..=24).contains(&part_count) 115 || !(1..=393216).contains(&byte_count) 116 || (byte_count as usize).div_ceil(PRIVATE_PAYLOAD_MAX_BYTES) != part_count as usize 117 { 118 return Err(OperationError::RecoveryRequired); 119 } 120 let manifest: Vec<u8> = row 121 .try_get::<Option<Vec<u8>>, _>(4) 122 .map_err(|_| OperationError::RecoveryRequired)? 123 .ok_or(OperationError::RecoveryRequired)?; 124 let decoded = crypto 125 .open_plan_part( 126 selected.workspace_id(), 127 anchor.operation_id(), 128 &digest, 129 0, 130 &manifest, 131 ) 132 .await?; 133 let decoded = decoded.expose_secret(|bytes| PlanManifest::decode(bytes, &prepared))?; 134 if decoded.plan_digest().as_bytes() != &digest 135 || decoded.transaction_id() != transaction 136 || decoded.part_count() != part_count as usize 137 || decoded.byte_count() != byte_count as usize 138 { 139 return Err(OperationError::RecoveryRequired); 140 } 141 // SQL bounds aggregate/count before materializing any untrusted part set. 142 let (count, total): (i64, i64) = sqlx::query_as("SELECT count(*),coalesce(sum(length(protected)),0) FROM signing_plan_parts WHERE workspace=? AND operation_id=?") 143 .bind(selected.workspace_id().as_bytes().as_slice()).bind(anchor.operation_id().as_bytes().as_slice()).fetch_one(&mut *connection).await.map_err(|_| OperationError::RecoveryRequired)?; 144 if count != part_count || total <= 0 || total > (MAX_PROTECTED_TOTAL - manifest.len()) as i64 { 145 return Err(OperationError::RecoveryRequired); 146 } 147 let rows = sqlx::query("SELECT part,CASE WHEN length(protected)>0 AND length(protected)<=262144 AND (SELECT coalesce(sum(length(p.protected)),0) FROM signing_plan_parts p WHERE p.workspace=signing_plan_parts.workspace AND p.operation_id=signing_plan_parts.operation_id)<=2097152 THEN protected END FROM signing_plan_parts WHERE workspace=? AND operation_id=? ORDER BY part LIMIT 25") 148 .bind(selected.workspace_id().as_bytes().as_slice()).bind(anchor.operation_id().as_bytes().as_slice()).fetch_all(&mut *connection).await.map_err(|_| OperationError::RecoveryRequired)?; 149 if rows.len() != part_count as usize { 150 return Err(OperationError::RecoveryRequired); 151 } 152 let mut wire = Zeroizing::new(Vec::with_capacity(byte_count as usize)); 153 let mut parts = Vec::new(); 154 for (index, row) in rows.iter().enumerate() { 155 let part: i64 = row 156 .try_get(0) 157 .map_err(|_| OperationError::RecoveryRequired)?; 158 if part != (index + 1) as i64 { 159 return Err(OperationError::RecoveryRequired); 160 } 161 let protected: Vec<u8> = row 162 .try_get::<Option<Vec<u8>>, _>(1) 163 .map_err(|_| OperationError::RecoveryRequired)? 164 .ok_or(OperationError::RecoveryRequired)?; 165 let plaintext = crypto 166 .open_plan_part( 167 selected.workspace_id(), 168 anchor.operation_id(), 169 &digest, 170 part as u8, 171 &protected, 172 ) 173 .await?; 174 let expected = if index + 1 == rows.len() { 175 byte_count as usize - index * PRIVATE_PAYLOAD_MAX_BYTES 176 } else { 177 PRIVATE_PAYLOAD_MAX_BYTES 178 }; 179 plaintext.expose_secret(|bytes| { 180 if bytes.len() != expected { 181 return Err(OperationError::RecoveryRequired); 182 } 183 wire.extend_from_slice(bytes); 184 Ok(()) 185 })?; 186 parts.push(protected); 187 } 188 let plan = CapturedSigningPlan::parse(prepared.request().command(), &wire) 189 .map_err(|_| OperationError::RecoveryRequired)?; 190 if plan.digest() != &digest { 191 return Err(OperationError::RecoveryRequired); 192 } 193 let protected = ProtectedPlan { 194 digest, 195 transaction, 196 manifest, 197 parts, 198 bytes: byte_count as usize, 199 }; 200 // Validate the original T1 observation before returning even to internal callers. 201 let bound_at = decoded.bound_at(); 202 let bound = decoded.bind(prepared, plan)?; 203 let (prepared, plan) = bound.into_parts(); 204 Ok((prepared, Some((plan, transaction, bound_at, protected)))) 205 } 206 207 pub(super) async fn insert( 208 connection: &mut SqliteConnection, 209 prepared: &PreparedOperation, 210 value: &ProtectedPlan, 211 ) -> Result<(), OperationError> { 212 let anchor = prepared.identity(); 213 sqlx::query("INSERT INTO signing_plans(workspace,operation_id,plan_digest,transaction_id,part_count,byte_count,protected) VALUES(?,?,?,?,?,?,?)") 214 .bind(anchor.workspace_id().as_bytes().as_slice()).bind(anchor.operation_id().as_bytes().as_slice()).bind(value.digest.as_slice()).bind(value.transaction.as_bytes().as_slice()).bind(value.parts.len() as i64).bind(value.bytes as i64).bind(&value.manifest).execute(&mut *connection).await.map_err(|_| OperationError::StorageFailure)?; 215 for (index, part) in value.parts.iter().enumerate() { 216 sqlx::query( 217 "INSERT INTO signing_plan_parts(workspace,operation_id,part,protected) VALUES(?,?,?,?)", 218 ) 219 .bind(anchor.workspace_id().as_bytes().as_slice()) 220 .bind(anchor.operation_id().as_bytes().as_slice()) 221 .bind((index + 1) as i64) 222 .bind(part) 223 .execute(&mut *connection) 224 .await 225 .map_err(|_| OperationError::StorageFailure)?; 226 } 227 Ok(()) 228 } 229 pub(super) async fn unchanged( 230 connection: &mut SqliteConnection, 231 prepared: &PreparedOperation, 232 value: Option<&ProtectedPlan>, 233 ) -> Result<(), OperationError> { 234 let anchor = prepared.identity(); 235 let count: i64 = sqlx::query_scalar( 236 "SELECT count(*) FROM signing_plans WHERE workspace=? AND operation_id=?", 237 ) 238 .bind(anchor.workspace_id().as_bytes().as_slice()) 239 .bind(anchor.operation_id().as_bytes().as_slice()) 240 .fetch_one(&mut *connection) 241 .await 242 .map_err(|_| OperationError::RecoveryRequired)?; 243 let Some(value) = value else { 244 let parts: i64 = sqlx::query_scalar( 245 "SELECT count(*) FROM signing_plan_parts WHERE workspace=? AND operation_id=?", 246 ) 247 .bind(anchor.workspace_id().as_bytes().as_slice()) 248 .bind(anchor.operation_id().as_bytes().as_slice()) 249 .fetch_one(&mut *connection) 250 .await 251 .map_err(|_| OperationError::RecoveryRequired)?; 252 return if count == 0 && parts == 0 { 253 Ok(()) 254 } else { 255 Err(OperationError::RecoveryRequired) 256 }; 257 }; 258 let matched: i64 = sqlx::query_scalar("SELECT count(*) FROM signing_plans WHERE workspace=? AND operation_id=? AND plan_digest=? AND transaction_id=? AND part_count=? AND byte_count=? AND protected=?") 259 .bind(anchor.workspace_id().as_bytes().as_slice()).bind(anchor.operation_id().as_bytes().as_slice()).bind(value.digest.as_slice()).bind(value.transaction.as_bytes().as_slice()).bind(value.parts.len() as i64).bind(value.bytes as i64).bind(&value.manifest).fetch_one(&mut *connection).await.map_err(|_| OperationError::RecoveryRequired)?; 260 let parts: i64 = sqlx::query_scalar( 261 "SELECT count(*) FROM signing_plan_parts WHERE workspace=? AND operation_id=?", 262 ) 263 .bind(anchor.workspace_id().as_bytes().as_slice()) 264 .bind(anchor.operation_id().as_bytes().as_slice()) 265 .fetch_one(&mut *connection) 266 .await 267 .map_err(|_| OperationError::RecoveryRequired)?; 268 if count != 1 || matched != 1 || parts != value.parts.len() as i64 { 269 return Err(OperationError::RecoveryRequired); 270 } 271 for (index, part) in value.parts.iter().enumerate() { 272 let matched: i64 = sqlx::query_scalar("SELECT count(*) FROM signing_plan_parts WHERE workspace=? AND operation_id=? AND part=? AND protected=?") 273 .bind(anchor.workspace_id().as_bytes().as_slice()).bind(anchor.operation_id().as_bytes().as_slice()).bind((index + 1) as i64).bind(part).fetch_one(&mut *connection).await.map_err(|_| OperationError::RecoveryRequired)?; 274 if matched != 1 { 275 return Err(OperationError::RecoveryRequired); 276 } 277 } 278 Ok(()) 279 }