stock_envelope_port.rs (7496B)
1 //! Actual stock refusal and shared report/carrier boundaries. 2 use super::*; 3 use nostr::JsonUtil; 4 use radroots_domain::{ 5 CommandDigest, EnvelopeEventId, OperationId, Sequence, SigningAttemptId, TransactionId, 6 }; 7 use radroots_storage::{ 8 command::{CommitAttempt, OperationError, PrivateEnvelopeCandidate}, 9 inventory::{ 10 InventoryCheckpointRef, InventoryStore, StockEnvelopeReceipt, StockEnvelopeRequest, 11 StockEnvelopeSource, StockEvidenceReceipt, 12 }, 13 workspace::WorkspaceBinding, 14 }; 15 use radroots_storage_sqlite::workspace::{SellerStockConfig, StockEnrollment}; 16 use sha2::{Digest, Sha256}; 17 use sqlx::Connection; 18 19 fn copy(proof: &AttachmentProof) -> AttachmentProof { 20 proof 21 .with_secret(|bytes| AttachmentProof::from_protected_input(bytes)) 22 .unwrap() 23 } 24 fn minimum(input: &AttachmentInput, revision: u64) -> InventoryCheckpointRef { 25 InventoryCheckpointRef::from_host_metadata( 26 input.authority(), 27 Sequence::new(revision).unwrap(), 28 (revision != 0).then_some(CheckpointDigest::from_bytes([12; 32])), 29 ) 30 .unwrap() 31 } 32 fn request(binding: &WorkspaceBinding) -> StockEnvelopeRequest { 33 StockEnvelopeRequest::new( 34 binding.clone(), 35 minimum(binding.input(), 0).with_optional_authorization(binding.stock_authorization()), 36 OperationId::from_bytes([80; 32]), 37 CommandDigest::from_bytes([81; 32]), 38 key(), 39 None, 40 ) 41 .unwrap() 42 } 43 fn carrier() -> String { 44 // A genuine signed carrier with opaque synthetic content. Neither this 45 // signature nor the source model verifies a stock seal or mints authority. 46 let signer = nostr::Keys::new(nostr::SecretKey::from_slice(&[3; 32]).unwrap()); 47 nostr::UnsignedEvent { 48 id: None, 49 pubkey: signer.public_key(), 50 created_at: nostr::Timestamp::from_secs(100), 51 kind: nostr::Kind::Custom(1059), 52 tags: nostr::Tags::from_list(vec![nostr::Tag::public_key( 53 nostr::PublicKey::from_slice(key().as_bytes()).unwrap(), 54 )]), 55 content: String::from("synthetic original carrier"), 56 } 57 .sign_with_keys(&signer) 58 .unwrap() 59 .as_json() 60 } 61 async fn stock(f: &Fixture) -> (NativeWorkspace, StockEnrollment, WorkspaceBinding) { 62 let enrollment = StockEnrollment::prepare( 63 SellerStockConfig::new( 64 key(), 65 key(), 66 "stock-envelope-boundary", 67 UnixSeconds::new(200).unwrap(), 68 ) 69 .unwrap(), 70 f.clock.as_ref(), 71 ) 72 .unwrap(); 73 let store = 74 NativeWorkspace::initialize_seller_stock(&f.path, &enrollment, f.crypto(), f.clock.clone()) 75 .await 76 .unwrap(); 77 let binding = store 78 .authenticate(enrollment.input().clone(), enrollment.proof()) 79 .await 80 .unwrap(); 81 (store, enrollment, binding) 82 } 83 84 #[tokio::test] 85 async fn envelope_ports_refuse_stock_without_original_work_and_ordinary_outbox_without_writes() { 86 let f = Fixture::new(); 87 let (store, enrollment, binding) = stock(&f).await; 88 let outbox_fixture = Fixture::new(); 89 let (outbox, _, _) = outbox_fixture.create().await; 90 let candidate = PrivateEnvelopeCandidate::from_obtained(key(), &carrier(), &[3; 32]).unwrap(); 91 for (port, capture_error, query_error) in [ 92 ( 93 &store as &dyn InventoryStore, 94 OperationError::MissingHistory, 95 OperationError::StaleState, 96 ), 97 ( 98 &outbox as &dyn InventoryStore, 99 OperationError::UnsupportedOperation, 100 OperationError::UnsupportedOperation, 101 ), 102 ] { 103 assert_eq!( 104 port.capture_stock_envelope(request(&binding), copy(enrollment.proof()), &candidate) 105 .await 106 .unwrap_err(), 107 capture_error 108 ); 109 assert_eq!( 110 port.stock_envelope(request(&binding), copy(enrollment.proof())) 111 .await 112 .unwrap_err(), 113 query_error 114 ); 115 } 116 // Current catalog and authoritative history remain unchanged by refusal. 117 let mut connection = sqlx::SqliteConnection::connect_with( 118 &sqlx::sqlite::SqliteConnectOptions::new() 119 .filename(f.path.join("stock_execution_v1.sqlite")) 120 .read_only(true), 121 ) 122 .await 123 .unwrap(); 124 let catalog: i64 = sqlx::query_scalar("PRAGMA user_version") 125 .fetch_one(&mut connection) 126 .await 127 .unwrap(); 128 let entries: i64 = sqlx::query_scalar("SELECT count(*) FROM stock_operations") 129 .fetch_one(&mut connection) 130 .await 131 .unwrap(); 132 assert_eq!(catalog, 17); 133 assert_eq!(entries, 0); 134 connection.close().await.unwrap(); 135 assert!( 136 !outbox_fixture 137 .path 138 .join("stock_execution_v1.sqlite") 139 .exists() 140 ); 141 store 142 .authenticate(enrollment.input().clone(), enrollment.proof()) 143 .await 144 .unwrap(); 145 outbox.close().await.unwrap(); 146 store.close().await.unwrap(); 147 } 148 149 #[tokio::test] 150 async fn reported_envelope_source_preserves_exact_carrier_and_refuses_tampered_or_mixed_reports() { 151 let f = Fixture::new(); 152 let (store, _, binding) = stock(&f).await; 153 let selected = request(&binding); 154 let attempt = CommitAttempt::new( 155 selected.attempt().workspace_id(), 156 selected.operation_id(), 157 selected.command_digest(), 158 Some(TransactionId::from_bytes([82; 32])), 159 ); 160 let evidence = StockEvidenceReceipt::from_committed_store( 161 attempt, 162 SigningAttemptId::from_bytes([83; 32]), 163 key(), 164 [84; 32], 165 None, 166 ) 167 .unwrap(); 168 let raw = carrier(); 169 let event = nostr::Event::from_json(&raw).unwrap(); 170 let id = EnvelopeEventId::from_bytes(event.id.to_bytes()); 171 let digest = Sha256::digest(raw.as_bytes()).into(); 172 let report = |id, digest| { 173 StockEnvelopeReceipt::from_committed_store( 174 &selected, 175 attempt, 176 evidence, 177 TransactionId::from_bytes([85; 32]), 178 id, 179 digest, 180 minimum(binding.input(), 1), 181 ) 182 .unwrap() 183 }; 184 // These public report constructors confer no persistence/stock permission. 185 let receipt = report(id, digest); 186 let source = StockEnvelopeSource::from_retained_wire(receipt, &raw).unwrap(); 187 source.with_json(|retained| assert_eq!(retained.as_bytes(), raw.as_bytes())); 188 assert_eq!(source.receipt(), receipt); 189 assert_eq!(format!("{source:?}"), "StockEnvelopeSource(<redacted>)"); 190 for (receipt, wire) in [ 191 ( 192 report(EnvelopeEventId::from_bytes([99; 32]), digest), 193 raw.clone(), 194 ), 195 (report(id, [99; 32]), raw.clone()), 196 (receipt, format!("{raw} ")), 197 (receipt, "x".repeat(65537)), 198 (receipt, "é".repeat(32769)), 199 ] { 200 assert!(matches!( 201 StockEnvelopeSource::from_retained_wire(receipt, &wire), 202 Err(OperationError::InvalidEvidence) 203 )); 204 } 205 for field in ["id", "sig"] { 206 let mut altered: serde_json::Value = serde_json::from_str(&raw).unwrap(); 207 altered[field] = "0".repeat(if field == "id" { 64 } else { 128 }).into(); 208 assert!(StockEnvelopeSource::from_retained_wire(receipt, &altered.to_string()).is_err()); 209 } 210 let original = raw.clone(); 211 drop(raw); 212 source.with_json(|retained| assert_eq!(retained, original)); 213 store.close().await.unwrap(); 214 }