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
20 changes: 16 additions & 4 deletions docs/CI.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
7 changes: 7 additions & 0 deletions docs/REFERENCE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
19 changes: 18 additions & 1 deletion examples/ci/gitlab-ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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
32 changes: 29 additions & 3 deletions src/secfoo/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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.",
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down
178 changes: 178 additions & 0 deletions src/secfoo/report/gitlab.py
Original file line number Diff line number Diff line change
@@ -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,
}
Loading
Loading