historical_writer.rs (13832B)
1 //! Fixture producer compiled only against the exact historical Lib archive. 2 //! An ephemeral signer stays in memory; only public expectations are emitted. 3 use radroots_mobile_ffi::*; 4 use secp256k1::{Keypair, Message, Secp256k1}; 5 use serde_json::{Value, json}; 6 use std::os::fd::AsRawFd; 7 use std::path::Path; 8 9 struct EphemeralSigner(Keypair); 10 #[async_trait::async_trait] 11 impl RadrootsHostSigner for EphemeralSigner { 12 async fn signer_status(&self) -> SignerStatusRecord { 13 SignerStatusRecord { 14 schema_version: MOBILE_FFI_SCHEMA_VERSION, 15 availability: SignerAvailabilityRecord::Ready, 16 } 17 } 18 async fn sign(&self, request: HostSigningRequest) -> HostSigningResult { 19 assert_eq!(request.public_key, self.0.x_only_public_key().0.to_string()); 20 let digest: [u8; 32] = request.event_id_digest.try_into().unwrap(); 21 let signature = 22 Secp256k1::new().sign_schnorr_no_aux_rand(&Message::from_digest(digest), &self.0); 23 HostSigningResult { 24 schema_version: MOBILE_FFI_SCHEMA_VERSION, 25 outcome: HostSigningOutcome::Signed, 26 operation_id: request.operation_id, 27 signer_request_id: request.signer_request_id, 28 public_key: request.public_key, 29 purpose: request.purpose, 30 signature_hex: Some(signature.to_string()), 31 completed_at_unix_ms: std::time::SystemTime::now() 32 .duration_since(std::time::UNIX_EPOCH) 33 .unwrap() 34 .as_millis() 35 .try_into() 36 .unwrap(), 37 } 38 } 39 } 40 41 fn input(content: String, media: Vec<FfiPreparedMediaInput>) -> FfiAddDraftInput { 42 FfiAddDraftInput { 43 schema_version: MOBILE_FFI_SCHEMA_VERSION, 44 command_type: if media.is_empty() { 45 FfiAddCommandType::CreateUpdate 46 } else { 47 FfiAddCommandType::CreatePhotoUpdate 48 }, 49 content, 50 identifier: None, 51 title: None, 52 summary: None, 53 location: None, 54 event_timing: None, 55 event_start_date: None, 56 event_end_date: None, 57 event_start_unix_s: None, 58 event_end_unix_s: None, 59 event_timezone: None, 60 price_amount: None, 61 currency: None, 62 unit: None, 63 quantity: None, 64 food_published_at_unix_s: None, 65 food_status: None, 66 media, 67 } 68 } 69 70 fn expectation(status: &FfiDraftStatusRecord) -> Value { 71 let settled = status.settlement.as_ref().map(|s| { 72 json!({ 73 "signed":s.signed,"admitted":s.admitted,"pending":s.pending, 74 "delivery_plans":s.delivery_plans,"delivery_satisfied":s.delivery_satisfied 75 }) 76 }); 77 json!({ "draft_id": status.draft_id, "revision":status.revision, 78 "author_public_key":status.author_public_key,"card_id":status.card_id, 79 "operation_id":status.operation_id,"state":format!("{:?}",status.state), 80 "created_at_unix_ms":status.created_at_unix_ms, 81 "updated_at_unix_ms":status.updated_at_unix_ms,"settlement":settled }) 82 } 83 84 async fn queue( 85 runtime: &RadrootsRuntime, 86 status: &FfiDraftStatusRecord, 87 at: u64, 88 ) -> FfiDraftStatusRecord { 89 runtime 90 .phase1_queue_draft( 91 status.draft_id.clone(), 92 status.revision, 93 FfiQueuePolicyRecord { 94 schema_version: MOBILE_FFI_SCHEMA_VERSION, 95 relay_urls: vec![ 96 "wss://relay-one.example".into(), 97 "wss://relay-two.example".into(), 98 ], 99 satisfaction: FfiRelaySatisfaction::AllAccepted, 100 delivery_deadline_unix_ms: 2_000_000_000_000, 101 cancellation: FfiCancellationPolicy::LocalCooperative, 102 }, 103 at, 104 ) 105 .await 106 .unwrap() 107 } 108 109 #[tokio::test] 110 async fn produce_pre_refactor_owner_state() { 111 if let Ok(root) = std::env::var("TERA_LEGACY_DOWNGRADE_ROOT") { 112 refuse_current_owner_downgrade(Path::new(&root)).await; 113 return; 114 } 115 let output = std::env::var("TERA_LEGACY_FIXTURE_OUTPUT").unwrap(); 116 let root = Path::new(&output); 117 let host: Value = 118 serde_json::from_slice(&std::fs::read(root.join("host-metadata.json")).unwrap()).unwrap(); 119 let generation = host["source_generation"].as_str().unwrap(); 120 let key = Keypair::new(&Secp256k1::new(), &mut secp256k1::rand::thread_rng()); 121 let transient_secret = key.secret_key().secret_bytes(); 122 let public_key = key.x_only_public_key().0.to_string(); 123 let data = root.join("data"); 124 std::fs::create_dir_all(data.join("radroots/users").join(&public_key)).unwrap(); 125 let runtime = RadrootsRuntime::with_host_signer( 126 data.to_string_lossy().into(), 127 public_key.clone(), 128 generation.into(), 129 host["generation_created_at_unix_ms"].as_u64().unwrap(), 130 ProtectedDataAvailability::Available, 131 Box::new(EphemeralSigner(key)), 132 ) 133 .await 134 .unwrap(); 135 let preferences = runtime.phase1_settings().await.unwrap(); 136 runtime 137 .phase1_replace_settings(FfiReplaceSettingsRecord { 138 schema_version: MOBILE_FFI_SCHEMA_VERSION, 139 expected_revision: preferences.revision, 140 relays: FfiRelayPreferencesRecord { 141 schema_version: MOBILE_FFI_SCHEMA_VERSION, 142 environment: FfiMobileNetworkEnvironment::Public, 143 endpoints: ["wss://relay-one.example", "wss://relay-two.example"] 144 .into_iter() 145 .map(|url| FfiRelayPreferenceRecord { 146 schema_version: MOBILE_FFI_SCHEMA_VERSION, 147 url: url.into(), 148 access: FfiRelayAccessPreference::ReadWrite, 149 }) 150 .collect(), 151 }, 152 blossom: FfiBlossomPreferencesRecord { 153 schema_version: MOBILE_FFI_SCHEMA_VERSION, 154 environment: FfiMobileNetworkEnvironment::Public, 155 authority: FfiBlossomAuthorityPreference::PublicWebPki, 156 primary_origin: "https://blossom.example".into(), 157 fallback_origins: vec![], 158 }, 159 media_network: preferences.media_network, 160 local_storage: preferences.local_storage, 161 }) 162 .await 163 .unwrap(); 164 runtime.phase1_apply_settings_to_runtime().await.unwrap(); 165 runtime 166 .configure_blossom( 167 FfiBlossomHostKind::Native, 168 FfiBlossomEndpointAuthority::PublicWebPki, 169 "https://blossom.example".into(), 170 vec![], 171 ) 172 .unwrap(); 173 let image = 174 std::fs::File::open(root.join(host["staged_relative_path"].as_str().unwrap())).unwrap(); 175 let media = FfiPreparedMediaInput { 176 schema_version: MOBILE_FFI_SCHEMA_VERSION, 177 opaque_reference: format!("media:{}", host["media_sha256"].as_str().unwrap()), 178 file_descriptor: image.as_raw_fd().try_into().unwrap(), 179 sha256: host["media_sha256"].as_str().unwrap().into(), 180 media_type: "image/png".into(), 181 byte_size: host["media_bytes"].as_u64().unwrap(), 182 width: host["media_width"].as_u64().unwrap().try_into().unwrap(), 183 height: host["media_height"].as_u64().unwrap().try_into().unwrap(), 184 alt: "Historical synthetic image é".into(), 185 prepared_at_unix_s: 1_786_000_000, 186 }; 187 let media_id = format!("{:032x}", 1); 188 let saved = runtime 189 .phase1_save_draft( 190 media_id.clone(), 191 input("Historical pending photo é".into(), vec![media.clone()]), 192 1_786_000_000, 193 None, 194 1_786_000_000_000, 195 ) 196 .await 197 .unwrap(); 198 let job = runtime 199 .phase1_prepare_add_media_background(FfiBlossomUploadIntent { 200 schema_version: MOBILE_FFI_SCHEMA_VERSION, 201 draft_id: media_id, 202 expected_revision: saved.revision, 203 media, 204 }) 205 .await 206 .unwrap(); 207 let native = json!({"draft_id":job.draft.draft_id,"revision":job.draft.revision, 208 "operation_id":job.operation_id,"remote_url":job.remote_url, 209 "sha256":job.expected_sha256,"byte_size":job.byte_size}); 210 // Never serialize the returned upload authorization header. 211 let transient_authorization = job.authorization_header.as_bytes().to_vec(); 212 assert!(!transient_authorization.is_empty()); 213 let pending_updated_at = job.draft.updated_at_unix_ms; 214 let pending_id = job.draft.draft_id.clone(); 215 let mut statuses = vec![expectation(&job.draft)]; 216 drop(job); 217 for index in 2..=106 { 218 let id = format!("{index:032x}"); 219 let at = std::time::SystemTime::now() 220 .duration_since(std::time::UNIX_EPOCH) 221 .unwrap() 222 .as_millis() 223 .try_into() 224 .unwrap(); 225 assert!(at >= pending_updated_at); 226 let saved = runtime 227 .phase1_save_draft( 228 id, 229 input( 230 format!("Historical synthetic draft {index} e\u{301}"), 231 vec![], 232 ), 233 1_786_000_000, 234 None, 235 at, 236 ) 237 .await 238 .unwrap(); 239 let status = if index == 2 || index == 3 { 240 let queued = queue(&runtime, &saved, at).await; 241 if index == 3 { 242 runtime 243 .phase1_sign_queued_draft(queued.draft_id.clone(), queued.revision) 244 .await 245 .unwrap() 246 } else { 247 queued 248 } 249 } else { 250 saved 251 }; 252 statuses.push(expectation(&status)); 253 } 254 let first_page = runtime.phase1_draft_heads(100).await.unwrap(); 255 assert_eq!(first_page.len(), 100); 256 assert!(!first_page.iter().any(|row| row.draft_id == pending_id)); 257 runtime.shutdown().await.unwrap(); 258 drop(runtime); 259 drop(image); 260 reject_secret(root, &transient_secret); 261 reject_authorization(root, &transient_authorization); 262 std::fs::write(root.join("rust-metadata.json"),serde_json::to_vec_pretty(&json!({ 263 "public_key":public_key,"source_generation":generation,"drafts":statuses, 264 "native_pending":native,"actual_first_page_count":100,"pending_media_outside_first_page":true, 265 "secret_scan":"Actual closed owner files contain neither transient signer bytes nor hexadecimal secret; neither form is emitted.", 266 "authorization_scan":"Actual closed owner files contain no returned upload authorization header; its value is never emitted.", 267 "network_effects":"No socket or HTTP delivery was requested; only local save, queue, signing/admission and upload-job preparation."})).unwrap()).unwrap(); 268 } 269 270 fn reject_authorization(root: &Path, authorization: &[u8]) { 271 for entry in std::fs::read_dir(root).unwrap() { 272 let path = entry.unwrap().path(); 273 if path.is_dir() { 274 reject_authorization(&path, authorization); 275 } else { 276 let bytes = std::fs::read(path).unwrap(); 277 assert!( 278 !bytes 279 .windows(authorization.len()) 280 .any(|part| part == authorization), 281 "Transient authorization reached fixture output" 282 ); 283 } 284 } 285 } 286 287 fn reject_secret(root: &Path, secret: &[u8; 32]) { 288 let encoded = secret 289 .iter() 290 .map(|b| format!("{b:02x}")) 291 .collect::<String>(); 292 for entry in std::fs::read_dir(root).unwrap() { 293 let path = entry.unwrap().path(); 294 if path.is_dir() { 295 reject_secret(&path, secret); 296 } else { 297 let bytes = std::fs::read(path).unwrap(); 298 assert!( 299 !bytes.windows(32).any(|part| part == secret), 300 "Transient signer bytes reached fixture output" 301 ); 302 assert!( 303 !bytes 304 .windows(encoded.len()) 305 .any(|part| part.eq_ignore_ascii_case(encoded.as_bytes())), 306 "Transient signer encoding reached fixture output" 307 ); 308 } 309 } 310 } 311 312 async fn refuse_current_owner_downgrade(root: &Path) { 313 let managed = std::path::PathBuf::from(std::env::var("CARGO_TARGET_DIR").unwrap()) 314 .canonicalize() 315 .unwrap(); 316 let root = root.canonicalize().unwrap(); 317 assert!(root.starts_with(managed) && root.file_name().unwrap() == "old_reader_probe"); 318 let host: Value = 319 serde_json::from_slice(&std::fs::read(root.join("host-metadata.json")).unwrap()).unwrap(); 320 let rust: Value = 321 serde_json::from_slice(&std::fs::read(root.join("rust-metadata.json")).unwrap()).unwrap(); 322 let public = rust["public_key"].as_str().unwrap(); 323 let owner = root.join("data/radroots/users").join(public); 324 let before: [Vec<u8>; 2] = 325 ["runtime.sqlite", "private.sqlite"].map(|name| std::fs::read(owner.join(name)).unwrap()); 326 let result = RadrootsRuntime::new( 327 root.join("data").to_string_lossy().into(), 328 public.into(), 329 host["source_generation"].as_str().unwrap().into(), 330 host["generation_created_at_unix_ms"].as_u64().unwrap(), 331 ProtectedDataAvailability::Available, 332 ) 333 .await; 334 assert!( 335 result.is_err(), 336 "Historical reader must refuse a newer current-owner schema" 337 ); 338 let failure = result.err().unwrap(); 339 assert_eq!(failure.report().code, "schema_too_new"); 340 assert_eq!( 341 failure.report().safe_message, 342 "SDK persistent storage schema is newer than this runtime" 343 ); 344 for (index, name) in ["runtime.sqlite", "private.sqlite"].iter().enumerate() { 345 assert_eq!(std::fs::read(owner.join(name)).unwrap(), before[index]); 346 } 347 }