assay-registry 2.18.0

Pack registry client for remote pack distribution (SPEC-Pack-Registry-v1)
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
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
//! Local cache layer for packs.
//!
//! Provides caching with integrity verification on read (TOCTOU protection).
//!
//! # Cache Structure
//!
//! ```text
//! ~/.assay/cache/packs/{name}/{version}/
//!   pack.yaml        # Pack content
//!   metadata.json    # Cache metadata
//!   signature.json   # DSSE envelope (optional)
//! ```

use std::path::{Path, PathBuf};

use chrono::{DateTime, Duration, Utc};
use serde::{Deserialize, Serialize};
use tokio::fs;
use tracing::{debug, warn};

use crate::error::{RegistryError, RegistryResult};
use crate::types::{DsseEnvelope, FetchResult, PackHeaders};
use crate::verify::compute_digest;

/// Default cache TTL (24 hours).
const DEFAULT_TTL_SECS: i64 = 24 * 60 * 60;

/// Cache metadata stored alongside pack content.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CacheMeta {
    /// When the pack was fetched.
    pub fetched_at: DateTime<Utc>,

    /// Content digest (sha256:...).
    pub digest: String,

    /// ETag for conditional requests.
    #[serde(default)]
    pub etag: Option<String>,

    /// When the cache entry expires.
    pub expires_at: DateTime<Utc>,

    /// Key ID used to sign (if signed).
    #[serde(default)]
    pub key_id: Option<String>,

    /// Registry URL this was fetched from.
    #[serde(default)]
    pub registry_url: Option<String>,
}

/// Pack cache for storing and retrieving packs locally.
#[derive(Debug, Clone)]
pub struct PackCache {
    /// Base cache directory.
    cache_dir: PathBuf,
}

/// Cached pack entry.
#[derive(Debug, Clone)]
pub struct CacheEntry {
    /// Pack content.
    pub content: String,

    /// Cache metadata.
    pub metadata: CacheMeta,

    /// DSSE envelope (if signed).
    pub signature: Option<DsseEnvelope>,
}

impl PackCache {
    /// Create a new cache with default location.
    ///
    /// Default: `~/.assay/cache/packs`
    pub fn new() -> RegistryResult<Self> {
        let cache_dir = default_cache_dir()?;
        Ok(Self { cache_dir })
    }

    /// Create a cache with a custom directory.
    pub fn with_dir(cache_dir: impl Into<PathBuf>) -> Self {
        Self {
            cache_dir: cache_dir.into(),
        }
    }

    /// Get the cache directory.
    pub fn cache_dir(&self) -> &Path {
        &self.cache_dir
    }

    /// Get the path for a pack's cache directory.
    fn pack_dir(&self, name: &str, version: &str) -> PathBuf {
        self.cache_dir.join(name).join(version)
    }

    /// Get a cached pack, verifying integrity on read.
    ///
    /// Returns `None` if not cached or expired.
    /// Returns `Err` if integrity verification fails (caller should evict and re-fetch).
    pub async fn get(&self, name: &str, version: &str) -> RegistryResult<Option<CacheEntry>> {
        let pack_dir = self.pack_dir(name, version);

        // Check if pack exists
        let pack_path = pack_dir.join("pack.yaml");
        let meta_path = pack_dir.join("metadata.json");

        if !pack_path.exists() || !meta_path.exists() {
            debug!(name, version, "pack not in cache");
            return Ok(None);
        }

        // Read metadata first
        let meta_content =
            fs::read_to_string(&meta_path)
                .await
                .map_err(|e| RegistryError::Cache {
                    message: format!("failed to read cache metadata: {}", e),
                })?;
        let metadata: CacheMeta =
            serde_json::from_str(&meta_content).map_err(|e| RegistryError::Cache {
                message: format!("failed to parse cache metadata: {}", e),
            })?;

        // Check expiry
        if metadata.expires_at < Utc::now() {
            debug!(
                name,
                version,
                expires_at = %metadata.expires_at,
                "cache entry expired"
            );
            return Ok(None);
        }

        // Read content
        let content = fs::read_to_string(&pack_path)
            .await
            .map_err(|e| RegistryError::Cache {
                message: format!("failed to read cached pack: {}", e),
            })?;

        // CRITICAL: Verify digest BEFORE returning (TOCTOU protection)
        let computed_digest = compute_digest(&content);
        if computed_digest != metadata.digest {
            warn!(
                name,
                version,
                expected = %metadata.digest,
                actual = %computed_digest,
                "cache integrity check failed"
            );
            return Err(RegistryError::DigestMismatch {
                name: name.to_string(),
                version: version.to_string(),
                expected: metadata.digest,
                actual: computed_digest,
            });
        }

        // Read signature if present
        let sig_path = pack_dir.join("signature.json");
        let signature = if sig_path.exists() {
            let sig_content = fs::read_to_string(&sig_path).await.ok();
            sig_content.and_then(|s| serde_json::from_str(&s).ok())
        } else {
            None
        };

        debug!(name, version, "cache hit");
        Ok(Some(CacheEntry {
            content,
            metadata,
            signature,
        }))
    }

    /// Store a pack in the cache.
    pub async fn put(
        &self,
        name: &str,
        version: &str,
        result: &FetchResult,
        registry_url: Option<&str>,
    ) -> RegistryResult<()> {
        let pack_dir = self.pack_dir(name, version);

        // Create directory
        fs::create_dir_all(&pack_dir)
            .await
            .map_err(|e| RegistryError::Cache {
                message: format!("failed to create cache directory: {}", e),
            })?;

        // Calculate expiry from Cache-Control header
        let expires_at = parse_cache_control_expiry(&result.headers);

        // Build metadata
        let metadata = CacheMeta {
            fetched_at: Utc::now(),
            digest: result.computed_digest.clone(),
            etag: result.headers.etag.clone(),
            expires_at,
            key_id: result.headers.key_id.clone(),
            registry_url: registry_url.map(String::from),
        };

        // Write files atomically (write to temp, then rename)
        let pack_path = pack_dir.join("pack.yaml");
        let meta_path = pack_dir.join("metadata.json");

        // Write content
        write_atomic(&pack_path, &result.content).await?;

        // Write metadata
        let meta_json =
            serde_json::to_string_pretty(&metadata).map_err(|e| RegistryError::Cache {
                message: format!("failed to serialize metadata: {}", e),
            })?;
        write_atomic(&meta_path, &meta_json).await?;

        // Write signature if present
        if let Some(sig_b64) = &result.headers.signature {
            // Try to parse as DSSE envelope
            if let Ok(envelope) = parse_signature(sig_b64) {
                let sig_path = pack_dir.join("signature.json");
                let sig_json =
                    serde_json::to_string_pretty(&envelope).map_err(|e| RegistryError::Cache {
                        message: format!("failed to serialize signature: {}", e),
                    })?;
                write_atomic(&sig_path, &sig_json).await?;
            }
        }

        debug!(name, version, "cached pack");
        Ok(())
    }

    /// Get cached metadata without loading content.
    pub async fn get_metadata(&self, name: &str, version: &str) -> Option<CacheMeta> {
        let meta_path = self.pack_dir(name, version).join("metadata.json");

        let content = fs::read_to_string(&meta_path).await.ok()?;
        serde_json::from_str(&content).ok()
    }

    /// Get the ETag for conditional requests.
    pub async fn get_etag(&self, name: &str, version: &str) -> Option<String> {
        self.get_metadata(name, version).await.and_then(|m| m.etag)
    }

    /// Check if a pack is cached and not expired.
    pub async fn is_cached(&self, name: &str, version: &str) -> bool {
        match self.get_metadata(name, version).await {
            Some(meta) => meta.expires_at >= Utc::now(),
            None => false,
        }
    }

    /// Evict a pack from the cache.
    pub async fn evict(&self, name: &str, version: &str) -> RegistryResult<()> {
        let pack_dir = self.pack_dir(name, version);

        if pack_dir.exists() {
            fs::remove_dir_all(&pack_dir)
                .await
                .map_err(|e| RegistryError::Cache {
                    message: format!("failed to evict cache entry: {}", e),
                })?;
            debug!(name, version, "evicted from cache");
        }

        Ok(())
    }

    /// Clear all cached packs.
    pub async fn clear(&self) -> RegistryResult<()> {
        if self.cache_dir.exists() {
            fs::remove_dir_all(&self.cache_dir)
                .await
                .map_err(|e| RegistryError::Cache {
                    message: format!("failed to clear cache: {}", e),
                })?;
            debug!("cleared pack cache");
        }
        Ok(())
    }

    /// List all cached packs.
    pub async fn list(&self) -> RegistryResult<Vec<(String, String, CacheMeta)>> {
        let mut result = Vec::new();

        if !self.cache_dir.exists() {
            return Ok(result);
        }

        let mut names = fs::read_dir(&self.cache_dir)
            .await
            .map_err(|e| RegistryError::Cache {
                message: format!("failed to read cache directory: {}", e),
            })?;

        while let Some(name_entry) = names.next_entry().await.map_err(|e| RegistryError::Cache {
            message: format!("failed to read directory entry: {}", e),
        })? {
            let name_path = name_entry.path();
            if !name_path.is_dir() {
                continue;
            }

            let name = name_entry.file_name().to_string_lossy().to_string();

            let mut versions =
                fs::read_dir(&name_path)
                    .await
                    .map_err(|e| RegistryError::Cache {
                        message: format!("failed to read version directory: {}", e),
                    })?;

            while let Some(version_entry) =
                versions
                    .next_entry()
                    .await
                    .map_err(|e| RegistryError::Cache {
                        message: format!("failed to read directory entry: {}", e),
                    })?
            {
                let version_path = version_entry.path();
                if !version_path.is_dir() {
                    continue;
                }

                let version = version_entry.file_name().to_string_lossy().to_string();

                if let Some(meta) = self.get_metadata(&name, &version).await {
                    result.push((name.clone(), version, meta));
                }
            }
        }

        Ok(result)
    }
}

impl Default for PackCache {
    fn default() -> Self {
        Self::new().unwrap_or_else(|_| Self::with_dir("/tmp/assay-cache/packs"))
    }
}

/// Get the default cache directory.
fn default_cache_dir() -> RegistryResult<PathBuf> {
    let base = dirs::cache_dir()
        .or_else(dirs::home_dir)
        .ok_or_else(|| RegistryError::Cache {
            message: "could not determine cache directory".to_string(),
        })?;

    Ok(base.join("assay").join("cache").join("packs"))
}

/// Parse Cache-Control header to determine expiry.
fn parse_cache_control_expiry(headers: &PackHeaders) -> DateTime<Utc> {
    let now = Utc::now();
    let default_ttl = Duration::seconds(DEFAULT_TTL_SECS);

    let ttl = headers
        .cache_control
        .as_ref()
        .and_then(|cc| {
            // Parse max-age=N
            cc.split(',')
                .find(|part| part.trim().starts_with("max-age="))
                .and_then(|part| {
                    part.trim()
                        .strip_prefix("max-age=")
                        .and_then(|v| v.parse::<i64>().ok())
                })
        })
        .map(Duration::seconds)
        .unwrap_or(default_ttl);

    now + ttl
}

/// Parse signature from Base64.
fn parse_signature(b64: &str) -> RegistryResult<DsseEnvelope> {
    use base64::{engine::general_purpose::STANDARD as BASE64, Engine};

    let bytes = BASE64.decode(b64).map_err(|e| RegistryError::Cache {
        message: format!("invalid base64 signature: {}", e),
    })?;

    serde_json::from_slice(&bytes).map_err(|e| RegistryError::Cache {
        message: format!("invalid DSSE envelope: {}", e),
    })
}

/// Write content to file atomically.
async fn write_atomic(path: &Path, content: &str) -> RegistryResult<()> {
    let temp_path = path.with_extension("tmp");

    fs::write(&temp_path, content)
        .await
        .map_err(|e| RegistryError::Cache {
            message: format!("failed to write temp file: {}", e),
        })?;

    fs::rename(&temp_path, path)
        .await
        .map_err(|e| RegistryError::Cache {
            message: format!("failed to rename temp file: {}", e),
        })?;

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use base64::Engine;
    use tempfile::TempDir;

    fn create_test_cache() -> (PackCache, TempDir) {
        let temp_dir = TempDir::new().unwrap();
        let cache = PackCache::with_dir(temp_dir.path().join("cache"));
        (cache, temp_dir)
    }

    fn create_fetch_result(content: &str) -> FetchResult {
        FetchResult {
            content: content.to_string(),
            headers: PackHeaders {
                digest: Some(compute_digest(content)),
                signature: None,
                key_id: None,
                etag: Some("\"abc123\"".to_string()),
                cache_control: Some("max-age=3600".to_string()),
                content_length: Some(content.len() as u64),
            },
            computed_digest: compute_digest(content),
        }
    }

    #[tokio::test]
    async fn test_cache_roundtrip() {
        let (cache, _temp_dir) = create_test_cache();
        let content = "name: test\nversion: 1.0.0";
        let result = create_fetch_result(content);

        // Put
        cache
            .put("test-pack", "1.0.0", &result, None)
            .await
            .unwrap();

        // Get
        let entry = cache.get("test-pack", "1.0.0").await.unwrap().unwrap();
        assert_eq!(entry.content, content);
        assert_eq!(entry.metadata.digest, compute_digest(content));
    }

    #[tokio::test]
    async fn test_cache_miss() {
        let (cache, _temp_dir) = create_test_cache();

        let result = cache.get("nonexistent", "1.0.0").await.unwrap();
        assert!(result.is_none());
    }

    #[tokio::test]
    async fn test_cache_integrity_failure() {
        let (cache, _temp_dir) = create_test_cache();
        let content = "name: test\nversion: 1.0.0";
        let result = create_fetch_result(content);

        // Put
        cache
            .put("test-pack", "1.0.0", &result, None)
            .await
            .unwrap();

        // Corrupt the cached file
        let pack_path = cache.pack_dir("test-pack", "1.0.0").join("pack.yaml");
        fs::write(&pack_path, "corrupted content").await.unwrap();

        // Get should fail integrity check
        let err = cache.get("test-pack", "1.0.0").await.unwrap_err();
        assert!(matches!(err, RegistryError::DigestMismatch { .. }));
    }

    #[tokio::test]
    async fn test_cache_expiry() {
        let (cache, _temp_dir) = create_test_cache();
        let content = "name: test\nversion: 1.0.0";
        let result = FetchResult {
            content: content.to_string(),
            headers: PackHeaders {
                digest: Some(compute_digest(content)),
                signature: None,
                key_id: None,
                etag: None,
                cache_control: Some("max-age=0".to_string()), // Expire immediately
                content_length: None,
            },
            computed_digest: compute_digest(content),
        };

        // Put
        cache
            .put("test-pack", "1.0.0", &result, None)
            .await
            .unwrap();

        // Wait a moment
        tokio::time::sleep(std::time::Duration::from_millis(10)).await;

        // Get should return None (expired)
        let entry = cache.get("test-pack", "1.0.0").await.unwrap();
        assert!(entry.is_none());
    }

    #[tokio::test]
    async fn test_cache_evict() {
        let (cache, _temp_dir) = create_test_cache();
        let content = "name: test\nversion: 1.0.0";
        let result = create_fetch_result(content);

        // Put
        cache
            .put("test-pack", "1.0.0", &result, None)
            .await
            .unwrap();
        assert!(cache.is_cached("test-pack", "1.0.0").await);

        // Evict
        cache.evict("test-pack", "1.0.0").await.unwrap();
        assert!(!cache.is_cached("test-pack", "1.0.0").await);
    }

    #[tokio::test]
    async fn test_cache_clear() {
        let (cache, _temp_dir) = create_test_cache();
        let content = "name: test\nversion: 1.0.0";
        let result = create_fetch_result(content);

        // Put multiple packs
        cache.put("pack1", "1.0.0", &result, None).await.unwrap();
        cache.put("pack2", "1.0.0", &result, None).await.unwrap();

        // Clear
        cache.clear().await.unwrap();

        // Both should be gone
        assert!(!cache.is_cached("pack1", "1.0.0").await);
        assert!(!cache.is_cached("pack2", "1.0.0").await);
    }

    #[tokio::test]
    async fn test_cache_list() {
        let (cache, _temp_dir) = create_test_cache();
        let content = "name: test\nversion: 1.0.0";
        let result = create_fetch_result(content);

        // Put multiple packs
        cache.put("pack1", "1.0.0", &result, None).await.unwrap();
        cache.put("pack1", "2.0.0", &result, None).await.unwrap();
        cache.put("pack2", "1.0.0", &result, None).await.unwrap();

        // List
        let entries = cache.list().await.unwrap();
        assert_eq!(entries.len(), 3);
    }

    #[tokio::test]
    async fn test_get_etag() {
        let (cache, _temp_dir) = create_test_cache();
        let content = "name: test\nversion: 1.0.0";
        let result = create_fetch_result(content);

        // Put
        cache
            .put("test-pack", "1.0.0", &result, None)
            .await
            .unwrap();

        // Get ETag
        let etag = cache.get_etag("test-pack", "1.0.0").await;
        assert_eq!(etag, Some("\"abc123\"".to_string()));
    }

    #[tokio::test]
    async fn test_parse_cache_control() {
        let headers = PackHeaders {
            digest: None,
            signature: None,
            key_id: None,
            etag: None,
            cache_control: Some("max-age=7200, public".to_string()),
            content_length: None,
        };

        let expires = parse_cache_control_expiry(&headers);
        let now = Utc::now();

        // Should be approximately 2 hours in the future
        let diff = expires - now;
        assert!(diff.num_seconds() >= 7190 && diff.num_seconds() <= 7210);
    }

    #[tokio::test]
    async fn test_default_ttl() {
        let headers = PackHeaders {
            digest: None,
            signature: None,
            key_id: None,
            etag: None,
            cache_control: None, // No Cache-Control
            content_length: None,
        };

        let expires = parse_cache_control_expiry(&headers);
        let now = Utc::now();

        // Should be approximately 24 hours in the future
        let diff = expires - now;
        assert!(diff.num_hours() >= 23 && diff.num_hours() <= 25);
    }

    #[tokio::test]
    async fn test_cache_with_signature() {
        let (cache, _temp_dir) = create_test_cache();
        let content = "name: test\nversion: 1.0.0";

        // Create a mock DSSE envelope
        let envelope = DsseEnvelope {
            payload_type: "application/vnd.assay.pack+yaml;v=1".to_string(),
            payload: base64::engine::general_purpose::STANDARD.encode(content),
            signatures: vec![],
        };
        let envelope_json = serde_json::to_vec(&envelope).unwrap();
        let envelope_b64 = base64::engine::general_purpose::STANDARD.encode(&envelope_json);

        let result = FetchResult {
            content: content.to_string(),
            headers: PackHeaders {
                digest: Some(compute_digest(content)),
                signature: Some(envelope_b64),
                key_id: Some("sha256:test-key".to_string()),
                etag: None,
                cache_control: Some("max-age=3600".to_string()),
                content_length: None,
            },
            computed_digest: compute_digest(content),
        };

        // Put
        cache
            .put("test-pack", "1.0.0", &result, None)
            .await
            .unwrap();

        // Get
        let entry = cache.get("test-pack", "1.0.0").await.unwrap().unwrap();
        assert!(entry.signature.is_some());
        assert_eq!(
            entry.signature.unwrap().payload_type,
            "application/vnd.assay.pack+yaml;v=1"
        );
    }

    // ==================== Cache Robustness Tests (SPEC §7.2) ====================

    #[tokio::test]
    async fn test_pack_yaml_corrupt_evict_refetch() {
        // SPEC §7.2: Corrupted cache entry should be detected and evictable
        let (cache, _temp_dir) = create_test_cache();
        let content = "name: test\nversion: \"1.0.0\"";
        let result = create_fetch_result(content);

        // Put valid content
        cache
            .put("test-pack", "1.0.0", &result, None)
            .await
            .unwrap();

        // Verify it works
        let entry = cache.get("test-pack", "1.0.0").await.unwrap();
        assert!(entry.is_some());

        // Corrupt the cached file
        let pack_path = cache.pack_dir("test-pack", "1.0.0").join("pack.yaml");
        fs::write(&pack_path, "corrupted: content\nmalicious: true")
            .await
            .unwrap();

        // Get should fail with DigestMismatch
        let err = cache.get("test-pack", "1.0.0").await.unwrap_err();
        assert!(
            matches!(err, RegistryError::DigestMismatch { .. }),
            "Should detect corruption: {:?}",
            err
        );

        // Evict the corrupted entry
        cache.evict("test-pack", "1.0.0").await.unwrap();

        // Now cache should be empty
        let entry = cache.get("test-pack", "1.0.0").await.unwrap();
        assert!(entry.is_none(), "Cache should be empty after evict");
    }

    #[tokio::test]
    async fn test_signature_json_corrupt_handling() {
        // SPEC §7.2: Corrupted signature.json should not crash, signature becomes None
        let (cache, _temp_dir) = create_test_cache();
        let content = "name: test\nversion: \"1.0.0\"";

        // Create with valid signature
        let envelope = DsseEnvelope {
            payload_type: "application/vnd.assay.pack+yaml;v=1".to_string(),
            payload: base64::engine::general_purpose::STANDARD.encode(content),
            signatures: vec![],
        };
        let envelope_json = serde_json::to_vec(&envelope).unwrap();
        let envelope_b64 = base64::engine::general_purpose::STANDARD.encode(&envelope_json);

        let result = FetchResult {
            content: content.to_string(),
            headers: PackHeaders {
                digest: Some(compute_digest(content)),
                signature: Some(envelope_b64),
                key_id: Some("sha256:test-key".to_string()),
                etag: None,
                cache_control: Some("max-age=3600".to_string()),
                content_length: None,
            },
            computed_digest: compute_digest(content),
        };

        cache
            .put("test-pack", "1.0.0", &result, None)
            .await
            .unwrap();

        // Verify signature exists
        let entry = cache.get("test-pack", "1.0.0").await.unwrap().unwrap();
        assert!(entry.signature.is_some());

        // Corrupt the signature file
        let sig_path = cache.pack_dir("test-pack", "1.0.0").join("signature.json");
        fs::write(&sig_path, "this is not valid json{{{")
            .await
            .unwrap();

        // Get should still work, but signature is None (graceful degradation)
        let entry = cache.get("test-pack", "1.0.0").await.unwrap().unwrap();
        assert!(
            entry.signature.is_none(),
            "Corrupt signature should be None, not error"
        );
        // Content should still be valid
        assert_eq!(entry.content, content);
    }

    #[tokio::test]
    async fn test_metadata_json_corrupt_handling() {
        // SPEC §7.2: Corrupted metadata.json should return cache miss
        let (cache, _temp_dir) = create_test_cache();
        let content = "name: test\nversion: \"1.0.0\"";
        let result = create_fetch_result(content);

        cache
            .put("test-pack", "1.0.0", &result, None)
            .await
            .unwrap();

        // Corrupt the metadata file
        let meta_path = cache.pack_dir("test-pack", "1.0.0").join("metadata.json");
        fs::write(&meta_path, "invalid json content").await.unwrap();

        // Get should fail with cache error (not crash)
        let result = cache.get("test-pack", "1.0.0").await;
        assert!(
            matches!(result, Err(RegistryError::Cache { .. })),
            "Should return cache error for corrupt metadata: {:?}",
            result
        );
    }

    #[tokio::test]
    async fn test_atomic_write_prevents_partial_cache() {
        // SPEC §7.2: Atomic writes prevent partial/corrupt cache entries
        let (cache, _temp_dir) = create_test_cache();
        let content = "name: test\nversion: \"1.0.0\"";
        let result = create_fetch_result(content);

        // After put, no .tmp files should exist
        cache
            .put("test-pack", "1.0.0", &result, None)
            .await
            .unwrap();

        let pack_dir = cache.pack_dir("test-pack", "1.0.0");

        // Check no temp files remain
        let mut entries = fs::read_dir(&pack_dir).await.unwrap();
        while let Some(entry) = entries.next_entry().await.unwrap() {
            let name = entry.file_name();
            let name_str = name.to_string_lossy();
            assert!(
                !name_str.ends_with(".tmp"),
                "Temp file should not remain: {}",
                name_str
            );
        }
    }

    #[tokio::test]
    async fn test_cache_registry_url_tracking() {
        // SPEC §7.1: Cache should track which registry pack came from
        let (cache, _temp_dir) = create_test_cache();
        let content = "name: test\nversion: \"1.0.0\"";
        let result = create_fetch_result(content);

        cache
            .put(
                "test-pack",
                "1.0.0",
                &result,
                Some("https://registry.example.com/v1"),
            )
            .await
            .unwrap();

        let meta = cache.get_metadata("test-pack", "1.0.0").await.unwrap();
        assert_eq!(
            meta.registry_url,
            Some("https://registry.example.com/v1".to_string())
        );
    }
}