id: github-codeql-sarif-gate
namespace: company.team
description: |
Track CodeQL code-scanning alerts as regressions instead of a growing
backlog: fetch open alerts from the GitHub code-scanning API, diff high
and critical findings against a stored baseline, and when new findings
appear open a labeled issue, alert Slack, and fail the run.
triggers:
- id: on_analysis_webhook
type: io.kestra.plugin.core.trigger.Webhook
description: GitHub (or your CI) POSTs here when a CodeQL analysis completes or
on push. Shipped with a keyed URL, treat the key as a secret.
key: "{{ secret('CODEQL_WEBHOOK_KEY') }}"
- id: daily_sweep
type: io.kestra.plugin.core.trigger.Schedule
description: Optional nightly sweep in case a webhook is missed. Ships disabled,
enable it once the webhook is wired.
cron: "0 6 * * *"
disabled: true
inputs:
- id: repository
type: STRING
defaults: your-org/your-repo
description: GitHub repository to gate in owner/repo form, used for the
code-scanning API calls and as the target for the issue it opens.
- id: alert_threshold
type: INT
defaults: 0
description: Number of new high or critical alerts tolerated before the gate
fails. Zero means any new finding blocks.
- id: branch
type: STRING
defaults: main
description: Branch context recorded in the issue and Slack notice so triage
starts at the right ref.
tasks:
# --- 1. collect ---
- id: fetch_open_alerts
type: io.kestra.plugin.core.http.Request
description: List every open code-scanning alert so the gate sees the full
picture, not just the newest analysis run.
method: GET
uri: "https://api.github.com/repos/{{ inputs.repository
}}/code-scanning/alerts?state=open&per_page=100"
headers:
Authorization: "Bearer {{ secret('GITHUB_TOKEN') }}"
Accept: "application/vnd.github+json"
X-GitHub-Api-Version: "2022-11-28"
- id: fetch_latest_analysis
type: io.kestra.plugin.core.http.Request
description: Fetch the most recent code-scanning analysis for triage context.
Allowed to fail so a missing analysis never blocks the alert check itself.
allowFailure: true
method: GET
uri: "https://api.github.com/repos/{{ inputs.repository
}}/code-scanning/analyses?per_page=1"
headers:
Authorization: "Bearer {{ secret('GITHUB_TOKEN') }}"
Accept: "application/vnd.github+json"
X-GitHub-Api-Version: "2022-11-28"
- id: read_baseline
type: io.kestra.plugin.core.kv.Get
description: Load the alert numbers recorded by the last clean run. A first run
has no baseline and every open high or critical alert counts as
pre-existing.
key: "codeql_alerts_{{ inputs.repository }}"
errorOnMissing: false
# --- 2. assess ---
- id: assess
type: io.kestra.plugin.scripts.python.Script
description: Filter open alerts to high and critical severity, split them into
new versus baseline-known, and emit a verdict through the outputs
protocol.
containerImage: python:3.12-slim
inputFiles:
alerts.json: "{{ outputs.fetch_open_alerts.body ?? '[]' }}"
latest_analysis.json: "{{ outputs.fetch_latest_analysis.body ?? '[]' }}"
baseline.json: "{{ outputs.read_baseline.value ?? '{}' }}"
threshold.txt: "{{ inputs.alert_threshold }}"
script: |
import json
def load_json(path, fallback):
try:
with open(path) as fh:
raw = fh.read().strip()
if not raw:
return fallback
return json.loads(raw)
except Exception:
return fallback
alerts = load_json("alerts.json", [])
if not isinstance(alerts, list):
alerts = []
baseline = load_json("baseline.json", {})
if not isinstance(baseline, dict):
baseline = {}
analyses = load_json("latest_analysis.json", [])
if not isinstance(analyses, list):
analyses = []
try:
with open("threshold.txt") as fh:
threshold = int(fh.read().strip())
except Exception:
threshold = 0
known_raw = baseline.get("known_numbers")
first_run = not isinstance(known_raw, list)
known = set()
if isinstance(known_raw, list):
for n in known_raw:
if isinstance(n, int):
known.add(n)
else:
try:
known.add(int(n))
except Exception:
continue
HIGH = {"critical", "high"}
def is_high(alert):
level = str(alert.get("security_severity_level") or "").lower()
if level in HIGH:
return True
rule = alert.get("rule")
if isinstance(rule, dict):
rule_level = str(rule.get("security_severity_level") or "").lower()
if rule_level in HIGH:
return True
return False
hc = []
total_open = 0
for alert in alerts:
if not isinstance(alert, dict):
continue
total_open += 1
state = str(alert.get("state") or "open").lower()
if state != "open":
continue
if is_high(alert):
hc.append(alert)
current_numbers = []
for a in hc:
num = a.get("number")
if isinstance(num, int):
current_numbers.append(num)
current_numbers = sorted(current_numbers)
new_alerts = []
if not first_run:
for a in hc:
num = a.get("number")
if isinstance(num, int) and num not in known:
new_alerts.append(a)
items = []
for a in sorted(new_alerts, key=lambda x: x.get("number") or 0):
rule = a.get("rule")
rule_id = "unknown"
if isinstance(rule, dict):
rule_id = str(rule.get("id") or rule.get("name") or "unknown")
path = ""
instance = a.get("most_recent_instance")
if isinstance(instance, dict):
loc = instance.get("location")
if isinstance(loc, dict):
path = str(loc.get("path") or "")
severity = str(a.get("security_severity_level") or "").lower()
if not severity and isinstance(rule, dict):
severity = str(rule.get("security_severity_level") or "unknown").lower()
if not severity:
severity = "unknown"
items.append({
"number": a.get("number"),
"severity": severity,
"rule": rule_id,
"path": path,
"html_url": str(a.get("html_url") or ""),
})
new_count = len(items)
blocked = new_count > threshold
verdict = "regression" if blocked else "pass"
def summarize(entries):
if not entries:
return "none"
text = "; ".join(
("#%s %s (%s) %s" % (e["number"], e["rule"], e["severity"], e["path"])).strip()
for e in entries
)
return text.replace('"', "'")
analysis_tool = "unknown"
analysis_ref = "unknown"
if analyses and isinstance(analyses[0], dict):
latest = analyses[0]
tool = latest.get("tool")
if isinstance(tool, dict):
analysis_tool = str(tool.get("name") or "unknown")
analysis_ref = str(latest.get("ref") or "unknown")
payload = {"outputs": {
"verdict": verdict,
"blocked": blocked,
"total_open": total_open,
"open_high_critical": len(hc),
"new_high_critical_count": new_count,
"new_high_critical": items,
"new_summary": summarize(items),
"current_numbers": current_numbers,
"analysis_tool": analysis_tool,
"analysis_ref": analysis_ref,
"first_run": first_run,
"threshold": threshold,
}}
print("::" + json.dumps(payload) + "::")
print("verdict=%s open=%d high_critical=%d new=%d first_run=%s" % (
verdict, total_open, len(hc), new_count, first_run))
# --- 3. gate ---
- id: gate
type: io.kestra.plugin.core.flow.If
description: A new high or critical alert over the threshold stops the run. A
clean run records the new baseline so the next comparison starts from
today's position.
condition: "{{ outputs.assess.vars.blocked }}"
then:
- id: open_issue
type: io.kestra.plugin.github.issues.Create
description: Open a labeled GitHub issue listing the new alerts with links, so
triage lands in the same backlog engineers already work from.
jwtToken: "{{ secret('GITHUB_TOKEN') }}"
repository: "{{ inputs.repository }}"
title: "CodeQL: {{ outputs.assess.vars.new_high_critical_count }} new
high/critical alert(s) in {{ inputs.repository }}"
body: |
## CodeQL regression
**{{ outputs.assess.vars.new_high_critical_count }} new high or critical alert(s)** on branch `{{ inputs.branch }}`
({{ outputs.assess.vars.open_high_critical }} open high/critical of {{ outputs.assess.vars.total_open }} open total).
Latest analysis tool: {{ outputs.assess.vars.analysis_tool }} (ref {{ outputs.assess.vars.analysis_ref }}).
{% for a in outputs.assess.vars.new_high_critical %}
- [#{{ a.number }}]({{ a.html_url }}) {{ a.rule }} ({{ a.severity }}) in `{{ a.path }}`
{% endfor %}
Execution: {{ execution.id }}
Fix or dismiss the alerts, then close this issue. The gate baseline was not advanced, so the next run still sees these alerts as new.
labels:
- security
- codeql
- id: alert_slack
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
description: Tell the team how many new high or critical alerts appeared and
that a GitHub issue is waiting.
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
payload: |
{
"text": "CodeQL gate found {{ outputs.assess.vars.new_high_critical_count }} new high/critical alert(s) in {{ inputs.repository }} (branch {{ inputs.branch }}): {{ outputs.assess.vars.new_summary }}. A GitHub issue has been opened. Execution {{ execution.id }}."
}
- id: fail_the_run
type: io.kestra.plugin.core.execution.Fail
description: Fail the execution so whatever pipeline watches this gate sees red
instead of a quiet success.
errorMessage: "CodeQL gate found {{ outputs.assess.vars.new_high_critical_count
}} new high/critical alert(s) in {{ inputs.repository }}."
else:
- id: advance_baseline
type: io.kestra.plugin.core.kv.Set
description: A clean run stores the current high and critical alert numbers, so
only genuinely new findings count as regressions next time.
key: "codeql_alerts_{{ inputs.repository }}"
kvType: JSON
overwrite: true
value: |
{
"repository": "{{ inputs.repository }}",
"recorded_at": "{{ now() }}",
"known_numbers": {{ outputs.assess.vars.current_numbers | toJson }}
}
- id: log_clean
type: io.kestra.plugin.core.log.Log
description: Record the all-clear so the execution history doubles as an audit
trail of gate runs.
message: "CodeQL gate passed for {{ inputs.repository }}: {{
outputs.assess.vars.open_high_critical }} open high/critical, {{
outputs.assess.vars.new_high_critical_count }} new, first_run={{
outputs.assess.vars.first_run }}."
errors:
- id: alert_failure
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
description: Alert when the gate itself cannot run, because a dead gate is
indistinguishable from a clean repository.
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
payload: |
{
"text": "CodeQL gate FAILED in flow {{ flow.id }} (execution {{ execution.id }}). Alerts were NOT assessed. Verify the GITHUB_TOKEN secret and code-scanning access on {{ inputs.repository }}."
}
outputs:
- id: verdict
type: STRING
description: Gate result, either pass or regression.
value: "{{ outputs.assess.vars.verdict }}"
- id: total_open
type: INT
description: Number of open code-scanning alerts of every severity.
value: "{{ outputs.assess.vars.total_open }}"
- id: new_high_critical
type: INT
description: Number of new high or critical alerts since the last clean baseline.
value: "{{ outputs.assess.vars.new_high_critical_count }}"
- id: new_alerts
type: JSON
description: Structured list of the new high and critical alerts with rule,
severity, path, and link.
value: "{{ outputs.assess.vars.new_high_critical }}"