id: github-actions-unpinned-action-audit
namespace: company.team
description: |
Clone a repository, find every GitHub Actions step and reusable workflow that references a
third-party action by a mutable tag or branch instead of a full commit SHA, resolve the commit each
reference points to today, and post the exact pinned lines to Slack. Only new findings are posted.
inputs:
- id: git_url
type: STRING
displayName: Repository
description: HTTPS URL of the repository whose workflows should be audited.
defaults: https://github.com/kestra-io/blueprints
- id: branch
type: STRING
displayName: Branch
defaults: main
- id: trusted_owners
type: JSON
displayName: Trusted owners
description: Action owners that may stay on tags, for example GitHub's own
actions or your organization. Use [] to require SHAs everywhere.
defaults: '["actions", "github"]'
tasks:
- id: audit
type: io.kestra.plugin.core.flow.WorkingDirectory
description: Clone and scan in the same working directory.
tasks:
- id: clone
type: io.kestra.plugin.git.Clone
description: Shallow checkout of the branch. Add username and password for a
private repository.
url: "{{ inputs.git_url }}"
branch: "{{ inputs.branch }}"
depth: 1
- id: find_unpinned
type: io.kestra.plugin.scripts.python.Script
description: List every `uses:` reference in workflows and composite actions
that is not pinned to a 40-character commit SHA.
containerImage: python:3.12-slim
script: |
import json
import pathlib
import re
trusted = {o.lower() for o in json.loads('{{ inputs.trusted_owners | toJson }}')}
USES = re.compile(r"""^\s*(?:-\s*)?uses:\s*["']?([^"'\s#]+)""")
SHA = re.compile(r"^[0-9a-f]{40}$")
files = sorted(pathlib.Path(".github/workflows").glob("*.y*ml"))
files += sorted(pathlib.Path(".").glob("**/action.y*ml"))
findings, scanned = [], 0
for path in files:
for number, line in enumerate(path.read_text(encoding="utf-8", errors="replace").splitlines(), 1):
match = USES.match(line)
if not match:
continue
scanned += 1
ref = match.group(1)
if ref.startswith("./"):
continue
if ref.startswith("docker://"):
if "@sha256:" not in ref:
findings.append({"file": str(path), "line": number, "uses": ref, "kind": "docker",
"action": ref, "ref": ""})
continue
if "@" not in ref:
continue
action, version = ref.rsplit("@", 1)
owner_repo = "/".join(action.split("/")[:2])
if SHA.match(version) or owner_repo.split("/")[0].lower() in trusted:
continue
findings.append({"file": str(path), "line": number, "uses": ref, "kind": "action",
"action": action, "owner_repo": owner_repo, "ref": version})
print(f"{len(files)} workflow files, {scanned} uses references, {len(findings)} not pinned to a SHA")
print("::" + json.dumps({"outputs": {"findings": findings, "count": len(findings)}}) + "::")
- id: load_known
type: io.kestra.plugin.core.kv.Get
description: Findings already reported for this repository.
key: "unpinned_actions_{{ inputs.git_url | slugify }}"
errorOnMissing: false
- id: resolve_shas
type: io.kestra.plugin.scripts.python.Script
description: Resolve each tag or branch to the commit it points to today through
the GitHub API, and keep only findings not reported before.
containerImage: python:3.12-slim
env:
GITHUB_TOKEN: "{{ secret('GITHUB_TOKEN') }}"
inputFiles:
findings.json: "{{ outputs.find_unpinned.vars.findings | toJson }}"
known.json: "{{ (outputs.load_known.value ?? []) | toJson }}"
outputFiles:
- pin-suggestions.txt
script: |
import json
import os
import urllib.error
import urllib.request
def load(name):
with open(name, encoding="utf-8") as f:
data = json.load(f)
return json.loads(data) if isinstance(data, str) else data
findings = load("findings.json")
known = set(load("known.json") or [])
def resolve(owner_repo, ref, cache={}):
key = f"{owner_repo}@{ref}"
if key not in cache:
request = urllib.request.Request(
f"https://api.github.com/repos/{owner_repo}/commits/{ref}",
headers={"Accept": "application/vnd.github.sha", "User-Agent": "Kestra-Actions-Audit"})
request.add_header("Authorization", f"Bearer {os.environ['GITHUB_TOKEN']}")
try:
with urllib.request.urlopen(request, timeout=20) as response:
cache[key] = response.read().decode().strip()
except urllib.error.HTTPError as error:
if error.code in (401, 403):
raise SystemExit(f"GitHub API returned {error.code}: check GITHUB_TOKEN or the rate limit.")
cache[key] = None
return cache[key]
fingerprints, fresh, lines = [], [], []
for f in findings:
fingerprint = f"{f['file']}|{f['uses']}"
fingerprints.append(fingerprint)
if f["kind"] == "action":
sha = resolve(f["owner_repo"], f["ref"])
f["pinned"] = f"{f['action']}@{sha} # {f['ref']}" if sha else None
else:
f["pinned"] = None
if f["pinned"]:
lines.append(f"{f['file']}:{f['line']}\n - uses: {f['uses']}\n + uses: {f['pinned']}\n")
else:
lines.append(f"{f['file']}:{f['line']}\n ! {f['uses']} (pin by digest or remove; ref not found)\n")
if fingerprint not in known:
fresh.append(f)
with open("pin-suggestions.txt", "w", encoding="utf-8") as out:
out.write("\n".join(lines) or "Every third-party reference is pinned to a commit SHA.\n")
print(f"{len(findings)} unpinned references, {len(fresh)} not reported before")
print("::" + json.dumps({"outputs": {
"fresh": fresh[:25],
"fresh_count": len(fresh),
"total": len(findings),
"fingerprints": sorted(set(fingerprints)),
}}) + "::")
- id: if_new_findings
type: io.kestra.plugin.core.flow.If
description: Post only when references appeared that were not reported before.
condition: "{{ outputs.resolve_shas.vars.fresh_count > 0 }}"
then:
- id: alert_slack
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
description: List the new unpinned references with the line that pins them.
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
messageText: |
:lock: *{{ outputs.resolve_shas.vars.fresh_count }} new GitHub Actions reference(s) not pinned to a commit SHA* in {{ inputs.git_url }} ({{ inputs.branch }}), {{ outputs.resolve_shas.vars.total }} in total.
{% for f in outputs.resolve_shas.vars.fresh %}
`{{ f.file }}:{{ f.line }}` `{{ f.uses }}`{% if f.pinned is not null %}
> pin as `{{ f.pinned }}`{% else %}
> could not resolve; pin it by digest or replace it{% endif %}
{% endfor %}
Full list with replacements: execution {{ execution.id }}, output file `pin-suggestions.txt`.
- id: remember_findings
type: io.kestra.plugin.core.kv.Set
description: Store the current findings, so fixed references drop out and only
new ones are posted. Runs after the alert.
key: "unpinned_actions_{{ inputs.git_url | slugify }}"
kvType: JSON
overwrite: true
value: "{{ outputs.resolve_shas.vars.fingerprints | toJson }}"
errors:
- id: alert_failure
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
description: A failed audit must not look like a clean repository.
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
messageText: ":warning: GitHub Actions pinning audit for {{ inputs.git_url }}
failed in execution {{ execution.id }} ({{ flow.namespace }}.{{ flow.id
}}). The clone may have failed, or GITHUB_TOKEN may be invalid."
triggers:
- id: daily
type: io.kestra.plugin.core.trigger.Schedule
description: Audit every morning. Disabled until the secrets are set.
cron: "0 7 * * *"
disabled: true