socket-patch-core 3.2.0

Core library for socket-patch: manifest, hash, crawlers, patch engine, API client
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
//! On-disk verification: which manifest entries are actually applied?
//!
//! A patch is "applied" iff every file the manifest claims it modified
//! currently hashes to its `afterHash`. Anything else — missing file,
//! hash mismatch, even one file ahead of expectations — disqualifies
//! the patch from the VEX document. Callers feed the failures into a
//! stderr warning + `--json` envelope warning list; the spec we agreed
//! on is "never emit `affected` or `under_investigation` — just omit".
//!
//! The CLI is responsible for resolving PURL → on-disk package path
//! (it already does this for `apply` / `scan` via the ecosystem
//! dispatcher). We accept a pre-built map so this module stays free of
//! ecosystem-crawler dependencies.

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

use crate::manifest::schema::PatchManifest;
use crate::patch::apply::{verify_file_patch, VerifyStatus};

/// One entry per manifest PURL that did NOT pass verification. The
/// `reason` is a short snake_case tag the CLI can route on (matches
/// the `error_code` convention used by `json_envelope::PatchEvent`).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FailedPatch {
    pub purl: String,
    pub reason: String,
}

/// Result of partitioning the manifest into applied vs failed sets.
#[derive(Debug, Clone, Default)]
pub struct VerifyOutcome {
    /// PURLs whose on-disk files all hash to their `afterHash`.
    pub applied: Vec<String>,
    /// PURLs whose verification failed (with a routing tag).
    pub failed: Vec<FailedPatch>,
}

/// Walk the manifest and bucket each PURL into `applied` / `failed`.
///
/// `package_paths` is the CLI-supplied `purl -> on-disk package dir`
/// map (from `find_packages_for_purls`). A PURL absent from the map is
/// recorded as `package_not_found` and ends up in `failed`.
pub async fn applied_patches(
    manifest: &PatchManifest,
    package_paths: &HashMap<String, PathBuf>,
) -> VerifyOutcome {
    let mut out = VerifyOutcome::default();

    for (purl, record) in &manifest.patches {
        let pkg_path = match package_paths.get(purl) {
            Some(p) => p,
            None => {
                out.failed.push(FailedPatch {
                    purl: purl.clone(),
                    reason: "package_not_found".to_string(),
                });
                continue;
            }
        };

        match verify_patch_record(pkg_path, record).await {
            Ok(()) => out.applied.push(purl.clone()),
            Err(reason) => out.failed.push(FailedPatch {
                purl: purl.clone(),
                reason,
            }),
        }
    }

    out
}

/// Returns `Ok(())` if every file in `record.files` is `AlreadyPatched`.
/// Otherwise returns a short routing tag describing the first failure.
///
/// A record with **no files** is *not* treated as applied. Verification
/// is the strict counterpart to `--no-verify`: it must produce positive
/// on-disk evidence before a patch is attested as `not_affected`. A
/// zero-file record offers nothing to hash, so — per the module's
/// "omit when unconfirmed" contract — it is reported as `no_files` and
/// dropped from the VEX document rather than vacuously attested.
async fn verify_patch_record(
    pkg_path: &Path,
    record: &crate::manifest::schema::PatchRecord,
) -> Result<(), String> {
    if record.files.is_empty() {
        return Err("no_files".to_string());
    }

    for (file_name, file_info) in &record.files {
        let result = verify_file_patch(pkg_path, file_name, file_info).await;
        match result.status {
            VerifyStatus::AlreadyPatched => continue,
            VerifyStatus::Ready => return Err("not_applied".to_string()),
            VerifyStatus::HashMismatch => return Err("hash_mismatch".to_string()),
            VerifyStatus::NotFound => return Err("file_not_found".to_string()),
        }
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::hash::git_sha256::compute_git_sha256_from_bytes;
    use crate::manifest::schema::{PatchFileInfo, PatchRecord};
    use std::collections::HashMap;

    fn record_with_one_file(after_hash: &str) -> PatchRecord {
        let mut files = HashMap::new();
        files.insert(
            "index.js".to_string(),
            PatchFileInfo {
                before_hash: "aaaa".to_string(),
                after_hash: after_hash.to_string(),
            },
        );
        PatchRecord {
            uuid: "u".to_string(),
            exported_at: "2024-01-01T00:00:00Z".to_string(),
            files,
            vulnerabilities: HashMap::new(),
            description: String::new(),
            license: String::new(),
            tier: String::new(),
        }
    }

    #[tokio::test]
    async fn applied_when_all_files_match_after_hash() {
        let pkg_dir = tempfile::tempdir().unwrap();
        let patched = b"patched-content";
        let hash = compute_git_sha256_from_bytes(patched);
        tokio::fs::write(pkg_dir.path().join("index.js"), patched)
            .await
            .unwrap();

        let mut manifest = PatchManifest::new();
        manifest
            .patches
            .insert("pkg:npm/x@1.0.0".to_string(), record_with_one_file(&hash));

        let mut paths = HashMap::new();
        paths.insert("pkg:npm/x@1.0.0".to_string(), pkg_dir.path().to_path_buf());

        let out = applied_patches(&manifest, &paths).await;
        assert_eq!(out.applied, vec!["pkg:npm/x@1.0.0".to_string()]);
        assert!(out.failed.is_empty());
    }

    #[tokio::test]
    async fn missing_path_falls_into_failed() {
        let mut manifest = PatchManifest::new();
        manifest.patches.insert(
            "pkg:npm/x@1.0.0".to_string(),
            record_with_one_file("deadbeef"),
        );

        let paths: HashMap<String, PathBuf> = HashMap::new();
        let out = applied_patches(&manifest, &paths).await;
        assert!(out.applied.is_empty());
        assert_eq!(out.failed.len(), 1);
        assert_eq!(out.failed[0].reason, "package_not_found");
    }

    #[tokio::test]
    async fn hash_mismatch_falls_into_failed() {
        let pkg_dir = tempfile::tempdir().unwrap();
        tokio::fs::write(pkg_dir.path().join("index.js"), b"not the right content")
            .await
            .unwrap();

        let mut manifest = PatchManifest::new();
        manifest.patches.insert(
            "pkg:npm/x@1.0.0".to_string(),
            record_with_one_file(
                "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
            ),
        );

        let mut paths = HashMap::new();
        paths.insert("pkg:npm/x@1.0.0".to_string(), pkg_dir.path().to_path_buf());

        let out = applied_patches(&manifest, &paths).await;
        assert!(out.applied.is_empty());
        assert_eq!(out.failed[0].reason, "hash_mismatch");
    }

    #[tokio::test]
    async fn missing_file_falls_into_failed() {
        let pkg_dir = tempfile::tempdir().unwrap();
        let mut manifest = PatchManifest::new();
        manifest.patches.insert(
            "pkg:npm/x@1.0.0".to_string(),
            record_with_one_file(
                "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
            ),
        );

        let mut paths = HashMap::new();
        paths.insert("pkg:npm/x@1.0.0".to_string(), pkg_dir.path().to_path_buf());

        let out = applied_patches(&manifest, &paths).await;
        assert_eq!(out.failed[0].reason, "file_not_found");
    }

    #[tokio::test]
    async fn partial_apply_still_fails() {
        // Two files in the patch: only one is patched on disk → patch
        // is not "fully" applied → reported as failed (not_applied for
        // the second file).
        let pkg_dir = tempfile::tempdir().unwrap();
        let patched_a = b"AAA";
        let hash_a = compute_git_sha256_from_bytes(patched_a);
        let original_b = b"original-b";
        let before_b = compute_git_sha256_from_bytes(original_b);

        tokio::fs::write(pkg_dir.path().join("a.js"), patched_a)
            .await
            .unwrap();
        tokio::fs::write(pkg_dir.path().join("b.js"), original_b)
            .await
            .unwrap();

        let mut files = HashMap::new();
        files.insert(
            "a.js".to_string(),
            PatchFileInfo {
                before_hash: "aaaa".to_string(),
                after_hash: hash_a,
            },
        );
        files.insert(
            "b.js".to_string(),
            PatchFileInfo {
                before_hash: before_b,
                after_hash: "deadbeef".to_string(),
            },
        );

        let mut manifest = PatchManifest::new();
        manifest.patches.insert(
            "pkg:npm/x@1.0.0".to_string(),
            PatchRecord {
                uuid: "u".to_string(),
                exported_at: String::new(),
                files,
                vulnerabilities: HashMap::new(),
                description: String::new(),
                license: String::new(),
                tier: String::new(),
            },
        );

        let mut paths = HashMap::new();
        paths.insert("pkg:npm/x@1.0.0".to_string(), pkg_dir.path().to_path_buf());

        let out = applied_patches(&manifest, &paths).await;
        assert!(out.applied.is_empty());
        assert_eq!(out.failed[0].reason, "not_applied");
    }

    // ── Edge-case + degenerate-input coverage ─────────────────────

    /// `VerifyOutcome::default()` is the empty outcome — defaulting
    /// is used by the CLI's `--no-verify` path.
    #[test]
    fn outcome_default_is_empty() {
        let o = VerifyOutcome::default();
        assert!(o.applied.is_empty());
        assert!(o.failed.is_empty());
    }

    /// `FailedPatch` equality + clone for downstream consumers
    /// (the CLI emits these in `--json` warnings).
    #[test]
    fn failed_patch_value_semantics() {
        let a = FailedPatch {
            purl: "pkg:npm/x@1".to_string(),
            reason: "hash_mismatch".to_string(),
        };
        let b = a.clone();
        assert_eq!(a, b);
    }

    /// Empty manifest → empty outcome. No iteration, no panic.
    #[tokio::test]
    async fn empty_manifest_returns_empty_outcome() {
        let manifest = PatchManifest::new();
        let paths: HashMap<String, PathBuf> = HashMap::new();
        let out = applied_patches(&manifest, &paths).await;
        assert!(out.applied.is_empty());
        assert!(out.failed.is_empty());
    }

    /// A patch with `files = {}` must NOT be treated as applied.
    /// Verification requires positive on-disk evidence before a patch
    /// is attested as `not_affected`; a zero-file record offers nothing
    /// to hash, so it is omitted with reason `no_files`. Attesting it as
    /// "fixed" would be an evidence-free claim, contradicting the
    /// module's "omit when unconfirmed" contract. (The `--no-verify`
    /// path, which trusts the manifest wholesale, is unaffected — it
    /// never calls this function.)
    #[tokio::test]
    async fn patch_record_with_zero_files_is_not_applied() {
        let pkg_dir = tempfile::tempdir().unwrap();
        let mut manifest = PatchManifest::new();
        manifest.patches.insert(
            "pkg:npm/empty@1.0.0".to_string(),
            PatchRecord {
                uuid: "u".to_string(),
                exported_at: String::new(),
                files: HashMap::new(),
                vulnerabilities: HashMap::new(),
                description: String::new(),
                license: String::new(),
                tier: String::new(),
            },
        );

        let mut paths = HashMap::new();
        paths.insert(
            "pkg:npm/empty@1.0.0".to_string(),
            pkg_dir.path().to_path_buf(),
        );

        let out = applied_patches(&manifest, &paths).await;
        assert!(
            out.applied.is_empty(),
            "a zero-file patch must not be attested as applied"
        );
        assert_eq!(out.failed.len(), 1);
        assert_eq!(out.failed[0].purl, "pkg:npm/empty@1.0.0");
        assert_eq!(out.failed[0].reason, "no_files");
    }

    /// Extra `package_paths` entries that aren't in the manifest
    /// are ignored — we iterate manifest entries, not the map.
    #[tokio::test]
    async fn extra_package_paths_are_ignored() {
        let pkg_dir = tempfile::tempdir().unwrap();
        let patched = b"patched";
        let hash = compute_git_sha256_from_bytes(patched);
        tokio::fs::write(pkg_dir.path().join("index.js"), patched)
            .await
            .unwrap();

        let mut manifest = PatchManifest::new();
        manifest
            .patches
            .insert("pkg:npm/x@1.0.0".to_string(), record_with_one_file(&hash));

        let mut paths = HashMap::new();
        paths.insert("pkg:npm/x@1.0.0".to_string(), pkg_dir.path().to_path_buf());
        // Stray entry not in the manifest.
        paths.insert(
            "pkg:npm/stray@9.9.9".to_string(),
            pkg_dir.path().to_path_buf(),
        );

        let out = applied_patches(&manifest, &paths).await;
        assert_eq!(out.applied.len(), 1);
        assert_eq!(out.applied[0], "pkg:npm/x@1.0.0");
        assert!(out.failed.is_empty());
    }

    /// Multi-file patch where the FIRST file fails — the iteration
    /// halts after the first failure (we don't keep going to
    /// surface every reason). Lock this in so future refactors
    /// don't accidentally start running the second file's check.
    ///
    /// The patch lists two files. `a.js` has the wrong content (no
    /// match for before_hash or after_hash); `b.js` is fine. Order
    /// is non-deterministic across HashMap iteration, so we only
    /// assert "one failure reason", not which one.
    #[tokio::test]
    async fn multi_file_first_failure_short_circuits() {
        let pkg_dir = tempfile::tempdir().unwrap();
        // a.js: corrupt
        tokio::fs::write(pkg_dir.path().join("a.js"), b"garbage")
            .await
            .unwrap();
        // b.js: at the right after_hash so it would pass.
        let patched_b = b"patched-b";
        let hash_b = compute_git_sha256_from_bytes(patched_b);
        tokio::fs::write(pkg_dir.path().join("b.js"), patched_b)
            .await
            .unwrap();

        let mut files = HashMap::new();
        files.insert(
            "a.js".to_string(),
            PatchFileInfo {
                before_hash: "aaaa".to_string(),
                after_hash: "deadbeef".to_string(),
            },
        );
        files.insert(
            "b.js".to_string(),
            PatchFileInfo {
                before_hash: "cccc".to_string(),
                after_hash: hash_b,
            },
        );

        let mut manifest = PatchManifest::new();
        manifest.patches.insert(
            "pkg:npm/x@1.0.0".to_string(),
            PatchRecord {
                uuid: "u".to_string(),
                exported_at: String::new(),
                files,
                vulnerabilities: HashMap::new(),
                description: String::new(),
                license: String::new(),
                tier: String::new(),
            },
        );

        let mut paths = HashMap::new();
        paths.insert("pkg:npm/x@1.0.0".to_string(), pkg_dir.path().to_path_buf());

        let out = applied_patches(&manifest, &paths).await;
        assert!(out.applied.is_empty());
        assert_eq!(out.failed.len(), 1, "first failure must short-circuit");
        // Reason depends on iteration order, but it MUST be one of
        // the two failure tags (not the success path).
        let reason = &out.failed[0].reason;
        assert!(
            matches!(reason.as_str(), "hash_mismatch" | "not_applied"),
            "unexpected reason: {reason}"
        );
    }

    /// A new-file patch (empty `beforeHash`) whose file exists on disk
    /// at the `afterHash` content counts as applied. `verify_file_patch`
    /// returns `AlreadyPatched` before its is-new-file `Ready` branch, so
    /// the created-and-applied case is not misreported as `not_applied`.
    #[tokio::test]
    async fn new_file_present_at_after_hash_is_applied() {
        let pkg_dir = tempfile::tempdir().unwrap();
        let created = b"freshly-created-file";
        let hash = compute_git_sha256_from_bytes(created);
        tokio::fs::write(pkg_dir.path().join("new.js"), created)
            .await
            .unwrap();

        let mut files = HashMap::new();
        files.insert(
            "new.js".to_string(),
            PatchFileInfo {
                before_hash: String::new(), // new file
                after_hash: hash,
            },
        );

        let mut manifest = PatchManifest::new();
        manifest.patches.insert(
            "pkg:npm/x@1.0.0".to_string(),
            PatchRecord {
                uuid: "u".to_string(),
                exported_at: String::new(),
                files,
                vulnerabilities: HashMap::new(),
                description: String::new(),
                license: String::new(),
                tier: String::new(),
            },
        );

        let mut paths = HashMap::new();
        paths.insert("pkg:npm/x@1.0.0".to_string(), pkg_dir.path().to_path_buf());

        let out = applied_patches(&manifest, &paths).await;
        assert_eq!(out.applied, vec!["pkg:npm/x@1.0.0".to_string()]);
        assert!(out.failed.is_empty());
    }

    /// A new-file patch whose file is absent on disk is `not_applied`
    /// (the creation hasn't happened yet) — NOT `file_not_found`. The
    /// empty `beforeHash` routes through the `Ready` branch.
    #[tokio::test]
    async fn new_file_absent_is_not_applied() {
        let pkg_dir = tempfile::tempdir().unwrap();
        let mut files = HashMap::new();
        files.insert(
            "new.js".to_string(),
            PatchFileInfo {
                before_hash: String::new(), // new file, not yet created
                after_hash:
                    "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"
                        .to_string(),
            },
        );

        let mut manifest = PatchManifest::new();
        manifest.patches.insert(
            "pkg:npm/x@1.0.0".to_string(),
            PatchRecord {
                uuid: "u".to_string(),
                exported_at: String::new(),
                files,
                vulnerabilities: HashMap::new(),
                description: String::new(),
                license: String::new(),
                tier: String::new(),
            },
        );

        let mut paths = HashMap::new();
        paths.insert("pkg:npm/x@1.0.0".to_string(), pkg_dir.path().to_path_buf());

        let out = applied_patches(&manifest, &paths).await;
        assert!(out.applied.is_empty());
        assert_eq!(out.failed[0].reason, "not_applied");
    }

    /// A no-op patch where `beforeHash == afterHash` and the file is at
    /// that content is applied — `verify_file_patch` checks `afterHash`
    /// first, so it never mistakes the file for the un-patched `Ready`
    /// state.
    #[tokio::test]
    async fn noop_patch_before_equals_after_is_applied() {
        let pkg_dir = tempfile::tempdir().unwrap();
        let content = b"unchanged-content";
        let hash = compute_git_sha256_from_bytes(content);
        tokio::fs::write(pkg_dir.path().join("index.js"), content)
            .await
            .unwrap();

        let mut files = HashMap::new();
        files.insert(
            "index.js".to_string(),
            PatchFileInfo {
                before_hash: hash.clone(),
                after_hash: hash,
            },
        );

        let mut manifest = PatchManifest::new();
        manifest.patches.insert(
            "pkg:npm/x@1.0.0".to_string(),
            PatchRecord {
                uuid: "u".to_string(),
                exported_at: String::new(),
                files,
                vulnerabilities: HashMap::new(),
                description: String::new(),
                license: String::new(),
                tier: String::new(),
            },
        );

        let mut paths = HashMap::new();
        paths.insert("pkg:npm/x@1.0.0".to_string(), pkg_dir.path().to_path_buf());

        let out = applied_patches(&manifest, &paths).await;
        assert_eq!(out.applied, vec!["pkg:npm/x@1.0.0".to_string()]);
        assert!(out.failed.is_empty());
    }

    /// A multi-file patch where EVERY file is at its `afterHash` is
    /// applied — the loop must run to completion (no early `Ok`) and
    /// bucket the PURL into `applied`.
    #[tokio::test]
    async fn multi_file_all_patched_is_applied() {
        let pkg_dir = tempfile::tempdir().unwrap();
        let a = b"patched-a";
        let b = b"patched-b";
        let hash_a = compute_git_sha256_from_bytes(a);
        let hash_b = compute_git_sha256_from_bytes(b);
        tokio::fs::write(pkg_dir.path().join("a.js"), a).await.unwrap();
        tokio::fs::write(pkg_dir.path().join("b.js"), b).await.unwrap();

        let mut files = HashMap::new();
        files.insert(
            "a.js".to_string(),
            PatchFileInfo { before_hash: "aaaa".to_string(), after_hash: hash_a },
        );
        files.insert(
            "b.js".to_string(),
            PatchFileInfo { before_hash: "bbbb".to_string(), after_hash: hash_b },
        );

        let mut manifest = PatchManifest::new();
        manifest.patches.insert(
            "pkg:npm/x@1.0.0".to_string(),
            PatchRecord {
                uuid: "u".to_string(),
                exported_at: String::new(),
                files,
                vulnerabilities: HashMap::new(),
                description: String::new(),
                license: String::new(),
                tier: String::new(),
            },
        );

        let mut paths = HashMap::new();
        paths.insert("pkg:npm/x@1.0.0".to_string(), pkg_dir.path().to_path_buf());

        let out = applied_patches(&manifest, &paths).await;
        assert_eq!(out.applied, vec!["pkg:npm/x@1.0.0".to_string()]);
        assert!(out.failed.is_empty());
    }

    /// A manifest with both an applied PURL and a failing PURL splits
    /// cleanly across the two buckets. Order is HashMap-nondeterministic,
    /// so we assert membership, not index.
    #[tokio::test]
    async fn mixed_manifest_splits_into_both_buckets() {
        let ok_dir = tempfile::tempdir().unwrap();
        let patched = b"patched-content";
        let hash = compute_git_sha256_from_bytes(patched);
        tokio::fs::write(ok_dir.path().join("index.js"), patched)
            .await
            .unwrap();

        // Failing package: file present but at the wrong content.
        let bad_dir = tempfile::tempdir().unwrap();
        tokio::fs::write(bad_dir.path().join("index.js"), b"wrong")
            .await
            .unwrap();

        let mut manifest = PatchManifest::new();
        manifest
            .patches
            .insert("pkg:npm/ok@1.0.0".to_string(), record_with_one_file(&hash));
        manifest.patches.insert(
            "pkg:npm/bad@1.0.0".to_string(),
            record_with_one_file(
                "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
            ),
        );

        let mut paths = HashMap::new();
        paths.insert("pkg:npm/ok@1.0.0".to_string(), ok_dir.path().to_path_buf());
        paths.insert("pkg:npm/bad@1.0.0".to_string(), bad_dir.path().to_path_buf());

        let out = applied_patches(&manifest, &paths).await;
        assert_eq!(out.applied, vec!["pkg:npm/ok@1.0.0".to_string()]);
        assert_eq!(out.failed.len(), 1);
        assert_eq!(out.failed[0].purl, "pkg:npm/bad@1.0.0");
        assert_eq!(out.failed[0].reason, "hash_mismatch");
    }

    /// At most ONE `FailedPatch` is recorded per PURL even when several
    /// files would fail — `verify_patch_record` returns on the first
    /// failure. Two distinct failing files, single failure recorded.
    #[tokio::test]
    async fn at_most_one_failure_recorded_per_purl() {
        let pkg_dir = tempfile::tempdir().unwrap();
        // a.js: hash mismatch (neither before nor after).
        tokio::fs::write(pkg_dir.path().join("a.js"), b"garbage")
            .await
            .unwrap();
        // b.js: absent → would be file_not_found.

        let mut files = HashMap::new();
        files.insert(
            "a.js".to_string(),
            PatchFileInfo { before_hash: "aaaa".to_string(), after_hash: "deadbeef".to_string() },
        );
        files.insert(
            "b.js".to_string(),
            PatchFileInfo { before_hash: "bbbb".to_string(), after_hash: "deadbeef".to_string() },
        );

        let mut manifest = PatchManifest::new();
        manifest.patches.insert(
            "pkg:npm/x@1.0.0".to_string(),
            PatchRecord {
                uuid: "u".to_string(),
                exported_at: String::new(),
                files,
                vulnerabilities: HashMap::new(),
                description: String::new(),
                license: String::new(),
                tier: String::new(),
            },
        );

        let mut paths = HashMap::new();
        paths.insert("pkg:npm/x@1.0.0".to_string(), pkg_dir.path().to_path_buf());

        let out = applied_patches(&manifest, &paths).await;
        assert!(out.applied.is_empty());
        assert_eq!(out.failed.len(), 1, "one FailedPatch per PURL, not per file");
        assert!(
            matches!(out.failed[0].reason.as_str(), "hash_mismatch" | "file_not_found"),
            "unexpected reason: {}",
            out.failed[0].reason
        );
    }
}