mod.rs (27991B)
1 use super::*; 2 use radroots_domain::{ 3 ActorRole, AuthorityRef, CheckpointDigest, CheckpointRef, Coverage, Generation, PublicKey, 4 RouteDigest, Sequence, UnixSeconds, 5 }; 6 pub(super) mod issuance_records; 7 mod operation_records; 8 mod plan_records; 9 use radroots_domain::{ActorRef, SourceId}; 10 use radroots_secrets::{ 11 EncryptedEnvelope, SecretId, SecretRef, 12 context::{EnvelopeContext, EnvelopePurpose, EnvelopeSubject, PayloadSchemaId}, 13 envelope::{Nonce, SealMaterial, SealRequest}, 14 file::{FileOpenMode, FileProvider}, 15 id::{BackendKind, KeyVersion}, 16 memory::MemoryProvider, 17 provider::{AccessPolicy, SecretProvider}, 18 wrapping::SecretMaterial, 19 }; 20 use std::{ 21 fs as host_fs, 22 os::unix::fs::{DirBuilderExt, PermissionsExt, symlink}, 23 }; 24 25 pub(super) fn participant() -> PublicKey { 26 PublicKey::from_hex("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798").unwrap() 27 } 28 fn selection() -> AttachmentInput { 29 AttachmentInput::new( 30 WorkspaceId::from_bytes([1; 32]), 31 AuthorityRef::new(ExecutorId::from_bytes([2; 32]), Generation::new(1).unwrap()), 32 participant(), 33 "local://synthetic", 34 participant(), 35 GrantId::from_bytes([3; 32]), 36 CheckpointRef::new( 37 CheckpointDigest::from_bytes([4; 32]), 38 Sequence::new(0).unwrap(), 39 Coverage::Partial, 40 vec![SourceId::from_bytes([5; 32])], 41 ) 42 .unwrap(), 43 RouteDigest::from_bytes([6; 32]), 44 ) 45 .unwrap() 46 } 47 fn reference(id: &str, backend: BackendKind, version: u32) -> SecretRef { 48 SecretRef::new( 49 SecretId::parse(id).unwrap(), 50 backend, 51 KeyVersion::new(version).unwrap(), 52 ) 53 } 54 pub(super) struct CryptoFixture { 55 _temp: tempfile::TempDir, 56 pub(super) provider: Arc<FileProvider>, 57 } 58 impl CryptoFixture { 59 pub(super) fn root(&self) -> std::path::PathBuf { 60 self._temp.path().canonicalize().unwrap() 61 } 62 pub(super) fn new() -> Self { 63 let temp = tempfile::tempdir().unwrap(); 64 let root = temp.path().canonicalize().unwrap(); 65 let provider = Arc::new( 66 FileProvider::open( 67 root.join("vault"), 68 FileOpenMode::CreateNew, 69 SecretMaterial::from_slice(&[0xA5; 32]).unwrap(), 70 ) 71 .unwrap(), 72 ); 73 let fixture = Self { 74 _temp: temp, 75 provider, 76 }; 77 fixture.provision(&reference("grant-key", BackendKind::File, 1), 0x11); 78 fixture 79 } 80 fn provision(&self, reference: &SecretRef, nonce: u8) { 81 self.provider 82 .provision( 83 reference, 84 &SecretMaterial::from_slice(&[0x41; 32]).unwrap(), 85 Nonce::new([nonce; 24]), 86 ) 87 .unwrap(); 88 } 89 pub(super) fn crypto(&self) -> WorkspaceCrypto { 90 self.crypto_with_provider(self.provider.clone()) 91 } 92 pub(super) fn crypto_with_provider( 93 &self, 94 provider: Arc<dyn SecretProvider>, 95 ) -> WorkspaceCrypto { 96 WorkspaceCrypto::new( 97 provider, 98 reference("grant-key", BackendKind::File, 1), 99 SecretMaterial::from_slice(&[0x41; 32]).unwrap(), 100 AccessPolicy::standard(), 101 ) 102 .unwrap() 103 } 104 } 105 async fn envelope( 106 provider: &dyn SecretProvider, 107 reference: SecretRef, 108 plaintext: &[u8], 109 nonce: u8, 110 ) -> Vec<u8> { 111 let input = selection(); 112 let context = EnvelopeContext::new( 113 EnvelopePurpose::parse("radroots.workspace.grant").unwrap(), 114 EnvelopeSubject::parse( 115 "workspace_grant", 116 format!("{}{}", input.workspace_id(), input.grant_id()), 117 ) 118 .unwrap(), 119 PayloadSchemaId::parse("radroots.workspace.grant.v1").unwrap(), 120 ); 121 let plaintext = SecretMaterial::from_slice(plaintext).unwrap(); 122 EncryptedEnvelope::seal( 123 provider, 124 SealRequest::new( 125 reference, 126 context, 127 &plaintext, 128 SealMaterial::new( 129 SecretMaterial::from_slice(&[0x41; 32]).unwrap(), 130 Nonce::new([nonce; 24]), 131 ), 132 ), 133 ) 134 .await 135 .unwrap() 136 .encode() 137 .unwrap() 138 } 139 140 #[tokio::test] 141 async fn protected_payload_enforces_native_limits_reference_and_context_after_real_crypto() { 142 let fixture = CryptoFixture::new(); 143 let input = selection(); 144 assert!(matches!( 145 WorkspaceCrypto::new( 146 fixture.provider.clone(), 147 reference("grant-key", BackendKind::File, 1), 148 SecretMaterial::from_slice(&[1; 31]).unwrap(), 149 AccessPolicy::standard() 150 ), 151 Err(WorkspaceError::Unavailable) 152 )); 153 assert!(matches!( 154 WorkspaceCrypto::new( 155 Arc::new(MemoryProvider::new()), 156 reference("grant-key", BackendKind::Memory, 1), 157 SecretMaterial::from_slice(&[1; 32]).unwrap(), 158 AccessPolicy::standard() 159 ), 160 Err(WorkspaceError::Unavailable) 161 )); 162 let crypto = fixture.crypto(); 163 let boundary = vec![b'x'; crypto::PRIVATE_PAYLOAD_MAX_BYTES]; 164 let sealed = crypto 165 .seal(input.workspace_id(), input.grant_id(), &boundary) 166 .await 167 .unwrap(); 168 crypto 169 .open(input.workspace_id(), input.grant_id(), &sealed) 170 .await 171 .unwrap() 172 .expose_secret(|value| assert_eq!(value, boundary)); 173 assert!(matches!( 174 crypto 175 .open(WorkspaceId::from_bytes([9; 32]), input.grant_id(), &sealed) 176 .await, 177 Err(WorkspaceError::RecoveryRequired) 178 )); 179 assert!(matches!( 180 crypto 181 .open(input.workspace_id(), GrantId::from_bytes([9; 32]), &sealed) 182 .await, 183 Err(WorkspaceError::RecoveryRequired) 184 )); 185 let oversized = vec![b'x'; crypto::PRIVATE_PAYLOAD_MAX_BYTES + 1]; 186 assert!(matches!( 187 crypto 188 .seal(input.workspace_id(), input.grant_id(), &oversized) 189 .await, 190 Err(WorkspaceError::InvalidInput) 191 )); 192 assert!(matches!( 193 crypto 194 .open( 195 input.workspace_id(), 196 input.grant_id(), 197 &vec![0; crypto::PROTECTED_MAX_BYTES + 1] 198 ) 199 .await, 200 Err(WorkspaceError::RecoveryRequired) 201 )); 202 let sealed = envelope( 203 fixture.provider.as_ref(), 204 reference("grant-key", BackendKind::File, 1), 205 &oversized, 206 0x61, 207 ) 208 .await; 209 assert!(matches!( 210 crypto 211 .open(input.workspace_id(), input.grant_id(), &sealed) 212 .await, 213 Err(WorkspaceError::RecoveryRequired) 214 )); 215 for (id, version, nonce) in [("other-key", 1, 0x12), ("grant-key", 2, 0x13)] { 216 fixture.provision(&reference(id, BackendKind::File, version), nonce); 217 let sealed = envelope( 218 fixture.provider.as_ref(), 219 reference(id, BackendKind::File, version), 220 b"private", 221 nonce + 0x60, 222 ) 223 .await; 224 assert!(matches!( 225 crypto 226 .open(input.workspace_id(), input.grant_id(), &sealed) 227 .await, 228 Err(WorkspaceError::RecoveryRequired) 229 )); 230 } 231 let memory = MemoryProvider::new(); 232 memory 233 .provision( 234 &reference("grant-key", BackendKind::Memory, 1), 235 SecretMaterial::from_slice(&[0x41; 32]).unwrap(), 236 ) 237 .unwrap(); 238 let sealed = envelope( 239 &memory, 240 reference("grant-key", BackendKind::Memory, 1), 241 b"private", 242 0x64, 243 ) 244 .await; 245 assert!(matches!( 246 crypto 247 .open(input.workspace_id(), input.grant_id(), &sealed) 248 .await, 249 Err(WorkspaceError::RecoveryRequired) 250 )); 251 } 252 253 #[test] 254 fn persisted_grant_refuses_inconsistent_scope_actor_and_revisions() { 255 use serde_json::{Value, json}; 256 let input = selection(); 257 let proof = AttachmentProof::from_protected_input(&[7; 32]).unwrap(); 258 let record = record::GrantRecord::new( 259 input.clone(), 260 ActorRef::new( 261 participant(), 262 ActorRole::Buyer, 263 None, 264 Some(input.grant_id()), 265 ), 266 "synthetic-device".into(), 267 UnixSeconds::new(200).unwrap(), 268 &proof, 269 ) 270 .unwrap(); 271 let encoded = record.encode().unwrap(); 272 let original: Value = serde_json::from_slice(&encoded).unwrap(); 273 let second_key = "c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5"; 274 for (pointer, value) in [ 275 ("/version", json!(2)), 276 ("/scope", json!("seller_stock")), 277 ("/actor/role", json!("seller")), 278 ("/actor/organization", json!(participant().to_hex())), 279 ("/actor/participant", json!(second_key)), 280 ("/actor/grant_id", Value::Null), 281 ("/principal", json!("")), 282 ("/principal", json!("x".repeat(129))), 283 ("/principal", json!("bad\nlabel")), 284 ("/revision", json!("0")), 285 ("/expires_at", json!("0")), 286 ] { 287 let mut changed = original.clone(); 288 *changed.pointer_mut(pointer).unwrap() = value; 289 assert!( 290 matches!( 291 record::GrantRecord::decode(&serde_json::to_vec(&changed).unwrap()), 292 Err(WorkspaceError::RecoveryRequired) 293 ), 294 "{pointer}" 295 ); 296 } 297 let mut unknown = original.clone(); 298 unknown["unknown"] = json!(true); 299 assert!(matches!( 300 record::GrantRecord::decode(&serde_json::to_vec(&unknown).unwrap()), 301 Err(WorkspaceError::RecoveryRequired) 302 )); 303 let mut exhausted = original; 304 exhausted["revision"] = json!(i64::MAX.to_string()); 305 let mut exhausted = 306 record::GrantRecord::decode(&serde_json::to_vec(&exhausted).unwrap()).unwrap(); 307 assert_eq!(exhausted.revoke(), Err(WorkspaceError::RecoveryRequired)); 308 let record = record::GrantRecord::decode(&encoded).unwrap(); 309 assert_eq!( 310 record 311 .authenticate(&input, &proof, UnixSeconds::new(100).unwrap()) 312 .unwrap() 313 .grant_revision() 314 .get(), 315 1 316 ); 317 } 318 319 struct FixedClock(u64); 320 impl WorkspaceClock for FixedClock { 321 fn now(&self) -> Result<UnixSeconds, WorkspaceError> { 322 UnixSeconds::new(self.0).map_err(|_| WorkspaceError::Unavailable) 323 } 324 } 325 #[tokio::test] 326 async fn outbox_open_refuses_valid_protected_stock_scope_without_repair() { 327 use sha2::{Digest, Sha256}; 328 use sqlx::Connection; 329 330 let fixture = CryptoFixture::new(); 331 let path = fixture 332 ._temp 333 .path() 334 .canonicalize() 335 .unwrap() 336 .join("wrong-stock-scope"); 337 let (owner, input, proof) = NativeWorkspace::initialize_local_outbox( 338 &path, 339 LocalOutboxConfig::seller( 340 participant(), 341 participant(), 342 "synthetic-device", 343 UnixSeconds::new(200).unwrap(), 344 ) 345 .unwrap(), 346 fixture.crypto(), 347 Arc::new(FixedClock(100)), 348 ) 349 .await 350 .unwrap(); 351 owner.close().await.unwrap(); 352 let database = path.join("execution_v1.sqlite"); 353 let options = sqlx::sqlite::SqliteConnectOptions::new().filename(&database); 354 let mut connection = sqlx::SqliteConnection::connect_with(&options) 355 .await 356 .unwrap(); 357 let original: Vec<u8> = sqlx::query_scalar("SELECT protected FROM workspace_grant") 358 .fetch_one(&mut connection) 359 .await 360 .unwrap(); 361 let crypto = fixture.crypto(); 362 let clear = crypto 363 .open(input.workspace_id(), input.grant_id(), &original) 364 .await 365 .unwrap(); 366 let mut wire: serde_json::Value = 367 clear.expose_secret(|bytes| serde_json::from_slice(bytes).unwrap()); 368 wire["scope"] = serde_json::json!("seller_stock_owner"); 369 let mut verifier = Sha256::new(); 370 verifier.update(b"radroots.seller_stock.credential.v1\0"); 371 verifier.update(input.workspace_id().as_bytes()); 372 verifier.update(input.grant_id().as_bytes()); 373 proof.with_secret(|secret| verifier.update(secret)); 374 wire["verifier"] = serde_json::json!(<[u8; 32]>::from(verifier.finalize())); 375 let encoded = zeroize::Zeroizing::new(serde_json::to_vec(&wire).unwrap()); 376 let metadata = record::GrantRecord::decode(&encoded).unwrap(); 377 assert_eq!( 378 metadata 379 .authenticate(&input, &proof, UnixSeconds::new(100).unwrap()) 380 .unwrap() 381 .scope(), 382 WorkspaceScope::SellerStockOwner 383 ); 384 let sealed = crypto 385 .seal(input.workspace_id(), input.grant_id(), &encoded) 386 .await 387 .unwrap(); 388 sqlx::query("UPDATE workspace_grant SET protected=?") 389 .bind(sealed) 390 .execute(&mut connection) 391 .await 392 .unwrap(); 393 connection.close().await.unwrap(); 394 let retained = host_fs::read(&database).unwrap(); 395 assert!(matches!( 396 NativeWorkspace::open_existing(&path, input, fixture.crypto(), Arc::new(FixedClock(100))) 397 .await, 398 Err(WorkspaceError::RecoveryRequired) 399 )); 400 assert_eq!(host_fs::read(&database).unwrap(), retained); 401 } 402 #[tokio::test] 403 async fn seller_scope_survives_protected_close_reopen_without_stock_or_buyer_upgrade() { 404 let fixture = CryptoFixture::new(); 405 let path = fixture 406 ._temp 407 .path() 408 .canonicalize() 409 .unwrap() 410 .join("seller-outbox"); 411 let (owner, input, proof) = NativeWorkspace::initialize_local_outbox( 412 &path, 413 LocalOutboxConfig::seller( 414 participant(), 415 participant(), 416 "seller-device", 417 UnixSeconds::new(200).unwrap(), 418 ) 419 .unwrap(), 420 fixture.crypto(), 421 Arc::new(FixedClock(100)), 422 ) 423 .await 424 .unwrap(); 425 let binding = owner.authenticate(input.clone(), &proof).await.unwrap(); 426 assert_eq!(binding.scope(), WorkspaceScope::NewSellerOutbox); 427 assert_eq!(binding.actor().role(), ActorRole::Seller); 428 assert_eq!(binding.actor().organization(), None); 429 assert_eq!(input.checkpoint().coverage(), Coverage::Partial); 430 owner.close().await.unwrap(); 431 let reopened = NativeWorkspace::open_existing( 432 &path, 433 input.clone(), 434 fixture.crypto(), 435 Arc::new(FixedClock(100)), 436 ) 437 .await 438 .unwrap(); 439 assert_eq!( 440 reopened.authenticate(input.clone(), &proof).await.unwrap(), 441 binding 442 ); 443 let wrong = AttachmentProof::from_protected_input(&[0xEF; 32]).unwrap(); 444 assert_eq!( 445 reopened 446 .authenticate(input.clone(), &wrong) 447 .await 448 .unwrap_err(), 449 WorkspaceError::Unauthorized 450 ); 451 reopened.close().await.unwrap(); 452 let expired = NativeWorkspace::open_existing( 453 &path, 454 input.clone(), 455 fixture.crypto(), 456 Arc::new(FixedClock(200)), 457 ) 458 .await 459 .unwrap(); 460 assert_eq!( 461 expired 462 .authenticate(input.clone(), &proof) 463 .await 464 .unwrap_err(), 465 WorkspaceError::GrantExpired 466 ); 467 expired.close().await.unwrap(); 468 let reopened = NativeWorkspace::open_existing( 469 &path, 470 input.clone(), 471 fixture.crypto(), 472 Arc::new(FixedClock(100)), 473 ) 474 .await 475 .unwrap(); 476 reopened.revoke(input.clone(), &proof).await.unwrap(); 477 reopened.close().await.unwrap(); 478 let revoked = NativeWorkspace::open_existing( 479 &path, 480 input.clone(), 481 fixture.crypto(), 482 Arc::new(FixedClock(100)), 483 ) 484 .await 485 .unwrap(); 486 assert_eq!( 487 revoked 488 .authenticate(input.clone(), &proof) 489 .await 490 .unwrap_err(), 491 WorkspaceError::GrantRevoked 492 ); 493 revoked.close().await.unwrap(); 494 assert!(matches!( 495 NativeWorkspace::initialize_local_outbox( 496 &path, 497 LocalOutboxConfig::new( 498 participant(), 499 participant(), 500 "buyer", 501 UnixSeconds::new(200).unwrap() 502 ) 503 .unwrap(), 504 fixture.crypto(), 505 Arc::new(FixedClock(100)), 506 ) 507 .await, 508 Err(WorkspaceError::NamespaceUnavailable) 509 )); 510 } 511 #[tokio::test] 512 async fn enrollment_requires_bounded_principal_current_time_and_usable_key() { 513 for principal in [String::new(), "x".repeat(129), "bad\nlabel".into()] { 514 assert!(matches!( 515 LocalOutboxConfig::new( 516 participant(), 517 participant(), 518 principal, 519 UnixSeconds::new(200).unwrap() 520 ), 521 Err(WorkspaceError::InvalidInput) 522 )); 523 } 524 assert!(matches!( 525 LocalOutboxConfig::new( 526 participant(), 527 participant(), 528 "device", 529 UnixSeconds::new(0).unwrap() 530 ), 531 Err(WorkspaceError::InvalidInput) 532 )); 533 let fixture = CryptoFixture::new(); 534 for (now, expiry, expected) in [ 535 (0, 200, WorkspaceError::Unavailable), 536 (100, 100, WorkspaceError::GrantExpired), 537 ] { 538 let path = fixture 539 ._temp 540 .path() 541 .canonicalize() 542 .unwrap() 543 .join(format!("refused-{now}")); 544 let result = NativeWorkspace::initialize_local_outbox( 545 &path, 546 LocalOutboxConfig::new( 547 participant(), 548 participant(), 549 "device", 550 UnixSeconds::new(expiry).unwrap(), 551 ) 552 .unwrap(), 553 fixture.crypto(), 554 Arc::new(FixedClock(now)), 555 ) 556 .await; 557 assert!(matches!(result, Err(error) if error == expected)); 558 assert!(!path.exists()); 559 } 560 let wrong = WorkspaceCrypto::new( 561 fixture.provider.clone(), 562 reference("grant-key", BackendKind::File, 1), 563 SecretMaterial::from_slice(&[0x42; 32]).unwrap(), 564 AccessPolicy::standard(), 565 ) 566 .unwrap(); 567 let path = fixture 568 ._temp 569 .path() 570 .canonicalize() 571 .unwrap() 572 .join("wrong-key"); 573 assert!(matches!( 574 NativeWorkspace::initialize_local_outbox( 575 &path, 576 LocalOutboxConfig::new( 577 participant(), 578 participant(), 579 "device", 580 UnixSeconds::new(200).unwrap() 581 ) 582 .unwrap(), 583 wrong, 584 Arc::new(FixedClock(100)) 585 ) 586 .await, 587 Err(WorkspaceError::Unavailable) 588 )); 589 // Failed initialization remains visible. A second call cannot overwrite it. 590 assert!(matches!( 591 NativeWorkspace::initialize_local_outbox( 592 &path, 593 LocalOutboxConfig::new( 594 participant(), 595 participant(), 596 "device", 597 UnixSeconds::new(200).unwrap() 598 ) 599 .unwrap(), 600 fixture.crypto(), 601 Arc::new(FixedClock(100)) 602 ) 603 .await, 604 Err(WorkspaceError::NamespaceUnavailable) 605 )); 606 } 607 608 fn set_mode(path: &std::path::Path, mode: u32) { 609 host_fs::set_permissions(path, host_fs::Permissions::from_mode(mode)).unwrap(); 610 } 611 #[test] 612 fn namespace_rechecks_permissions_links_replacement_and_sidecars() { 613 for fault in 0..8 { 614 let temp = tempfile::tempdir().unwrap(); 615 let base = temp.path().canonicalize().unwrap(); 616 let path = base.join("outbox"); 617 let namespace = fs::Namespace::acquire(&path, true).unwrap(); 618 let database = namespace.database_path(); 619 match fault { 620 0 => set_mode(&path, 0o750), 621 1 => set_mode(&database, 0o640), 622 2 => { 623 host_fs::hard_link(&database, base.join("linked-database")).unwrap(); 624 } 625 3 => { 626 host_fs::rename(&database, base.join("old-database")).unwrap(); 627 host_fs::write(&database, b"replacement").unwrap(); 628 set_mode(&database, 0o600); 629 } 630 4 => { 631 let lock = path.join(".execution_v1.lock"); 632 host_fs::rename(&lock, base.join("old-lock")).unwrap(); 633 host_fs::write(&lock, b"").unwrap(); 634 set_mode(&lock, 0o600); 635 } 636 5 => { 637 host_fs::rename(&path, base.join("old-root")).unwrap(); 638 host_fs::DirBuilder::new() 639 .mode(0o700) 640 .create(&path) 641 .unwrap(); 642 } 643 6 => { 644 let sidecar = path.join("execution_v1.sqlite-wal"); 645 host_fs::write(&sidecar, b"").unwrap(); 646 set_mode(&sidecar, 0o644); 647 } 648 7 => { 649 symlink(&database, path.join("execution_v1.sqlite-wal")).unwrap(); 650 } 651 _ => unreachable!(), 652 } 653 assert_eq!( 654 namespace.validate(), 655 Err(WorkspaceError::NamespaceUnavailable), 656 "fault {fault}" 657 ); 658 drop(namespace); 659 } 660 let temp = tempfile::tempdir().unwrap(); 661 let base = temp.path().canonicalize().unwrap(); 662 let path = base.join("outbox"); 663 let namespace = fs::Namespace::acquire(&path, true).unwrap(); 664 for suffix in ["-wal", "-shm", "-journal"] { 665 let path = path.join(format!("execution_v1.sqlite{suffix}")); 666 host_fs::write(&path, b"").unwrap(); 667 set_mode(&path, 0o600); 668 } 669 namespace.validate().unwrap(); 670 host_fs::write(path.join("unexpected"), b"retain").unwrap(); 671 assert_eq!(namespace.validate(), Err(WorkspaceError::RecoveryRequired)); 672 assert_eq!(host_fs::read(path.join("unexpected")).unwrap(), b"retain"); 673 } 674 675 #[test] 676 fn namespace_refuses_unsafe_paths_empty_database_and_nonempty_lock_without_repair() { 677 assert!(matches!( 678 fs::Namespace::acquire(std::path::Path::new("relative"), false), 679 Err(WorkspaceError::NamespaceUnavailable) 680 )); 681 let temp = tempfile::tempdir().unwrap(); 682 let base = temp.path().canonicalize().unwrap(); 683 assert!(matches!( 684 fs::Namespace::acquire(&base.join("child/../outbox"), true), 685 Err(WorkspaceError::NamespaceUnavailable) 686 )); 687 let mutable = base.join("mutable"); 688 host_fs::create_dir(&mutable).unwrap(); 689 set_mode(&mutable, 0o777); 690 assert!(matches!( 691 fs::Namespace::acquire(&mutable.join("outbox"), true), 692 Err(WorkspaceError::NamespaceUnavailable) 693 )); 694 let regular = base.join("regular"); 695 host_fs::write(®ular, b"retain").unwrap(); 696 assert!(matches!( 697 fs::Namespace::acquire(®ular, false), 698 Err(WorkspaceError::NamespaceUnavailable) 699 )); 700 let target = base.join("target"); 701 host_fs::create_dir(&target).unwrap(); 702 symlink(&target, base.join("alias")).unwrap(); 703 assert!(matches!( 704 fs::Namespace::acquire(&base.join("alias/outbox"), true), 705 Err(WorkspaceError::NamespaceUnavailable) 706 )); 707 for nonempty_lock in [false, true] { 708 let path = base.join(format!("existing-{nonempty_lock}")); 709 let namespace = fs::Namespace::acquire(&path, true).unwrap(); 710 drop(namespace); 711 if nonempty_lock { 712 host_fs::write(path.join(".execution_v1.lock"), b"retain").unwrap(); 713 } 714 assert!(matches!( 715 fs::Namespace::acquire(&path, false), 716 Err(WorkspaceError::RecoveryRequired) 717 )); 718 if nonempty_lock { 719 assert_eq!( 720 host_fs::read(path.join(".execution_v1.lock")).unwrap(), 721 b"retain" 722 ); 723 } 724 } 725 } 726 727 #[tokio::test] 728 async fn existing_database_rejects_corrupt_version_missing_grant_and_oversized_rows_without_repair() 729 { 730 use sqlx::Connection; 731 let fixture = CryptoFixture::new(); 732 let base = fixture._temp.path().canonicalize().unwrap(); 733 for fault in 0..9 { 734 let path = base.join(format!("corrupt-{fault}")); 735 let (store, input, proof) = NativeWorkspace::initialize_local_outbox( 736 &path, 737 LocalOutboxConfig::new( 738 participant(), 739 participant(), 740 "device", 741 UnixSeconds::new(200).unwrap(), 742 ) 743 .unwrap(), 744 fixture.crypto(), 745 Arc::new(FixedClock(100)), 746 ) 747 .await 748 .unwrap(); 749 let options = sqlx::sqlite::SqliteConnectOptions::new() 750 .filename(path.join("execution_v1.sqlite")) 751 .create_if_missing(false); 752 let mut connection = sqlx::SqliteConnection::connect_with(&options) 753 .await 754 .unwrap(); 755 sqlx::query("PRAGMA ignore_check_constraints=ON") 756 .execute(&mut connection) 757 .await 758 .unwrap(); 759 let retained_protected: Option<Vec<u8>> = if fault >= 7 { 760 Some( 761 sqlx::query_scalar("SELECT protected FROM workspace_grant") 762 .fetch_one(&mut connection) 763 .await 764 .unwrap(), 765 ) 766 } else { 767 None 768 }; 769 let expected_error = if fault >= 7 { 770 WorkspaceError::WrongNamespace 771 } else { 772 WorkspaceError::RecoveryRequired 773 }; 774 let statement = match fault { 775 0 => "PRAGMA user_version=12", 776 1 => "DELETE FROM workspace_grant", 777 2 => "UPDATE workspace_grant SET grant_id=zeroblob(31)", 778 3 => "UPDATE workspace_grant SET protected=zeroblob(0)", 779 4 => "UPDATE workspace_grant SET protected=zeroblob(262145)", 780 5 => "UPDATE workspace_grant SET protected=zeroblob(262144)", 781 6 => "UPDATE workspace_grant SET workspace=zeroblob(31)", 782 7 => "UPDATE workspace_grant SET workspace=zeroblob(32)", 783 8 => "UPDATE workspace_grant SET grant_id=zeroblob(32)", 784 _ => unreachable!(), 785 }; 786 sqlx::query(statement) 787 .execute(&mut connection) 788 .await 789 .unwrap(); 790 connection.close().await.unwrap(); 791 if fault != 0 { 792 assert_eq!( 793 store.authenticate(input.clone(), &proof).await.err(), 794 Some(expected_error), 795 "live fault {fault}" 796 ); 797 } 798 store.close().await.unwrap(); 799 let result = NativeWorkspace::open_existing( 800 &path, 801 input, 802 fixture.crypto(), 803 Arc::new(FixedClock(100)), 804 ) 805 .await; 806 assert!( 807 matches!(&result, Err(error) if *error == expected_error), 808 "fault {fault}: {result:?}" 809 ); 810 let mut connection = sqlx::SqliteConnection::connect_with(&options.clone().read_only(true)) 811 .await 812 .unwrap(); 813 let version: i64 = sqlx::query_scalar("PRAGMA user_version") 814 .fetch_one(&mut connection) 815 .await 816 .unwrap(); 817 let rows: i64 = sqlx::query_scalar("SELECT count(*) FROM workspace_grant") 818 .fetch_one(&mut connection) 819 .await 820 .unwrap(); 821 assert_eq!(version, if fault == 0 { 12 } else { 11 }); 822 assert_eq!(rows, if fault == 1 { 0 } else { 1 }); 823 if let Some(expected) = retained_protected { 824 let actual: Vec<u8> = sqlx::query_scalar("SELECT protected FROM workspace_grant") 825 .fetch_one(&mut connection) 826 .await 827 .unwrap(); 828 assert_eq!( 829 actual, expected, 830 "foreign row must retain its original ciphertext" 831 ); 832 } 833 if (3..=5).contains(&fault) { 834 let size: i64 = sqlx::query_scalar("SELECT length(protected) FROM workspace_grant") 835 .fetch_one(&mut connection) 836 .await 837 .unwrap(); 838 assert_eq!(size, [0, 262145, 262144][fault - 3]); 839 } 840 connection.close().await.unwrap(); 841 } 842 }