Multi-tier framework for evaluating AI agent skills and plugins with quality gates, security scanning, harness compatibility checks, semantic overlap detection, synthetic evaluation dataset generation, and live agent evaluation that measures how skills affect agent behavior. Ships reusable CI templates that bring every check to any repository.
Python agent-evaluationagent-pluginsagent-securityagent-skillsagentic-aibenchmarkci-templatesclaude-codecodexevaluateevaluationharnesspluginplugin-evaluationsecurity-scannerskill-evalskill-evaluationskill-evaluatorskill-gap-analysisskills
fix(tier1): report dependency advisories as structured findings (#421)
Narendran Raghavan38274ccf7fb5
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c79b32fc..f56aa6db 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -478,6 +478,37 @@ All notable changes to SkillEvaluator are documented in this file.`lift_overall`, and notes when they differ from the arm overall scores. Across-format test reconciles Overall and lift across every output of one run.+- The `dependency` check now reports each pip-audit and Safety advisory as a+ `DEPENDENCY` finding named by its advisory ID, at the requirements file and+ line, or the `pyproject.toml`, that pins the package. In 0.8.0 an advisory+ was only an error string such as `[CVE-HIGH] pyyaml==5.3: ...`: it failed+ the run, but JSON `findings`, the severity counts and SARIF results left it+ out, and a policy overlay could not change its severity. The finding+ metadata binds the scanned version to the declared exact pin, or marks a+ Safety advisory that matches no audited pin `unbound`, and records the+ advisory source, fixed versions, aliases, and a runtime, dev, test, docs, or+ build role from the requirements file name or optional group. Safety's+ severity now also comes from the CVSS object it prints with an API key, so+ a CVSS 9.8 advisory is `critical` and fails the run, and a score that is+ not a number from 0 to 10 is skipped; in 0.8.0 that object stopped the+ check with an `AttributeError`. A Safety advisory that+ pip-audit already reported under the same ID or CVE is not repeated. Safety+ JSON with a null `severity` or a top-level list, and a pip-audit advisory+ with a null `severity`, no longer stop the check with an `AttributeError`.+ A Safety `advisory` that is a number or null no longer stops it with a+ `TypeError`, and one that is an object no longer stops it with a+ `KeyError`. A pin on the line after a comment line that ends in a+ backslash is now audited; in 0.8.0 it was read as part of the comment, even+ though `pip install -r` installs it. A critical advisory does not stop a+ folder run before the remaining skills are audited. Line numbers in+ findings and warnings now count only line breaks an editor shows, so+ `--hash` continuation lines or a form feed before a pin no longer shift+ them. For every check, the CLI report now lists warnings that no finding+ repeats next to the findings, the Markdown report does so for an+ `INCOMPLETE` check without an error, escaping HTML in them as it does in+ errors, and a policy overlay that changes a finding's severity keeps those+ warnings, so the reason a scan is `INCOMPLETE` stays visible.+- Tier 3 dataset summaries honor explicit `should_trigger` routing labels beforelegacy `expected_skill` values. Report insights distinguish unavailable trialscores from scored attempts that miss the pass threshold. Dataset snapshotsdiff --git a/docs/tier1-validation.mdx b/docs/tier1-validation.mdxindex 04a5659a..9facc87d 100644--- a/docs/tier1-validation.mdx+++ b/docs/tier1-validation.mdx@@ -455,13 +455,76 @@ For `validate`, the default set is `schema`, `version`, `security`, `pii`, `licenonmatching declarations are reported as skipped. Version ranges, URL/pathdependencies, dynamic or Poetry metadata, malformed declarations, andmissing or failed scanner evidence leave the audit `INCOMPLETE`. Supply- pinned `requirements.txt` for unresolved declarations. `pip-audit` is the+ pinned `requirements.txt` for unresolved declarations. A requirements line+ that ends in a backslash continues on the next line unless it is a comment+ line, as in `pip install -r`, so a pin after a comment line that ends in a+ backslash is audited. `pip-audit` is theprimary scanner; Safety supplies secondary coverage for requirements fileswhen installed separately. The audit may use network-backed vulnerability databases.JSON and HTML export data retain `dependency_coverage` per target, includingrequested and actually audited pins. Unreadable declarations have unknowndeclaration counts and an empty audited inventory, not a completed scan.+ Each advisory is a `DEPENDENCY` finding whose check name is the advisory ID+ (a numeric Safety ID reads `SAFETY-<id>`). It points at the requirements+ file and the line that pins the package, or at `pyproject.toml`, so it+ appears in JSON `findings`, the severity counts, and SARIF results.+ `validate` on a folder of skills validates each skill as its own job, so+ each skill's report lists its advisories. When one dependency check covers+ several skills, as with `validate --type rules` or `--type workflows` on a+ folder, or `DependencySecurityValidator().validate()` on a folder in+ Python, a skill whose audit passes is summarized as one passed check, so+ its medium or low advisories are not listed; validate that skill on its own+ to see them. The finding metadata records:++ - `package_name` and `resolved_version`: the package and version the+ scanner checked.+ - `declared_constraint` and `declaration`: the exact pin as the target+ spells it, such as `PyYAML==5.3`, and where it is declared (`line 3`, or+ `optional group docs, declaration 2` in `pyproject.toml`). The raw line,+ with its markers and options, is never copied.+ - `resolution_status` and `dependency_relationship`: `resolved` and+ `direct` when the advisory matches an audited exact pin. Only exact pins+ are audited, with `--no-deps`, so the advisory applies to the version the+ target declares. Safety reads the raw requirements file, so it can+ report a version that no audited pin declares, such as a pin skipped+ because its marker does not match the scanner platform. That advisory is+ `unbound`: `declared_constraint`, `declaration`, and+ `dependency_relationship` are `null`, and the finding has no line.+ - `dependency_role`: `runtime`, `dev`, `test`, `docs`, or `build`, from a+ whole word of the requirements file name or the optional group name.+ Words are split at `-`, `_`, and `.`. `dev`, `devel`, `develop`,+ `development`, `devtools`, `lint`, and `linting` mean `dev`; `test`,+ `tests`, `testing`, `testutils`, `pytest`, and `unittest` mean `test`;+ `doc`, `docs`, and `documentation` mean `docs`; `build` means `build`.+ So `requirements-dev.txt` is `dev`, while `requirements-latest.txt` and+ `requirements-docker.txt` are `runtime`.+ - `advisory_id`, `advisory_source` (`pip-audit` or `Safety`),+ `affected_range` (Safety only; `null` for pip-audit), `fixed_versions`,+ and `aliases`.++ A `high` or `critical` advisory fails the run. A Python caller that builds+ `DependencySecurityValidator(fail_on_medium=True)` also fails on a `medium`+ pip-audit advisory; those findings record `fail_on_medium: true` in their+ metadata, so a policy overlay keeps that rule. Safety's severity is its+ level word or, when Safety runs with an API key, its CVSS object: the+ CVSS v3 level, then the v3 score, then the v2 score and level. A score+ that is not a number from 0 to 10 is skipped, and a Safety advisory with+ none of these is `medium`. When pip-audit already reported+ the same advisory ID or CVE for that package version, Safety's copy is+ left out, so one vulnerability is one finding. A critical advisory does not+ stop a folder run at that skill, as a critical finding of other checks+ does without `--continue-on-failure`: every skill is audited.++ A policy overlay can change one advisory with `DEPENDENCY.<advisory-id>`,+ such as `DEPENDENCY.PYSEC-2020-176: low`, or every advisory with+ `DEPENDENCY.*`. When one dependency check covers several skills, the+ overlay sees only the advisories that check lists, so it cannot raise a+ medium or low advisory of a skill whose audit passed. The warnings that say+ why an audit is `INCOMPLETE`, such as a line without an exact pin, still+ appear in the CLI and Markdown reports next to the advisories, and after a+ policy overlay changes an advisory's severity.+```bash title="Opt-in dependency audit"skillevaluator validate ./my-skill --checks dependency```diff --git a/src/skillevaluator/models/result.py b/src/skillevaluator/models/result.pyindex c2fb481b..d7c10539 100644--- a/src/skillevaluator/models/result.py+++ b/src/skillevaluator/models/result.py@@ -525,6 +525,8 @@ class ValidationResult:Call after mutating finding severities (e.g. LLM verification downgrade)so that result state is consistent with the actual finding objects.Independent gate failures remain errors regardless of those severities.+ HIGH and CRITICAL findings are errors, and so is a MEDIUM finding whose+ metadata sets ``fail_on_medium`` (a dependency audit with that option)."""self.errors.clear()self.warnings.clear()@@ -540,7 +542,8 @@ class ValidationResult:)self.summary.tally_severity(sev)- is_error = sev in (Severity.CRITICAL, Severity.HIGH)+ fail_on_medium = isinstance(finding.metadata, dict) and finding.metadata.get("fail_on_medium") is True+ is_error = sev.is_error(fail_on_medium=fail_on_medium)legacy_msg = finding.to_legacy_string()if is_error:self.errors.append(legacy_msg)@@ -550,6 +553,30 @@ class ValidationResult:self.warnings.append(legacy_msg)self.summary.warnings += 1+ def _finding_legacy_lines(self) -> set[str]:+ """Return the legacy error and warning lines that only repeat a structured finding."""+ represented = {finding.to_legacy_string() for finding in self.findings}+ for finding in self.findings:+ # merge_with_prefix puts skill labels before legacy messages but inside+ # structured finding paths. Recognize both forms, including nested merges.+ location = finding.location+ prefix = ""+ while location.startswith("[") and "] " in location:+ label, _, location = location.partition("] ")+ prefix += label + "] "+ represented.add(f"{prefix}{finding.tag} {finding.message} in {location}")+ return represented++ def independent_errors(self) -> list[str]:+ """Return errors no structured finding repeats, such as execution diagnostics."""+ represented = self._finding_legacy_lines()+ return [error for error in self.errors if error not in represented]++ def independent_warnings(self) -> list[str]:+ """Return warnings no structured finding repeats, such as why a scanner did not complete."""+ represented = self._finding_legacy_lines()+ return [warning for warning in self.warnings if warning not in represented]+def add_error(self, message: str) -> None:"""Add a legacy error string and mark validation as failed.diff --git a/src/skillevaluator/reporting/base.py b/src/skillevaluator/reporting/base.pyindex 007c8b4a..5b0dc8bb 100644--- a/src/skillevaluator/reporting/base.py+++ b/src/skillevaluator/reporting/base.py@@ -2505,29 +2505,13 @@ def passes_required_gate(result: ValidationResult) -> bool:return bool(result.passed or is_advisory_agent_eval_skip(result))-def _finding_legacy_lines(result: ValidationResult) -> set[str]:- """Return the legacy error and warning lines that only repeat a structured finding."""- represented = {finding.to_legacy_string() for finding in result.findings}- for finding in result.findings:- # merge_with_prefix puts skill labels before legacy messages but inside- # structured finding paths. Recognize both forms, including nested merges.- location = finding.location- prefix = ""- while location.startswith("[") and "] " in location:- label, _, location = location.partition("] ")- prefix += label + "] "- represented.add(f"{prefix}{finding.tag} {finding.message} in {location}")- return represented--def additional_errors(result: ValidationResult) -> list[str]:"""Return errors not already displayed through a structured finding.Findings also populate the legacy error list. Keep independent errors,including execution diagnostics, without repeating those mirrored entries."""- represented = _finding_legacy_lines(result)- return [error for error in result.errors if error not in represented]+ return result.independent_errors()def additional_warnings(result: ValidationResult) -> list[str]:@@ -2536,8 +2520,7 @@ def additional_warnings(result: ValidationResult) -> list[str]:Medium and low findings also populate the legacy warning list. Somescanners report why they did not run as a warning, so keep those lines."""- represented = _finding_legacy_lines(result)- return [warning for warning in result.warnings if warning not in represented]+ return result.independent_warnings()_SOURCE_VALIDATION_ERROR_STATUSES = frozenset({"missing", "error"})diff --git a/src/skillevaluator/reporting/cli.py b/src/skillevaluator/reporting/cli.pyindex 1678ce17..1a2d94cf 100644--- a/src/skillevaluator/reporting/cli.py+++ b/src/skillevaluator/reporting/cli.py@@ -39,6 +39,7 @@ from skillevaluator.reporting.base import (ReporterBase,_agent_eval_finite_number,additional_errors,+ additional_warnings,get_skip_reason,is_advisory_agent_eval_skip,is_cleanly_skipped,@@ -730,7 +731,15 @@ class CLIReporter(ReporterBase):console.print(f" [yellow][WARN][/yellow] {escape_markup(str(warning))}")return- if errors:+ # Warnings no finding repeats, such as why a scan is incomplete.+ warnings = additional_warnings(result)+ if warnings:+ if errors:+ console.print()+ console.print("[dim]Warnings:[/dim]")+ for warning in warnings:+ console.print(f" [yellow][WARN][/yellow] {escape_markup(str(warning))}")+ if errors or warnings:console.print()console.print("[dim]Issues:[/dim]")for i, finding in enumerate(result.findings, 1):diff --git a/src/skillevaluator/reporting/markdown.py b/src/skillevaluator/reporting/markdown.pyindex a628e427..353d9948 100644--- a/src/skillevaluator/reporting/markdown.py+++ b/src/skillevaluator/reporting/markdown.py@@ -24,6 +24,7 @@ from skillevaluator.evidence import evidence_ref_identityfrom skillevaluator.reporting.base import (ReporterBase,additional_errors,+ additional_warnings,assess_publication,get_skip_reason,is_advisory_agent_eval_skip,@@ -663,9 +664,12 @@ class MarkdownReporter(ReporterBase):lines.append(f"**Incomplete scanners:** {', '.join(result.incomplete_scans)}")lines.append("")self._render_failure(result, lines)- if not result.findings and not result.errors:- for warning in result.warnings[: self.max_findings_shown]:- lines.append(f"- ⚠️ {warning}")+ # Warnings say why a scan did not complete. Show them unless an error+ # already does; the findings table never repeats them. They can name+ # target files, so escape them as the error list does.+ if not additional_errors(result):+ for warning in additional_warnings(result)[: self.max_findings_shown]:+ lines.append(f"- ⚠️ {html.escape(warning, quote=False)}")def _render_finding_detail(self, index: int, finding: Finding, lines: list[str]) -> None:"""Render detailed information for a single finding."""diff --git a/src/skillevaluator/tier1/commands.py b/src/skillevaluator/tier1/commands.pyindex be82a8d3..ff9a9e6a 100644--- a/src/skillevaluator/tier1/commands.py+++ b/src/skillevaluator/tier1/commands.py@@ -437,9 +437,9 @@ def run_validation(# (check name, builder, applies-to-this-content-type). Quality scoring and# script linting are skill-oriented and skipped for rules/workflows. Finding- # severities (incl. the LICENSE.* / CVE findings added below) are normalized- # centrally by the active policy in emit_reports, so they honor the- # selected validation profile.+ # severities (incl. the LICENSE.* and DEPENDENCY.* advisory findings added+ # below) are normalized centrally by the active policy in emit_reports, so+ # they honor the selected validation profile.steps = (("schema", _schema_results, True),("version", _version_results, skill_like),diff --git a/src/skillevaluator/tier3/harbor/templates/eval.py b/src/skillevaluator/tier3/harbor/templates/eval.pyindex f45d21e7..01a2fc42 100644--- a/src/skillevaluator/tier3/harbor/templates/eval.py+++ b/src/skillevaluator/tier3/harbor/templates/eval.py@@ -3399,10 +3399,11 @@ def _judge_goal_accuracy_ragas(question, ground_truth, agent_text, tool_summary)RagasAI(content=agent_text),]# Collections metrics take the messages and reference as keywords, not a SingleTurnSample.+ scorer_timeout = _remaining_judge_timeout(_resolve_judge_wall_time_budget())result = loop.run_until_complete(asyncio.wait_for(metric.ascore(user_input=user_input, reference=ground_truth),- timeout=_remaining_judge_timeout(_resolve_judge_wall_time_budget()),+ timeout=scorer_timeout,))finally:diff --git a/src/skillevaluator/validators/dependencies.py b/src/skillevaluator/validators/dependencies.pyindex ed9e8def..80ff0bbc 100644--- a/src/skillevaluator/validators/dependencies.py+++ b/src/skillevaluator/validators/dependencies.py@@ -5,27 +5,90 @@Scans Python dependencies for known CVE vulnerabilities by queryingthe PyPI Advisory Database, OSV, and PyUp.io Safety DB.++Each advisory is a structured ``DEPENDENCY`` finding named by its advisory ID+and located at the requirements line, or the ``pyproject.toml``, that pins the+vulnerable version. Its metadata binds the scanned (resolved) version to the+declared exact pin."""from __future__ import annotations+import contextlibimport jsonimport mathimport reimport tempfileimport tomllib+from collections.abc import Collection, Mapping+from dataclasses import dataclassfrom pathlib import Pathfrom packaging.requirements import InvalidRequirement, Requirementfrom packaging.utils import canonicalize_name-from packaging.version import Version+from packaging.version import InvalidVersion, Versionfrom skillevaluator.utils.secure_fs import SecurePathError, SecureRootfrom skillevaluator.utils.tool_runner import Severity, ToolResult, Tools, cvss_to_severity, parse_json_output-from skillevaluator.validators.base import ValidationResult, ValidatorBase+from skillevaluator.validators.base import Finding, ValidationResult, ValidatorBase, continue_on_failure_scope_PIP_AUDIT_COMPLETED_EXIT_CODES = frozenset({0, 1})_PIP_AUDIT_SEVERITIES = frozenset(severity.value for severity in Severity)+# Name tokens of a requirements file stem (``requirements-dev``) or an optional+# dependency group (``docs``) that mark a non-runtime dependency. Whole tokens+# only, so ``requirements-latest`` stays runtime and ``requirements-docker``+# is not docs.+_DEPENDENCY_ROLE_TOKENS = {+ "dev": "dev",+ "devel": "dev",+ "develop": "dev",+ "development": "dev",+ "devtools": "dev",+ "lint": "dev",+ "linting": "dev",+ "test": "test",+ "tests": "test",+ "testing": "test",+ "testutils": "test",+ "pytest": "test",+ "unittest": "test",+ "doc": "docs",+ "docs": "docs",+ "documentation": "docs",+ "build": "build",+}+# pip's COMMENT_RE as ``join_lines`` matches it: a line that starts with ``#``+# after optional whitespace is a comment, and pip never continues it.+_COMMENT_LINE = re.compile(r"\s*#")+# Safety prints severity as a level word, null without an API key, or a CVSS+# object such as {"cvssv3": {"base_severity": "CRITICAL", "base_score": 9.8}}.+_SAFETY_CVSS_KEYS = (("cvssv3", "cvss_v3"), ("cvssv2", "cvss_v2"))+++@dataclass(frozen=True)+class DependencyDeclaration:+ """Where the audited target declared one exact pin.++ Holds the declared package name and version as parsed, never the raw+ declaration text, which may carry markers, pip options or URL credentials.+ """++ name: str+ exact_version: str+ line_number: int | None+ declaration: str+ role: str++ @property+ def declared_constraint(self) -> str:+ """The exact pin as the target spelled it, e.g. ``PyYAML==5.3``."""+ return f"{self.name}=={self.exact_version}"+++# Declared pins keyed by (PEP 503 name, version), as pip-audit reports them.+_DeclaredPins = Mapping[tuple[str, Version], DependencyDeclaration]+# An advisory pip-audit reported: (PEP 503 name, version, advisory ID or alias).+_AdvisoryKey = tuple[str, Version | str, str]class DependencySecurityValidator(ValidatorBase):@@ -43,7 +106,10 @@ class DependencySecurityValidator(ValidatorBase):Args:use_safety: Run Safety check for additional coverage- fail_on_medium: Treat MEDIUM severity as errors+ fail_on_medium: Treat MEDIUM pip-audit advisories as errors. Safety+ advisories stay supplementary. Each pip-audit finding records+ ``fail_on_medium`` in its metadata, so a policy overlay that+ rebuilds the result keeps this gate."""self.use_safety = use_safetyself.fail_on_medium = fail_on_medium@@ -74,11 +140,14 @@ class DependencySecurityValidator(ValidatorBase):)return result- result = self._validate_folder_or_skill(- skill_path,- audit_target,- action_description="Auditing dependencies for",- )+ # A critical advisory is about one skill's pins, not a configuration+ # error that affects every skill, so a folder run never stops early on it.+ with continue_on_failure_scope(True):+ result = self._validate_folder_or_skill(+ skill_path,+ audit_target,+ action_description="Auditing dependencies for",+ )if coverages:result.metadata["dependency_coverage"] = coveragesreturn result@@ -109,7 +178,8 @@ class DependencySecurityValidator(ValidatorBase):def _find_dependency_files(self, skill_path: Path) -> dict:"""Locate dependency files in skill directory."""return {- "requirements": list(skill_path.glob("requirements*.txt")),+ # Sorted, so findings and SARIF results keep one order on every filesystem.+ "requirements": sorted(skill_path.glob("requirements*.txt")),"pyproject": skill_path / "pyproject.toml"if (skill_path / "pyproject.toml").exists() or (skill_path / "pyproject.toml").is_symlink()else None,@@ -120,11 +190,12 @@ class DependencySecurityValidator(ValidatorBase):result = ValidationResult()result.add_message(f"Auditing {req_file.name}")- audit_result = self._run_pip_audit_on_file(req_file)+ declared: dict[tuple[str, Version], DependencyDeclaration] = {}+ audit_result = self._run_pip_audit_on_file(req_file, declared=declared)result.merge(audit_result)if self.use_safety and not audit_result.is_incomplete and Tools.safety.is_available:- result.merge(self._run_safety(req_file))+ result.merge(self._run_safety(req_file, declared, reported=self._reported_advisories(audit_result)))return result@@ -173,6 +244,7 @@ class DependencySecurityValidator(ValidatorBase):else:groups.update({f"optional group {name}": values for name, values in optional.items()})pins: set[str] = set()+ declared: dict[tuple[str, Version], DependencyDeclaration] = {}declaration_count = 0for group, declarations in groups.items():if not isinstance(declarations, list):@@ -212,6 +284,21 @@ class DependencySecurityValidator(ValidatorBase):incomplete(f"{label}: an exact version pin is required; supply resolved requirements.txt")continuepins.add(f"{requirement.name}=={specifiers[0].version}")+ # Runtime dependencies are read first, so a pin an optional group+ # repeats keeps its runtime role.+ with contextlib.suppress(InvalidVersion):+ declared.setdefault(+ (canonicalize_name(requirement.name), Version(specifiers[0].version)),+ DependencyDeclaration(+ name=requirement.name,+ exact_version=specifiers[0].version,+ line_number=None,+ declaration=label,+ role=self._role_from_name(group.removeprefix("optional group "))+ if group.startswith("optional group ")+ else "runtime",+ ),+ )result.metadata["dependency_coverage"].update({"declarations": declaration_count, "requested_pins": sorted(pins)}@@ -306,7 +393,9 @@ class DependencySecurityValidator(ValidatorBase):incomplete("pip-audit returned incomplete or invalid target evidence")return resultbatch_result = ValidationResult()- self._process_pip_audit(tool_result.stdout, batch_result, pyproject.name, exit_code=exit_code)+ self._process_pip_audit(+ tool_result.stdout, batch_result, pyproject.name, exit_code=exit_code, declared=declared+ )result.merge(batch_result)if batch_result.is_incomplete:return result@@ -315,13 +404,22 @@ class DependencySecurityValidator(ValidatorBase):return result- def _run_pip_audit_on_file(self, req_file: Path) -> ValidationResult:+ def _run_pip_audit_on_file(+ self,+ req_file: Path,+ *,+ declared: dict[tuple[str, Version], DependencyDeclaration] | None = None,+ ) -> ValidationResult:"""Audit only explicit pins, without installing packages or running build code.Parse the untrusted file ourselves so pip cannot follow includes, URLs,local projects, index options, or environment substitutions. Unsupporteddeclarations make coverage incomplete; valid pins are still audited.+ Each accepted pin is recorded in ``declared`` (a new mapping when none+ is given), so advisories can name the line that declared the version."""+ if declared is None:+ declared = {}result = ValidationResult()result.add_message(f"{req_file.name}: auditing explicit pins only; dependencies are not resolved or installed")try:@@ -336,12 +434,13 @@ class DependencySecurityValidator(ValidatorBase):pins: set[str] = set()# Accept pip-compile's hash continuations, but pass only parsed package# names and versions to the scanner. Never forward arbitrary pip syntax.- declarations = re.sub(r"\\\r?\n", " ", text).splitlines()+ declarations = self._requirement_lines(text)if len(declarations) > 4096:result.add_warning(f"{req_file.name}: dependency declaration limit (4096) exceeded")result.mark_scan_incomplete("pip-audit")return result- for index, declaration in enumerate(declarations, 1):+ role = self._role_from_name(req_file.stem)+ for index, declaration in declarations:declaration = re.split(r"\s+#", declaration, maxsplit=1)[0].strip()if not declaration or declaration.startswith("#"):continue@@ -361,7 +460,18 @@ class DependencySecurityValidator(ValidatorBase):f"{req_file.name}: line {index} skipped (marker does not match scanner platform)")continue- pins.add(f"{canonicalize_name(requirement.name)}=={Version(specifiers[0].version)}")+ name, version = canonicalize_name(requirement.name), Version(specifiers[0].version)+ pins.add(f"{name}=={version}")+ declared.setdefault(+ (name, version),+ DependencyDeclaration(+ name=requirement.name,+ exact_version=specifiers[0].version,+ line_number=index,+ declaration=f"line {index}",+ role=role,+ ),+ )except (InvalidRequirement, KeyError, TypeError, ValueError, RecursionError):# Do not leak URL credentials or arbitrary source text in diagnostics.result.add_warning(@@ -385,7 +495,7 @@ class DependencySecurityValidator(ValidatorBase):["-r", str(sanitized), "--no-deps", "--disable-pip", "--format", "json", "--progress-spinner", "off"],timeout=180,)- self._process_pip_audit_result(tool_result, result, req_file.name)+ self._process_pip_audit_result(tool_result, result, req_file.name, declared=declared)inventory = self._validated_pip_audit_report(tool_result.stdout)try:returned = (@@ -406,11 +516,46 @@ class DependencySecurityValidator(ValidatorBase):return result+ @staticmethod+ def _requirement_lines(text: str) -> list[tuple[int, str]]:+ """Join backslash continuations into ``(first physical line, text)`` pairs.++ Each backslash before a newline becomes a space, and the text is split+ where ``str.splitlines`` splits it, as before. A comment line never+ continues, as in pip's ``join_lines``: ``# note \\`` ends the+ declaration, so the pin on the next line, which ``pip install -r``+ installs, is audited too. The number is the line an editor or SARIF+ viewer shows where the declaration starts: only ``\\n``, ``\\r\\n``+ and ``\\r`` end a line, so a form feed or ``\\u2028`` does not shift+ it, and a pip-compile pin followed by ``--hash`` lines keeps its own+ line.+ """+ lines: list[tuple[int, str]] = []+ pending = ""+ start = line = 1+ for physical in text.splitlines(keepends=True):+ if not pending:+ start = line+ if physical.endswith(("\n", "\r")):+ line += 1+ for continuation in ("\\\n", "\\\r\n"):+ if physical.endswith(continuation) and not _COMMENT_LINE.match(physical):+ pending += physical[: -len(continuation)] + " "+ break+ else:+ lines.append((start, pending + physical.splitlines()[0]))+ pending = ""+ if pending:+ lines.append((start, pending))+ return lines+def _process_pip_audit_result(self,tool_result: ToolResult,result: ValidationResult,source: str,+ *,+ declared: _DeclaredPins | None = None,) -> None:"""Accept a pip-audit run only when its process state can be trusted."""if tool_result.success is not True or tool_result.error_message:@@ -429,7 +574,7 @@ class DependencySecurityValidator(ValidatorBase):result.mark_scan_incomplete("pip-audit")return- self._process_pip_audit(tool_result.stdout, result, source, exit_code=exit_code)+ self._process_pip_audit(tool_result.stdout, result, source, exit_code=exit_code, declared=declared)def _process_pip_audit(self,@@ -438,6 +583,7 @@ class DependencySecurityValidator(ValidatorBase):source: str,*,exit_code: int,+ declared: _DeclaredPins | None = None,) -> None:"""Parse a completed pip-audit process and report trustworthy evidence."""report = self._validated_pip_audit_report(output)@@ -457,11 +603,14 @@ class DependencySecurityValidator(ValidatorBase):vuln_count += 1self._report_vulnerability(result,+ source=source,pkg_name=pkg_name,pkg_version=pkg_version,vuln_id=vuln["id"],fix_versions=vuln["fix_versions"],+ aliases=[alias for alias in vuln.get("aliases", []) if isinstance(alias, str)],severity=self._get_vuln_severity(vuln),+ declared=declared,)if skipped_count:@@ -573,7 +722,13 @@ class DependencySecurityValidator(ValidatorBase):description = vulnerability.get("description")return description is None or isinstance(description, str)- def _run_safety(self, req_file: Path) -> ValidationResult:+ def _run_safety(+ self,+ req_file: Path,+ declared: _DeclaredPins | None = None,+ *,+ reported: Collection[_AdvisoryKey] = (),+ ) -> ValidationResult:"""Run Safety check for supplementary coverage."""result = ValidationResult()@@ -584,35 +739,112 @@ class DependencySecurityValidator(ValidatorBase):# Safety errors are non-critical (pip-audit is primary)if tool_result.success:- self._process_safety(tool_result.stdout, result)+ self._process_safety(tool_result.stdout, result, req_file.name, declared=declared, reported=reported)return result- def _process_safety(self, output: str, result: ValidationResult) -> None:- """Parse Safety output and report additional findings."""- data = parse_json_output(output)- if not data:+ @classmethod+ def _reported_advisories(cls, result: ValidationResult) -> set[_AdvisoryKey]:+ """Return ``(package, version, ID or alias)`` keys of the pip-audit advisories in ``result``."""+ reported: set[_AdvisoryKey] = set()+ for finding in result.findings:+ metadata = finding.metadata+ if finding.category != "DEPENDENCY" or metadata.get("advisory_source") != "pip-audit":+ continue+ package = cls._advisory_package_key(metadata.get("package_name"), metadata.get("resolved_version"))+ if package is not None:+ aliases = metadata.get("aliases")+ identifiers = [metadata.get("advisory_id"), *(aliases if isinstance(aliases, list) else [])]+ reported.update((*package, item) for item in identifiers if isinstance(item, str))+ return reported++ @staticmethod+ def _advisory_package_key(name: object, version: object) -> tuple[str, Version | str] | None:+ """Return a PEP 503 name and parsed version, so both scanners' spellings compare equal."""+ if not isinstance(name, str) or not isinstance(version, str):+ return None+ try:+ return canonicalize_name(name), Version(version)+ except InvalidVersion:+ return canonicalize_name(name), version++ def _process_safety(+ self,+ output: str,+ result: ValidationResult,+ source: str = "requirements.txt",+ *,+ declared: _DeclaredPins | None = None,+ reported: Collection[_AdvisoryKey] = (),+ ) -> None:+ """Parse Safety output and report additional findings.++ ``reported`` holds the pip-audit advisories of the same file as+ ``(package, version, ID or alias)`` keys. A Safety advisory whose ID or+ CVE pip-audit already reported for that package version is not repeated.+ """+ try:+ data = parse_json_output(output)+ except (RecursionError, ValueError):return- # Handle varying Safety output formats- vulnerabilities = data.get("vulnerabilities", data if isinstance(data, list) else [])+ # Safety reports a {"vulnerabilities": [...]} object; older releases a bare list.+ vulnerabilities = data.get("vulnerabilities") if isinstance(data, dict) else data+ if not isinstance(vulnerabilities, list):+ returnfor vuln in vulnerabilities:if not isinstance(vuln, dict):continue- pkg_name = vuln.get("package_name", vuln.get("name", "unknown"))- severity_str = vuln.get("severity", "medium").lower()- severity = Severity(severity_str) if severity_str in Severity else Severity.MEDIUM-- vuln_id = vuln.get("vulnerability_id", vuln.get("id", "Unknown"))- advisory = vuln.get("advisory", "")[:100]+ pkg_name = self._text_field(vuln, "package_name", "name") or "unknown"+ severity = self._safety_severity(vuln.get("severity"))++ vuln_id = self._identifier_field(vuln, "vulnerability_id", "id") or "Unknown"+ # Safety database IDs are bare numbers; name the source in the check.+ advisory_id = f"SAFETY-{vuln_id}" if vuln_id.isdigit() else vuln_id+ advisory = (self._text_field(vuln, "advisory") or "")[:100]+ pkg_version = self._text_field(vuln, "analyzed_version")+ declaration = self._declared_pin(declared, pkg_name, pkg_version)+ if pkg_version is None and declaration is not None:+ pkg_version = declaration.exact_version+ fix_versions = self._text_list_field(+ vuln, "fixed_versions", "closest_versions_without_known_vulnerabilities"+ )+ aliases = self._text_list_field(vuln, "aliases")+ cve = self._text_field(vuln, "CVE", "cve")+ if cve and cve != advisory_id and cve not in aliases:+ aliases.append(cve)+ package = self._advisory_package_key(pkg_name, pkg_version)+ if package is not None and any((*package, item) in reported for item in (vuln_id, advisory_id, *aliases)):+ # pip-audit is the primary scanner; one vulnerability is one finding.+ continue+ affected_range = self._text_field(vuln, "affected_range", "specifier", "vulnerable_spec") or ", ".join(+ self._text_list_field(vuln, "vulnerable_spec")+ )- # Safety findings are supplementary - only critical as errors+ # Safety findings are supplementary: fail_on_medium does not apply.result.add_finding(- tag="SAFETY",- severity=severity,- message=f"{pkg_name}: {vuln_id} - {advisory}",+ Finding(+ category="DEPENDENCY",+ severity=severity,+ check_name=advisory_id,+ message=f"{pkg_name}: {advisory_id} - {advisory}" if advisory else f"{pkg_name}: {advisory_id}",+ file_path=source,+ line_number=declaration.line_number if declaration else None,+ suggestion=self._upgrade_suggestion(pkg_name, fix_versions),+ metadata=self._advisory_metadata(+ pkg_name=pkg_name,+ pkg_version=pkg_version,+ advisory_id=advisory_id,+ advisory_source="Safety",+ affected_range=affected_range or None,+ fix_versions=fix_versions,+ aliases=aliases,+ declaration=declaration,+ source=source,+ ),+ ),fail_on_medium=False,)@@ -620,27 +852,187 @@ class DependencySecurityValidator(ValidatorBase):self,result: ValidationResult,*,+ source: str,pkg_name: str,pkg_version: str,vuln_id: str,fix_versions: list[str],+ aliases: list[str],severity: Severity,+ declared: _DeclaredPins | None = None,) -> None:- """Report a single vulnerability finding."""+ """Report one pip-audit advisory as a ``DEPENDENCY`` finding at its declaration.++ ``declared`` is ``None`` only for a caller that audited pins it collected+ itself and builds its own findings from the tagged ``CVE`` message.+ """fix_hint = f" -> upgrade to {fix_versions[0]}" if fix_versions else ""message = f"{pkg_name}=={pkg_version}: {vuln_id}{fix_hint}"+ if declared is None:+ result.add_finding(tag="CVE", severity=severity, message=message, fail_on_medium=self.fail_on_medium)+ return+ declaration = self._declared_pin(declared, pkg_name, pkg_version)+ metadata = self._advisory_metadata(+ pkg_name=pkg_name,+ pkg_version=pkg_version,+ advisory_id=vuln_id,+ advisory_source="pip-audit",+ # pip-audit JSON names fixed versions, not the affected range.+ affected_range=None,+ fix_versions=fix_versions,+ aliases=aliases,+ declaration=declaration,+ source=source,+ )+ if self.fail_on_medium:+ # Recorded on the finding, so a policy overlay that rebuilds the+ # result (recalculate_from_findings) still fails a medium advisory.+ metadata["fail_on_medium"] = Trueresult.add_finding(- tag="CVE",- severity=severity,- message=message,+ Finding(+ category="DEPENDENCY",+ severity=severity,+ check_name=vuln_id,+ message=message,+ file_path=source,+ line_number=declaration.line_number if declaration else None,+ suggestion=self._upgrade_suggestion(pkg_name, fix_versions),+ metadata=metadata,+ ),fail_on_medium=self.fail_on_medium,)+ def _advisory_metadata(+ self,+ *,+ pkg_name: str,+ pkg_version: str | None,+ advisory_id: str,+ advisory_source: str,+ affected_range: str | None,+ fix_versions: list[str],+ aliases: list[str],+ declaration: DependencyDeclaration | None,+ source: str,+ ) -> dict:+ """Bind an advisory to the scanned version and the exact pin that declared it."""+ return {+ "package_name": pkg_name,+ "resolved_version": pkg_version,+ "declared_constraint": declaration.declared_constraint if declaration else None,+ "declaration": declaration.declaration if declaration else None,+ # Only exact pins are audited, so a bound advisory applies to the+ # version the target declares, not to one pip resolved at scan time.+ # Safety reads the raw file, so it can report a version no audited+ # pin declares, such as a pin skipped for its platform marker.+ "resolution_status": "resolved" if declaration else "unbound",+ "dependency_role": declaration.role if declaration else self._role_from_name(Path(source).stem),+ # pip-audit runs with --no-deps, so every audited package is a pin+ # the file declares directly.+ "dependency_relationship": "direct" if declaration else None,+ "advisory_id": advisory_id,+ "advisory_source": advisory_source,+ "affected_range": affected_range,+ "fixed_versions": list(fix_versions),+ "aliases": list(aliases),+ }++ @staticmethod+ def _declared_pin(declared: _DeclaredPins | None, name: str, version: str | None) -> DependencyDeclaration | None:+ """Return the declaration of a scanned package version, matching PEP 503 names."""+ if not declared:+ return None+ canonical = canonicalize_name(name)+ if version is None:+ # Without a scanned version, bind only a package pinned once.+ matches = [item for (key, _version), item in declared.items() if key == canonical]+ return matches[0] if len(matches) == 1 else None+ try:+ return declared.get((canonical, Version(version)))+ except InvalidVersion:+ return None++ @staticmethod+ def _upgrade_suggestion(pkg_name: str, fix_versions: list[str]) -> str:+ if fix_versions:+ listed = ", ".join(fix_versions[:3]) + (", ..." if len(fix_versions) > 3 else "")+ return f"Upgrade {pkg_name} to a fixed version ({listed}) and update the pin."+ return f"No fixed version of {pkg_name} is listed; review the advisory before shipping this dependency."++ @staticmethod+ def _role_from_name(name: str) -> str:+ """Classify a requirements file stem or optional group name as runtime, dev, test, docs or build."""+ for token in name.casefold().replace("_", "-").replace(".", "-").split("-"):+ if token in _DEPENDENCY_ROLE_TOKENS:+ return _DEPENDENCY_ROLE_TOKENS[token]+ return "runtime"++ @staticmethod+ def _safety_severity(value: object) -> Severity:+ """Return Safety's severity: a level word, else its CVSS object, else medium.++ Safety prints null without an API key and, with one, an object such as+ ``{"cvssv3": {"base_severity": "CRITICAL", "base_score": 9.8}}``. The+ CVSS v3 level wins, then the v3 score, then the v2 score and level.+ """+ if isinstance(value, str):+ level = value.strip().casefold()+ return Severity(level) if level in Severity else Severity.MEDIUM+ if not isinstance(value, dict):+ return Severity.MEDIUM+ v3, v2 = (+ next((value[key] for key in keys if isinstance(value.get(key), dict)), {}) for keys in _SAFETY_CVSS_KEYS+ )+ level = v3.get("base_severity")+ if isinstance(level, str) and level.strip().casefold() in Severity:+ return Severity(level.strip().casefold())+ for block in (v3, v2):+ score = block.get("base_score")+ # The range check alone rejects NaN, infinity and huge JSON integers;+ # math.isfinite would raise OverflowError on an integer past float range.+ if not isinstance(score, bool) and isinstance(score, int | float) and 0.0 <= score <= 10.0:+ return cvss_to_severity(score)+ level = v2.get("base_severity")+ if isinstance(level, str) and level.strip().casefold() in Severity:+ return Severity(level.strip().casefold())+ return Severity.MEDIUM++ @staticmethod+ def _identifier_field(data: dict, *keys: str) -> str | None:+ """Return the first non-empty string or integer ID among ``keys``, as text."""+ for key in keys:+ value = data.get(key)+ if isinstance(value, int) and not isinstance(value, bool):+ return str(value)+ if isinstance(value, str) and value.strip():+ return value.strip()+ return None++ @staticmethod+ def _text_field(data: dict, *keys: str) -> str | None:+ """Return the first non-empty string value among ``keys``."""+ for key in keys:+ value = data.get(key)+ if isinstance(value, str) and value.strip():+ return value.strip()+ return None++ @staticmethod+ def _text_list_field(data: dict, *keys: str) -> list[str]:+ """Return the first non-empty list of strings among ``keys``."""+ for key in keys:+ value = data.get(key)+ if isinstance(value, list):+ items = [item.strip() for item in value if isinstance(item, str) and item.strip()]+ if items:+ return items+ return []+def _get_vuln_severity(self, vuln: dict) -> Severity:"""Extract severity from vulnerability data."""- # Explicit severity field- if "severity" in vuln:+ # Explicit severity field (the report validator allows null)+ if isinstance(vuln.get("severity"), str):sev = vuln["severity"].strip().casefold()try:return Severity(sev)diff --git a/src/skillevaluator/validators/policy.py b/src/skillevaluator/validators/policy.pyindex 2d002509..4ff8d725 100644--- a/src/skillevaluator/validators/policy.py+++ b/src/skillevaluator/validators/policy.py@@ -344,17 +344,23 @@ def apply_policy(if policy is None:return resultsfor result in results:- changed = False+ independent_warnings: list[str] | None = Nonefor finding in result.findings:current = (finding.severity if isinstance(finding.severity, Severity) else Severity(str(finding.severity).lower()))new_severity = policy.severity_for(finding.category, finding.check_name, current)if new_severity != current:+ if independent_warnings is None:+ # Read before any change: a mirrored line names the old severity.+ independent_warnings = result.independent_warnings()finding.severity = new_severity- changed = True- if changed:+ if independent_warnings is not None:result.recalculate_from_findings()+ # Rebuilding from findings drops every warning. Keep those no+ # finding mirrors, such as why a scanner did not complete.+ for warning in independent_warnings:+ result.add_warning(warning)if isinstance(result.metadata, dict):result.metadata["policy"] = policy.to_dict()return resultsdiff --git a/tests/tier3/test_judge_failure_artifacts.py b/tests/tier3/test_judge_failure_artifacts.pyindex 978326ed..c69caa7b 100644--- a/tests/tier3/test_judge_failure_artifacts.py+++ b/tests/tier3/test_judge_failure_artifacts.py@@ -772,6 +772,47 @@ def test_ragas_cleanup_consumes_late_task_exceptions(assert all(_RAGAS_TEST_KEY not in record.getMessage() for record in caplog.records)+def test_ragas_expired_setup_budget_does_not_create_a_scoring_coroutine(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, recwarn: pytest.WarningsRecorder+) -> None:+ """An exhausted setup deadline must not leave an unawaited scorer behind."""+ verifier = _load_verifier(tmp_path)+ _use_ragas_eligible_judge(monkeypatch)+ elapsed = [0.0]+ monkeypatch.setattr(verifier, "signal", SimpleNamespace())+ monkeypatch.setattr(verifier, "time", SimpleNamespace(monotonic=lambda: elapsed[0]))+ monkeypatch.setattr(verifier, "_JUDGE_WALL_TIME_BUDGET_SEC", 1.0)+ created: list[bool] = []++ class Metric:+ def __init__(self, llm):+ self.llm = llm+ elapsed[0] = 2.0++ def ascore(self, **_kwargs):+ created.append(True)+ return asyncio.sleep(0)++ client = _install_fake_ragas(monkeypatch, Metric)+ monkeypatch.setattr(+ verifier.urllib.request,+ "urlopen",+ lambda *_args, **_kwargs: pytest.fail("an exhausted budget must prevent fallback HTTP requests"),+ )++ result = verifier._call_required_judge(+ "goal_accuracy", verifier.judge_goal_accuracy, "question", "ground truth", "agent response"+ )++ assert result["status"] == "error"+ assert result["score"] is None+ assert "time budget exhausted" in result["reason"]+ assert [instance.closed for instance in client.instances] == [1]+ assert created == []+ gc.collect()+ assert not any("was never awaited" in str(warning.message) for warning in recwarn)++@pytest.mark.parametrize("cutoff", ["scorer_timeout", "deadline_alarm"])def test_ragas_goal_judge_obeys_the_required_judge_time_budget(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, cutoff: str@@ -780,10 +821,13 @@ def test_ragas_goal_judge_obeys_the_required_judge_time_budget(verifier = _load_verifier(tmp_path)_use_ragas_eligible_judge(monkeypatch)cancelled: list[bool] = []+ elapsed = [0.0]if cutoff == "scorer_timeout":# Without an interval timer only the scorer's own wait_for bounds it.monkeypatch.setattr(verifier, "signal", SimpleNamespace())monkeypatch.setattr(verifier, "_JUDGE_WALL_TIME_BUDGET_SEC", 0.01)+ # Setup expiry is covered separately; keep this case in the active-scorer phase.+ monkeypatch.setattr(verifier, "time", SimpleNamespace(monotonic=lambda: elapsed[0]))scorer_sleep = 0.05else:if not hasattr(signal, "setitimer") or signal.getitimer(signal.ITIMER_REAL)[0] > 0:@@ -809,6 +853,8 @@ def test_ragas_goal_judge_obeys_the_required_judge_time_budget(self.llm = llmasync def ascore(self, **_kwargs):+ if cutoff == "scorer_timeout":+ elapsed[0] = 1.0try:await asyncio.sleep(scorer_sleep)except asyncio.CancelledError:diff --git a/tests/validators/test_dependency_advisory_findings.py b/tests/validators/test_dependency_advisory_findings.pynew file mode 100644index 00000000..a69764ba--- /dev/null+++ b/tests/validators/test_dependency_advisory_findings.py@@ -0,0 +1,848 @@+# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.+# SPDX-License-Identifier: Apache-2.0+"""Dependency advisories are structured findings bound to the pin that declared them."""++from __future__ import annotations++import io+import json+import re+import subprocess+import sys+from pathlib import Path++import pytest+from rich.console import Console++from skillevaluator.reporting import JSONReporter, MarkdownReporter+from skillevaluator.reporting.cli import CLIReporter+from skillevaluator.reporting.sarif_reporter import SARIFReporter+from skillevaluator.utils.tool_runner import Severity, ToolResult, Tools+from skillevaluator.validators.base import ValidationResult+from skillevaluator.validators.dependencies import DependencySecurityValidator+from skillevaluator.validators.policy import ValidationPolicy, apply_policy++PYYAML_ADVISORY = {"id": "PYSEC-2020-176", "fix_versions": ["5.4"], "aliases": ["CVE-2020-14343"]}+++def _skill(tmp_path: Path, files: dict[str, str], name: str = "demo-skill") -> Path:+ skill = tmp_path / name+ skill.mkdir()+ (skill / "SKILL.md").write_text(f"---\nname: {name}\ndescription: Demo\n---\n", encoding="utf-8")+ for filename, text in files.items():+ (skill / filename).write_text(text, encoding="utf-8")+ return skill+++def pip_audit(monkeypatch):+ """Answer each pip-audit run from the pins it receives, with advisories by package name."""+ advisories: dict[str, list[dict]] = {}+ calls: list[list[str]] = []+ monkeypatch.setattr(Tools.pip_audit, "_path", "/usr/bin/pip-audit")++ def run(args, **kwargs):+ assert "--no-deps" in args and "--disable-pip" in args+ pins = Path(args[args.index("-r") + 1]).read_text(encoding="utf-8").splitlines()+ calls.append(pins)+ dependencies = [+ {"name": name, "version": version, "vulns": advisories.get(name.lower(), [])}+ for name, version in (pin.split("==") for pin in pins)+ ]+ found = any(dependency["vulns"] for dependency in dependencies)+ return ToolResult(True, json.dumps({"dependencies": dependencies, "fixes": []}), "", 1 if found else 0)++ monkeypatch.setattr(Tools.pip_audit, "run", run)+ return advisories, calls+++def safety(monkeypatch):+ """Make Safety available; set ``state["report"]`` to the JSON it prints."""+ state: dict = {"report": {"vulnerabilities": []}}+ monkeypatch.setattr(Tools.safety, "_path", "/usr/bin/safety")++ def run(args, **_kwargs):+ assert args[:2] == ["check", "-r"]+ return ToolResult(True, json.dumps(state["report"]), "", 64)++ monkeypatch.setattr(Tools.safety, "run", run)+ return state+++def test_requirements_advisory_is_a_structured_finding_at_its_line(tmp_path, pip_audit):+ advisories, _ = pip_audit+ advisories["pyyaml"] = [PYYAML_ADVISORY]+ skill = _skill(tmp_path, {"requirements.txt": "# runtime\npyyaml==5.3\n"})++ result = DependencySecurityValidator(use_safety=False).validate(skill)++ assert not result.passed and not result.is_incomplete+ assert len(result.findings) == 1+ finding = result.findings[0]+ assert finding.category == "DEPENDENCY"+ assert finding.check_name == "PYSEC-2020-176"+ assert finding.severity == Severity.HIGH+ assert finding.message == "pyyaml==5.3: PYSEC-2020-176 -> upgrade to 5.4"+ assert (finding.file_path, finding.line_number) == ("requirements.txt", 2)+ assert finding.suggestion == "Upgrade pyyaml to a fixed version (5.4) and update the pin."+ assert finding.metadata == {+ "package_name": "pyyaml",+ "resolved_version": "5.3",+ "declared_constraint": "pyyaml==5.3",+ "declaration": "line 2",+ "resolution_status": "resolved",+ "dependency_role": "runtime",+ "dependency_relationship": "direct",+ "advisory_id": "PYSEC-2020-176",+ "advisory_source": "pip-audit",+ "affected_range": None,+ "fixed_versions": ["5.4"],+ "aliases": ["CVE-2020-14343"],+ }+ assert result.summary.high_count == 1+ assert result.errors == ["[DEPENDENCY-HIGH] pyyaml==5.3: PYSEC-2020-176 -> upgrade to 5.4 in requirements.txt:2"]+++def test_json_and_sarif_reports_carry_the_advisory_and_its_line(tmp_path, pip_audit):+ advisories, _ = pip_audit+ advisories["pyyaml"] = [PYYAML_ADVISORY]+ hashed = "pyyaml==5.3 \\\n --hash=sha256:" + "a" * 64 + "\n"+ skill = _skill(tmp_path, {"requirements.txt": "idna==3.10 \\\n --hash=sha256:" + "b" * 64 + "\n" + hashed})+ validator = DependencySecurityValidator(use_safety=False)+ result = validator.validate(skill)+ result.validator_name = validator.name++ row = json.loads(JSONReporter().render_all([result]))["results"][0]+ assert [(item["check_name"], item["line_number"]) for item in row["findings"]] == [("PYSEC-2020-176", 3)]+ assert row["summary"]["high_count"] == 1++ sarif = json.loads(SARIFReporter(include_timestamp=False, scan_root=skill).render_all([result]))+ (sarif_result,) = sarif["runs"][0]["results"]+ assert sarif_result["ruleId"] == "Dependency-Vulnerability-Audit/PYSEC-2020-176"+ assert sarif_result["level"] == "error"+ location = sarif_result["locations"][0]["physicalLocation"]+ assert location["artifactLocation"]["uri"].endswith("demo-skill/requirements.txt")+ assert location["region"]["startLine"] == 3+ assert sarif_result["properties"]["metadata"]["declared_constraint"] == "pyyaml==5.3"+++def test_package_names_use_pep_503_normalization(tmp_path, pip_audit):+ advisories, calls = pip_audit+ advisories["pillow-simd"] = [{"id": "PYSEC-1", "fix_versions": []}]+ skill = _skill(tmp_path, {"requirements.txt": "Pillow_SIMD==9.0\n"})++ result = DependencySecurityValidator(use_safety=False).validate(skill)++ assert calls == [["pillow-simd==9.0"]]+ metadata = result.findings[0].metadata+ assert metadata["package_name"] == "pillow-simd"+ assert metadata["declared_constraint"] == "Pillow_SIMD==9.0"+ assert metadata["dependency_relationship"] == "direct"+ assert result.findings[0].suggestion == (+ "No fixed version of pillow-simd is listed; review the advisory before shipping this dependency."+ )+++ ("filename", "role"),+ [+ ("requirements.txt", "runtime"),+ ("requirements-docs.txt", "docs"),+ ("requirements-dev.txt", "dev"),+ ("requirements_test.txt", "test"),+ ("requirements.tests.txt", "test"),+ ("requirements-build.txt", "build"),+ ("requirements-devel.txt", "dev"),+ ("requirements-devtools.txt", "dev"),+ ("requirements_unittest.txt", "test"),+ ("requirements-pytest.txt", "test"),+ ("requirements-lint.txt", "dev"),+ ("requirements-latest.txt", "runtime"),+ ("requirements-docker.txt", "runtime"),+ ],+)+def test_requirement_filename_sets_dependency_role(tmp_path, pip_audit, filename, role):+ advisories, _ = pip_audit+ advisories["pyyaml"] = [PYYAML_ADVISORY]+ skill = _skill(tmp_path, {filename: "pyyaml==5.3\n"})++ result = DependencySecurityValidator(use_safety=False).validate(skill)++ assert [(finding.file_path, finding.metadata["dependency_role"]) for finding in result.findings] == [+ (filename, role)+ ]+++ ("group", "role"),+ [+ ("devtools", "dev"),+ ("dev-tools", "dev"),+ ("unittest", "test"),+ ("testutils", "test"),+ ("pytest", "test"),+ ("Docs", "docs"),+ ("device", "runtime"),+ ("latest", "runtime"),+ ("docker", "runtime"),+ ],+)+def test_optional_group_name_sets_dependency_role(group, role):+ assert DependencySecurityValidator._role_from_name(group) == role+++def test_requirements_files_are_audited_in_sorted_order(tmp_path, pip_audit, monkeypatch):+ advisories, _ = pip_audit+ advisories["pyyaml"] = [PYYAML_ADVISORY]+ advisories["idna"] = [{"id": "PYSEC-2024-60", "fix_versions": ["3.7"]}]+ skill = _skill(tmp_path, {"requirements.txt": "pyyaml==5.3\n", "requirements-dev.txt": "idna==3.6\n"})+ # Directory order differs between filesystems; list the files in reverse.+ glob = Path.glob++ def reversed_glob(self, pattern, *args, **kwargs):+ return iter(sorted(glob(self, pattern, *args, **kwargs), reverse=True))++ monkeypatch.setattr(Path, "glob", reversed_glob)++ result = DependencySecurityValidator(use_safety=False).validate(skill)++ assert [(finding.file_path, finding.check_name) for finding in result.findings] == [+ ("requirements-dev.txt", "PYSEC-2024-60"),+ ("requirements.txt", "PYSEC-2020-176"),+ ]+++def test_pyproject_advisory_names_the_declared_pin_and_group(tmp_path, pip_audit):+ advisories, _ = pip_audit+ advisories["pyyaml"] = [PYYAML_ADVISORY]+ advisories["idna"] = [{"id": "GHSA-demo-0001", "fix_versions": ["3.7"], "severity": "medium"}]+ pyproject = (+ '[project]\nname = "demo"\ndependencies = ["idna==3.10"]\n'+ '[project.optional-dependencies]\ndocs = ["requests==2.32.5", "PyYAML==5.3"]\ntest = ["idna==3.10"]\n'+ )+ skill = _skill(tmp_path, {"pyproject.toml": pyproject})++ result = DependencySecurityValidator(use_safety=False, fail_on_medium=True).validate(skill)++ findings = {finding.check_name: finding for finding in result.findings}+ assert set(findings) == {"PYSEC-2020-176", "GHSA-demo-0001"}+ yaml = findings["PYSEC-2020-176"]+ assert (yaml.file_path, yaml.line_number) == ("pyproject.toml", None)+ assert yaml.metadata["declared_constraint"] == "PyYAML==5.3"+ assert yaml.metadata["declaration"] == "optional group docs, declaration 2"+ assert yaml.metadata["dependency_role"] == "docs"+ assert yaml.metadata["dependency_relationship"] == "direct"+ # A pin repeated in an optional group keeps the runtime declaration.+ idna = findings["GHSA-demo-0001"]+ assert idna.severity == Severity.MEDIUM+ assert idna.metadata["declaration"] == "dependencies, declaration 1"+ assert idna.metadata["dependency_role"] == "runtime"+ # fail_on_medium still turns a medium pip-audit advisory into an error.+ assert any("GHSA-demo-0001" in error for error in result.errors)+++def test_policy_overlay_can_change_one_advisory(tmp_path, pip_audit):+ advisories, _ = pip_audit+ advisories["pyyaml"] = [PYYAML_ADVISORY]+ skill = _skill(tmp_path, {"requirements.txt": "pyyaml==5.3\n"})+ result = DependencySecurityValidator(use_safety=False).validate(skill)+ assert not result.passed++ policy = ValidationPolicy(profile="reviewed", severity_overrides={"DEPENDENCY.PYSEC-2020-176": Severity.LOW})+ (overlaid,) = apply_policy([result], policy)++ assert overlaid.passed+ assert overlaid.findings[0].severity == Severity.LOW+++ ("override_key", "passed", "severity"),+ [("DEPENDENCY.*", True, Severity.LOW), ("CVE.*", False, Severity.HIGH)],+)+def test_tier1_reports_apply_the_dependency_wildcard_not_a_cve_key(+ tmp_path, pip_audit, safety, override_key, passed, severity+):+ """The Tier 1 dependency check's advisories take ``DEPENDENCY.*`` overrides in emit_reports; no ``CVE.*`` key."""+ from skillevaluator.tier1.commands import emit_reports, run_validation++ advisories, _ = pip_audit+ advisories["pyyaml"] = [PYYAML_ADVISORY]+ skill = _skill(tmp_path, {"requirements.txt": "pyyaml==5.3\n"})+ results = run_validation(skill, checks="dependency", content_type="skill", on_check=lambda _name: None)+ (dependency,) = [result for result in results if result.validator_name == DependencySecurityValidator().name]+ assert not dependency.passed++ policy = ValidationPolicy(profile="reviewed", severity_overrides={override_key: Severity.LOW})+ reports_passed = emit_reports(+ [dependency], report_formats=("json",), output_dir=tmp_path / "out", policy=policy, announce_paths=False+ )++ assert reports_passed is passed+ assert [(item.category, item.check_name, item.severity) for item in dependency.findings] == [+ ("DEPENDENCY", "PYSEC-2020-176", severity)+ ]+++def test_policy_overlay_keeps_fail_on_medium_for_advisories_it_does_not_name(tmp_path, pip_audit, safety):+ """Rebuilding a result after an override still fails on medium pip-audit advisories, not on Safety's."""+ advisories, _ = pip_audit+ advisories["pyyaml"] = [PYYAML_ADVISORY]+ advisories["idna"] = [{"id": "GHSA-med-1", "fix_versions": ["3.7"], "severity": "medium"}]+ safety["report"] = {+ "vulnerabilities": [+ {"package_name": "idna", "analyzed_version": "3.6", "vulnerability_id": "70001", "severity": "medium"}+ ]+ }+ skill = _skill(tmp_path, {"requirements.txt": "idna==3.6\npyyaml==5.3\n"})+ result = DependencySecurityValidator(fail_on_medium=True).validate(skill)+ medium = "[DEPENDENCY-MEDIUM] idna==3.6: GHSA-med-1 -> upgrade to 3.7 in requirements.txt:1"+ safety_medium = "[DEPENDENCY-MEDIUM] idna: SAFETY-70001 in requirements.txt:1"+ assert not result.passed+ assert medium in result.errors and safety_medium in result.warnings++ policy = ValidationPolicy(profile="reviewed", severity_overrides={"DEPENDENCY.PYSEC-2020-176": Severity.LOW})+ (overlaid,) = apply_policy([result], policy)++ assert not overlaid.passed+ assert overlaid.errors == [medium]+ assert overlaid.warnings == [+ "[DEPENDENCY-LOW] pyyaml==5.3: PYSEC-2020-176 -> upgrade to 5.4 in requirements.txt:2",+ safety_medium,+ ]+ by_id = {finding.check_name: finding.metadata for finding in overlaid.findings}+ assert by_id["GHSA-med-1"]["fail_on_medium"] is True+ assert "fail_on_medium" not in by_id["SAFETY-70001"]+++def test_policy_overlay_keeps_the_incomplete_reason(tmp_path, pip_audit):+ """Rebuilding a result from changed findings keeps warnings that no finding mirrors."""+ advisories, _ = pip_audit+ advisories["pyyaml"] = [PYYAML_ADVISORY]+ skill = _skill(tmp_path, {"requirements.txt": "pyyaml==5.3\nrequests>=2\n"})+ result = DependencySecurityValidator(use_safety=False).validate(skill)+ reason = (+ "requirements.txt: line 2 requires an exact package version; "+ "URLs, local paths, includes and pip options are not audited"+ )+ assert result.warnings == [reason]++ policy = ValidationPolicy(profile="reviewed", severity_overrides={"DEPENDENCY.PYSEC-2020-176": Severity.LOW})+ (overlaid,) = apply_policy([result], policy)++ assert overlaid.is_incomplete and not overlaid.passed+ assert overlaid.errors == []+ assert overlaid.warnings == [+ "[DEPENDENCY-LOW] pyyaml==5.3: PYSEC-2020-176 -> upgrade to 5.4 in requirements.txt:1",+ reason,+ ]+ assert (overlaid.summary.errors, overlaid.summary.warnings) == (0, 2)+ # apply_policy runs more than once in a CLI run; a second pass changes nothing.+ apply_policy([overlaid], policy)+ assert overlaid.warnings[1:] == [reason]+++_POLICY_WITHOUT_REPORTING = """+import json+import sys++from skillevaluator.models.result import Finding, Severity, ValidationResult+from skillevaluator.validators.policy import ValidationPolicy, apply_policy++result = ValidationResult()+result.add_finding(+ Finding("DEPENDENCY", Severity.HIGH, "PYSEC-2020-176", "pyyaml==5.3: PYSEC-2020-176", "requirements.txt", 1)+)+result.add_warning("requirements.txt: line 2 requires an exact package version")+policy = ValidationPolicy(profile="reviewed", severity_overrides={"DEPENDENCY.PYSEC-2020-176": Severity.LOW})+apply_policy([result], policy)+print(json.dumps({+ "reporting": sorted(name for name in sys.modules if name.startswith("skillevaluator.reporting")),+ "errors": result.errors,+ "warnings": result.warnings,+}))+"""+++def test_policy_overlay_keeps_warnings_without_loading_the_reporting_package():+ """A caller that only applies a policy does not import the report writers.++ A fresh interpreter is used, since this test session has already imported them.+ """+ completed = subprocess.run(+ [sys.executable, "-c", _POLICY_WITHOUT_REPORTING],+ capture_output=True,+ text=True,+ encoding="utf-8",+ check=False,+ )++ assert completed.returncode == 0, completed.stderr+ assert json.loads(completed.stdout) == {+ "reporting": [],+ "errors": [],+ "warnings": [+ "[DEPENDENCY-LOW] pyyaml==5.3: PYSEC-2020-176 in requirements.txt:1",+ "requirements.txt: line 2 requires an exact package version",+ ],+ }+++def test_safety_findings_use_the_common_applicability_metadata(tmp_path, pip_audit, safety):+ skill = _skill(tmp_path, {"requirements.txt": "Pillow_SIMD==9.0\n"})+ safety["report"] = {+ "vulnerabilities": [+ {+ "package_name": "pillow-simd",+ "analyzed_version": "9.0",+ "vulnerability_id": "51457",+ "CVE": "CVE-2026-0001",+ "severity": None,+ "advisory": None,+ "vulnerable_spec": ["<9.1"],+ "fixed_versions": ["9.1"],+ }+ ]+ }++ result = DependencySecurityValidator().validate(skill)++ assert result.passed and not result.is_incomplete+ (finding,) = result.findings+ assert finding.category == "DEPENDENCY"+ assert finding.check_name == "SAFETY-51457"+ assert finding.severity == Severity.MEDIUM+ assert finding.message == "pillow-simd: SAFETY-51457"+ assert (finding.file_path, finding.line_number) == ("requirements.txt", 1)+ assert finding.metadata == {+ "package_name": "pillow-simd",+ "resolved_version": "9.0",+ "declared_constraint": "Pillow_SIMD==9.0",+ "declaration": "line 1",+ "resolution_status": "resolved",+ "dependency_role": "runtime",+ "dependency_relationship": "direct",+ "advisory_id": "SAFETY-51457",+ "advisory_source": "Safety",+ "affected_range": "<9.1",+ "fixed_versions": ["9.1"],+ "aliases": ["CVE-2026-0001"],+ }+++ "report",+ [+ [{"package_name": "idna", "vulnerability_id": "1", "severity": "critical"}],+ {"vulnerabilities": [{"package_name": "idna", "vulnerability_id": "1", "severity": {"cvssv3": 9.8}}]},+ {"vulnerabilities": [{"package_name": "idna", "vulnerability_id": "1", "advisory": 7}]},+ {"vulnerabilities": [{"package_name": "idna", "vulnerability_id": "1", "advisory": {"text": "x"}}]},+ {"vulnerabilities": [{"package_name": None, "vulnerability_id": None, "severity": None}]},+ {"vulnerabilities": "invalid"},+ "not a report",+ ],+ ids=[+ "top-level-list",+ "cvss-not-an-object",+ "numeric-advisory",+ "object-advisory",+ "null-fields",+ "invalid-list",+ "not-a-report",+ ],+)+def test_malformed_safety_output_never_crashes(tmp_path, pip_audit, safety, report):+ safety["report"] = report+ skill = _skill(tmp_path, {"requirements.txt": "idna==3.10\n"})++ result = DependencySecurityValidator().validate(skill)++ assert not result.is_incomplete+ for finding in result.findings:+ assert finding.category == "DEPENDENCY"+ assert finding.metadata["advisory_source"] == "Safety"+ assert finding.severity in {Severity.CRITICAL, Severity.MEDIUM}+ # Only a high or critical advisory fails the run.+ assert result.passed is not any(finding.severity == Severity.CRITICAL for finding in result.findings)+++# The severity object Safety prints with an API key.+SAFETY_CVSS_OBJECT = {+ "source": "CVE-2024-3651",+ "cvssv2": None,+ "cvssv3": {+ "base_score": 9.8,+ "impact_score": 5.9,+ "base_severity": "CRITICAL",+ "vector_string": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H",+ },+}+++ ("severity", "expected"),+ [+ ("high", Severity.HIGH),+ (" Critical ", Severity.CRITICAL),+ (None, Severity.MEDIUM),+ ("unknown", Severity.MEDIUM),+ (SAFETY_CVSS_OBJECT, Severity.CRITICAL),+ ({"cvssv3": {"base_severity": "NONE", "base_score": 9.1}}, Severity.CRITICAL),+ ({"cvssv3": {"base_score": 7.5}}, Severity.HIGH),+ ({"cvss_v3": {"base_severity": "high"}}, Severity.HIGH),+ ({"cvssv3": {"base_score": "9.8"}, "cvssv2": {"base_score": 7.5}}, Severity.HIGH),+ ({"cvssv2": {"base_score": 9.3, "base_severity": "HIGH"}}, Severity.CRITICAL),+ ({"cvss_v2": {"base_severity": "HIGH"}}, Severity.HIGH),+ ({"source": "CVE-2024-3651"}, Severity.MEDIUM),+ ({"cvssv3": {"base_score": True}}, Severity.MEDIUM),+ ({"cvssv3": {"base_score": float("nan")}}, Severity.MEDIUM),+ ({"cvssv3": {"base_score": 11}}, Severity.MEDIUM),+ ({"cvssv3": {"base_score": 10**400}}, Severity.MEDIUM),+ ({"cvssv3": {"base_score": -(10**400)}, "cvssv2": {"base_score": int("9" * 400)}}, Severity.MEDIUM),+ ({"cvssv3": {"base_score": float("inf")}, "cvssv2": {"base_score": 7.5}}, Severity.HIGH),+ ],+ ids=[+ "word-high",+ "word-padded",+ "null",+ "unknown-word",+ "object-critical",+ "object-v3-score",+ "object-v3-score-only",+ "object-v3-key-spelling",+ "object-v2-score-after-bad-v3",+ "object-v2-score",+ "object-v2-level-only",+ "object-without-score",+ "object-bool-score",+ "object-nan-score",+ "object-out-of-range",+ "object-huge-int-score",+ "object-huge-int-v3-and-v2-scores",+ "object-inf-v3-score-then-v2",+ ],+)+def test_safety_severity_reads_level_words_and_cvss_objects(tmp_path, pip_audit, safety, severity, expected):+ """With an API key, Safety prints severity as a CVSS object; a critical one fails the run."""+ safety["report"] = {+ "vulnerabilities": [+ {+ "package_name": "idna",+ "analyzed_version": "3.6",+ "vulnerability_id": "51457",+ "advisory": "x",+ "severity": severity,+ }+ ]+ }+ skill = _skill(tmp_path, {"requirements.txt": "idna==3.6\n"})++ result = DependencySecurityValidator().validate(skill)++ assert not result.is_incomplete+ assert [(finding.check_name, finding.severity) for finding in result.findings] == [("SAFETY-51457", expected)]+ assert result.passed is (expected not in {Severity.CRITICAL, Severity.HIGH})+++ ("advisory", "check_name"),+ [+ ({"vulnerability_id": "51457"}, "SAFETY-51457"),+ ({"vulnerability_id": 51457}, "SAFETY-51457"),+ ({"vulnerability_id": None, "id": 7}, "SAFETY-7"),+ ({"vulnerability_id": "PYUP-2024-1"}, "PYUP-2024-1"),+ ({"vulnerability_id": True}, "Unknown"),+ ],+ ids=["text", "number", "id-number", "named", "bool"],+)+def test_safety_advisory_ids_name_the_finding(tmp_path, pip_audit, safety, advisory, check_name):+ safety["report"] = {+ "vulnerabilities": [{"package_name": "idna", "analyzed_version": "3.6", "severity": "high", **advisory}]+ }+ skill = _skill(tmp_path, {"requirements.txt": "idna==3.6\n"})++ result = DependencySecurityValidator().validate(skill)++ (finding,) = result.findings+ assert (finding.check_name, finding.message) == (check_name, f"idna: {check_name}")+ assert finding.metadata["advisory_id"] == check_name+++def test_folder_run_audits_every_skill_after_a_critical_advisory(tmp_path, pip_audit):+ """A critical advisory is not a configuration error, so a folder run still audits later skills."""+ advisories, calls = pip_audit+ advisories["aaa"] = [{"id": "GHSA-crit-0001", "fix_versions": ["2.0"], "severity": "critical"}]+ advisories["pyyaml"] = [PYYAML_ADVISORY]+ root = tmp_path / "skills"+ root.mkdir()+ _skill(root, {"requirements.txt": "aaa==1.0\n"}, name="a-skill")+ _skill(root, {"requirements.txt": "pyyaml==5.3\n"}, name="b-skill")+ _skill(root, {"requirements.txt": "numpy>=1\n"}, name="c-skill")++ result = DependencySecurityValidator(use_safety=False).validate(root)++ assert calls == [["aaa==1.0"], ["pyyaml==5.3"]]+ assert [(finding.file_path, finding.check_name, finding.severity) for finding in result.findings] == [+ ("[a-skill] requirements.txt", "GHSA-crit-0001", Severity.CRITICAL),+ ("[b-skill] requirements.txt", "PYSEC-2020-176", Severity.HIGH),+ ]+ assert result.incomplete_scans == ["pip-audit"]+ # Accepting the first skill's advisory leaves the second one failing the run.+ policy = ValidationPolicy(profile="reviewed", severity_overrides={"DEPENDENCY.GHSA-crit-0001": Severity.LOW})+ (overlaid,) = apply_policy([result], policy)+ assert not overlaid.passed+ assert overlaid.summary.high_count == 1+++def test_safety_skips_an_advisory_pip_audit_already_reported(tmp_path, pip_audit, safety):+ """One vulnerability is one finding: Safety's copy of a pip-audit advisory is dropped by ID or CVE."""+ advisories, _ = pip_audit+ advisories["pyyaml"] = [{"id": "PYSEC-2021-142", "fix_versions": ["5.4"], "aliases": ["CVE-2020-14343"]}]+ safety["report"] = {+ "vulnerabilities": [+ {+ "package_name": "PyYAML",+ "analyzed_version": "5.3.0",+ "vulnerability_id": "39611",+ "CVE": "CVE-2020-14343",+ },+ {"package_name": "pyyaml", "analyzed_version": "5.3", "vulnerability_id": "PYSEC-2021-142"},+ {"package_name": "pyyaml", "analyzed_version": "5.3", "vulnerability_id": "38100", "CVE": "CVE-2019-20477"},+ {"package_name": "pyyaml", "analyzed_version": "5.2", "vulnerability_id": "39612", "CVE": "CVE-2020-14343"},+ ]+ }+ skill = _skill(tmp_path, {"requirements.txt": "pyyaml==5.3\n"})++ result = DependencySecurityValidator().validate(skill)++ assert [(finding.check_name, finding.metadata["advisory_source"]) for finding in result.findings] == [+ ("PYSEC-2021-142", "pip-audit"),+ ("SAFETY-38100", "Safety"),+ ("SAFETY-39612", "Safety"),+ ]+++def test_safety_advisory_without_a_matching_pin_is_unbound(tmp_path, pip_audit, safety):+ """Safety reads the raw file, so it can report a pin the audit skipped for its marker."""+ safety["report"] = {+ "vulnerabilities": [+ {"package_name": "legacy-lib", "analyzed_version": "1.0", "vulnerability_id": "70001", "severity": "high"}+ ]+ }+ skill = _skill(tmp_path, {"requirements-dev.txt": 'idna==3.10\nlegacy-lib==1.0; python_version < "3"\n'})++ result = DependencySecurityValidator().validate(skill)++ (finding,) = result.findings+ assert (finding.file_path, finding.line_number) == ("requirements-dev.txt", None)+ assert finding.metadata == {+ "package_name": "legacy-lib",+ "resolved_version": "1.0",+ "declared_constraint": None,+ "declaration": None,+ "resolution_status": "unbound",+ "dependency_role": "dev",+ "dependency_relationship": None,+ "advisory_id": "SAFETY-70001",+ "advisory_source": "Safety",+ "affected_range": None,+ "fixed_versions": [],+ "aliases": [],+ }+ assert not result.passed+++def test_null_pip_audit_severity_falls_back_instead_of_crashing(tmp_path, pip_audit):+ advisories, _ = pip_audit+ advisories["pyyaml"] = [{**PYYAML_ADVISORY, "severity": None}]+ skill = _skill(tmp_path, {"requirements.txt": "pyyaml==5.3\n"})++ result = DependencySecurityValidator(use_safety=False).validate(skill)++ assert not result.is_incomplete+ assert [(finding.check_name, finding.severity) for finding in result.findings] == [+ ("PYSEC-2020-176", Severity.HIGH)+ ]+++def test_callers_without_declarations_keep_the_tagged_message():+ """A caller that audits pins it collected itself converts this tagged form into its own findings."""+ report = {"dependencies": [{"name": "foo", "version": "1.0", "vulns": [{"id": "GHSA-x", "fix_versions": []}]}]}+ result = ValidationResult()++ DependencySecurityValidator(use_safety=False)._process_pip_audit_result(+ ToolResult(True, json.dumps(report), "", 1), result, "requirements.txt"+ )++ assert result.findings == []+ assert result.errors == ["[CVE-HIGH] foo==1.0: GHSA-x"]+++def test_warnings_name_the_physical_line_after_hash_continuations(tmp_path, pip_audit):+ text = "idna==3.10 \\\n --hash=sha256:" + "a" * 64 + "\nrequests>=2\n"+ skill = _skill(tmp_path, {"requirements.txt": text})++ result = DependencySecurityValidator(use_safety=False).validate(skill)++ assert result.is_incomplete+ assert any(warning.startswith("requirements.txt: line 3 requires an exact") for warning in result.warnings)+++ ("text", "numbers"),+ [+ ("", []),+ ("a==1\nb==2", [1, 2]),+ ("a==1 \\\n --hash=sha256:00 \\\r\n --hash=sha256:11\r\nb==2\r\n", [1, 4]),+ ("a==1 \\", [1]),+ ("a==1 \\\n", [1]),+ ("a==1 \\\\\nb==2\n", [1]),+ ("a==1 \\\rb==2\n", [1, 2]),+ ("a==1 \\\r\r\nb==2", [1, 2, 3]),+ ("\\\n\\\n\nc==3\x0bd==4\x85", [1, 4, 4]),+ ("# a\x0cnote\npyyaml==5.3\n", [1, 1, 2]),+ ("a==1\u2028b==2\nc==3\x1ed==4", [1, 1, 2, 2]),+ ],+ ids=[+ "empty",+ "no-final-newline",+ "hash-continuations-crlf",+ "trailing-backslash",+ "continuation-at-end",+ "escaped-backslash",+ "backslash-cr",+ "backslash-cr-crlf",+ "vertical-tab-and-nel",+ "form-feed",+ "line-separator-and-record-separator",+ ],+)+def test_continuation_join_matches_the_previous_text(text, numbers):+ """Without a comment line, the joined text is unchanged; only CR, LF and CRLF end a numbered line."""+ lines = DependencySecurityValidator._requirement_lines(text)++ assert [line for _number, line in lines] == re.sub(r"\\\r?\n", " ", text).splitlines()+ assert [number for number, _line in lines] == numbers+++ ("text", "expected"),+ [+ (+ "idna==3.10\n# pinned for py2 \\\npyyaml==5.3\n",+ [(1, "idna==3.10"), (2, "# pinned for py2 \\"), (3, "pyyaml==5.3")],+ ),+ (" # indented \\\r\npyyaml==5.3", [(1, " # indented \\"), (2, "pyyaml==5.3")]),+ ("a==1 \\\n# note \\\nb==2\n", [(1, "a==1 # note \\"), (3, "b==2")]),+ # Only a comment line ends the declaration; pip continues a pin whose+ # trailing comment ends in a backslash, and ignores the next line too.+ ("a==1 # note \\\nb==2\n", [(1, "a==1 # note b==2")]),+ ],+ ids=["comment-line", "indented-comment-crlf", "comment-after-continuation", "trailing-comment"],+)+def test_a_comment_line_ending_in_a_backslash_ends_the_declaration(text, expected):+ """As in pip's ``join_lines``, a backslash at the end of a comment line does not continue it."""+ assert DependencySecurityValidator._requirement_lines(text) == expected+++def test_pin_after_a_commented_backslash_is_audited(tmp_path, pip_audit):+ """``pip install -r`` installs the pin after ``# note \\``, so the audit checks it too."""+ advisories, calls = pip_audit+ advisories["pyyaml"] = [PYYAML_ADVISORY]+ skill = _skill(tmp_path, {"requirements.txt": "idna==3.10\n# pinned for py2 \\\npyyaml==5.3\n"})++ result = DependencySecurityValidator(use_safety=False).validate(skill)++ assert calls == [["idna==3.10", "pyyaml==5.3"]]+ assert not result.passed and not result.is_incomplete+ assert [(finding.check_name, finding.line_number) for finding in result.findings] == [("PYSEC-2020-176", 3)]+++def test_finding_line_follows_editor_line_breaks(tmp_path, pip_audit):+ """A form feed inside a comment does not shift the line that SARIF and editors show."""+ advisories, _ = pip_audit+ advisories["pyyaml"] = [PYYAML_ADVISORY]+ skill = _skill(tmp_path, {"requirements.txt": "# a\x0cnote\npyyaml==5.3\n"})++ result = DependencySecurityValidator(use_safety=False).validate(skill)++ assert [(finding.file_path, finding.line_number) for finding in result.findings] == [("requirements.txt", 2)]+++def test_cli_report_keeps_the_incomplete_reason_next_to_an_advisory(tmp_path, pip_audit):+ """A confirmed advisory fails the check, and the CLI still says why the audit was incomplete."""+ advisories, _ = pip_audit+ advisories["pyyaml"] = [PYYAML_ADVISORY]+ skill = _skill(tmp_path, {"requirements.txt": "pyyaml==5.3\nrequests>=2\n"})+ validator = DependencySecurityValidator(use_safety=False)+ result = validator.validate(skill)+ result.validator_name = validator.name+ buffer = io.StringIO()+ console = Console(file=buffer, width=200, color_system=None)++ CLIReporter(console=console).render_result(result, console)++ output = buffer.getvalue()+ assert result.is_incomplete and result.status == "incomplete"+ assert "[FAIL] Validation failed" in output+ assert "[WARN] requirements.txt: line 2 requires an exact package version" in output+ assert output.count("PYSEC-2020-176 -> upgrade to 5.4") == 1+ assert output.index("Warnings:") < output.index("Issues:")+++def test_markdown_report_keeps_the_incomplete_reason_next_to_an_advisory(tmp_path, pip_audit):+ """The PR-comment report still says why the audit was incomplete when an advisory is listed."""+ advisories, _ = pip_audit+ advisories["idna"] = [{"id": "OSV-2024-1", "fix_versions": ["3.11"], "severity": "medium"}]+ skill = _skill(tmp_path, {"requirements.txt": "idna==3.10\nrequests>=2\n"})+ validator = DependencySecurityValidator(use_safety=False)+ result = validator.validate(skill)+ result.validator_name = validator.name++ output = MarkdownReporter().render_all([result])++ assert result.status == "incomplete"+ assert "**Incomplete scanners:** pip-audit" in output+ assert "- ⚠️ requirements.txt: line 2 requires an exact package version" in output+ assert "idna==3.10: OSV-2024-1 -> upgrade to 3.11 | <code>requirements.txt:1</code>" in output+ # The advisory is in the findings table, not repeated as a warning line.+ assert "- ⚠️ [DEPENDENCY-MEDIUM]" not in output+++def test_markdown_report_escapes_the_incomplete_reason_next_to_an_advisory(tmp_path, pip_audit):+ """A warning that names a target file is escaped like the error list and the findings table.++ Windows does not allow ``<`` or ``>`` in file names, so the warning is added+ to a real audit result in the form the validator writes it.+ """+ advisories, _ = pip_audit+ advisories["pyyaml"] = [PYYAML_ADVISORY]+ skill = _skill(tmp_path, {"requirements.txt": "pyyaml==5.3\n"})+ validator = DependencySecurityValidator(use_safety=False)+ result = validator.validate(skill)+ result.validator_name = validator.name+ result.add_warning(+ "requirements-<img src=x onerror=alert(1)>.txt: line 2 requires an exact package version; "+ "URLs, local paths, includes and pip options are not audited"+ )+ result.mark_scan_incomplete("pip-audit")++ output = MarkdownReporter().render_all([result])++ assert result.findings and result.status == "incomplete"+ assert "<img" not in output+ assert "- ⚠️ requirements-<img src=x onerror=alert(1)>.txt: line 2 requires" in output+++def test_markdown_report_keeps_execution_errors_as_the_incomplete_reason():+ """With an execution error and no finding, the error explains the incomplete scan, as before."""+ result = ValidationResult()+ result.validator_name = "Dependency Vulnerability Audit"+ result.add_error("pip-audit crashed")+ result.add_warning("requirements.txt: pip-audit did not complete")+ result.mark_scan_incomplete("pip-audit")++ output = MarkdownReporter().render_all([result])++ assert "- ❌ pip-audit crashed" in output+ assert "- ⚠️ requirements.txt: pip-audit did not complete" not in output