stock.rs (17544B)
1 #![cfg(all(feature = "native", unix))] 2 //! Actual ordinary-client private inventory, not a model of SQL effects. 3 use radroots::stock::{ 4 CreatePoolInput, InventoryCheckpointRef, InventoryOutcome, InventoryReceipt, MapOptionInput, 5 PoolCorrectionInput, 6 }; 7 use radroots::{ 8 Client, Code, CommandContext, NativeConfig, OperationId, StartMode, WorkspaceSession, 9 }; 10 use radroots_domain::{ 11 CommandDigest, ListingOptionId, PoolId, PublicKey, Quantity, Sequence, UnixSeconds, 12 listing::{ListingCoordinate, ListingId, MeasurementUnit}, 13 stock::{AvailableStockCorrection, OptionMappingKey, PoolUnit}, 14 }; 15 use radroots_secrets::{ 16 SecretId, SecretRef, 17 envelope::Nonce, 18 file::{FileOpenMode, FileProvider}, 19 id::{BackendKind, KeyVersion}, 20 provider::AccessPolicy, 21 wrapping::SecretMaterial, 22 }; 23 use radroots_storage::{ 24 event::SourceGeneration, 25 workspace::{AttachmentProof, WorkspaceClock, WorkspaceError}, 26 }; 27 use radroots_storage_sqlite::{ 28 OpenMode, OpenOptions, Paths, 29 workspace::{ 30 LocalOutboxConfig, NativeWorkspace, SellerStockConfig, StockEnrollment, WorkspaceCrypto, 31 }, 32 }; 33 use std::sync::{ 34 Arc, 35 atomic::{AtomicU64, Ordering}, 36 }; 37 38 struct Clock(AtomicU64); 39 impl WorkspaceClock for Clock { 40 fn now(&self) -> Result<UnixSeconds, WorkspaceError> { 41 UnixSeconds::new(self.0.load(Ordering::SeqCst)).map_err(|_| WorkspaceError::Unavailable) 42 } 43 } 44 fn key() -> PublicKey { 45 PublicKey::from_hex("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798").unwrap() 46 } 47 fn reference() -> SecretRef { 48 SecretRef::new( 49 SecretId::parse("workspace-key").unwrap(), 50 BackendKind::File, 51 KeyVersion::new(1).unwrap(), 52 ) 53 } 54 fn proof(value: &AttachmentProof) -> AttachmentProof { 55 value 56 .with_secret(|bytes| AttachmentProof::from_protected_input(bytes)) 57 .unwrap() 58 } 59 struct Fixture { 60 _temp: tempfile::TempDir, 61 root: std::path::PathBuf, 62 provider: Arc<FileProvider>, 63 clock: Arc<Clock>, 64 } 65 impl Fixture { 66 fn new() -> Self { 67 let temp = tempfile::tempdir().unwrap(); 68 let root = temp.path().canonicalize().unwrap(); 69 let provider = Arc::new( 70 FileProvider::open( 71 root.join("vault"), 72 FileOpenMode::CreateNew, 73 SecretMaterial::from_slice(&[0xA5; 32]).unwrap(), 74 ) 75 .unwrap(), 76 ); 77 provider 78 .provision( 79 &reference(), 80 &SecretMaterial::from_slice(&[0x41; 32]).unwrap(), 81 Nonce::new([0x11; 24]), 82 ) 83 .unwrap(); 84 Self { 85 _temp: temp, 86 root, 87 provider, 88 clock: Arc::new(Clock(AtomicU64::new(100))), 89 } 90 } 91 fn crypto(&self) -> WorkspaceCrypto { 92 WorkspaceCrypto::new( 93 self.provider.clone(), 94 reference(), 95 SecretMaterial::from_slice(&[0x41; 32]).unwrap(), 96 AccessPolicy::standard(), 97 ) 98 .unwrap() 99 } 100 fn options(&self) -> OpenOptions { 101 let path = self.root.join("cache"); 102 std::fs::create_dir_all(&path).unwrap(); 103 OpenOptions::new(Paths::from_directory(path).unwrap(), OpenMode::Create) 104 .with_source_generation(SourceGeneration::new([17; 32]).unwrap(), 1) 105 .unwrap() 106 } 107 async fn client(&self, workspace: NativeWorkspace) -> Client { 108 Client::open(NativeConfig::public_read(self.options()).with_workspace(workspace)) 109 .await 110 .unwrap() 111 } 112 async fn owner(&self) -> (Client, NativeWorkspace, StockEnrollment) { 113 let enrollment = StockEnrollment::prepare( 114 SellerStockConfig::new( 115 key(), 116 key(), 117 "synthetic-stock-owner", 118 UnixSeconds::new(300).unwrap(), 119 ) 120 .unwrap(), 121 self.clock.as_ref(), 122 ) 123 .unwrap(); 124 let store = NativeWorkspace::initialize_seller_stock( 125 &self.root.join("stock"), 126 &enrollment, 127 self.crypto(), 128 self.clock.clone(), 129 ) 130 .await 131 .unwrap(); 132 (self.client(store.clone()).await, store, enrollment) 133 } 134 } 135 fn context(scope: &WorkspaceSession, op: u8) -> CommandContext { 136 scope 137 .command_context( 138 OperationId::from_bytes([op; 32]), 139 None, 140 None, 141 UnixSeconds::new(150).unwrap(), 142 ) 143 .unwrap() 144 } 145 fn pool() -> PoolId { 146 PoolId::from_bytes([70; 32]) 147 } 148 fn quantity(value: &str) -> Quantity { 149 Quantity::new(value.parse().unwrap(), MeasurementUnit::Each).unwrap() 150 } 151 fn creation() -> CreatePoolInput { 152 CreatePoolInput::new( 153 pool(), 154 "private test vegetables", 155 PoolUnit::new(MeasurementUnit::Each, 0).unwrap(), 156 quantity("10"), 157 ) 158 .unwrap() 159 } 160 fn correction(version: u64, kind: AvailableStockCorrection, amount: &str) -> PoolCorrectionInput { 161 PoolCorrectionInput::new( 162 pool(), 163 Sequence::new(version).unwrap(), 164 kind, 165 amount.parse().unwrap(), 166 "synthetic audited correction", 167 ) 168 .unwrap() 169 } 170 fn committed(value: InventoryOutcome) -> InventoryReceipt { 171 let InventoryOutcome::Committed(value) = value else { 172 panic!("effect must confirm") 173 }; 174 *value 175 } 176 fn native_future<T: Send>(future: T) -> T { 177 future 178 } 179 180 #[tokio::test] 181 async fn ordinary_stock_effects_queries_original_replay_and_reopen_use_the_selected_native_owner() { 182 let f = Fixture::new(); 183 let (client, native, enrollment) = f.owner().await; 184 let scope = client 185 .attach(enrollment.input().clone(), proof(enrollment.proof())) 186 .await 187 .unwrap(); 188 let first_minimum = native 189 .stock_authority(enrollment.input().clone(), enrollment.proof()) 190 .await 191 .unwrap() 192 .inventory_checkpoint() 193 .unwrap(); 194 client.start(StartMode::LocalOnly).await.unwrap(); 195 let stock = client.stock(&scope); 196 drop(stock.create_pool(context(&scope, 80), first_minimum, creation())); 197 assert!(stock.pool(first_minimum, pool()).await.unwrap().is_none()); 198 let original = committed( 199 native_future(stock.create_pool(context(&scope, 80), first_minimum, creation())) 200 .await 201 .unwrap(), 202 ); 203 assert_eq!(original.pool().version().get(), 1); 204 assert_eq!(original.pool().balances().physical().available.get(), 10); 205 let added = committed( 206 stock 207 .adjust( 208 context(&scope, 81), 209 original.checkpoint(), 210 correction(1, AvailableStockCorrection::Add, "3"), 211 ) 212 .await 213 .unwrap(), 214 ); 215 let removed = committed( 216 stock 217 .adjust( 218 context(&scope, 82), 219 added.checkpoint(), 220 correction(2, AvailableStockCorrection::Remove, "2"), 221 ) 222 .await 223 .unwrap(), 224 ); 225 let spoiled = committed( 226 stock 227 .spoil( 228 context(&scope, 83), 229 removed.checkpoint(), 230 correction(3, AvailableStockCorrection::Spoil, "1"), 231 ) 232 .await 233 .unwrap(), 234 ); 235 assert_eq!(spoiled.pool().version().get(), 4); 236 assert_eq!(spoiled.pool().balances().introduced().get(), 13); 237 assert_eq!(spoiled.pool().balances().physical().available.get(), 10); 238 assert_eq!(spoiled.pool().balances().physical().removed.get(), 2); 239 assert_eq!(spoiled.pool().balances().physical().waste.get(), 1); 240 let key = OptionMappingKey::new( 241 ListingCoordinate::new(key(), ListingId::from_bytes([89; 16])), 242 ListingOptionId::from_bytes([90; 32]), 243 ); 244 let mapped = committed( 245 stock 246 .map_option( 247 context(&scope, 84), 248 spoiled.checkpoint(), 249 MapOptionInput::new(key, pool(), quantity("2"), Sequence::new(0).unwrap()).unwrap(), 250 ) 251 .await 252 .unwrap(), 253 ); 254 assert_eq!(mapped.pool(), spoiled.pool()); 255 assert_eq!( 256 stock 257 .option_mapping(mapped.checkpoint(), key) 258 .await 259 .unwrap(), 260 mapped.mapping() 261 ); 262 let current = mapped.checkpoint(); 263 assert_eq!( 264 stock 265 .pool(current, pool()) 266 .await 267 .unwrap() 268 .unwrap() 269 .snapshot(), 270 spoiled.pool() 271 ); 272 assert_eq!( 273 stock 274 .operation( 275 current, 276 original.attempt().operation_id(), 277 Some(original.attempt().command_digest()) 278 ) 279 .await 280 .unwrap() 281 .unwrap(), 282 original 283 ); 284 assert_eq!( 285 stock 286 .adjust( 287 context(&scope, 85), 288 current, 289 correction(1, AvailableStockCorrection::Add, "1") 290 ) 291 .await 292 .unwrap_err() 293 .code(), 294 Code::StaleState 295 ); 296 assert_eq!( 297 stock 298 .adjust( 299 context(&scope, 85), 300 current, 301 correction(4, AvailableStockCorrection::Spoil, "1") 302 ) 303 .await 304 .unwrap_err() 305 .code(), 306 Code::InvalidInput 307 ); 308 assert_eq!( 309 stock 310 .spoil( 311 context(&scope, 85), 312 current, 313 correction(4, AvailableStockCorrection::Add, "1") 314 ) 315 .await 316 .unwrap_err() 317 .code(), 318 Code::InvalidInput 319 ); 320 let missing = OperationId::from_bytes([99; 32]); 321 let digest = CommandDigest::from_bytes([98; 32]); 322 // The native original-preparation loader reports a missing selected T0 as 323 // StaleState, before any consent lookup or cleanup. Preserve that refusal. 324 assert_eq!( 325 client 326 .operations(&scope) 327 .abort_proven_unissued(current, missing, digest) 328 .await 329 .unwrap_err() 330 .code(), 331 Code::StaleState 332 ); 333 assert_eq!( 334 client 335 .operations(&scope) 336 .preparation_abort(current, missing, digest) 337 .await 338 .unwrap_err() 339 .code(), 340 Code::StaleState 341 ); 342 f.clock.0.store(160, Ordering::SeqCst); 343 let replay = committed( 344 stock 345 .create_pool(context(&scope, 80), first_minimum, creation()) 346 .await 347 .unwrap(), 348 ); 349 assert_eq!(replay, original); 350 assert_eq!( 351 stock 352 .pool(current, pool()) 353 .await 354 .unwrap() 355 .unwrap() 356 .snapshot(), 357 spoiled.pool() 358 ); 359 client.close().await.unwrap(); 360 assert!( 361 native 362 .authenticate(enrollment.input().clone(), enrollment.proof()) 363 .await 364 .is_err() 365 ); 366 let native = NativeWorkspace::open_seller_stock( 367 &f.root.join("stock"), 368 enrollment.input().clone(), 369 f.crypto(), 370 f.clock.clone(), 371 ) 372 .await 373 .unwrap(); 374 let client = f.client(native.clone()).await; 375 let scope = client 376 .attach(enrollment.input().clone(), proof(enrollment.proof())) 377 .await 378 .unwrap(); 379 client.start(StartMode::LocalOnly).await.unwrap(); 380 assert_eq!( 381 client 382 .stock(&scope) 383 .pool(current, pool()) 384 .await 385 .unwrap() 386 .unwrap() 387 .snapshot(), 388 spoiled.pool() 389 ); 390 assert_eq!( 391 client 392 .stock(&scope) 393 .operation( 394 current, 395 original.attempt().operation_id(), 396 Some(original.attempt().command_digest()) 397 ) 398 .await 399 .unwrap() 400 .unwrap(), 401 original 402 ); 403 client.close().await.unwrap(); 404 } 405 406 #[tokio::test] 407 async fn identical_but_foreign_and_closed_scopes_cannot_reach_the_selected_owner() { 408 let f = Fixture::new(); 409 let (client, native, enrollment) = f.owner().await; 410 let scope = client 411 .attach(enrollment.input().clone(), proof(enrollment.proof())) 412 .await 413 .unwrap(); 414 let foreign = WorkspaceSession::attach( 415 Arc::new(native.clone()), 416 enrollment.input().clone(), 417 proof(enrollment.proof()), 418 ) 419 .await 420 .unwrap(); 421 let minimum = native 422 .stock_authority(enrollment.input().clone(), enrollment.proof()) 423 .await 424 .unwrap() 425 .inventory_checkpoint() 426 .unwrap(); 427 client.start(StartMode::LocalOnly).await.unwrap(); 428 assert_eq!( 429 client 430 .stock(&foreign) 431 .pool(minimum, pool()) 432 .await 433 .unwrap_err() 434 .code(), 435 Code::Unauthorized 436 ); 437 assert_eq!( 438 client 439 .stock(&scope) 440 .create_pool(context(&foreign, 80), minimum, creation()) 441 .await 442 .unwrap_err() 443 .code(), 444 Code::Unauthorized 445 ); 446 scope.close(); 447 assert_eq!( 448 client 449 .stock(&scope) 450 .pool(minimum, pool()) 451 .await 452 .unwrap_err() 453 .code(), 454 Code::CapabilityUnavailable 455 ); 456 foreign.close(); 457 client.close().await.unwrap(); 458 assert_eq!( 459 client 460 .stock(&scope) 461 .pool(minimum, pool()) 462 .await 463 .unwrap_err() 464 .code(), 465 Code::CapabilityUnavailable 466 ); 467 } 468 469 #[tokio::test] 470 async fn public_cache_and_preview_never_adopt_a_foreign_stock_workspace() { 471 let f = Fixture::new(); 472 let (owner, native, enrollment) = f.owner().await; 473 let scope = owner 474 .attach(enrollment.input().clone(), proof(enrollment.proof())) 475 .await 476 .unwrap(); 477 let minimum = native 478 .stock_authority(enrollment.input().clone(), enrollment.proof()) 479 .await 480 .unwrap() 481 .inventory_checkpoint() 482 .unwrap(); 483 let public = tempfile::tempdir().unwrap(); 484 let options = OpenOptions::new( 485 Paths::from_directory(public.path()).unwrap(), 486 OpenMode::Create, 487 ) 488 .with_source_generation(SourceGeneration::new([18; 32]).unwrap(), 1) 489 .unwrap(); 490 let cache = Client::open(NativeConfig::public_read(options)) 491 .await 492 .unwrap(); 493 let preview = Client::preview(); 494 for client in [&cache, &preview] { 495 client.start(StartMode::LocalOnly).await.unwrap(); 496 assert_eq!( 497 client 498 .stock(&scope) 499 .create_pool(context(&scope, 80), minimum, creation()) 500 .await 501 .unwrap_err() 502 .code(), 503 Code::MissingAuthority 504 ); 505 assert_eq!( 506 client 507 .operations(&scope) 508 .abort_proven_unissued( 509 minimum, 510 OperationId::from_bytes([99; 32]), 511 CommandDigest::from_bytes([98; 32]) 512 ) 513 .await 514 .unwrap_err() 515 .code(), 516 Code::MissingAuthority 517 ); 518 client.close().await.unwrap(); 519 } 520 native 521 .authenticate(enrollment.input().clone(), enrollment.proof()) 522 .await 523 .unwrap(); 524 assert_eq!( 525 native 526 .stock_authority(enrollment.input().clone(), enrollment.proof()) 527 .await 528 .unwrap() 529 .inventory_checkpoint() 530 .unwrap(), 531 minimum 532 ); 533 owner.close().await.unwrap(); 534 } 535 536 #[tokio::test] 537 async fn ordinary_outbox_refuses_cleanup_and_never_creates_stock_authority() { 538 let f = Fixture::new(); 539 let path = f.root.join("outbox"); 540 let (native, input, credential) = NativeWorkspace::initialize_local_outbox( 541 &path, 542 LocalOutboxConfig::new( 543 key(), 544 key(), 545 "synthetic-outbox", 546 UnixSeconds::new(300).unwrap(), 547 ) 548 .unwrap(), 549 f.crypto(), 550 f.clock.clone(), 551 ) 552 .await 553 .unwrap(); 554 let client = f.client(native.clone()).await; 555 let scope = client 556 .attach(input.clone(), proof(&credential)) 557 .await 558 .unwrap(); 559 let minimum = InventoryCheckpointRef::from_host_metadata( 560 input.authority(), 561 Sequence::new(0).unwrap(), 562 None, 563 ) 564 .unwrap(); 565 client.start(StartMode::LocalOnly).await.unwrap(); 566 let operation = OperationId::from_bytes([99; 32]); 567 let digest = CommandDigest::from_bytes([98; 32]); 568 assert_eq!( 569 client 570 .operations(&scope) 571 .abort_proven_unissued(minimum, operation, digest) 572 .await 573 .unwrap_err() 574 .code(), 575 Code::CapabilityUnavailable 576 ); 577 assert_eq!( 578 client 579 .operations(&scope) 580 .preparation_abort(minimum, operation, digest) 581 .await 582 .unwrap_err() 583 .code(), 584 Code::CapabilityUnavailable 585 ); 586 assert_eq!( 587 client 588 .stock(&scope) 589 .create_pool(context(&scope, 80), minimum, creation()) 590 .await 591 .unwrap_err() 592 .code(), 593 Code::Unauthorized 594 ); 595 assert!(!path.join("stock_execution_v1.sqlite").exists()); 596 native.authenticate(input, &credential).await.unwrap(); 597 client.close().await.unwrap(); 598 }