plan.rs (10838B)
1 //! Validated historical T1 metadata shared by concrete protected hosts. 2 //! This codec establishes neither a commit nor current issuance authority. 3 use super::{OperationError, PreparedOperation}; 4 use crate::command::{BoundSigningPlan, CapturedSigningPlan}; 5 use radroots_domain::{CommandDigest, OperationId, TransactionId, UnixSeconds, WorkspaceId}; 6 use serde::{Deserialize, Serialize}; 7 use zeroize::Zeroizing; 8 9 /// Maximum plaintext in each private plan record. 10 pub const PART_BYTES: usize = 16 * 1024; 11 /// Maximum parts in the complete existing known-kind plan profile. 12 pub const PARTS_MAX: usize = PLAN_BYTES_MAX / PART_BYTES; 13 /// Maximum complete retained plan representation. 14 pub const PLAN_BYTES_MAX: usize = radroots_protocol::chat::PLAN_MAX_BYTES; 15 16 #[derive(Serialize, Deserialize)] 17 #[serde(deny_unknown_fields)] 18 struct Wire { 19 version: u8, 20 workspace: WorkspaceId, 21 operation_id: OperationId, 22 command_digest: CommandDigest, 23 preparation_transaction: TransactionId, 24 plan_digest: CommandDigest, 25 transaction_id: TransactionId, 26 bound_at: UnixSeconds, 27 part_count: usize, 28 byte_count: usize, 29 } 30 31 /// Opaque validated retained metadata; its Serde representation stays private. 32 pub struct PlanManifest(Wire); 33 impl PlanManifest { 34 /// Captures structurally valid original T1 data before protection. The host 35 /// must still authenticate current access and confirm its actual transaction. 36 pub fn capture( 37 prepared: &PreparedOperation, 38 plan: &CapturedSigningPlan, 39 transaction: TransactionId, 40 bound_at: UnixSeconds, 41 ) -> Result<Self, OperationError> { 42 let anchor = prepared.identity(); 43 if plan.operation_id() != anchor.operation_id() 44 || plan.command_digest() != anchor.command_digest() 45 || plan.created_at() < prepared.issuance_window().prepared_at() 46 || plan.created_at() > bound_at 47 { 48 return Err(OperationError::InvalidCommand); 49 } 50 let result = Self(Wire { 51 version: 1, 52 workspace: anchor.workspace_id(), 53 operation_id: anchor.operation_id(), 54 command_digest: anchor.command_digest(), 55 preparation_transaction: prepared.transaction_id(), 56 plan_digest: CommandDigest::from_bytes(*plan.digest()), 57 transaction_id: transaction, 58 bound_at, 59 part_count: plan.protected_wire().len().div_ceil(PART_BYTES), 60 byte_count: plan.protected_wire().len(), 61 }); 62 result.validate(prepared)?; 63 Ok(result) 64 } 65 fn validate(&self, prepared: &PreparedOperation) -> Result<(), OperationError> { 66 let w = &self.0; 67 let anchor = prepared.identity(); 68 let window = prepared.issuance_window(); 69 if w.version != 1 70 || w.workspace != anchor.workspace_id() 71 || w.operation_id != anchor.operation_id() 72 || w.command_digest != anchor.command_digest() 73 || w.preparation_transaction != prepared.transaction_id() 74 || !(1..=PARTS_MAX).contains(&w.part_count) 75 || !(1..=PLAN_BYTES_MAX).contains(&w.byte_count) 76 || w.byte_count.div_ceil(PART_BYTES) != w.part_count 77 || w.bound_at < window.prepared_at() 78 || w.bound_at >= window.first_issue_not_after() 79 { 80 return Err(OperationError::RecoveryRequired); 81 } 82 Ok(()) 83 } 84 /// Encodes bounded metadata for explicit trusted-host protection. 85 pub fn encode(&self) -> Result<Zeroizing<Vec<u8>>, OperationError> { 86 let bytes = Zeroizing::new( 87 serde_json::to_vec(&self.0).map_err(|_| OperationError::RecoveryRequired)?, 88 ); 89 if bytes.len() > PART_BYTES { 90 return Err(OperationError::RecoveryRequired); 91 } 92 Ok(bytes) 93 } 94 /// Checks bounded decrypted metadata against the independently retained T0. 95 pub fn decode(bytes: &[u8], prepared: &PreparedOperation) -> Result<Self, OperationError> { 96 if bytes.len() > PART_BYTES { 97 return Err(OperationError::RecoveryRequired); 98 } 99 let result = 100 Self(serde_json::from_slice(bytes).map_err(|_| OperationError::RecoveryRequired)?); 101 result.validate(prepared)?; 102 Ok(result) 103 } 104 pub const fn plan_digest(&self) -> CommandDigest { 105 self.0.plan_digest 106 } 107 pub const fn transaction_id(&self) -> TransactionId { 108 self.0.transaction_id 109 } 110 pub const fn bound_at(&self) -> UnixSeconds { 111 self.0.bound_at 112 } 113 pub const fn part_count(&self) -> usize { 114 self.0.part_count 115 } 116 pub const fn byte_count(&self) -> usize { 117 self.0.byte_count 118 } 119 /// Checks complete original bytes before constructing a retained T1 report. 120 /// This is historical data validation; concrete completion remains required. 121 pub fn bind( 122 self, 123 prepared: PreparedOperation, 124 plan: CapturedSigningPlan, 125 ) -> Result<BoundSigningPlan, OperationError> { 126 self.validate(&prepared)?; 127 if plan.digest() != self.plan_digest().as_bytes() 128 || plan.protected_wire().len() != self.byte_count() 129 { 130 return Err(OperationError::RecoveryRequired); 131 } 132 BoundSigningPlan::from_committed_store( 133 prepared, 134 plan, 135 self.transaction_id(), 136 self.bound_at(), 137 ) 138 } 139 } 140 141 #[cfg(test)] 142 mod tests { 143 use super::*; 144 use crate::command::ChatSigningPlan; 145 use crate::command::protected::tests::request; 146 use radroots_domain::{EnvelopeEventId, IssuanceWindow, Sequence}; 147 use radroots_protocol::chat::{ChatRumor, ChatSeal}; 148 use radroots_protocol::intent::SigningReplay; 149 use radroots_protocol::nip59::CapturedDmRoute; 150 use serde_json::json; 151 152 fn make_prepared() -> PreparedOperation { 153 PreparedOperation::from_committed_store( 154 request(), 155 TransactionId::from_bytes([7; 32]), 156 Sequence::new(1).unwrap(), 157 IssuanceWindow::new( 158 UnixSeconds::new(100).unwrap(), 159 UnixSeconds::new(150).unwrap(), 160 ) 161 .unwrap(), 162 ) 163 .unwrap() 164 } 165 fn make_plan(prepared: &PreparedOperation, created: u64) -> CapturedSigningPlan { 166 // These are structural descriptors for pure codec tests. They supply 167 // neither authenticated ciphertext nor a verified relay advertisement. 168 let command = prepared.request().chat_command().unwrap(); 169 let now = UnixSeconds::new(created).unwrap(); 170 let rumor = ChatRumor::from_command(command, now).unwrap(); 171 let recipient = rumor.recipients()[0]; 172 let size = rumor.budget().rumor_ciphertext_bytes(); 173 let seal = (0..=2) 174 .find_map(|pad| { 175 let text = format!("Ag{}{}", "A".repeat(size - 2 - pad), "=".repeat(pad)); 176 ChatSeal::new(&rumor, recipient, now, &text).ok() 177 }) 178 .unwrap(); 179 let route = CapturedDmRoute::from_observed_descriptor( 180 recipient, 181 EnvelopeEventId::from_bytes([8; 32]), 182 r#"{"synthetic":"structural codec descriptor"}"#, 183 &["wss://codec.example/".into()], 184 ) 185 .unwrap(); 186 ChatSigningPlan::new( 187 command, 188 now, 189 vec![seal], 190 vec![route], 191 SigningReplay::NonReplayable, 192 ) 193 .unwrap() 194 .into() 195 } 196 #[test] 197 fn manifest_binds_original_preparation_plan_and_window_without_minting_authority() { 198 let prepared = make_prepared(); 199 let plan = make_plan(&prepared, 100); 200 let transaction = TransactionId::from_bytes([9; 32]); 201 let manifest = PlanManifest::capture( 202 &prepared, 203 &plan, 204 transaction, 205 UnixSeconds::new(100).unwrap(), 206 ) 207 .unwrap(); 208 let bytes = manifest.encode().unwrap(); 209 let value: serde_json::Value = serde_json::from_slice(&bytes).unwrap(); 210 assert_eq!(manifest.plan_digest().as_bytes(), plan.digest()); 211 assert_eq!(manifest.transaction_id(), transaction); 212 assert_eq!(manifest.bound_at().get(), 100); 213 assert_eq!( 214 manifest.part_count(), 215 plan.protected_wire().len().div_ceil(PART_BYTES) 216 ); 217 assert_eq!(manifest.byte_count(), plan.protected_wire().len()); 218 for (pointer, replacement) in [ 219 ("/version", json!(2)), 220 ("/workspace", json!("11".repeat(32))), 221 ("/operation_id", json!("22".repeat(32))), 222 ("/command_digest", json!("33".repeat(32))), 223 ("/preparation_transaction", json!("44".repeat(32))), 224 ("/part_count", json!(0)), 225 ("/part_count", json!(25)), 226 ("/part_count", json!(2)), 227 ("/byte_count", json!(0)), 228 ("/byte_count", json!(PLAN_BYTES_MAX + 1)), 229 ("/bound_at", json!("99")), 230 ("/bound_at", json!("150")), 231 ] { 232 let mut damaged = value.clone(); 233 *damaged.pointer_mut(pointer).unwrap() = replacement; 234 assert!( 235 PlanManifest::decode(&serde_json::to_vec(&damaged).unwrap(), &prepared).is_err(), 236 "{pointer}" 237 ); 238 } 239 assert!(PlanManifest::decode(b"{}", &prepared).is_err()); 240 assert!(PlanManifest::decode(&vec![0; PART_BYTES + 1], &prepared).is_err()); 241 let mut foreign = value.clone(); 242 foreign["plan_digest"] = json!("55".repeat(32)); 243 let foreign = 244 PlanManifest::decode(&serde_json::to_vec(&foreign).unwrap(), &prepared).unwrap(); 245 assert!( 246 foreign 247 .bind(make_prepared(), make_plan(&make_prepared(), 100)) 248 .is_err() 249 ); 250 let decoded = PlanManifest::decode(&bytes, &prepared).unwrap(); 251 let bound = decoded.bind(prepared, plan).unwrap(); 252 assert_eq!(bound.transaction_id(), transaction); 253 let late = make_prepared(); 254 let late_plan = make_plan(&late, 101); 255 assert!( 256 PlanManifest::capture( 257 &late, 258 &late_plan, 259 transaction, 260 UnixSeconds::new(151).unwrap() 261 ) 262 .is_err() 263 ); 264 assert!( 265 PlanManifest::capture( 266 &late, 267 &late_plan, 268 transaction, 269 UnixSeconds::new(100).unwrap() 270 ) 271 .is_err() 272 ); 273 assert!( 274 PlanManifest::capture( 275 &late, 276 &make_plan(&late, 99), 277 transaction, 278 UnixSeconds::new(100).unwrap() 279 ) 280 .is_err() 281 ); 282 } 283 }