Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
8 changes: 4 additions & 4 deletions src/skillevaluator/doctor.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
120 changes: 109 additions & 11 deletions src/skillevaluator/utils/tool_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.

Expand All @@ -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.
"""
Expand All @@ -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

Expand All @@ -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":
Expand Down Expand Up @@ -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":
Expand All @@ -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:
Expand Down Expand Up @@ -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()
Expand All @@ -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
Expand Down Expand Up @@ -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(
Expand Down
16 changes: 16 additions & 0 deletions tests/test_doctor.py
Original file line number Diff line number Diff line change
Expand Up @@ -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":
Expand Down
2 changes: 1 addition & 1 deletion tests/utils/test_scanner_install.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"]

Expand Down
Loading
Loading