ramparts 0.8.7

Security scanner for Model Context Protocol (MCP) servers and AI agent skills (Claude Code commands, agentskills.io bundles, Cursor / Codex / Windsurf / Gemini equivalents).
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
//! OSV.dev integration for stdio MCP servers' transitive dependencies.
//!
//! When ramparts scans a stdio MCP server launched via `npx` (npm) or
//! `uvx` (PyPI), the scanner can extract the package name+version from
//! the command/args and ask OSV.dev whether that release has known
//! security advisories. Findings are surfaced through the existing YARA
//! result type (`rule_name = "VulnerableDependency"`) so they propagate
//! into terminal, JSON, markdown, and SARIF outputs without any new
//! plumbing.
//!
//! This is an opportunistic, fail-soft check: an OSV query that times
//! out, errors, or returns a non-200 status logs a warning and is
//! treated as "no known vulns" rather than failing the whole scan.
//! Downstream consumers should treat the absence of OSV findings as
//! "we didn't see any" rather than "definitely clean".
//!
//! Supports two ecosystems today (covering the two most common stdio
//! MCP server launch patterns); adding new ones is a matter of
//! extending `parse_package_spec_from_command` and the ecosystem
//! mapping in `query_osv`.

use crate::types::{YaraRuleMetadata, YaraScanResult};
use reqwest::Client;
use serde::Deserialize;
use std::time::Duration;
use tracing::{debug, warn};

const OSV_QUERY_URL: &str = "https://api.osv.dev/v1/query";
const OSV_QUERY_TIMEOUT_SECS: u64 = 5;

/// A parsed (ecosystem, name, version) triple ready to send to OSV.
#[derive(Debug, Clone)]
pub struct PackageSpec {
    pub ecosystem: &'static str,
    pub name: String,
    pub version: Option<String>,
}

/// Parse a stdio MCP launch command into a `PackageSpec` suitable for an
/// OSV query. Returns `None` when the command isn't a recognized package
/// runner or the args don't yield a clean package reference. We only
/// recognize the conservative subset we can parse without false positives:
///
/// - `npx [-y|--yes] [pkg@ver] [...rest]` → npm:pkg@ver
/// - `uvx [--from pkg[==ver]] [pkg[==ver]] [...rest]` → PyPI:pkg@ver
///
/// Anything more exotic (custom scripts, shell pipelines, npx-with-multiple-
/// packages) returns `None` so we don't emit false positives.
pub fn parse_package_spec_from_command(command: &str, args: &[String]) -> Option<PackageSpec> {
    match command {
        "npx" => parse_npx(args),
        "uvx" => parse_uvx(args),
        _ => None,
    }
}

fn parse_npx(args: &[String]) -> Option<PackageSpec> {
    // First positional arg that doesn't start with `-` is the package.
    let pkg_arg = args.iter().find(|a| !a.starts_with('-'))?;
    let (name, version) = split_npm_spec(pkg_arg)?;
    Some(PackageSpec {
        ecosystem: "npm",
        name,
        version,
    })
}

/// Split an npm package reference into (name, version). Handles scoped
/// packages (`@scope/pkg`) where the leading `@` must NOT be parsed as a
/// version separator.
fn split_npm_spec(raw: &str) -> Option<(String, Option<String>)> {
    let raw = raw.trim();
    if raw.is_empty() {
        return None;
    }
    // Scoped package: @scope/pkg[@ver]
    if let Some(stripped) = raw.strip_prefix('@') {
        let (scope, rest) = stripped.split_once('/')?;
        if let Some((pkg, ver)) = rest.split_once('@') {
            return Some((format!("@{scope}/{pkg}"), version_or_none(ver)));
        }
        return Some((format!("@{scope}/{rest}"), None));
    }
    if let Some((name, ver)) = raw.split_once('@') {
        return Some((name.to_string(), version_or_none(ver)));
    }
    Some((raw.to_string(), None))
}

fn parse_uvx(args: &[String]) -> Option<PackageSpec> {
    // `uvx --from pkg[==ver] cmd ...` or `uvx pkg[==ver] [...]`. Take the
    // first non-flag token after a known flag, or the first non-flag token
    // overall.
    let mut iter = args.iter().peekable();
    while let Some(arg) = iter.peek() {
        if *arg == "--from" {
            iter.next();
            if let Some(spec) = iter.next() {
                let (name, version) = split_pypi_spec(spec)?;
                return Some(PackageSpec {
                    ecosystem: "PyPI",
                    name,
                    version,
                });
            }
            return None;
        }
        if arg.starts_with('-') {
            iter.next();
            continue;
        }
        break;
    }
    let pkg = iter.next()?;
    let (name, version) = split_pypi_spec(pkg)?;
    Some(PackageSpec {
        ecosystem: "PyPI",
        name,
        version,
    })
}

fn split_pypi_spec(raw: &str) -> Option<(String, Option<String>)> {
    // PyPI version specifiers we care about: `pkg==1.2.3`, `pkg`. We leave
    // looser specs (`pkg>=1.0`) alone because OSV needs an exact version
    // to give a useful answer.
    let raw = raw.trim();
    if raw.is_empty() {
        return None;
    }
    if let Some((name, ver)) = raw.split_once("==") {
        return Some((name.to_string(), version_or_none(ver)));
    }
    Some((raw.to_string(), None))
}

/// Parse a dependency manifest bundled with a skill into OSV-queryable
/// specs (OWASP AST02: skill-bundle dependencies are the delivery
/// mechanism for staged-loader / dependency-confusion attacks; scanning
/// only the launch command misses them entirely).
///
/// Conservative on purpose: only exactly-pinned versions are returned.
/// - `requirements.txt`: `name==version` lines (extras and environment
///   markers stripped); ranges (`>=`) are skipped.
/// - `package.json`: `dependencies` + `devDependencies` entries whose
///   version is exact (no `^ ~ > < * x ||` range syntax).
pub fn parse_manifest_specs(filename: &str, content: &str) -> Vec<PackageSpec> {
    match filename {
        "requirements.txt" => content
            .lines()
            .filter_map(|line| {
                let line = line.split('#').next().unwrap_or("").trim();
                let (name, rest) = line.split_once("==")?;
                // strip extras: `pkg[extra]==1.0` -> `pkg`
                let name = name.split('[').next().unwrap_or(name).trim();
                // strip env markers / trailing tokens: `1.0 ; python<3` -> `1.0`
                let version = rest
                    .split(';')
                    .next()
                    .unwrap_or("")
                    .split_whitespace()
                    .next()
                    .unwrap_or("");
                if name.is_empty() || version.is_empty() {
                    return None;
                }
                Some(PackageSpec {
                    ecosystem: "PyPI",
                    name: name.to_string(),
                    version: Some(version.to_string()),
                })
            })
            .collect(),
        "package.json" => {
            let Ok(json) = serde_json::from_str::<serde_json::Value>(content) else {
                return Vec::new();
            };
            let mut specs = Vec::new();
            for section in ["dependencies", "devDependencies"] {
                let Some(deps) = json.get(section).and_then(|d| d.as_object()) else {
                    continue;
                };
                for (name, ver) in deps {
                    let Some(ver) = ver.as_str() else { continue };
                    let exact = ver.starts_with(|c: char| c.is_ascii_digit())
                        && !ver.contains(['^', '~', '>', '<', '*', 'x', '|', ' ']);
                    if exact {
                        specs.push(PackageSpec {
                            ecosystem: "npm",
                            name: name.clone(),
                            version: Some(ver.to_string()),
                        });
                    }
                }
            }
            specs
        }
        _ => Vec::new(),
    }
}

fn version_or_none(s: &str) -> Option<String> {
    let s = s.trim();
    // npm/PyPI both treat "latest" as a tag rather than a real version. OSV
    // can't resolve tags, so drop these and return the package alone — OSV
    // will tell us "any known vulns at all", which is still useful info.
    if s.is_empty() || s.eq_ignore_ascii_case("latest") {
        None
    } else {
        Some(s.to_string())
    }
}

#[derive(Debug, Deserialize)]
struct OsvQueryResponse {
    #[serde(default)]
    vulns: Vec<OsvVulnerability>,
}

#[derive(Debug, Deserialize)]
struct OsvVulnerability {
    id: String,
    #[serde(default)]
    summary: Option<String>,
    #[serde(default)]
    details: Option<String>,
    #[serde(default)]
    severity: Vec<OsvSeverity>,
    #[serde(default)]
    aliases: Vec<String>,
    #[serde(default)]
    affected: Vec<OsvAffected>,
}

#[derive(Debug, Deserialize)]
struct OsvSeverity {
    #[serde(rename = "type")]
    severity_type: String,
    score: String,
}

/// Subset of OSV's `affected[]` we need to surface the fix version. OSV records
/// the release a vulnerability was fixed in inside `ranges[].events[].fixed`;
/// a record with no `fixed` event means no fix is available yet.
#[derive(Debug, Deserialize)]
struct OsvAffected {
    #[serde(default)]
    package: Option<OsvAffectedPackage>,
    #[serde(default)]
    ranges: Vec<OsvRange>,
}

#[derive(Debug, Deserialize)]
struct OsvAffectedPackage {
    #[serde(default)]
    name: String,
    #[serde(default)]
    ecosystem: String,
}

#[derive(Debug, Deserialize)]
struct OsvRange {
    #[serde(default)]
    events: Vec<OsvRangeEvent>,
}

#[derive(Debug, Deserialize)]
struct OsvRangeEvent {
    #[serde(default)]
    fixed: Option<String>,
}

/// Query OSV.dev for vulnerabilities affecting `spec`. Returns an empty
/// `Vec` on any failure (network error, non-200 status, parse error) — the
/// caller is responsible for treating "no findings" as "we didn't see any"
/// rather than "definitely clean".
///
/// Takes `Client` by reference (cheap clones internally via `Arc`) and
/// `PackageSpec` by value so callers can spawn the resulting future onto
/// a `tokio::task` without lifetime gymnastics.
pub async fn query_osv(client: Client, spec: PackageSpec) -> Vec<YaraScanResult> {
    debug!(
        "Querying OSV.dev for {}/{} ({:?})",
        spec.ecosystem, spec.name, spec.version
    );
    let request_body = build_osv_request(&spec);
    let response = match client
        .post(OSV_QUERY_URL)
        .timeout(Duration::from_secs(OSV_QUERY_TIMEOUT_SECS))
        .json(&request_body)
        .send()
        .await
    {
        Ok(r) => r,
        Err(e) => {
            warn!(
                "OSV query failed for {}/{}: {}",
                spec.ecosystem, spec.name, e
            );
            return Vec::new();
        }
    };
    if !response.status().is_success() {
        warn!(
            "OSV returned {} for {}/{}",
            response.status(),
            spec.ecosystem,
            spec.name
        );
        return Vec::new();
    }
    let body: OsvQueryResponse = match response.json().await {
        Ok(b) => b,
        Err(e) => {
            warn!(
                "Failed to parse OSV response for {}/{}: {}",
                spec.ecosystem, spec.name, e
            );
            return Vec::new();
        }
    };

    body.vulns
        .into_iter()
        .map(|v| osv_finding_to_yara_result(&spec, v))
        .collect()
}

fn build_osv_request(spec: &PackageSpec) -> serde_json::Value {
    let mut req = serde_json::json!({
        "package": {
            "name": spec.name,
            "ecosystem": spec.ecosystem,
        }
    });
    if let Some(version) = &spec.version {
        req["version"] = serde_json::Value::String(version.clone());
    }
    req
}

fn osv_finding_to_yara_result(spec: &PackageSpec, vuln: OsvVulnerability) -> YaraScanResult {
    let cvss = vuln
        .severity
        .iter()
        .find(|s| s.severity_type.starts_with("CVSS"))
        .map(|s| s.score.as_str())
        .unwrap_or("unknown");
    let severity = severity_label_for_cvss(cvss);
    let summary = vuln
        .summary
        .as_deref()
        .or(vuln.details.as_deref())
        .unwrap_or("No summary provided by OSV");
    let aliases = if vuln.aliases.is_empty() {
        String::new()
    } else {
        format!(" (aliases: {})", vuln.aliases.join(", "))
    };
    let context = format!(
        "{}/{} {}: {}{aliases}",
        spec.ecosystem,
        spec.name,
        spec.version.as_deref().unwrap_or("(any version)"),
        summary
    );
    let fixed_version = extract_fixed_version(spec, &vuln.affected);
    YaraScanResult {
        target_type: "dependency".to_string(),
        target_name: format!(
            "{}/{}@{}",
            spec.ecosystem,
            spec.name,
            spec.version.as_deref().unwrap_or("?")
        ),
        rule_name: "VulnerableDependency".to_string(),
        rule_file: Some("osv".to_string()),
        matched_text: Some(vuln.id.clone()),
        context,
        rule_metadata: Some(YaraRuleMetadata {
            name: Some("Vulnerable Dependency".to_string()),
            author: Some("OSV.dev".to_string()),
            date: None,
            version: None,
            description: Some(summary.to_string()),
            severity: Some(severity.to_string()),
            category: Some("supply-chain".to_string()),
            confidence: Some("HIGH".to_string()),
            tags: vec!["dependency".to_string(), "osv".to_string()],
        }),
        owasp_tags: crate::taxonomy::tags_for_yara_rule("VulnerableDependency"),
        installed_version: spec.version.clone(),
        fixed_version,
        phase: Some("pre-scan".to_string()),
        rules_executed: None,
        security_issues_detected: None,
        total_items_scanned: None,
        total_matches: None,
        status: Some("warning".to_string()),
    }
}

/// Compare two package names within an ecosystem. PyPI treats runs of `-`,
/// `_`, and `.` as equivalent and is case-insensitive (PEP 503), so
/// `pip_install_test` and `pip-install-test` are the same project; OSV returns
/// the canonical name while our spec carries the name as typed on the command
/// line. Other ecosystems compare case-insensitively as-is.
fn pkg_names_match(ecosystem: &str, a: &str, b: &str) -> bool {
    if ecosystem.eq_ignore_ascii_case("PyPI") {
        normalize_pypi_name(a) == normalize_pypi_name(b)
    } else {
        a.eq_ignore_ascii_case(b)
    }
}

/// PEP 503 name normalization: lowercase and collapse any run of `-`, `_`, or
/// `.` into a single `-`. PyPI names are ASCII, so ASCII lowercasing suffices.
fn normalize_pypi_name(name: &str) -> String {
    let mut out = String::with_capacity(name.len());
    let mut prev_sep = false;
    for c in name.chars() {
        if matches!(c, '-' | '_' | '.') {
            if !prev_sep {
                out.push('-');
            }
            prev_sep = true;
        } else {
            out.push(c.to_ascii_lowercase());
            prev_sep = false;
        }
    }
    out
}

/// Best-effort "the advisory says this is fixed in version X" signal, pulled
/// from OSV's `affected[].ranges[].events[].fixed`. OSV can list several
/// affected packages; we only read `fixed` from the package we queried (or an
/// entry that carries no package object, which OSV occasionally omits), never
/// from a different package in a multi-package advisory. This is a surfacing
/// hint for the UI, not a precise range resolution: when a package has several
/// ranges (e.g. parallel release branches with separate fixes) we surface the
/// first `fixed` we find rather than resolving which range covers the installed
/// version, since that needs per-ecosystem version comparison. The result is
/// always a valid fix, just not necessarily the lowest one for the installed
/// branch. Returns `None` when OSV lists no fixed version for our package.
fn extract_fixed_version(spec: &PackageSpec, affected: &[OsvAffected]) -> Option<String> {
    fn first_fixed(a: &OsvAffected) -> Option<String> {
        a.ranges
            .iter()
            .flat_map(|r| r.events.iter())
            .find_map(|e| e.fixed.clone())
    }
    let names_our_pkg = |a: &OsvAffected| {
        a.package.as_ref().is_some_and(|p| {
            p.ecosystem.eq_ignore_ascii_case(spec.ecosystem)
                && pkg_names_match(spec.ecosystem, &p.name, &spec.name)
        })
    };
    // If the advisory explicitly names our package, trust only those entries so
    // a sibling package's fix never leaks in. Only when nothing names our
    // package do we fall back to entries with no package object, which OSV
    // occasionally omits.
    if affected.iter().any(&names_our_pkg) {
        return affected
            .iter()
            .filter(|a| names_our_pkg(a))
            .find_map(first_fixed);
    }
    affected
        .iter()
        .filter(|a| a.package.is_none())
        .find_map(first_fixed)
}

/// Map a CVSS score string (e.g. "9.8", "CVSS:3.1/AV:N/...") to a coarse
/// severity label aligned with the rest of ramparts' severity vocabulary.
fn severity_label_for_cvss(score_text: &str) -> &'static str {
    // Some OSV records put the full CVSS vector in `score`; others put just
    // the numeric base score. Try to extract a leading float either way.
    let numeric = score_text
        .split('/')
        .find_map(|part| part.parse::<f32>().ok());
    match numeric {
        Some(n) if n >= 9.0 => "CRITICAL",
        Some(n) if n >= 7.0 => "HIGH",
        Some(n) if n >= 4.0 => "MEDIUM",
        Some(_) => "LOW",
        None => "MEDIUM",
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parses_plain_npx_pkg() {
        let spec = parse_package_spec_from_command(
            "npx",
            &[
                "-y".into(),
                "@modelcontextprotocol/server-everything".into(),
            ],
        )
        .expect("should parse");
        assert_eq!(spec.ecosystem, "npm");
        assert_eq!(spec.name, "@modelcontextprotocol/server-everything");
        assert_eq!(spec.version, None);
    }

    #[test]
    fn parses_npx_with_pinned_version() {
        let spec = parse_package_spec_from_command("npx", &["lodash@4.17.21".into()])
            .expect("should parse");
        assert_eq!(spec.name, "lodash");
        assert_eq!(spec.version, Some("4.17.21".into()));
    }

    #[test]
    fn parses_npx_scoped_with_version() {
        let spec = parse_package_spec_from_command("npx", &["@scope/pkg@1.2.3".into()])
            .expect("should parse");
        assert_eq!(spec.name, "@scope/pkg");
        assert_eq!(spec.version, Some("1.2.3".into()));
    }

    #[test]
    fn drops_latest_tag() {
        let spec = parse_package_spec_from_command("npx", &["lodash@latest".into()])
            .expect("should parse");
        assert_eq!(spec.version, None);
    }

    #[test]
    fn parses_uvx_with_from_flag() {
        let spec = parse_package_spec_from_command(
            "uvx",
            &["--from".into(), "ruff==0.8.4".into(), "ruff".into()],
        )
        .expect("should parse");
        assert_eq!(spec.ecosystem, "PyPI");
        assert_eq!(spec.name, "ruff");
        assert_eq!(spec.version, Some("0.8.4".into()));
    }

    #[test]
    fn parses_uvx_positional() {
        let spec = parse_package_spec_from_command("uvx", &["black".into()]).expect("should parse");
        assert_eq!(spec.ecosystem, "PyPI");
        assert_eq!(spec.name, "black");
    }

    #[test]
    fn rejects_unrecognized_runner() {
        assert!(parse_package_spec_from_command("python3", &["script.py".into()]).is_none());
        assert!(
            parse_package_spec_from_command("docker", &["run".into(), "image".into()]).is_none()
        );
    }

    #[test]
    fn cvss_severity_buckets() {
        assert_eq!(severity_label_for_cvss("9.8"), "CRITICAL");
        assert_eq!(severity_label_for_cvss("7.5"), "HIGH");
        assert_eq!(severity_label_for_cvss("5.0"), "MEDIUM");
        assert_eq!(severity_label_for_cvss("3.1"), "LOW");
        assert_eq!(
            severity_label_for_cvss("CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H"),
            "MEDIUM"
        );
        assert_eq!(severity_label_for_cvss(""), "MEDIUM");
    }

    #[test]
    fn extracts_fixed_version_from_affected() {
        let vuln: OsvVulnerability = serde_json::from_value(serde_json::json!({
            "id": "GHSA-test-fixed",
            "summary": "bad bug",
            "affected": [{
                "package": { "name": "lodash", "ecosystem": "npm" },
                "ranges": [{
                    "type": "SEMVER",
                    "events": [ { "introduced": "0" }, { "fixed": "4.17.21" } ]
                }]
            }]
        }))
        .expect("valid osv json");
        let spec = PackageSpec {
            ecosystem: "npm",
            name: "lodash".into(),
            version: Some("4.17.20".into()),
        };
        assert_eq!(
            extract_fixed_version(&spec, &vuln.affected),
            Some("4.17.21".to_string())
        );
    }

    #[test]
    fn no_fixed_version_when_absent() {
        // A record whose only event is `introduced` (no fix released yet).
        let vuln: OsvVulnerability = serde_json::from_value(serde_json::json!({
            "id": "GHSA-test-nofix",
            "affected": [{
                "package": { "name": "lodash", "ecosystem": "npm" },
                "ranges": [{ "type": "SEMVER", "events": [ { "introduced": "0" } ] }]
            }]
        }))
        .expect("valid osv json");
        let spec = PackageSpec {
            ecosystem: "npm",
            name: "lodash".into(),
            version: Some("4.17.20".into()),
        };
        assert_eq!(extract_fixed_version(&spec, &vuln.affected), None);
    }

    #[test]
    fn ignores_fix_from_a_different_package() {
        // Multi-package advisory: our package has no fix, a sibling does. We
        // must not borrow the sibling's fixed version.
        let vuln: OsvVulnerability = serde_json::from_value(serde_json::json!({
            "id": "GHSA-test-multi",
            "affected": [
                {
                    "package": { "name": "lodash", "ecosystem": "npm" },
                    "ranges": [{ "type": "SEMVER", "events": [ { "introduced": "0" } ] }]
                },
                {
                    "package": { "name": "other-pkg", "ecosystem": "npm" },
                    "ranges": [{
                        "type": "SEMVER",
                        "events": [ { "introduced": "0" }, { "fixed": "2.0.0" } ]
                    }]
                }
            ]
        }))
        .expect("valid osv json");
        let spec = PackageSpec {
            ecosystem: "npm",
            name: "lodash".into(),
            version: Some("4.17.20".into()),
        };
        assert_eq!(extract_fixed_version(&spec, &vuln.affected), None);
    }

    #[test]
    fn package_less_fallback_only_when_no_named_match() {
        let spec = PackageSpec {
            ecosystem: "npm",
            name: "lodash".into(),
            version: Some("4.17.20".into()),
        };

        // A named entry for our package (no fix) wins over a package-less entry
        // that does have one: a named-but-unfixed package reports no fix.
        let with_named: OsvVulnerability = serde_json::from_value(serde_json::json!({
            "id": "GHSA-test-mixed",
            "affected": [
                {
                    "package": { "name": "lodash", "ecosystem": "npm" },
                    "ranges": [{ "type": "SEMVER", "events": [ { "introduced": "0" } ] }]
                },
                { "ranges": [{ "type": "SEMVER", "events": [ { "fixed": "9.9.9" } ] }] }
            ]
        }))
        .expect("valid osv json");
        assert_eq!(extract_fixed_version(&spec, &with_named.affected), None);

        // With no named entry at all, the package-less fix is used.
        let unlabeled: OsvVulnerability = serde_json::from_value(serde_json::json!({
            "id": "GHSA-test-unlabeled",
            "affected": [
                { "ranges": [{ "type": "SEMVER", "events": [ { "fixed": "9.9.9" } ] }] }
            ]
        }))
        .expect("valid osv json");
        assert_eq!(
            extract_fixed_version(&spec, &unlabeled.affected),
            Some("9.9.9".to_string())
        );
    }

    #[test]
    fn matches_pypi_names_up_to_normalization() {
        // PyPI treats pip_install_test and pip-install-test as one project; the
        // OSV record's canonical name must still match our as-typed spec name.
        let vuln: OsvVulnerability = serde_json::from_value(serde_json::json!({
            "id": "GHSA-test-pypi",
            "affected": [{
                "package": { "name": "pip_install_test", "ecosystem": "PyPI" },
                "ranges": [{
                    "type": "ECOSYSTEM",
                    "events": [ { "introduced": "0" }, { "fixed": "1.2.0" } ]
                }]
            }]
        }))
        .expect("valid osv json");
        let spec = PackageSpec {
            ecosystem: "PyPI",
            name: "pip-install-test".into(),
            version: Some("1.1.0".into()),
        };
        assert_eq!(
            extract_fixed_version(&spec, &vuln.affected),
            Some("1.2.0".to_string())
        );
    }

    #[test]
    fn osv_finding_populates_installed_and_fixed() {
        let vuln: OsvVulnerability = serde_json::from_value(serde_json::json!({
            "id": "GHSA-test-full",
            "summary": "bug",
            "severity": [{ "type": "CVSS_V3", "score": "9.8" }],
            "affected": [{
                "package": { "name": "lodash", "ecosystem": "npm" },
                "ranges": [{
                    "type": "SEMVER",
                    "events": [ { "introduced": "0" }, { "fixed": "4.17.21" } ]
                }]
            }]
        }))
        .expect("valid osv json");
        let spec = PackageSpec {
            ecosystem: "npm",
            name: "lodash".into(),
            version: Some("4.17.20".into()),
        };
        let result = osv_finding_to_yara_result(&spec, vuln);
        assert_eq!(result.installed_version, Some("4.17.20".to_string()));
        assert_eq!(result.fixed_version, Some("4.17.21".to_string()));
        assert_eq!(result.target_type, "dependency");
    }

    #[test]
    fn parses_requirements_txt_pins_only() {
        let content = "requests==2.31.0\nflask>=2.0  # range, skipped\n\
                       pyyaml[safe]==6.0.1 ; python_version<'3.12'\n# comment\n";
        let specs = parse_manifest_specs("requirements.txt", content);
        assert_eq!(specs.len(), 2);
        assert_eq!(specs[0].name, "requests");
        assert_eq!(specs[0].version.as_deref(), Some("2.31.0"));
        assert_eq!(specs[1].name, "pyyaml");
        assert_eq!(specs[1].version.as_deref(), Some("6.0.1"));
    }

    #[test]
    fn parses_package_json_exact_versions_only() {
        let content = r#"{
            "dependencies": { "lodash": "4.17.20", "axios": "^1.0.0" },
            "devDependencies": { "left-pad": "1.3.0" }
        }"#;
        let specs = parse_manifest_specs("package.json", content);
        let names: Vec<&str> = specs.iter().map(|s| s.name.as_str()).collect();
        assert!(names.contains(&"lodash"));
        assert!(names.contains(&"left-pad"));
        assert!(!names.contains(&"axios"));
    }

    #[test]
    fn unknown_manifest_yields_nothing() {
        assert!(parse_manifest_specs("Gemfile", "gem 'rails'").is_empty());
    }
}