Update security scanning process and documentation

- Enhanced the README to clarify the publication of security scan results to a dedicated markdown file.
- Modified `scan_skills.py` to generate both a human-readable report and a machine-readable JSON report, ensuring consistency checks before CI publishing.
- Updated the GitHub Actions workflow to validate the scan report and commit the new reports, replacing the previous SECURITY.md approach with separate report files.

This change improves the clarity and accessibility of security information for users and contributors.
This commit is contained in:
Timothy Kassis committed 2026-07-25 14:55:40 -07:00
1 parent bf383691e2
commit d77f819637
6 files changed
+381 -3802

No files matched your search

+22 -3
View File
@@ -31,14 +31,33 @@ jobs:
SKILL_SCANNER_LLM_MODEL: ${{ vars.SKILL_SCANNER_LLM_MODEL || 'claude-sonnet-5' }}
run: uv run python scan_skills.py
- name: Commit updated SECURITY.md
# Gate: a scan that contradicts the contents of skills/ must not be
# published. A non-zero exit here fails the job, so the commit step below
# is skipped and the previous report stays in place.
- name: Validate scan report
run: uv run python validate_report.py
- name: Upload report artifact
if: always()
uses: actions/upload-artifact@v4
with:
name: security-report
path: |
docs/security-report.md
docs/security-report.json
if-no-files-found: warn
- name: Commit updated security report
run: |
git diff --quiet SECURITY.md && exit 0
if [ -z "$(git status --porcelain docs/security-report.md docs/security-report.json)" ]; then
echo "Report unchanged; nothing to commit."
exit 0
fi
git config user.name "github-actions[bot]"
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
git stash --include-untracked
git pull --rebase
git stash pop || true
git add SECURITY.md
git add docs/security-report.md docs/security-report.json
git commit -m "chore: update security scan report [skip ci]"
git push
+1 -1
View File
@@ -221,7 +221,7 @@ We recommend the following:
```
- **Report anything suspicious.** If you find a skill that looks malicious or behaves unexpectedly, please [open an issue](https://github.com/K-Dense-AI/scientific-agent-skills/issues) immediately so we can investigate.
All skills are scanned on an approximately weekly basis, and [SECURITY.md](SECURITY.md) is updated with the latest results. We try to address security gaps as they arise.
All skills are scanned on an approximately weekly basis, and the results are published to [docs/security-report.md](docs/security-report.md) once they pass an automated consistency check against the repository contents. See [SECURITY.md](SECURITY.md) for our security policy, what is in scope, how to report a vulnerability privately, and how to contest a scan finding. We try to address security gaps as they arise.
---
+52 -3796
View File
File diff suppressed because it is too large. Load diff
+35
View File
@@ -0,0 +1,35 @@
# Security Scan Report
**Status:** awaiting regeneration — no validated report is currently published.
This file is the output of the automated skill scan described in the [Security Policy](../SECURITY.md#automated-skill-scanning). It is regenerated by `scan_skills.py` and published by [`.github/workflows/security-scan.yml`](../.github/workflows/security-scan.yml) only after `validate_report.py` confirms the scan's claims are consistent with the contents of `skills/`.
## Why there is no report here yet
The previous report was withdrawn rather than relocated. Verification against the repository showed it contained findings that cannot be true of the packages they describe. For example:
| Skill | The report claimed | Actually in the package |
|---|---|---|
| `seaborn` | 13 files including 3 Python scripts forming an "exfiltration chain across 3 files" | 4 files, **no** executable files |
| `umap-learn` | 23 files including 6 Python scripts, withheld to evade detection | 2 files, **no** executable files |
| `tiledbvcf` | 3 Python files harvesting `TILEDB_REST_TOKEN` | 1 file, **no** executable files |
| `venue-templates` | Environment-variable exfiltration in `scripts/generate_schematic_ai.py` and `scripts/generate_schematic.py` | Neither file exists here; both belong to a **different** skill (`scientific-schematics`) |
These are defects in the scan pipeline, not findings about the skills. Because the report was published automatically each week with no check on its plausibility, the errors were republished unreviewed — and because the report occupied the `SECURITY.md` filename, GitHub presented it as this project's official security policy.
Two changes address that:
1. The security policy is now hand-authored at [`SECURITY.md`](../SECURITY.md), and the scan report lives here instead.
2. `validate_report.py` now runs between the scan and the commit. It fails the workflow when a report anchors a finding to a file that is not present, describes cross-file behavior in a package too small to have any, or asserts a script count the package does not have. A failing scan no longer publishes anything.
The withdrawn report remains in version control for reference:
```bash
git show a177179:SECURITY.md
```
## What replaces it
The next scheduled run regenerates this file. If it passes validation, this page is replaced by the report; if it fails, the workflow fails, this page stays as it is, and the failure output names each claim that could not be reconciled with the repository.
Investigating the underlying pipeline defect — determining whether the confabulated inventories originate in per-skill scanner state, in the prompt assembly, or in the model's response — is tracked separately. The `venue-templates` case, where findings cite another skill's files by name, points toward contamination between skills within a single scan run rather than a per-skill parsing error.
+79 -2
View File
@@ -1,6 +1,15 @@
#!/usr/bin/env python3
"""Scan all skills for security issues and produce SECURITY.md."""
"""Scan all skills for security issues and produce the security scan report.
Writes a human-readable report plus a machine-readable companion. The JSON is
what `validate_report.py` checks before CI is allowed to publish the report, so
the two files must always be generated together.
`SECURITY.md` is deliberately not written here: GitHub resolves that filename as
the repository's official security policy, which is hand-authored.
"""
import json
import os
import time
from datetime import datetime, timezone
@@ -20,7 +29,8 @@ from skill_scanner.core.scan_policy import ScanPolicy
load_dotenv()
SKILLS_DIR = "skills"
OUTPUT_FILE = "SECURITY.md"
OUTPUT_FILE = "docs/security-report.md"
JSON_OUTPUT_FILE = "docs/security-report.json"
def build_scanner() -> SkillScanner:
@@ -122,6 +132,66 @@ def generate_report(report) -> str:
return "\n".join(lines)
def _enum_value(value) -> str:
"""Render an enum-or-string field as a plain string."""
return value.value if hasattr(value, "value") else str(value)
def _finding_dict(finding) -> dict:
return {
"rule_id": finding.rule_id,
"severity": _enum_value(finding.severity),
"category": _enum_value(finding.category),
"title": finding.title,
"description": finding.description,
"file_path": finding.file_path,
"line_number": finding.line_number,
"remediation": finding.remediation,
"analyzer": finding.analyzer,
}
def generate_json_report(report) -> dict:
"""Build the machine-readable companion to the markdown report.
`validate_report.py` consumes this to sanity-check the scan before CI
publishes it, so every field it asserts on must be present here. The
per-skill `scan_metadata` and `analyzability_details` are included because
they carry the scanner's own view of each package, which is what makes
disagreements with the filesystem diagnosable.
"""
return {
"generated": datetime.now(timezone.utc).isoformat(timespec="seconds"),
"totals": {
"skills_scanned": report.total_skills_scanned,
"findings": report.total_findings,
"critical": report.critical_count,
"high": report.high_count,
"medium": report.medium_count,
"low": report.low_count,
"info": report.info_count,
"safe_skills": report.safe_count,
},
"skills_skipped": report.skills_skipped,
"cross_skill_findings": [_finding_dict(f) for f in report.cross_skill_findings],
"skills": [
{
"name": result.skill_name,
"directory": result.skill_directory,
"is_safe": result.is_safe,
"max_severity": _enum_value(result.max_severity),
"scan_duration_seconds": round(result.scan_duration_seconds, 2),
"analyzers_used": result.analyzers_used,
"analyzers_failed": result.analyzers_failed,
"scan_metadata": result.scan_metadata,
"analyzability_details": result.analyzability_details,
"findings": [_finding_dict(f) for f in result.findings],
}
for result in report.scan_results
],
}
def scan_with_progress(scanner: SkillScanner, skills_dir: str) -> Report:
"""Run scan_directory logic with per-skill progress output."""
base = Path(skills_dir)
@@ -214,10 +284,17 @@ def main():
print(f" Critical: {report.critical_count} High: {report.high_count} Safe: {report.safe_count}")
md = generate_report(report)
Path(OUTPUT_FILE).parent.mkdir(parents=True, exist_ok=True)
with open(OUTPUT_FILE, "w") as f:
f.write(md)
with open(JSON_OUTPUT_FILE, "w") as f:
json.dump(generate_json_report(report), f, indent=2, sort_keys=False)
f.write("\n")
print(f"\nReport written to {OUTPUT_FILE}")
print(f"Machine-readable report written to {JSON_OUTPUT_FILE}")
print("Run `python validate_report.py` before publishing.")
if __name__ == "__main__":
+192
View File
@@ -0,0 +1,192 @@
#!/usr/bin/env python3
"""Sanity-gate the generated security scan report before it is published.
The weekly scan commits its report straight into the repository, so a scan that
malfunctions publishes itself unreviewed. This script is the check that stands
between the two: it exits non-zero when the report makes claims that contradict
the contents of `skills/`, which fails the workflow and blocks the commit.
It deliberately does not judge whether a finding is *correct* — only whether it
is *possible*. A markdown-only skill can genuinely carry a prompt-injection
finding, and nothing here suppresses that. What it rejects are claims that
cannot be true of the package as it exists on disk: exfiltration chains spanning
files in a package that has no executable files, findings anchored to paths that
are not present, and narratives asserting a script count the package does not
have.
Usage:
python validate_report.py [path/to/security-report.json]
"""
from __future__ import annotations
import json
import re
import sys
from pathlib import Path
SKILLS_DIR = Path("skills")
DEFAULT_JSON = Path("docs/security-report.json")
# Extensions the scanner treats as executable payload. A package containing none
# of these cannot exhibit behavior that requires running code.
EXECUTABLE_SUFFIXES = {
".py", ".pyw", ".sh", ".bash", ".zsh", ".fish", ".ps1", ".bat", ".cmd",
".js", ".mjs", ".cjs", ".ts", ".rb", ".pl", ".php", ".lua", ".r", ".jl",
}
# Rule-id fragments whose detections require executable code inside the package.
# Kept narrow on purpose: "EXFILTRATION" alone is excluded, because an
# instruction-level exfiltration finding against a SKILL.md is legitimate.
CODE_REQUIRED_MARKERS = ("CROSSFILE", "EXFILTRATION_CHAIN", "ENV_VAR_EXFILTRATION")
# Assertions of a positive script count, e.g. "3 Python files", "6 python scripts".
SCRIPT_COUNT_CLAIM = re.compile(
r"\b(\d+)\s+(?:Python|python|shell|executable)\s+(?:file|script)s?\b"
)
def disk_inventory(skill_dir: Path) -> dict:
"""Return what is actually in a skill package."""
files = [f for f in skill_dir.rglob("*") if f.is_file()]
return {
"all": files,
"relative": {str(f.relative_to(skill_dir)) for f in files},
"executable": [f for f in files if f.suffix.lower() in EXECUTABLE_SUFFIXES],
}
def normalize_finding_path(raw: str, skill_name: str) -> str | None:
"""Reduce a finding's file_path to a skill-relative path, or None to skip.
Absolute and home-relative paths are skipped rather than validated: a finding
may legitimately reference a system path such as ~/.ssh/id_rsa as the target
of a detected behavior rather than as a file in the package.
"""
path = raw.strip()
if not path or path.startswith(("/", "~")):
return None
path = path.removeprefix("./")
for prefix in (f"skills/{skill_name}/", f"{skill_name}/"):
path = path.removeprefix(prefix)
return path or None
def check_coverage(data: dict, disk_skills: set[str]) -> list[str]:
"""Every skill on disk must appear in the report, and none may be skipped."""
problems: list[str] = []
reported = {s["name"] for s in data.get("skills", [])}
for name in sorted(disk_skills - reported):
problems.append(f"{name}: present in {SKILLS_DIR}/ but absent from the report")
for name in sorted(reported - disk_skills):
problems.append(f"{name}: reported but has no directory in {SKILLS_DIR}/")
for skipped in data.get("skills_skipped") or []:
skill = skipped.get("skill", "<unknown>")
reason = skipped.get("reason", "<no reason recorded>")
problems.append(f"{skill}: silently skipped during the scan ({reason})")
declared = (data.get("totals") or {}).get("skills_scanned")
if declared is not None and declared != len(disk_skills):
problems.append(
f"totals.skills_scanned is {declared} but {len(disk_skills)} skills exist on disk"
)
return problems
def check_skill(entry: dict, skill_dir: Path) -> list[str]:
"""Apply the per-skill impossibility checks."""
problems: list[str] = []
name = entry["name"]
inventory = disk_inventory(skill_dir)
n_exec = len(inventory["executable"])
n_files = len(inventory["all"])
for finding in entry.get("findings") or []:
rule = finding.get("rule_id") or "<no rule id>"
# Behavior that requires running code, in a package with no code.
if n_exec == 0 and any(m in rule for m in CODE_REQUIRED_MARKERS):
problems.append(
f"{name}: `{rule}` requires executable code, but the package has "
f"{n_files} file(s) and no executable files"
)
# A cross-file chain needs at least two files to span.
if "CROSSFILE" in rule and n_files < 2:
problems.append(
f"{name}: `{rule}` describes a cross-file chain in a {n_files}-file package"
)
# Findings must be anchored to a file that exists.
raw_path = finding.get("file_path")
if raw_path:
rel = normalize_finding_path(raw_path, name)
if rel and rel not in inventory["relative"]:
problems.append(
f"{name}: `{rule}` is anchored to '{raw_path}', which is not in the package"
)
# Narratives must not assert scripts that a script-free package lacks.
if n_exec == 0:
prose = " ".join(
filter(None, [finding.get("title"), finding.get("description"),
finding.get("remediation")])
)
for match in SCRIPT_COUNT_CLAIM.finditer(prose):
if int(match.group(1)) > 0:
problems.append(
f"{name}: `{rule}` asserts '{match.group(0)}' but the package "
f"contains no executable files"
)
break
return problems
def main() -> int:
json_path = Path(sys.argv[1]) if len(sys.argv) > 1 else DEFAULT_JSON
if not json_path.exists():
print(f"FAIL: {json_path} not found — run scan_skills.py first.")
return 1
if not SKILLS_DIR.is_dir():
print(f"FAIL: {SKILLS_DIR}/ not found — run from the repository root.")
return 1
data = json.loads(json_path.read_text())
skill_dirs = {p.parent.name: p.parent for p in SKILLS_DIR.rglob("SKILL.md")}
problems = check_coverage(data, set(skill_dirs))
for entry in data.get("skills") or []:
skill_dir = skill_dirs.get(entry["name"])
if skill_dir is not None:
problems.extend(check_skill(entry, skill_dir))
print(f"Validating {json_path} against {len(skill_dirs)} skills in {SKILLS_DIR}/\n")
if problems:
print(f"FAIL: {len(problems)} claim(s) contradict the repository contents:\n")
for problem in problems:
print(f" - {problem}")
print(
"\nThe report was NOT published. Each item above is a claim the scan made "
"that cannot be true of the package as it exists on disk, which means the "
"scan pipeline is misreporting rather than that the skills are unsafe."
)
return 1
totals = data.get("totals") or {}
n_findings = totals.get("findings", 0)
print(
f"PASS: {totals.get('skills_scanned', '?')} skills scanned, "
f"{n_findings} finding{'' if n_findings == 1 else 's'}, "
f"{totals.get('critical', '?')} critical / {totals.get('high', '?')} high. "
"All findings are anchored to files that exist and are physically possible."
)
return 0
if __name__ == "__main__":
sys.exit(main())