Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 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
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, and the Tier 1 reference says which.
- 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
2 changes: 1 addition & 1 deletion docs/tier1-reference.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -453,7 +453,7 @@ For `validate`, the default set is `schema`, `version`, `security`, `pii`, `lice
<Accordion title="code-integrity — code risk, secrets, and hygiene">
Combines three validation groups:

- **Code risk (Bandit and Semgrep)** — SQL or command injection, hardcoded passwords, insecure cryptography, unsafe deserialization, `shell=True`, `eval()`/`exec()`, CWE patterns, and language-specific anti-patterns.
- **Code risk (Bandit and Semgrep)** — SQL or command injection, hardcoded passwords, insecure cryptography, unsafe deserialization, `shell=True`, `eval()`/`exec()`, CWE patterns, and language-specific anti-patterns. Folders named `tests` or `test` are skipped at any depth, and so are `evals`, `results`, `versions`, `node_modules` and the other artifact folders. Bandit also skips files named `test_*.py` or `*_test.py`.
Comment thread
Saibernard marked this conversation as resolved.
Resolved
- **Secrets (Gitleaks)** — API keys, tokens, passwords, private keys, database credentials, and other high-confidence secret patterns. Authored eval files, including `evals/evals.json`, graders such as `evals/grader.py`, and `evals/files` inputs, are scanned too. Generated Tier 3 output in `evals/results` is skipped. Files under a folder named `tests`, `examples`, `fixtures`, or `mocks`, or the singular form, are skipped at any depth, including the Harbor task graders in `evals/harbor/<case>/tests/`, so a secret there is not reported. To keep an intentional test token, add a `gitleaks:allow` comment on its line or list the finding in a `.gitleaksignore` file at the skill root.
- **Hygiene** — dead relative Markdown links, banned or unpinned dependency declarations, and static discovery of conventional Python test filenames.

Expand Down
74 changes: 62 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,56 @@ 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 test directories when tests 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 that exists, written as a pattern
that matches only below it. Test files outside those directories are
left out of the report by name, see ``_is_test_file``.
"""
test_dirs = {"tests", "test"} if self.exclude_tests else set()
patterns: list[str] = []
for dirpath, dirnames, _ 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(self._bandit_pattern(base / name) for name in excluded)
return sorted(patterns)

@staticmethod
def _is_test_file(entry: object) -> bool:
"""Whether a Bandit finding or scan error is about a ``test_*.py`` or ``*_test.py`` file.

These are dropped from the report and not listed in ``--exclude``.
One entry per file made the option grow with the number of test
files, past what a Windows command line holds.
"""
name = Path(str(entry.get("filename") or "")).name if isinstance(entry, dict) else ""
return fnmatch(name, "test_*.py") or fnmatch(name, "*_test.py")

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

Bandit excludes everything below an entry that is a directory, so a
plain path goes in as it is. A path with pattern characters is
escaped and ends in ``*``. Bandit also splits the option at every
comma, so a comma is written as ``?``. The entries only name test and
artifact directories, and a path that differs in that one character
is one of those as well.
"""
pattern = glob.escape(str(path)).replace(",", "?")
return pattern if pattern == str(path) else f"{pattern}{os.sep}*"

def _process_bandit_output(
self,
output: str,
Expand All @@ -230,6 +275,8 @@ def _process_bandit_output(
result.add_error("Bandit JSON field 'errors' must be a list; scan did not complete")
result.mark_scan_incomplete("bandit")
return
if self.exclude_tests:
errors = [error for error in errors if not self._is_test_file(error)]
if errors:
for error in errors[:3]:
detail = error.get("reason") or error.get("message") if isinstance(error, dict) else str(error)
Expand All @@ -243,6 +290,9 @@ def _process_bandit_output(
if exit_code == 0 and issues:
result.add_error("Bandit returned findings with clean exit code 0; scanner status is inconsistent")
result.mark_scan_incomplete("bandit")
# After the exit code checks, which are about everything Bandit found.
if self.exclude_tests:
issues = [issue for issue in issues if not self._is_test_file(issue)]
Comment thread
Saibernard marked this conversation as resolved.
Resolved

if not issues:
if not errors:
Expand Down
161 changes: 161 additions & 0 deletions tests/validators/test_bandit_excludes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
# 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


@needs_bandit
def test_parse_errors_in_test_files_do_not_leave_the_scan_incomplete(plain_root: Path) -> None:
# Test files outside tests/ are scanned and left out of the report, so
# one that Bandit cannot parse must not count either.
skill = _skill(plain_root / "skills" / "webapp-checks")
(skill / "scripts" / "test_broken.py").write_text("def broken(:\n", encoding="utf-8")

assert _flagged_files(skill) == LIVE_FILES


@needs_bandit
def test_skill_passes_when_only_its_test_files_have_findings(plain_root: Path) -> None:
skill = plain_root / "skills" / "webapp-checks"
(skill / "scripts").mkdir(parents=True)
(skill / "scripts" / "run.py").write_text("print('ok')\n", encoding="utf-8")
(skill / "scripts" / "test_run.py").write_text(RISKY, encoding="utf-8")

result = CodeRiskValidator(use_semgrep=False).validate(skill)

assert result.passed and not result.is_incomplete
assert result.findings == []


def _exclude_entries(mock_run, skill: Path) -> list[str]:
mock_run.return_value = ToolResult(success=True, stdout=json.dumps({"results": []}), stderr="", exit_code=0)
CodeRiskValidator()._run_bandit(skill)
args = mock_run.call_args.args[0]
return args[args.index("--exclude") + 1].split(",")


@patch.object(Tools.bandit, "_path", "/usr/bin/bandit")
@patch.object(Tools.bandit, "run")
def test_exclude_entries_are_folders_below_the_skill(mock_run, tmp_path: Path) -> None:
skill = _skill(tmp_path / "webapp-testing")

entries = _exclude_entries(mock_run, skill)

root = skill.resolve()
# A plain folder goes in as it is, and Bandit skips everything below it.
# The comma in "pkg,one" cannot, because Bandit splits the option there.
assert sorted(entries) == sorted(
[
str(root / "evals"),
str(root / "tests"),
str(root / "versions"),
str(root / "pkg?one" / "test" / "*"),
]
)


@patch.object(Tools.bandit, "_path", "/usr/bin/bandit")
@patch.object(Tools.bandit, "run")
def test_exclude_does_not_grow_with_the_number_of_test_files(mock_run, tmp_path: Path) -> None:
# One entry per test file would not fit a Windows command line for a
# skill that ships a few hundred of them.
skill = _skill(tmp_path / "webapp-testing")
before = _exclude_entries(mock_run, skill)
for index in range(300):
(skill / "scripts" / f"test_case_{index}.py").write_text(RISKY, encoding="utf-8")

assert _exclude_entries(mock_run, skill) == before


@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