diff --git a/docs/CI.md b/docs/CI.md index 444370e..dd894b7 100644 --- a/docs/CI.md +++ b/docs/CI.md @@ -186,17 +186,29 @@ secfoo: --project-name "$CI_PROJECT_PATH" \ --skill sast --skill secret-scanning \ --fail-on high --max-cost 2.00 > secfoo-result.json || code=$? + - secfoo findings export --format gitlab-sast -o gl-sast-report.json + - secfoo findings export --format gitlab-secret-detection -o gl-secret-detection-report.json - secfoo findings export --format sarif -o secfoo.sarif - exit ${code:-0} artifacts: when: always + reports: + sast: gl-sast-report.json + secret_detection: gl-secret-detection-report.json paths: [secfoo-result.json, secfoo.sarif] ``` -Set the provider key as a masked CI/CD variable. The SARIF file is kept as -an artifact; GitLab's own security dashboard expects its report formats, -not SARIF, so treat this as the hand-off file for other tools. Full job, -including merge-request rules and a container-image variant: +Set the provider key as a masked CI/CD variable. GitLab's merge-request +security widget and Vulnerability Report don't read SARIF, so the job also +exports findings in GitLab's own report formats (schema v15): +`--format gitlab-sast` carries the SAST findings and +`--format gitlab-secret-detection` the secret-scanning ones (the secret +value itself is never copied). Attached under `artifacts: reports:`, they +show up in the MR widget and the Vulnerability Report on GitLab Ultimate; +on other tiers they are plain downloadable artifacts. SCA findings have no +GitLab report here (GitLab's dependency-scanning format describes +dependency files), so they stay in the SARIF and JSON Lines exports. Full +job, including merge-request rules and a container-image variant: [examples/ci/gitlab-ci.yml](../examples/ci/gitlab-ci.yml). ## Bitbucket Pipelines diff --git a/docs/REFERENCE.md b/docs/REFERENCE.md index 9e24f5b..b303ac4 100644 --- a/docs/REFERENCE.md +++ b/docs/REFERENCE.md @@ -342,6 +342,13 @@ inventing one. secfoo findings export --format sarif --project 1 -o findings.sarif ``` +For GitLab, `--format gitlab-sast` and `--format gitlab-secret-detection` +write GitLab's SAST and Secret Detection report JSON (schema v15) for +`artifacts: reports: sast:` / `secret_detection:`. Each carries only its own +skill's findings (SCA findings are left out, with a note on stderr); every +vulnerability's primary identifier is its secfoo fingerprint, followed by its +CWEs, and secret values are never copied. See [CI.md](CI.md#gitlab-ci). + After a scan has populated secfoo's local findings database, upload the export in a GitHub Actions job (the checkout, scan and export must use the same runner and secfoo store): diff --git a/examples/ci/gitlab-ci.yml b/examples/ci/gitlab-ci.yml index 99bcf15..5c7a8d8 100644 --- a/examples/ci/gitlab-ci.yml +++ b/examples/ci/gitlab-ci.yml @@ -3,6 +3,12 @@ # AI security review as a GitLab CI job. Set OPENAI_API_KEY (or # ANTHROPIC_API_KEY / GEMINI_API_KEY) as a masked CI/CD variable under # Settings -> CI/CD -> Variables. +# +# Findings are exported in GitLab's own report formats and attached as +# `artifacts: reports:`, so they show in the merge-request security widget +# and the Vulnerability Report (GitLab Ultimate; on other tiers the reports +# are still downloadable job artifacts). The SARIF and JSON Lines files are +# kept for other tools. secfoo: stage: test image: python:3.12-slim @@ -18,12 +24,17 @@ secfoo: --project-name "$CI_PROJECT_PATH" \ --skill sast --skill secret-scanning \ --fail-on high --max-cost 2.00 > secfoo-result.json || code=$? + - secfoo findings export --format gitlab-sast -o gl-sast-report.json + - secfoo findings export --format gitlab-secret-detection -o gl-secret-detection-report.json - secfoo findings export --format sarif -o secfoo.sarif - secfoo findings export -o secfoo-findings.jsonl - exit ${code:-0} artifacts: when: always expire_in: 30 days + reports: + sast: gl-sast-report.json + secret_detection: gl-secret-detection-report.json paths: - secfoo-result.json - secfoo.sarif @@ -40,4 +51,10 @@ secfoo: # name: ghcr.io/secfoo-com/secfoo:latest # entrypoint: [""] # script: -# - secfoo run --agent api --target . --depth quick --json --rescan --skill sast --fail-on high > secfoo-result.json +# - secfoo run --agent api --target . --depth quick --json --rescan --skill sast --fail-on high > secfoo-result.json || code=$? +# - secfoo findings export --format gitlab-sast -o gl-sast-report.json +# - exit ${code:-0} +# artifacts: +# when: always +# reports: +# sast: gl-sast-report.json diff --git a/src/secfoo/cli.py b/src/secfoo/cli.py index 25cfbef..0ffdd34 100644 --- a/src/secfoo/cli.py +++ b/src/secfoo/cli.py @@ -29,6 +29,7 @@ from secfoo.context_run import resolve_run_context from secfoo.context_sources import ContextSourceError from secfoo.cost import format_cost, format_tokens, sum_optional +from secfoo.report.gitlab import REPORT_TYPES as GITLAB_REPORT_TYPES, findings_to_gitlab from secfoo.report.jsonl import findings_to_jsonl from secfoo.report.sarif import findings_to_sarif from secfoo.runner import _project_display_name, already_scanned_skills, execute_runs @@ -1857,6 +1858,15 @@ class FindingsStatus(str, Enum): class FindingsFormat(str, Enum): JSONL = "jsonl" SARIF = "sarif" + GITLAB_SAST = "gitlab-sast" + GITLAB_SECRET_DETECTION = "gitlab-secret-detection" + + +# GitLab report formats -> the report type findings_to_gitlab builds. +_GITLAB_REPORT_TYPES = { + FindingsFormat.GITLAB_SAST: "sast", + FindingsFormat.GITLAB_SECRET_DETECTION: "secret_detection", +} # Lifecycle bookkeeping that means nothing outside this one SQLite file. @@ -1884,7 +1894,11 @@ def findings_export( project: int | None = typer.Option(None, "--project", help="Limit to one project id."), status: FindingsStatus = typer.Option(FindingsStatus.OPEN, "--status", help="open, closed, or all."), output: Path | None = typer.Option(None, "--output", "-o", help="Write the export here instead of stdout."), - format: Annotated[FindingsFormat, typer.Option("--format", help="Export format: jsonl or sarif.")] = FindingsFormat.JSONL, + format: Annotated[FindingsFormat, typer.Option( + "--format", + help="Export format: jsonl, sarif, or GitLab's gitlab-sast (SAST findings) / " + "gitlab-secret-detection (secret-scanning findings) report.", + )] = FindingsFormat.JSONL, no_locations: bool = typer.Option( False, "--no-locations", help="Drop file paths, line numbers, code-region hashes and reachability evidence.", @@ -1896,7 +1910,7 @@ def findings_export( "--runtime-priority", help="SARIF: raise findings reached in production to level 'error'.", )] = False, ) -> None: - """Export structured findings (SAST, SCA, secret scanning) as JSONL or SARIF. + """Export structured findings (SAST, SCA, secret scanning) as JSONL, SARIF or a GitLab report. One record per finding, with its skill, severity, stack (language/ framework) and code-free construct description -- the same shape for @@ -1927,15 +1941,27 @@ def findings_export( records.append(record) for note in lookup.notes: err_console.print(f"[yellow]Note:[/] {note}") + written = len(records) if format is FindingsFormat.SARIF: text = json.dumps(findings_to_sarif(records, runtime_priority=runtime_priority), indent=2, sort_keys=True) + "\n" + elif format in _GITLAB_REPORT_TYPES: + report = findings_to_gitlab( + records, report_type=_GITLAB_REPORT_TYPES[format], start_time=datetime.now(timezone.utc), + ) + written = len(report["vulnerabilities"]) + if written < len(records): + err_console.print( + f"[yellow]Note:[/] left out {len(records) - written} finding(s) from other skills; " + f"--format {format.value} carries only {GITLAB_REPORT_TYPES[report['scan']['type']][0]} findings." + ) + text = json.dumps(report, indent=2, sort_keys=True) + "\n" else: text = findings_to_jsonl(records) if output is None: sys.stdout.write(text) return output.write_text(text, encoding="utf-8") - err_console.print(f"Wrote {len(records)} finding(s) to {output}.") + err_console.print(f"Wrote {written} finding(s) to {output}.") EXIT_RUNTIME_REACHED = 4 diff --git a/src/secfoo/report/gitlab.py b/src/secfoo/report/gitlab.py new file mode 100644 index 0000000..63fcac8 --- /dev/null +++ b/src/secfoo/report/gitlab.py @@ -0,0 +1,178 @@ +"""Serialize exported structured findings as GitLab security reports, without I/O. + +GitLab's merge-request security widget and Vulnerability Report don't read +SARIF; they read their own report JSON (security-report-schemas v15). SAST +findings become a SAST report (`artifacts: reports: sast:`) and +secret-scanning findings a Secret Detection report +(`artifacts: reports: secret_detection:`). SCA findings have no place in +either: GitLab's dependency-scanning format describes dependency files, +which secfoo doesn't record. +""" + +from __future__ import annotations + +import re +import uuid +from datetime import datetime + +from secfoo.__about__ import __version__ +from secfoo.report.sarif import _line, _sites + +SCHEMA_VERSION = "15.0.7" +_SCHEMA_URL = ( + "https://gitlab.com/gitlab-org/security-products/security-report-schemas/-/raw/" + f"v{SCHEMA_VERSION}/dist/{{name}}-report-format.json" +) + +# report type -> (secfoo skill it carries, GitLab vulnerability category, schema file name) +REPORT_TYPES = { + "sast": ("sast", "sast", "sast"), + "secret_detection": ("secret-scanning", "secret_detection", "secret-detection"), +} + +_SEVERITIES = { + "critical": "Critical", + "high": "High", + "medium": "Medium", + "low": "Low", + "info": "Info", + "informational": "Info", +} +# Field limits from the v15 schema. +_NAME_MAX = 255 +_DESCRIPTION_MAX = 1_048_576 +_SOLUTION_MAX = 7_000 +# Secret Detection requires a commit; GitLab's own analyzer uses this +# placeholder when the scan isn't tied to one. +_NO_COMMIT = "0000000" +_TOOL = { + "id": "secfoo", + "name": "secfoo", + "url": "https://github.com/secfoo-com/secfoo", + "vendor": {"name": "secfoo"}, + "version": __version__, +} + + +def _text(value: object, limit: int) -> str | None: + text = str(value or "").strip() + return text[:limit] if text else None + + +def _timestamp(value: datetime) -> str: + # The schema's pattern has no fraction and no zone. + return value.strftime("%Y-%m-%dT%H:%M:%S") + + +def _location(record: dict) -> dict: + """The finding's first site (#112), else its location_file/location_line.""" + path, start, end = record.get("location_file"), record.get("location_line"), None + for site in _sites(record): + if isinstance(site, dict) and str(site.get("path") or "").strip(): + path, start, end = site.get("path"), site.get("start_line"), site.get("end_line") + break + location: dict = {} + path = str(path or "").strip().replace("\\", "/") + if path: + location["file"] = path + start_line = _line(start) + if start_line is not None: + location["start_line"] = start_line + end_line = _line(end) + if end_line is not None and end_line > start_line: + location["end_line"] = end_line + return location + + +def _identifiers(skill: str, record: dict) -> list[dict]: + # GitLab treats the first identifier as the primary one and tracks a + # vulnerability by it plus its location, so the per-finding secfoo + # fingerprint goes first: two findings sharing a CWE stay separate. + identifiers = [] + fingerprint = str(record.get("fingerprint") or "").strip() + if fingerprint: + identifiers.append({ + "type": "secfoo_fingerprint", + "name": f"secfoo fingerprint {fingerprint}", + "value": fingerprint, + }) + cwes = sorted(set(re.findall(r"\bCWE-([1-9][0-9]*)\b", str(record.get("cwe") or "").upper())), key=int) + for number in cwes: + identifiers.append({ + "type": "cwe", + "name": f"CWE-{number}", + "value": number, + "url": f"https://cwe.mitre.org/data/definitions/{number}.html", + }) + if not identifiers: + identifiers.append({"type": "secfoo_skill", "name": f"secfoo {skill}", "value": skill}) + return identifiers + + +def _vulnerability_id(skill: str, record: dict, location: dict, index: int) -> str: + # Fingerprints are unique per project, so the project is part of the key. + fingerprint = str(record.get("fingerprint") or "").strip() + if fingerprint: + key = f"{record.get('project') or ''}/{skill}/{fingerprint}" + else: + key = f"{record.get('project') or ''}/{skill}/{location.get('file', '')}/{location.get('start_line', '')}/{index}" + return str(uuid.uuid5(uuid.NAMESPACE_URL, "https://github.com/secfoo-com/secfoo#" + key)) + + +def _commit(record: dict) -> dict: + ref = str(record.get("current_ref") or "").strip() + return {"sha": ref if re.fullmatch(r"[0-9a-fA-F]{7,64}", ref) else _NO_COMMIT} + + +def findings_to_gitlab( + records: list[dict], *, report_type: str, start_time: datetime, end_time: datetime | None = None, +) -> dict: + """Build a GitLab `sast` or `secret_detection` report (schema v15). + + Records from other skills are left out. Secret evidence is never + copied: the report names the secret type and where it is, not the value. + """ + skill, category, schema_name = REPORT_TYPES[report_type] + vulnerabilities = [] + for index, record in enumerate(records): + if record.get("skill_id") != skill: + continue + location = _location(record) + if report_type == "secret_detection": + title = record.get("secret_type") or record.get("title") + description = record.get("exposure") or record.get("construct") + solution = record.get("remediation") + location["commit"] = _commit(record) + else: + title = record.get("title") + description = record.get("description") or record.get("construct") + solution = record.get("recommendation") + severity = str(record.get("severity") or "").strip().lower() + vulnerability = { + "id": _vulnerability_id(skill, record, location, index), + "category": category, + "name": _text(title, _NAME_MAX) or f"{skill} finding", + "severity": _SEVERITIES.get(severity, "Unknown"), + "identifiers": _identifiers(skill, record), + "location": location, + } + description = _text(description, _DESCRIPTION_MAX) + if description: + vulnerability["description"] = description + solution = _text(solution, _SOLUTION_MAX) + if solution: + vulnerability["solution"] = solution + vulnerabilities.append(vulnerability) + return { + "schema": _SCHEMA_URL.format(name=schema_name), + "version": SCHEMA_VERSION, + "scan": { + "analyzer": dict(_TOOL), + "scanner": dict(_TOOL), + "type": report_type, + "start_time": _timestamp(start_time), + "end_time": _timestamp(end_time or start_time), + "status": "success", + }, + "vulnerabilities": vulnerabilities, + } diff --git a/tests/fixtures/gitlab-sast-report-format-15.json b/tests/fixtures/gitlab-sast-report-format-15.json new file mode 100644 index 0000000..ee1ba5c --- /dev/null +++ b/tests/fixtures/gitlab-sast-report-format-15.json @@ -0,0 +1,80 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "$comment": "The parts of GitLab's security-report-schemas v15 sast-report-format.json that a producer must satisfy (required fields, enums, patterns, length limits), for offline validation in tests. Source: https://gitlab.com/gitlab-org/security-products/security-report-schemas/-/blob/v15.0.7/dist/sast-report-format.json", + "title": "Report format for GitLab SAST", + "type": "object", + "required": ["scan", "version", "vulnerabilities"], + "properties": { + "scan": { + "type": "object", + "required": ["analyzer", "end_time", "scanner", "start_time", "status", "type"], + "properties": { + "end_time": {"$ref": "#/definitions/time"}, + "start_time": {"$ref": "#/definitions/time"}, + "analyzer": {"$ref": "#/definitions/tool"}, + "scanner": {"$ref": "#/definitions/tool"}, + "status": {"type": "string", "enum": ["success", "failure"]}, + "type": {"type": "string", "enum": ["sast"]} + } + }, + "schema": {"type": "string", "pattern": "^https?://.+", "format": "uri"}, + "version": {"type": "string", "pattern": "^[0-9]+\\.[0-9]+\\.[0-9]+$"}, + "vulnerabilities": { + "type": "array", + "items": { + "type": "object", + "required": ["id", "identifiers", "location"], + "properties": { + "id": {"type": "string", "minLength": 1}, + "name": {"type": "string", "maxLength": 255}, + "description": {"type": "string", "maxLength": 1048576}, + "severity": {"type": "string", "enum": ["Info", "Unknown", "Low", "Medium", "High", "Critical"]}, + "solution": {"type": "string", "maxLength": 7000}, + "identifiers": {"$ref": "#/definitions/identifiers"}, + "location": { + "type": "object", + "properties": { + "file": {"type": "string", "minLength": 1}, + "start_line": {"type": "integer", "minimum": 1}, + "end_line": {"type": "integer", "minimum": 1}, + "class": {"type": "string"}, + "method": {"type": "string"} + } + } + } + } + } + }, + "definitions": { + "time": {"type": "string", "pattern": "^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}$"}, + "tool": { + "type": "object", + "required": ["id", "name", "version", "vendor"], + "properties": { + "id": {"type": "string", "minLength": 1}, + "name": {"type": "string", "minLength": 1}, + "url": {"type": "string", "pattern": "^https?://.+", "format": "uri"}, + "version": {"type": "string", "minLength": 1}, + "vendor": { + "type": "object", + "required": ["name"], + "properties": {"name": {"type": "string", "minLength": 1}} + } + } + }, + "identifiers": { + "type": "array", + "minItems": 1, + "items": { + "type": "object", + "required": ["type", "name", "value"], + "properties": { + "type": {"type": "string", "minLength": 1}, + "name": {"type": "string", "minLength": 1}, + "url": {"type": "string", "pattern": "^(https?|ftp)://.+", "format": "uri"}, + "value": {"type": "string", "minLength": 1} + } + } + } + } +} diff --git a/tests/fixtures/gitlab-secret-detection-report-format-15.json b/tests/fixtures/gitlab-secret-detection-report-format-15.json new file mode 100644 index 0000000..8df2813 --- /dev/null +++ b/tests/fixtures/gitlab-secret-detection-report-format-15.json @@ -0,0 +1,91 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "$comment": "The parts of GitLab's security-report-schemas v15 secret-detection-report-format.json that a producer must satisfy (required fields, enums, patterns, length limits), for offline validation in tests. Source: https://gitlab.com/gitlab-org/security-products/security-report-schemas/-/blob/v15.0.7/dist/secret-detection-report-format.json", + "title": "Report format for GitLab Secret Detection", + "type": "object", + "required": ["scan", "version", "vulnerabilities"], + "properties": { + "scan": { + "type": "object", + "required": ["analyzer", "end_time", "scanner", "start_time", "status", "type"], + "properties": { + "end_time": {"$ref": "#/definitions/time"}, + "start_time": {"$ref": "#/definitions/time"}, + "analyzer": {"$ref": "#/definitions/tool"}, + "scanner": {"$ref": "#/definitions/tool"}, + "status": {"type": "string", "enum": ["success", "failure"]}, + "type": {"type": "string", "enum": ["secret_detection"]} + } + }, + "schema": {"type": "string", "pattern": "^https?://.+", "format": "uri"}, + "version": {"type": "string", "pattern": "^[0-9]+\\.[0-9]+\\.[0-9]+$"}, + "vulnerabilities": { + "type": "array", + "items": { + "type": "object", + "required": ["id", "identifiers", "location"], + "properties": { + "id": {"type": "string", "minLength": 1}, + "name": {"type": "string", "maxLength": 255}, + "description": {"type": "string", "maxLength": 1048576}, + "severity": {"type": "string", "enum": ["Info", "Unknown", "Low", "Medium", "High", "Critical"]}, + "solution": {"type": "string", "maxLength": 7000}, + "identifiers": {"$ref": "#/definitions/identifiers"}, + "location": { + "type": "object", + "required": ["commit"], + "properties": { + "file": {"type": "string"}, + "commit": { + "type": "object", + "required": ["sha"], + "properties": { + "author": {"type": "string"}, + "date": {"type": "string"}, + "message": {"type": "string"}, + "sha": {"type": "string", "minLength": 1} + } + }, + "start_line": {"type": "integer"}, + "end_line": {"type": "integer"}, + "class": {"type": "string"}, + "method": {"type": "string"} + } + } + } + } + } + }, + "definitions": { + "time": {"type": "string", "pattern": "^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}$"}, + "tool": { + "type": "object", + "required": ["id", "name", "version", "vendor"], + "properties": { + "id": {"type": "string", "minLength": 1}, + "name": {"type": "string", "minLength": 1}, + "url": {"type": "string", "pattern": "^https?://.+", "format": "uri"}, + "version": {"type": "string", "minLength": 1}, + "vendor": { + "type": "object", + "required": ["name"], + "properties": {"name": {"type": "string", "minLength": 1}} + } + } + }, + "identifiers": { + "type": "array", + "minItems": 1, + "items": { + "type": "object", + "required": ["type", "name", "value"], + "properties": { + "type": {"type": "string", "minLength": 1}, + "name": {"type": "string", "minLength": 1}, + "url": {"type": "string", "pattern": "^(https?|ftp)://.+", "format": "uri"}, + "value": {"type": "string", "minLength": 1} + } + } + } + } +} diff --git a/tests/test_cli_memory.py b/tests/test_cli_memory.py index 6bd259b..ce3871f 100644 --- a/tests/test_cli_memory.py +++ b/tests/test_cli_memory.py @@ -217,6 +217,43 @@ def list_structured_findings(self, **kwargs): assert result.stdout == "" +def test_findings_export_gitlab_reports_split_sast_and_secrets(monkeypatch, tmp_path): + from test_report.test_gitlab import VALIDATORS + + class Repository: + def __enter__(self): + return self + + def __exit__(self, *exc): + return False + + def list_structured_findings(self, **kwargs): + return [ + ("sast", {"id": 1, "display_name": "proj", "fingerprint": "a", "title": "SQL injection", + "severity": "High", "cwe": "CWE-89", "location_file": "app/db.py", "location_line": "4"}), + ("secret-scanning", {"id": 2, "display_name": "proj", "fingerprint": "s", "secret_type": "API token", + "severity": "High", "evidence": "private-evidence", "location_file": "ci.yml"}), + ] + + monkeypatch.setattr("secfoo.cli.RunRepository", Repository) + output = tmp_path / "gl-sast-report.json" + result = runner.invoke(app, ["findings", "export", "--format", "gitlab-sast", "-o", str(output)]) + assert result.exit_code == 0, result.output + report = json.loads(output.read_text(encoding="utf-8")) + VALIDATORS["sast"].validate(report) + assert [v["name"] for v in report["vulnerabilities"]] == ["SQL injection"] + assert "Wrote 1 finding(s)" in result.stderr + assert "left out 1 finding(s)" in result.stderr + + result = runner.invoke(app, ["findings", "export", "--format", "gitlab-secret-detection", "--no-locations"]) + assert result.exit_code == 0, result.output + report = json.loads(result.stdout) + VALIDATORS["secret_detection"].validate(report) + (vulnerability,) = report["vulnerabilities"] + assert vulnerability["location"] == {"commit": {"sha": "0000000"}} + assert "private-evidence" not in result.stdout + + def test_findings_export_rejects_unknown_format(): result = runner.invoke(app, ["findings", "export", "--format", "xml"]) assert result.exit_code == 2 diff --git a/tests/test_report/test_gitlab.py b/tests/test_report/test_gitlab.py new file mode 100644 index 0000000..845d4f1 --- /dev/null +++ b/tests/test_report/test_gitlab.py @@ -0,0 +1,135 @@ +"""GitLab SAST / Secret Detection report contract tests, validated offline +against the v15 report schemas.""" + +import json +from datetime import datetime, timezone +from pathlib import Path + +import pytest +from jsonschema import Draft7Validator, FormatChecker + +from secfoo.__about__ import __version__ +from secfoo.report.gitlab import findings_to_gitlab + +FIXTURES = Path(__file__).parents[1] / "fixtures" +VALIDATORS = { + report_type: Draft7Validator( + json.loads((FIXTURES / f"gitlab-{name}-report-format-15.json").read_text()), format_checker=FormatChecker(), + ) + for report_type, name in (("sast", "sast"), ("secret_detection", "secret-detection")) +} +NOW = datetime(2026, 11, 26, 9, 30, 15, 123456, tzinfo=timezone.utc) + + +def gitlab_report(records, report_type="sast", **kwargs): + document = findings_to_gitlab(records, report_type=report_type, start_time=NOW, **kwargs) + VALIDATORS[report_type].validate(document) + return document + + +RECORDS = [ + {"skill_id": "sast", "project": "proj", "fingerprint": "fp-sqli", "severity": "High", "cwe": "CWE-89", + "title": "SQL injection", "description": "Untrusted query", "recommendation": "Use bound parameters", + "location_file": "app/db.py", "location_line": "42"}, + {"skill_id": "sast", "project": "proj", "fingerprint": "fp-other", "severity": "High", "cwe": "CWE-89", + "title": "Another query"}, + {"skill_id": "sca-reachability", "severity": "Medium", "issue": "Unsafe dependency"}, + {"skill_id": "secret-scanning", "project": "proj", "fingerprint": "fp-key", "severity": "Critical", + "secret_type": "API token", "evidence": "never-copy-secret-evidence", "exposure": "Committed to CI config", + "remediation": "Rotate the token", "current_ref": "0123456789abcdef0123456789abcdef01234567", + "location_file": "ci.yml", "location_line": "7"}, +] + + +def test_sast_report_validates_and_carries_only_sast_findings(): + document = gitlab_report(RECORDS) + assert document["version"] == "15.0.7" + assert document["schema"].endswith("/v15.0.7/dist/sast-report-format.json") + scan = document["scan"] + assert scan["type"] == "sast" + assert scan["analyzer"]["version"] == scan["scanner"]["version"] == __version__ + assert scan["start_time"] == scan["end_time"] == "2026-11-26T09:30:15" + first, second = document["vulnerabilities"] + assert first["category"] == "sast" + assert first["name"] == "SQL injection" + assert first["description"] == "Untrusted query" + assert first["solution"] == "Use bound parameters" + assert first["severity"] == "High" + assert first["location"] == {"file": "app/db.py", "start_line": 42} + assert first["identifiers"] == [ + {"type": "secfoo_fingerprint", "name": "secfoo fingerprint fp-sqli", "value": "fp-sqli"}, + {"type": "cwe", "name": "CWE-89", "value": "89", "url": "https://cwe.mitre.org/data/definitions/89.html"}, + ] + # Same CWE, different finding: the primary identifier and id keep them apart. + assert first["identifiers"][0] != second["identifiers"][0] + assert first["id"] != second["id"] + assert second["location"] == {} + assert RECORDS[0]["location_line"] == "42" # Serialization doesn't mutate source records. + + +def test_secret_detection_report_validates_and_never_copies_evidence(): + document = gitlab_report(RECORDS, report_type="secret_detection") + assert document["scan"]["type"] == "secret_detection" + assert document["schema"].endswith("/v15.0.7/dist/secret-detection-report-format.json") + (vulnerability,) = document["vulnerabilities"] + assert vulnerability["category"] == "secret_detection" + assert vulnerability["name"] == "API token" + assert vulnerability["severity"] == "Critical" + assert vulnerability["description"] == "Committed to CI config" + assert vulnerability["solution"] == "Rotate the token" + assert vulnerability["location"] == { + "file": "ci.yml", "start_line": 7, "commit": {"sha": "0123456789abcdef0123456789abcdef01234567"}, + } + assert "never-copy-secret-evidence" not in json.dumps(document) + + +@pytest.mark.parametrize("ref", [None, "", "working-tree", "not a sha"]) +def test_secret_without_a_commit_uses_the_placeholder_sha(ref): + document = gitlab_report([{"skill_id": "secret-scanning", "current_ref": ref}], report_type="secret_detection") + assert document["vulnerabilities"][0]["location"]["commit"] == {"sha": "0000000"} + + +@pytest.mark.parametrize(("severity", "expected"), [ + ("Critical", "Critical"), (" HIGH ", "High"), ("Medium", "Medium"), ("Low", "Low"), + ("Info", "Info"), ("Informational", "Info"), (None, "Unknown"), ("unverified", "Unknown"), +]) +def test_severity_mapping(severity, expected): + document = gitlab_report([{"skill_id": "sast", "severity": severity}]) + assert document["vulnerabilities"][0]["severity"] == expected + + +def test_ids_are_stable_and_scoped_to_the_project(): + record = {"skill_id": "sast", "project": "a", "fingerprint": "fp"} + first = gitlab_report([record])["vulnerabilities"][0]["id"] + assert gitlab_report([record])["vulnerabilities"][0]["id"] == first + assert gitlab_report([{**record, "project": "b"}])["vulnerabilities"][0]["id"] != first + + +def test_findings_without_fingerprint_or_cwe_still_have_an_identifier(): + (vulnerability,) = gitlab_report([{"skill_id": "sast", "cwe": "unverified"}])["vulnerabilities"] + assert vulnerability["identifiers"] == [{"type": "secfoo_skill", "name": "secfoo sast", "value": "sast"}] + assert vulnerability["name"] == "sast finding" + + +def test_first_site_wins_and_invalid_lines_are_dropped(): + sites = [{"path": "src\\a.py", "start_line": 3, "end_line": 9}, {"path": "b.py", "start_line": 1}] + document = gitlab_report([ + {"skill_id": "sast", "locations": json.dumps(sites), "location_file": "ignored.py"}, + {"skill_id": "sast", "location_file": "c.py", "location_line": "4-8"}, + ]) + first, second = document["vulnerabilities"] + assert first["location"] == {"file": "src/a.py", "start_line": 3, "end_line": 9} + assert second["location"] == {"file": "c.py"} + + +def test_long_fields_are_truncated_to_the_schema_limits(): + (vulnerability,) = gitlab_report([ + {"skill_id": "sast", "title": "t" * 300, "recommendation": "r" * 8000}, + ])["vulnerabilities"] + assert len(vulnerability["name"]) == 255 + assert len(vulnerability["solution"]) == 7000 + + +def test_empty_exports_are_valid(): + for report_type in ("sast", "secret_detection"): + assert gitlab_report([], report_type=report_type)["vulnerabilities"] == []