From c59b06b31b6c1a763265e4e85d27124571ea1b55 Mon Sep 17 00:00:00 2001 From: Narendran Raghavan Date: Fri, 13 Nov 2026 20:38:59 -0800 Subject: [PATCH] Honor pinned SkillSpector during automatic selection Signed-off-by: Narendran Raghavan --- CHANGELOG.md | 9 +- src/skillevaluator/doctor.py | 8 +- src/skillevaluator/utils/tool_runner.py | 120 ++++++++++++-- tests/test_doctor.py | 16 ++ tests/utils/test_scanner_install.py | 2 +- tests/utils/test_tool_runner.py | 198 ++++++++++++++++++++++++ 6 files changed, 335 insertions(+), 18 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bab2333fe..1eeef20c6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -205,8 +205,8 @@ All notable changes to SkillEvaluator are documented in this file. a machine without uv can run the Tier 1 security check. Before, that run ended `INCOMPLETE` with "skillspector not installed", because the pinned, checksum-verified SkillSpector wheel is only run through `uv tool run`. A uv - on `PATH` or an installed `skillspector` is still used first, and - SkillSpector stays out of SkillEvaluator's own dependencies. The public + on `PATH` or an installed `skillspector` matching the pinned release is still + used first, and SkillSpector stays out of SkillEvaluator's own dependencies. The public Docker image gains the same behavior: with network access its Tier 1 run now completes instead of ending `INCOMPLETE`. - Root help shows the SkillEvaluator wordmark in more terminals: the @@ -247,6 +247,11 @@ All notable changes to SkillEvaluator are documented in this file. ### Fixed +- Automatic SkillSpector selection now verifies the pinned release on first use + and falls back to the verified managed wheel for a different or unverifiable + version. Discovery stays free of subprocesses, version probes omit provider + credentials and respect the caller timeout, and explicit executable overrides + remain available. Doctor reports the path and source selected by the probe. - `health-check --tier 1` (and `doctor --tier 1`) labels a scanner that SkillEvaluator provisions itself: `(uv tool run)` for SkillSpector and `(managed)` for the downloaded Gitleaks binary. Before, the Gitleaks row diff --git a/src/skillevaluator/doctor.py b/src/skillevaluator/doctor.py index 49f56f37e..76804c677 100644 --- a/src/skillevaluator/doctor.py +++ b/src/skillevaluator/doctor.py @@ -72,16 +72,16 @@ def _scanner_row(tool: Any, timeout: float) -> Row: return (label, "fail", tool.configuration_error) if not tool.is_available: return (label, "fail", f"not installed. {tool.get_install_hint()}") + version_args = ["version"] if tool.command == "gitleaks" else ["--version"] + result = tool.run(version_args, timeout=timeout, log_command=False, **_probe_run_options(tool.command)) + if result.error_message: + return (label, "fail", result.error_message) location = tool.path if tool.resolution_source.startswith("override:"): location += f" (from {tool.override_env})" elif tool.resolution_source != "automatic": # Managed provisioning: "uv tool run" for SkillSpector, "managed" for Gitleaks. location += f" ({tool.resolution_source})" - version_args = ["version"] if tool.command == "gitleaks" else ["--version"] - result = tool.run(version_args, timeout=timeout, log_command=False, **_probe_run_options(tool.command)) - if result.error_message: - return (label, "fail", result.error_message) if result.exit_code != 0: return (label, "fail", f"version probe exited with status {result.exit_code}; {location}") match = _VERSION_RE.search(result.stdout) or _VERSION_RE.search(result.stderr) diff --git a/src/skillevaluator/utils/tool_runner.py b/src/skillevaluator/utils/tool_runner.py index 730b8dc01..71cc1752c 100644 --- a/src/skillevaluator/utils/tool_runner.py +++ b/src/skillevaluator/utils/tool_runner.py @@ -16,6 +16,7 @@ import subprocess import sys import tempfile +import time from collections.abc import Callable, Mapping from dataclasses import dataclass from pathlib import Path @@ -126,6 +127,17 @@ def _captured_text(value: str | bytes | None) -> str: return value +def _skillspector_version(stdout: str, stderr: str) -> str | None: + """Read an unambiguous SkillSpector identity line, preserving release suffixes.""" + pattern = r"skillspector(?:,?\s+version)?\s+v?(\d+\.\d+\.\d+[A-Za-z0-9._+-]*)" + versions = { + match.group(1) + for line in (stdout + "\n" + stderr).splitlines() + if (match := re.fullmatch(pattern, line.strip(), flags=re.IGNORECASE)) + } + return versions.pop() if len(versions) == 1 else None + + class ExternalTool: """Wrapper for external CLI tools with consistent error handling. @@ -152,8 +164,9 @@ def __init__( override_env: Optional environment variable containing an explicit absolute executable path. Invalid overrides fail closed rather than silently falling back to another executable. - managed: When the tool is not installed, fall back to SkillEvaluator's - pinned provisioning: the verified SkillSpector wheel through + managed: Fall back to SkillEvaluator's pinned provisioning when the + tool is missing, or automatically discovered SkillSpector is not + the pinned release: the verified SkillSpector wheel through ``uv tool run`` (a uv on PATH, else the one installed with SkillEvaluator), or the downloaded Gitleaks binary. """ @@ -171,6 +184,7 @@ def refresh(self) -> None: self._version: str | None = None self._uv_run: tuple[str, tuple[str, ...]] | None = None self._ensure: tuple[str, Callable[[], str | None]] | None = None + self._skillspector_candidate: str | None = None override_env = self.override_env name = self.name @@ -189,8 +203,40 @@ def refresh(self) -> None: self.command, prefer_interpreter_sibling=self._prefer_interpreter_sibling, ) - if self._path is None and self._managed: - self._resolve_managed() + if self._managed: + if self._path is not None and self.command == "skillspector": + # Discovery must stay cheap and must never execute a PATH + # program during module import or unrelated CLI commands. + self._skillspector_candidate = self._path + elif self._path is None: + self._resolve_managed() + + def _require_pinned_skillspector(self, version: str | None) -> None: + """Keep automatic SkillSpector resolution on the supported pinned release.""" + if version == SKILLSPECTOR_VERSION: + return + detail = ( + f"Automatically discovered SkillSpector {version or '(version could not be verified)'} " + f"at {self._path}; expected pinned version {SKILLSPECTOR_VERSION}." + ) + self._path = None + self._version = None + self._resolve_managed() + override = self.override_env or "SKILLEVALUATOR_SKILLSPECTOR_PATH" + if self._path is not None: + logger.warning( + "%s Using the managed runtime via uv tool run. Set %s to an absolute executable path " + "for an intentional override.", + detail, + override, + ) + else: + self._configuration_error = ( + f"{detail} The pinned runtime requires uv and a valid SKILLEVALUATOR_RUNTIME_DIR; " + f"install uv or correct the runtime directory, or set {override} to an absolute executable path " + "for an intentional override." + ) + logger.warning("%s", self._configuration_error) def _resolve_managed(self) -> None: if self.command == "skillspector": @@ -227,6 +273,8 @@ def path(self) -> str | None: @property def version(self) -> str | None: """The pinned release for managed installs, otherwise what the tool's version command reports.""" + if self._skillspector_candidate is not None and self._skillspector_candidate == self._path: + self.run(["--version"], timeout=30, log_command=False) if self.resolution_source == "uv tool run": return SKILLSPECTOR_VERSION if self.resolution_source == "managed": @@ -235,17 +283,34 @@ def version(self) -> str | None: return None if self._version is None: argv = [self._path, "version" if self.command == "gitleaks" else "--version"] + options = {} + if self.command == "skillspector": + from skillevaluator.validators.security import _skillspector_process_env + + options["env"] = _skillspector_process_env() try: - proc = subprocess.run(argv, capture_output=True, text=True, timeout=30, check=False) + proc = subprocess.run( + argv, capture_output=True, text=True, errors="replace", timeout=30, check=False, **options + ) except (OSError, subprocess.SubprocessError): proc = None - match = proc and re.search(r"\d+\.\d+(?:\.\d+)?", proc.stdout or proc.stderr or "") - self._version = match.group(0) if match else "" + if self.command == "skillspector": + self._version = ( + _skillspector_version(proc.stdout or "", proc.stderr or "") + if proc is not None and proc.returncode == 0 + else "" + ) or "" + else: + match = proc and ( + re.search(r"\d+\.\d+(?:\.\d+)?", proc.stdout or "") + or re.search(r"\d+\.\d+(?:\.\d+)?", proc.stderr or "") + ) + self._version = match.group(0) if match else "" return self._version or None @property def configuration_error(self) -> str | None: - """Return why an explicit executable override was rejected, if it was.""" + """Return why executable selection could not satisfy the scanner configuration.""" return self._configuration_error def get_install_hint(self) -> str: @@ -301,13 +366,47 @@ def run( Returns: ToolResult with stdout, stderr, and error info """ + child_env = dict(env or {}) if replace_env else ({**os.environ, **env} if env else None) + requested_timeout = timeout + if self._skillspector_candidate is not None and self._skillspector_candidate == self._path: + from skillevaluator.validators.security import _skillspector_process_env + + self._skillspector_candidate = None + started = time.monotonic() + try: + probe = subprocess.run( + [self._path, "--version"], + capture_output=True, + text=True, + errors="replace", + timeout=min(30, timeout), + check=False, + env=_skillspector_process_env(child_env), + ) + except (OSError, subprocess.SubprocessError): + probe = None + version = ( + _skillspector_version(probe.stdout or "", probe.stderr or "") + if probe is not None and probe.returncode == 0 + else None + ) + self._version = version or "" + self._require_pinned_skillspector(version) + if version == SKILLSPECTOR_VERSION and args == ["--version"]: + return ToolResult(True, probe.stdout or "", probe.stderr or "", probe.returncode) + timeout -= time.monotonic() - started + if not self.is_available: return ToolResult( success=False, stdout="", stderr="", exit_code=-1, - error_message=f"{self.name} not installed. {self.get_install_hint()}", + error_message=self.configuration_error or f"{self.name} not installed. {self.get_install_hint()}", + ) + if timeout <= 0: + return ToolResult( + False, "", "", -1, error_message=f"{self.name} timed out after {requested_timeout} seconds" ) launch_args = self._launch_args() @@ -320,7 +419,6 @@ def run( logger.info(f"Running {self.name}: {' '.join(cmd[:5])}...") try: - child_env = dict(env or {}) if replace_env else ({**os.environ, **env} if env else None) # Text mode decodes with Python's selected codec (the locale codec, # or UTF-8 in UTF-8 mode), which is what Python scanners write. A # strict decode of bytes outside that codec (a Windows traceback @@ -349,7 +447,7 @@ def run( stdout=_captured_text(exc.stdout), stderr=_captured_text(exc.stderr), exit_code=-1, - error_message=f"{self.name} timed out after {timeout} seconds", + error_message=f"{self.name} timed out after {requested_timeout} seconds", ) except FileNotFoundError: return ToolResult( diff --git a/tests/test_doctor.py b/tests/test_doctor.py index 4c185ad18..6874c4638 100644 --- a/tests/test_doctor.py +++ b/tests/test_doctor.py @@ -159,6 +159,22 @@ def test_tier1_reports_managed_provisioning_without_naming_an_override(scanners, assert scanners.calls[0][0][-2:] == ["skillspector", "--version"] +def test_tier1_reports_source_selected_during_probe(scanners, monkeypatch) -> None: + tool = Tools.skillspector + + def run(*args, **kwargs): + tool._path = "/doctor-tools/uv" + tool.resolution_source = "uv tool run" + return tool_runner.ToolResult(True, "SkillSpector v2.13.4", "", 0) + + monkeypatch.setattr(tool, "run", run) + + assert _rows(tier="1", checks="security")["SkillSpector"] == ( + "pass", + "2.13.4 at /doctor-tools/uv (uv tool run)", + ) + + @pytest.mark.parametrize("failure", ["missing", "malformed override", "timeout", "exit status"]) def test_tier1_scanner_failure_does_not_hide_other_scanners(scanners, monkeypatch, failure) -> None: if failure == "missing": diff --git a/tests/utils/test_scanner_install.py b/tests/utils/test_scanner_install.py index d6df982bd..f77e32547 100644 --- a/tests/utils/test_scanner_install.py +++ b/tests/utils/test_scanner_install.py @@ -113,7 +113,7 @@ def test_installed_scanner_wins_over_fallback(self): found = {"uv": "/opt/uv", "skillspector": "/usr/bin/skillspector"} with patch.object(tool_runner, "resolve_tool_path", _resolver(found)): tool = ExternalTool("skillspector", "skillspector", managed=True) - with patch("subprocess.run", return_value=CompletedProcess([], 0, "", "")) as run: + with patch("subprocess.run", return_value=CompletedProcess([], 0, "SkillSpector v2.13.4", "")) as run: tool.run(["--version"]) assert run.call_args.args[0] == ["/usr/bin/skillspector", "--version"] diff --git a/tests/utils/test_tool_runner.py b/tests/utils/test_tool_runner.py index b558c4c6c..0f5e2ce73 100644 --- a/tests/utils/test_tool_runner.py +++ b/tests/utils/test_tool_runner.py @@ -7,6 +7,7 @@ and Tools registry with mocked subprocess and filesystem where appropriate. """ +import importlib.util import locale import os import sys @@ -460,6 +461,203 @@ def test_get_install_hint_for_unknown_tools(self): assert "PATH" in hint +@pytest.mark.skipif(sys.platform == "win32", reason="POSIX fake console scripts") +class TestAutomaticSkillSpectorVersion: + """Automatic resolution must not silently change the pinned scanner release.""" + + @pytest.fixture + def scanner_bin(self, tmp_path, monkeypatch): + bindir = tmp_path / "bin" + bindir.mkdir() + monkeypatch.setenv("PATH", str(bindir)) + monkeypatch.setenv("SKILLEVALUATOR_RUNTIME_DIR", str(tmp_path / "runtime")) + monkeypatch.delenv("SKILLEVALUATOR_SKILLSPECTOR_PATH", raising=False) + monkeypatch.setattr(sys, "executable", str(bindir / "python")) + # Provisioning has its own checksum/download tests. Keep selection offline. + monkeypatch.setattr(tool_runner, "ensure_skillspector_wheel", lambda: None) + monkeypatch.setattr(tool_runner, "_packaged_uv", lambda: None) + uv = bindir / "uv" + uv.write_text('#!/bin/sh\nprintf "%s\\n" "$@"\n') + uv.chmod(0o755) + return bindir + + @staticmethod + def _scanner(bindir, version_output, version_exit=0): + scanner = bindir / "skillspector" + scanner.write_text( + '#!/bin/sh\nif [ "$1" = "--version" ]; then\n' + f" printf '%s\\n' '{version_output}'\n exit {version_exit}\n" + "fi\nprintf 'direct scanner\\n'\n" + ) + scanner.chmod(0o755) + return scanner + + @pytest.mark.parametrize( + ("version_output", "version_exit"), + [ + ("SkillSpector v2.11.2", 0), + ("SkillSpector v2.14.0", 0), + ("version unavailable", 0), + ("SkillSpector v2.13.4", 2), + ("SkillSpector v2.13.4rc1", 0), + ("SkillSpector v2.13.4_rc1", 0), + ("Dependency foo 2.13.4 initialized; scanner version unavailable", 0), + ("SkillSpector v2.13.4\nSkillSpector v2.11.2", 0), + ], + ) + def test_mismatched_or_unverified_version_runs_pinned_wheel( + self, scanner_bin, version_output, version_exit, caplog, monkeypatch + ): + scanner = self._scanner(scanner_bin, version_output, version_exit) + monkeypatch.setattr(tool_runner.logger, "propagate", True) + + tool = ExternalTool("SkillSpector", "skillspector", managed=True) + result = tool.run(["scan", "target"], log_command=False) + + assert result.success + assert result.exit_code == 0 + assert result.stdout.splitlines() == [ + "tool", + "run", + "--quiet", + "--from", + str(scanner_bin.parent / "runtime/skillspector/2.13.4/skillspector-2.13.4-py3-none-any.whl"), + "skillspector", + "scan", + "target", + ] + assert tool.path == str(scanner_bin / "uv") + assert tool.version == "2.13.4" + assert tool.resolution_source == "uv tool run" + assert str(scanner) in caplog.text + assert "2.13.4" in caplog.text + + def test_constructor_refresh_and_path_lookup_do_not_launch_scanner(self, scanner_bin): + scanner = self._scanner(scanner_bin, "SkillSpector v2.13.4") + marker = scanner_bin / "launched" + scanner.write_text(scanner.read_text().replace("#!/bin/sh\n", f"#!/bin/sh\n: > '{marker}'\n")) + + tool = ExternalTool("SkillSpector", "skillspector", managed=True) + tool.refresh() + + assert tool.path == str(scanner) + assert tool.is_available + assert not marker.exists() + assert tool.run(["scan", "target"], log_command=False).success + assert marker.exists() + + def test_fresh_module_import_does_not_launch_scanner(self, scanner_bin, monkeypatch): + self._scanner(scanner_bin, "SkillSpector v2.13.4") + calls = [] + + def run(argv, **kwargs): + calls.append(argv) + return CompletedProcess(argv, 0, "SkillSpector v2.13.4", "") + + monkeypatch.setattr(tool_runner.subprocess, "run", run) + name = "skillevaluator.utils._tool_runner_import_test" + spec = importlib.util.spec_from_file_location(name, tool_runner.__file__) + module = importlib.util.module_from_spec(spec) + monkeypatch.setitem(sys.modules, name, module) + + spec.loader.exec_module(module) + + assert module.Tools.skillspector.path == str(scanner_bin / "skillspector") + assert calls == [] + + def test_lazy_probe_uses_sanitized_environment_and_caller_timeout(self, scanner_bin, monkeypatch): + self._scanner(scanner_bin, "SkillSpector v2.13.4") + monkeypatch.setenv("NVIDIA_API_KEY", "ambient-secret") + real_run = tool_runner.subprocess.run + calls = [] + + def run(argv, **kwargs): + calls.append((argv, kwargs)) + return real_run(argv, **kwargs) + + monkeypatch.setattr(tool_runner.subprocess, "run", run) + tool = ExternalTool("SkillSpector", "skillspector", managed=True) + result = tool.run( + ["scan", "target"], + timeout=5, + env={"PATH": str(scanner_bin), "NVIDIA_API_KEY": "requested-scan-secret"}, + replace_env=True, + log_command=False, + ) + + assert result.success + assert calls[0][0] == [str(scanner_bin / "skillspector"), "--version"] + assert 0 < calls[0][1]["timeout"] <= 5 + assert calls[0][1]["env"] == {"PATH": str(scanner_bin)} + assert calls[-1][1]["env"]["NVIDIA_API_KEY"] == "requested-scan-secret" + + def test_matching_pinned_version_uses_installed_scanner(self, scanner_bin): + scanner = self._scanner(scanner_bin, "SkillSpector v2.13.4") + + tool = ExternalTool("SkillSpector", "skillspector", managed=True) + + assert tool.run(["scan", "target"], log_command=False).stdout == "direct scanner\n" + assert tool.path == str(scanner) + assert tool.version == "2.13.4" + assert tool.resolution_source == "automatic" + + def test_stale_scanner_falls_back_to_packaged_uv(self, scanner_bin, monkeypatch): + self._scanner(scanner_bin, "SkillSpector v2.11.2") + packaged_uv = scanner_bin / "packaged-uv" + (scanner_bin / "uv").rename(packaged_uv) + monkeypatch.setattr(tool_runner, "_packaged_uv", lambda: str(packaged_uv)) + + tool = ExternalTool("SkillSpector", "skillspector", managed=True) + result = tool.run(["scan", "target"], log_command=False) + + assert result.success + assert result.exit_code == 0 + assert result.stdout.splitlines()[:4] == ["tool", "run", "--quiet", "--from"] + assert result.stdout.splitlines()[4].endswith("/2.13.4/skillspector-2.13.4-py3-none-any.whl") + assert tool.path == str(packaged_uv) + assert tool.resolution_source == "uv tool run" + + def test_explicit_older_override_is_preserved(self, scanner_bin, monkeypatch): + scanner = self._scanner(scanner_bin, "SkillSpector v2.11.2") + monkeypatch.setenv("SKILLEVALUATOR_SKILLSPECTOR_PATH", str(scanner)) + + tool = ExternalTool( + "SkillSpector", "skillspector", override_env="SKILLEVALUATOR_SKILLSPECTOR_PATH", managed=True + ) + + assert tool.run(["scan", "target"], log_command=False).stdout == "direct scanner\n" + assert tool.path == str(scanner.resolve()) + assert tool.version == "2.11.2" + assert tool.resolution_source == "override:SKILLEVALUATOR_SKILLSPECTOR_PATH" + + @pytest.mark.parametrize("unavailable", ["uv", "runtime"]) + def test_mismatched_version_cannot_run_when_managed_runtime_unavailable( + self, scanner_bin, monkeypatch, unavailable + ): + scanner = self._scanner(scanner_bin, "SkillSpector v2.11.2") + if unavailable == "uv": + (scanner_bin / "uv").unlink() + else: + monkeypatch.setattr(tool_runner, "managed_skillspector_wheel", lambda: None) + + tool = ExternalTool( + "SkillSpector", "skillspector", override_env="SKILLEVALUATOR_SKILLSPECTOR_PATH", managed=True + ) + result = tool.run(["scan", "target"], log_command=False) + + assert not tool.is_available + assert not result.success + assert result.exit_code == -1 + assert result.stdout == "" + assert tool.configuration_error + assert result.error_message == tool.configuration_error + assert str(scanner) in tool.configuration_error + assert "2.11.2" in tool.configuration_error + assert "2.13.4" in tool.configuration_error + assert "uv" in tool.get_install_hint() + assert "SKILLEVALUATOR_SKILLSPECTOR_PATH" in tool.get_install_hint() + + class TestToolsRegistry: """Tests for Tools class (tool registry)."""