Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,12 @@ All notable changes to SkillEvaluator are documented in this file.
wrappers. Delay seconds must be finite and non-negative; HTTP dates remain
supported. Malformed inner values do not discard a valid outer delay, and
rate-limited calls stop when the requested wait exceeds the retry budget.
- The Tier 1 code check scans a skill's Python files whatever the skill or a
folder above it is called. Bandit reads each exclude entry as a substring of
the whole path, so a name containing `test`, `evals`, `results`, `versions`
or `.git`, such as `webapp-testing` or `.github/skills/`, left no file to
scan and the check passed. Only real test and artifact folders and test
files inside the skill are skipped now.
- Git repository-root lookups preserve trailing whitespace in directory names
instead of resolving a different path, keeping report links, repository context,
and generated-results ignore entries tied to the actual checkout.
Expand Down
60 changes: 48 additions & 12 deletions src/skillevaluator/validators/code_risk.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,9 @@

from __future__ import annotations

import glob
import os
from fnmatch import fnmatch
from pathlib import Path

from skillevaluator.config import CONFIG_DIR
Expand Down Expand Up @@ -174,20 +176,13 @@ def _run_bandit(self, skill_path: Path) -> ValidationResult:
result.mark_scan_incomplete("bandit")
return result

# Tier 1 artifact dirs (evals/, results/, versions/, ...) hold
# snapshot copies of the live skill; scanning them produces
# duplicate findings. Bandit takes a single comma-separated
# ``--exclude`` arg that combines the test exclusion (when on)
# with the artifact exclusion list.
excludes: list[str] = []
if self.exclude_tests:
excludes.extend(["tests", "test", "*_test.py", "test_*.py"])
excludes.extend(sorted(SCAN_EXCLUDED_DIRS))

# resolve() so a skill dir named like an option token (e.g.
# "--exclude=*") cannot be parsed as a scanner flag.
args = ["-r", str(skill_path.resolve()), "-f", "json", "-q", "-ll"]
args.extend(["--exclude", ",".join(excludes)])
root = skill_path.resolve()
args = ["-r", str(root), "-f", "json", "-q", "-ll"]
# Always passed, also when empty, because Bandit's own default list
# is matched the same way and has ".git" in it.
args.extend(["--exclude", ",".join(self._bandit_excludes(root))])
Comment thread
Saibernard marked this conversation as resolved.
Resolved

tool_result = Tools.bandit.run(args, timeout=120)

Expand All @@ -205,6 +200,47 @@ def _run_bandit(self, skill_path: Path) -> ValidationResult:

return result

def _bandit_excludes(self, root: Path) -> list[str]:
"""Patterns for the artifact directories Bandit skips below *root*, and for tests when they are excluded.

Tier 1 artifact dirs (evals/, results/, versions/, ...) hold snapshot
copies of the live skill, and scanning them produces duplicate
findings. Bandit drops a file when an ``--exclude`` entry is a
substring of its whole path, so a bare name such as "test" also hid
every file of a skill called "webapp-testing". Each entry is
therefore the path of a directory or file that exists, written as a
pattern that matches only below that directory or only that file.
"""
test_dirs = {"tests", "test"} if self.exclude_tests else set()
patterns: list[str] = []
for dirpath, dirnames, filenames in os.walk(root):
base = Path(dirpath)
excluded = [
name
for name in dirnames
if name in test_dirs or matches_filesystem_name(base / name, SCAN_EXCLUDED_DIRS)
]
dirnames[:] = [name for name in dirnames if name not in excluded]
patterns.extend(f"{self._bandit_pattern(base / name)}{os.sep}*" for name in excluded)
if self.exclude_tests:
patterns.extend(
Comment thread
Saibernard marked this conversation as resolved.
Resolved
self._bandit_pattern(base / name)
for name in filenames
if fnmatch(name, "test_*.py") or fnmatch(name, "*_test.py")
)
return sorted(patterns)

@staticmethod
def _bandit_pattern(path: Path) -> str:
"""*path* as a pattern for one ``--exclude`` entry.

Bandit splits the option at every comma, so a comma in the path is
written as ``?``. The entries only name tests and artifact
directories, and a path that differs in that one character is one of
those as well.
"""
return glob.escape(str(path)).replace(",", "?")

def _process_bandit_output(
self,
output: str,
Expand Down
112 changes: 112 additions & 0 deletions tests/validators/test_bandit_excludes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

"""What Bandit scans must not depend on how the skill or a folder above it is named.

Bandit drops a file when an ``--exclude`` entry is a substring of its whole
path, so the bare names the check used to pass ("test", "evals", "results",
"versions", ".git") hid every file of a skill such as ``webapp-testing``.
"""

import json
import tempfile
from collections.abc import Iterator
from pathlib import Path
from unittest.mock import patch

import pytest

from skillevaluator.utils.tool_runner import ToolResult, Tools
from skillevaluator.validators.code_risk import CodeRiskValidator

RISKY = "import subprocess\n\n\ndef run(command):\n subprocess.call(command, shell=True)\n"
LIVE_FILES = {"scripts/run.py", "scripts/contest.py", "pkg,one/mod.py"}
TEST_FILES = {"scripts/test_run.py", "scripts/run_test.py", "tests/helper.py", "pkg,one/test/helper.py"}
ARTIFACT_COPIES = {"evals/results/run.py", "versions/v1/run.py"}

needs_bandit = pytest.mark.skipif(not Tools.bandit.is_available, reason="Bandit is not installed")


@pytest.fixture
def plain_root() -> Iterator[Path]:
"""A directory whose own path holds none of the excluded names, unlike pytest's ``tmp_path``."""
with tempfile.TemporaryDirectory(prefix="se_") as tmp:
root = Path(tmp).resolve()
if any(name in str(root) for name in ("test", "evals", "results", "versions", ".git")):
pytest.skip(f"{root} already contains an excluded name")
yield root


def _skill(path: Path) -> Path:
for relative in sorted(LIVE_FILES | TEST_FILES | ARTIFACT_COPIES):
file = path / relative
file.parent.mkdir(parents=True, exist_ok=True)
file.write_text(RISKY, encoding="utf-8")
(path / "SKILL.md").write_text(
"---\nname: demo\ndescription: Use when checking a web app.\n---\n", encoding="utf-8"
)
return path


def _flagged_files(skill: Path, **options: bool) -> set[str]:
result = CodeRiskValidator(use_semgrep=False, **options).validate(skill)
assert not result.is_incomplete
root = skill.resolve()
return {Path(finding.file_path).relative_to(root).as_posix() for finding in result.findings}


@needs_bandit
@pytest.mark.parametrize(
"name", ["webapp-checks", "webapp-testing", "unit-conversions", "search-results", "latest-evals"]
)
def test_skill_name_does_not_decide_what_bandit_scans(plain_root: Path, name: str) -> None:
# Tests and artifact copies are skipped, and a file whose name only
# contains "test" (contest.py) is not a test.
assert _flagged_files(_skill(plain_root / "skills" / name)) == LIVE_FILES


@needs_bandit
@pytest.mark.parametrize("above", ["skills-test", ".github", "results/2026"])
def test_folder_above_the_skill_does_not_hide_it(plain_root: Path, above: str) -> None:
assert _flagged_files(_skill(plain_root / above / "skills" / "webapp-checks")) == LIVE_FILES


@needs_bandit
def test_tests_are_scanned_when_they_are_not_excluded(plain_root: Path) -> None:
skill = _skill(plain_root / "skills" / "webapp-testing")

assert _flagged_files(skill, exclude_tests=False) == LIVE_FILES | TEST_FILES


@needs_bandit
@pytest.mark.parametrize("name", ["a,b", "a[1]", "a*b?c"])
Comment thread
Saibernard marked this conversation as resolved.
Resolved
def test_commas_and_pattern_characters_in_a_name_keep_the_same_files(plain_root: Path, name: str) -> None:
# Bandit splits --exclude at commas and reads each entry as a pattern.
assert _flagged_files(_skill(plain_root / "skills" / name)) == LIVE_FILES


@patch.object(Tools.bandit, "_path", "/usr/bin/bandit")
@patch.object(Tools.bandit, "run")
def test_exclude_entries_are_paths_below_the_skill(mock_run, tmp_path: Path) -> None:
mock_run.return_value = ToolResult(success=True, stdout=json.dumps({"results": []}), stderr="", exit_code=0)
skill = _skill(tmp_path / "webapp-testing")

CodeRiskValidator()._run_bandit(skill)

args = mock_run.call_args.args[0]
entries = args[args.index("--exclude") + 1].split(",")
assert len(entries) == 6
assert all(Path(entry).is_absolute() and entry.startswith(str(skill.resolve())) for entry in entries)


@patch.object(Tools.bandit, "_path", "/usr/bin/bandit")
@patch.object(Tools.bandit, "run")
def test_exclude_is_passed_empty_when_there_is_nothing_to_skip(mock_run, tmp_path: Path) -> None:
# Without the option Bandit falls back to its own list, which has ".git" in it.
mock_run.return_value = ToolResult(success=True, stdout=json.dumps({"results": []}), stderr="", exit_code=0)
(tmp_path / "run.py").write_text(RISKY, encoding="utf-8")

CodeRiskValidator()._run_bandit(tmp_path)

args = mock_run.call_args.args[0]
assert args[args.index("--exclude") + 1] == ""
Loading