cloacina 0.6.0

A Rust library for resilient task execution and orchestration.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
/*
 *  Copyright 2025-2026 Colliery Software
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

//! Package verification for secure loading.
//!
//! This module provides:
//! - [`SecurityConfig`] for configuring signature requirements
//! - [`VerificationError`] for specific failure types
//! - [`SignatureSource`] for specifying where to find signatures
//! - [`verify_and_load_package`] for verified package loading

use super::audit;
use crate::crypto::verify_signature;
use crate::database::universal_types::UniversalUuid;
use std::path::{Path, PathBuf};
use thiserror::Error;

use super::package_signer::{DbPackageSigner, DetachedSignature, PackageSigner};
use super::{DbKeyManager, KeyManager};

/// Security configuration for package verification.
#[derive(Debug, Clone, Default)]
pub struct SecurityConfig {
    /// Whether package signatures are required (default: false).
    ///
    /// When `true`, packages without valid signatures from trusted keys
    /// will fail to load with a hard error.
    ///
    /// When `false`, packages load without verification (for local development).
    pub require_signatures: bool,

    /// Master encryption key for decrypting signing keys (optional).
    ///
    /// Only needed if using database-stored signing keys for signing operations.
    /// For verification-only scenarios (loading packages), this is not required.
    pub key_encryption_key: Option<[u8; 32]>,

    /// Organization ID against which uploaded-package signatures are
    /// verified. The verification flow looks up trusted keys scoped to
    /// this org (`KeyManager::find_trusted_key(org_id, fingerprint)`).
    /// `None` means "no org binding configured" — verification cannot
    /// run, and `require_signatures = true` becomes fail-safe (reject
    /// all uploads). Set this to the server's default-org UUID when
    /// signature verification is enabled. (T-0557 Bug 2)
    pub verification_org_id: Option<UniversalUuid>,
}

impl SecurityConfig {
    /// Create a security config that requires signatures.
    pub fn require_signatures() -> Self {
        Self {
            require_signatures: true,
            key_encryption_key: None,
            verification_org_id: None,
        }
    }

    /// Create a security config with no signature requirements (for development).
    pub fn development() -> Self {
        Self::default()
    }

    /// Set the key encryption key for signing operations.
    pub fn with_encryption_key(mut self, key: [u8; 32]) -> Self {
        self.key_encryption_key = Some(key);
        self
    }
}

/// Errors that occur during package verification.
///
/// These are hard failures - there are no "warnings" for security.
#[derive(Debug, Error)]
pub enum VerificationError {
    #[error("Package has been tampered with: hash mismatch (expected {expected}, got {actual})")]
    TamperedPackage {
        /// Expected hash from the signature
        expected: String,
        /// Actual hash computed from the package
        actual: String,
    },

    #[error("Package signed by untrusted key: {fingerprint}")]
    UntrustedSigner {
        /// Fingerprint of the key that signed the package
        fingerprint: String,
    },

    #[error("Invalid signature: cryptographic verification failed")]
    InvalidSignature,

    #[error("Signature not found for package (hash: {hash})")]
    SignatureNotFound {
        /// Hash of the package we're looking for a signature for
        hash: String,
    },

    #[error("Signature file malformed: {reason}")]
    MalformedSignature {
        /// Description of what's wrong with the signature
        reason: String,
    },

    #[error("Failed to read package file: {error}")]
    FileReadError {
        /// The underlying IO error
        error: String,
    },

    #[error("Failed to compute package hash: {error}")]
    HashError {
        /// Description of the hash computation error
        error: String,
    },

    #[error("Database error: {error}")]
    DatabaseError {
        /// The underlying database error
        error: String,
    },

    #[error("Key manager error: {error}")]
    KeyManagerError {
        /// The underlying key manager error
        error: String,
    },
}

/// Where to find the signature for a package.
#[derive(Debug, Clone, Default)]
pub enum SignatureSource {
    /// Load signature from database by package hash.
    Database,

    /// Load signature from a detached `.sig` file.
    DetachedFile {
        /// Path to the signature file
        path: PathBuf,
    },

    /// Try detached file first (package_path + ".sig"), then database.
    #[default]
    Auto,
}

/// Result of successful verification.
#[derive(Debug, Clone)]
pub struct VerificationResult {
    /// Hash of the verified package
    pub package_hash: String,
    /// Fingerprint of the key that signed it
    pub signer_fingerprint: String,
    /// Name of the trusted key (if available)
    pub signer_name: Option<String>,
}

/// Verify a package signature.
///
/// This function performs full cryptographic verification:
/// 1. Computes the package hash
/// 2. Loads the signature (from database or file)
/// 3. Finds the trusted key that signed it
/// 4. Verifies the Ed25519 signature
///
/// # Arguments
///
/// * `package_path` - Path to the package file to verify
/// * `org_id` - Organization ID to check trusted keys for
/// * `signature_source` - Where to find the signature
/// * `package_signer` - Package signer for database operations
/// * `key_manager` - Key manager for trusted key lookup
///
/// # Returns
///
/// `Ok(VerificationResult)` if verification succeeds, `Err(VerificationError)` otherwise.
pub async fn verify_package<P: AsRef<Path>>(
    package_path: P,
    org_id: UniversalUuid,
    signature_source: SignatureSource,
    package_signer: &DbPackageSigner,
    key_manager: &DbKeyManager,
) -> Result<VerificationResult, VerificationError> {
    let package_path = package_path.as_ref();

    // 1. Compute package hash
    let package_data =
        std::fs::read(package_path).map_err(|e| VerificationError::FileReadError {
            error: e.to_string(),
        })?;

    let package_hash = compute_package_hash(&package_data)?;

    // 2. Load signature based on source
    let signature = match signature_source {
        SignatureSource::Database => load_signature_from_db(&package_hash, package_signer).await?,

        SignatureSource::DetachedFile { path } => load_signature_from_file(&path)?,

        SignatureSource::Auto => {
            // Try detached file first
            let sig_path = package_path.with_extension(format!(
                "{}.sig",
                package_path
                    .extension()
                    .map(|e| e.to_str().unwrap_or(""))
                    .unwrap_or("")
            ));

            if sig_path.exists() {
                load_signature_from_file(&sig_path)?
            } else {
                load_signature_from_db(&package_hash, package_signer).await?
            }
        }
    };

    // 3. Verify hash matches (tamper detection)
    if signature.package_hash != package_hash {
        audit::log_verification_failure(
            org_id,
            &package_hash,
            "tampered",
            Some(&signature.key_fingerprint),
        );
        return Err(VerificationError::TamperedPackage {
            expected: signature.package_hash,
            actual: package_hash,
        });
    }

    // 4. Find trusted key by fingerprint
    let trusted_key = key_manager
        .find_trusted_key(org_id, &signature.key_fingerprint)
        .await
        .map_err(|e| VerificationError::KeyManagerError {
            error: e.to_string(),
        })?
        .ok_or_else(|| {
            audit::log_verification_failure(
                org_id,
                &package_hash,
                "untrusted_signer",
                Some(&signature.key_fingerprint),
            );
            VerificationError::UntrustedSigner {
                fingerprint: signature.key_fingerprint.clone(),
            }
        })?;

    // 5. Verify Ed25519 signature
    let hash_bytes = hex::decode(&package_hash).map_err(|e| VerificationError::HashError {
        error: e.to_string(),
    })?;

    let sig_bytes = signature.signature_bytes().map_err(|_| {
        audit::log_verification_failure(
            org_id,
            &package_hash,
            "invalid_signature",
            Some(&signature.key_fingerprint),
        );
        VerificationError::InvalidSignature
    })?;

    if verify_signature(&hash_bytes, &sig_bytes, &trusted_key.public_key).is_err() {
        audit::log_verification_failure(
            org_id,
            &package_hash,
            "invalid_signature",
            Some(&signature.key_fingerprint),
        );
        return Err(VerificationError::InvalidSignature);
    }

    // 6. Success - audit log
    audit::log_verification_success(
        org_id,
        &package_hash,
        &signature.key_fingerprint,
        trusted_key.key_name.as_deref(),
    );

    Ok(VerificationResult {
        package_hash,
        signer_fingerprint: signature.key_fingerprint,
        signer_name: trusted_key.key_name,
    })
}

/// Verify a package using only a detached signature and public key (offline mode).
///
/// This is useful when the database is not available or for offline verification.
///
/// # Arguments
///
/// * `package_path` - Path to the package file to verify
/// * `signature_path` - Path to the detached signature file
/// * `public_key` - The 32-byte Ed25519 public key to verify against
///
/// # Returns
///
/// `Ok(())` if verification succeeds, `Err(VerificationError)` otherwise.
pub fn verify_package_offline<P: AsRef<Path>, S: AsRef<Path>>(
    package_path: P,
    signature_path: S,
    public_key: &[u8],
) -> Result<VerificationResult, VerificationError> {
    let package_path = package_path.as_ref();
    let signature_path = signature_path.as_ref();

    // 1. Load package and compute hash
    let package_data =
        std::fs::read(package_path).map_err(|e| VerificationError::FileReadError {
            error: e.to_string(),
        })?;

    let package_hash = compute_package_hash(&package_data)?;

    // 2. Load signature from file
    let signature = load_signature_from_file(signature_path)?;

    // 3. Verify hash matches
    if signature.package_hash != package_hash {
        return Err(VerificationError::TamperedPackage {
            expected: signature.package_hash,
            actual: package_hash,
        });
    }

    // 4. Verify key fingerprint matches
    let expected_fingerprint = crate::crypto::compute_key_fingerprint(public_key);
    if signature.key_fingerprint != expected_fingerprint {
        return Err(VerificationError::UntrustedSigner {
            fingerprint: signature.key_fingerprint,
        });
    }

    // 5. Verify signature
    let hash_bytes = hex::decode(&package_hash).map_err(|e| VerificationError::HashError {
        error: e.to_string(),
    })?;

    let sig_bytes = signature
        .signature_bytes()
        .map_err(|_| VerificationError::InvalidSignature)?;

    verify_signature(&hash_bytes, &sig_bytes, public_key)
        .map_err(|_| VerificationError::InvalidSignature)?;

    tracing::info!(
        event_type = "verification.success.offline",
        package = %package_path.display(),
        signer_fingerprint = %signature.key_fingerprint,
        "Package signature verified (offline mode)"
    );

    Ok(VerificationResult {
        package_hash,
        signer_fingerprint: signature.key_fingerprint,
        signer_name: None,
    })
}

/// Verify a package signature against in-memory bytes. Same flow as
/// `verify_package` but takes a `&[u8]` instead of a path; useful for
/// upload handlers that already have the package buffered (T-0557 Bug 2).
pub async fn verify_package_bytes(
    package_data: &[u8],
    org_id: UniversalUuid,
    signature_source: SignatureSource,
    package_signer: &DbPackageSigner,
    key_manager: &DbKeyManager,
) -> Result<VerificationResult, VerificationError> {
    let package_hash = compute_package_hash(package_data)?;

    let signature = match signature_source {
        SignatureSource::Database => load_signature_from_db(&package_hash, package_signer).await?,
        SignatureSource::DetachedFile { path } => load_signature_from_file(&path)?,
        SignatureSource::Auto => {
            // No on-disk path to derive a sidecar from — fall back to
            // database lookup. Callers wanting detached-file behavior
            // must pass `DetachedFile` explicitly.
            load_signature_from_db(&package_hash, package_signer).await?
        }
    };

    if signature.package_hash != package_hash {
        audit::log_verification_failure(
            org_id,
            &package_hash,
            "tampered",
            Some(&signature.key_fingerprint),
        );
        return Err(VerificationError::TamperedPackage {
            expected: signature.package_hash,
            actual: package_hash,
        });
    }

    let trusted_key = key_manager
        .find_trusted_key(org_id, &signature.key_fingerprint)
        .await
        .map_err(|e| VerificationError::KeyManagerError {
            error: e.to_string(),
        })?
        .ok_or_else(|| {
            audit::log_verification_failure(
                org_id,
                &package_hash,
                "untrusted_signer",
                Some(&signature.key_fingerprint),
            );
            VerificationError::UntrustedSigner {
                fingerprint: signature.key_fingerprint.clone(),
            }
        })?;

    let hash_bytes = hex::decode(&package_hash).map_err(|e| VerificationError::HashError {
        error: e.to_string(),
    })?;

    let sig_bytes = signature.signature_bytes().map_err(|_| {
        audit::log_verification_failure(
            org_id,
            &package_hash,
            "invalid_signature",
            Some(&signature.key_fingerprint),
        );
        VerificationError::InvalidSignature
    })?;

    if verify_signature(&hash_bytes, &sig_bytes, &trusted_key.public_key).is_err() {
        audit::log_verification_failure(
            org_id,
            &package_hash,
            "invalid_signature",
            Some(&signature.key_fingerprint),
        );
        return Err(VerificationError::InvalidSignature);
    }

    audit::log_verification_success(
        org_id,
        &package_hash,
        &signature.key_fingerprint,
        trusted_key.key_name.as_deref(),
    );

    Ok(VerificationResult {
        package_hash,
        signer_fingerprint: signature.key_fingerprint,
        signer_name: trusted_key.key_name,
    })
}

/// Compute SHA256 hash of package data.
fn compute_package_hash(data: &[u8]) -> Result<String, VerificationError> {
    use sha2::{Digest, Sha256};

    let mut hasher = Sha256::new();
    hasher.update(data);
    Ok(hex::encode(hasher.finalize()))
}

/// Load signature from database.
async fn load_signature_from_db(
    package_hash: &str,
    package_signer: &DbPackageSigner,
) -> Result<DetachedSignature, VerificationError> {
    let signature = package_signer
        .find_signature(package_hash)
        .await
        .map_err(|e| VerificationError::DatabaseError {
            error: e.to_string(),
        })?
        .ok_or_else(|| VerificationError::SignatureNotFound {
            hash: package_hash.to_string(),
        })?;

    Ok(DetachedSignature::from_signature_info(&signature))
}

/// Load signature from file.
fn load_signature_from_file(path: &Path) -> Result<DetachedSignature, VerificationError> {
    DetachedSignature::read_from_file(path).map_err(|e| VerificationError::MalformedSignature {
        reason: e.to_string(),
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::crypto::generate_signing_keypair;
    use base64::Engine;
    use tempfile::NamedTempFile;

    #[test]
    fn test_security_config_default() {
        let config = SecurityConfig::default();
        assert!(!config.require_signatures);
        assert!(config.key_encryption_key.is_none());
    }

    #[test]
    fn test_security_config_require_signatures() {
        let config = SecurityConfig::require_signatures();
        assert!(config.require_signatures);
    }

    #[test]
    fn test_security_config_with_encryption_key() {
        let key = [0x42u8; 32];
        let config = SecurityConfig::default().with_encryption_key(key);
        assert_eq!(config.key_encryption_key, Some(key));
    }

    #[test]
    fn test_verify_package_offline_with_invalid_signature() {
        // Create a test package
        let package_file = NamedTempFile::new().unwrap();
        std::fs::write(package_file.path(), b"test package content").unwrap();

        // Generate a keypair
        let keypair = generate_signing_keypair();

        // Create a signature file with wrong hash
        let sig = DetachedSignature {
            version: 1,
            algorithm: "ed25519".to_string(),
            package_hash: "wrong_hash".to_string(),
            key_fingerprint: keypair.fingerprint.clone(),
            signature: base64::engine::general_purpose::STANDARD.encode([0u8; 64]),
            signed_at: chrono::Utc::now().to_rfc3339(),
        };

        let sig_file = NamedTempFile::new().unwrap();
        sig.write_to_file(sig_file.path()).unwrap();

        // Verification should fail due to hash mismatch
        let result =
            verify_package_offline(package_file.path(), sig_file.path(), &keypair.public_key);

        assert!(matches!(
            result,
            Err(VerificationError::TamperedPackage { .. })
        ));
    }

    #[test]
    fn test_signature_source_default() {
        let source = SignatureSource::default();
        assert!(matches!(source, SignatureSource::Auto));
    }

    #[test]
    fn test_verify_package_offline_valid_signature() {
        let package_file = NamedTempFile::new().unwrap();
        let content = b"valid package content";
        std::fs::write(package_file.path(), content).unwrap();

        let keypair = generate_signing_keypair();

        // Compute correct hash and sign it
        use sha2::{Digest, Sha256};
        let mut hasher = Sha256::new();
        hasher.update(content);
        let package_hash = hex::encode(hasher.finalize());

        let hash_bytes = hex::decode(&package_hash).unwrap();
        let signature_bytes =
            crate::crypto::sign_package(&hash_bytes, &keypair.private_key).unwrap();

        let sig = DetachedSignature {
            version: 1,
            algorithm: "ed25519".to_string(),
            package_hash: package_hash.clone(),
            key_fingerprint: keypair.fingerprint.clone(),
            signature: base64::engine::general_purpose::STANDARD.encode(&signature_bytes),
            signed_at: chrono::Utc::now().to_rfc3339(),
        };

        let sig_file = NamedTempFile::new().unwrap();
        sig.write_to_file(sig_file.path()).unwrap();

        let result =
            verify_package_offline(package_file.path(), sig_file.path(), &keypair.public_key);
        assert!(result.is_ok());
        let verification = result.unwrap();
        assert_eq!(verification.package_hash, package_hash);
        assert_eq!(verification.signer_fingerprint, keypair.fingerprint);
    }

    #[test]
    fn test_verify_package_offline_tampered_content() {
        let package_file = NamedTempFile::new().unwrap();
        let original = b"original content";
        std::fs::write(package_file.path(), original).unwrap();

        let keypair = generate_signing_keypair();

        use sha2::{Digest, Sha256};
        let mut hasher = Sha256::new();
        hasher.update(original);
        let package_hash = hex::encode(hasher.finalize());

        let hash_bytes = hex::decode(&package_hash).unwrap();
        let signature_bytes =
            crate::crypto::sign_package(&hash_bytes, &keypair.private_key).unwrap();

        let sig = DetachedSignature {
            version: 1,
            algorithm: "ed25519".to_string(),
            package_hash,
            key_fingerprint: keypair.fingerprint.clone(),
            signature: base64::engine::general_purpose::STANDARD.encode(&signature_bytes),
            signed_at: chrono::Utc::now().to_rfc3339(),
        };

        let sig_file = NamedTempFile::new().unwrap();
        sig.write_to_file(sig_file.path()).unwrap();

        // Tamper with the package content
        std::fs::write(package_file.path(), b"tampered content").unwrap();

        let result =
            verify_package_offline(package_file.path(), sig_file.path(), &keypair.public_key);
        assert!(matches!(
            result,
            Err(VerificationError::TamperedPackage { .. })
        ));
    }

    #[test]
    fn test_verify_package_offline_wrong_key() {
        let package_file = NamedTempFile::new().unwrap();
        let content = b"content";
        std::fs::write(package_file.path(), content).unwrap();

        let signer = generate_signing_keypair();
        let wrong_verifier = generate_signing_keypair();

        use sha2::{Digest, Sha256};
        let mut hasher = Sha256::new();
        hasher.update(content);
        let package_hash = hex::encode(hasher.finalize());

        let hash_bytes = hex::decode(&package_hash).unwrap();
        let signature_bytes =
            crate::crypto::sign_package(&hash_bytes, &signer.private_key).unwrap();

        let sig = DetachedSignature {
            version: 1,
            algorithm: "ed25519".to_string(),
            package_hash,
            key_fingerprint: signer.fingerprint.clone(),
            signature: base64::engine::general_purpose::STANDARD.encode(&signature_bytes),
            signed_at: chrono::Utc::now().to_rfc3339(),
        };

        let sig_file = NamedTempFile::new().unwrap();
        sig.write_to_file(sig_file.path()).unwrap();

        let result = verify_package_offline(
            package_file.path(),
            sig_file.path(),
            &wrong_verifier.public_key,
        );
        assert!(result.is_err());
    }

    #[test]
    fn test_verify_package_offline_nonexistent_package() {
        let keypair = generate_signing_keypair();
        let sig_file = NamedTempFile::new().unwrap();

        let sig = DetachedSignature {
            version: 1,
            algorithm: "ed25519".to_string(),
            package_hash: "hash".to_string(),
            key_fingerprint: "fp".to_string(),
            signature: "sig".to_string(),
            signed_at: chrono::Utc::now().to_rfc3339(),
        };
        sig.write_to_file(sig_file.path()).unwrap();

        let result = verify_package_offline(
            std::path::Path::new("/nonexistent/package"),
            sig_file.path(),
            &keypair.public_key,
        );
        assert!(result.is_err());
    }

    #[test]
    fn test_verify_package_offline_nonexistent_signature() {
        let keypair = generate_signing_keypair();
        let package_file = NamedTempFile::new().unwrap();
        std::fs::write(package_file.path(), b"content").unwrap();

        let result = verify_package_offline(
            package_file.path(),
            std::path::Path::new("/nonexistent/sig"),
            &keypair.public_key,
        );
        assert!(result.is_err());
    }

    #[test]
    fn test_load_signature_from_file_valid() {
        let sig = DetachedSignature {
            version: 1,
            algorithm: "ed25519".to_string(),
            package_hash: "abc".to_string(),
            key_fingerprint: "def".to_string(),
            signature: "c2lnbmF0dXJl".to_string(),
            signed_at: chrono::Utc::now().to_rfc3339(),
        };
        let temp = NamedTempFile::new().unwrap();
        sig.write_to_file(temp.path()).unwrap();

        let result = load_signature_from_file(temp.path());
        assert!(result.is_ok());
        assert_eq!(result.unwrap().package_hash, "abc");
    }

    #[test]
    fn test_load_signature_from_file_invalid() {
        let temp = NamedTempFile::new().unwrap();
        std::fs::write(temp.path(), "not json").unwrap();

        let result = load_signature_from_file(temp.path());
        assert!(matches!(
            result,
            Err(VerificationError::MalformedSignature { .. })
        ));
    }
}