id: github-actions-moved-tag-sentinel
namespace: company.platform
description: |
Daily check of every external GitHub Action a repository's workflows depend on.
Exact-version tags such as v4.1.1 are meant to be immutable, so a tag that now
points at a different commit than it did yesterday, or a SHA pin that no longer
matches the version named in its comment, is treated as a possible supply-chain
compromise and sent to Slack. Floating refs such as v4 or main are reported as
advisory only, because they are supposed to move.
inputs:
- id: repository
type: STRING
displayName: Repository to audit
description: Public GitHub repository whose workflows are scanned, in owner/repo form.
defaults: kestra-io/kestra
- id: scan_path
type: STRING
displayName: Path to scan
description: Directory inside the checkout searched recursively for workflow and
composite-action YAML files.
defaults: ".github"
- id: use_github_token
type: BOOL
displayName: Authenticate GitHub API calls
description: Anonymous calls are limited to 60 per hour per IP address. Turn
this on to use the GITHUB_TOKEN secret and raise the limit to 5000 per
hour.
defaults: false
- id: dry_run
type: BOOL
displayName: Dry run
description: Log the Slack alert instead of sending it, and keep the baseline
where it is so every dry run reports the same findings. Leave this on
until the findings look right.
defaults: true
variables:
baseline_key: "gha_tag_baseline_{{ inputs.repository | replace({'/': '_'}) }}"
triggers:
- id: daily
type: io.kestra.plugin.core.trigger.Schedule
description: A tag can be rewritten at any hour and the damage starts with the
next workflow run, so the check runs every day at 06:30 rather than only
when your own code changes.
cron: "30 6 * * *"
tasks:
- id: read_baseline
type: io.kestra.plugin.core.kv.Get
description: The commit each exact-version tag pointed at the last time this
flow delivered its findings. Missing on the first run, which is not an
error.
key: "{{ render(vars.baseline_key) }}"
errorOnMissing: false
- id: checkout_and_check
type: io.kestra.plugin.core.flow.WorkingDirectory
description: One directory so the checkout, the reference extraction and the tag
resolution all see the same files.
tasks:
- id: clone_repository
type: io.kestra.plugin.git.Clone
description: Shallow clone of the default branch.
url: "https://github.com/{{ inputs.repository }}.git"
- id: extract_refs
type: io.kestra.plugin.scripts.python.Script
description: >
Finds every uses: line that points at another repository and
classifies its ref. A full 40-character SHA is a pin, an exact
semantic version such as v4.1.1 is an immutable-by-convention tag, and
anything else (v4, v4.1, main) is floating. Local actions and
docker:// references are ignored. A scan_path that does not exist
fails the task, so a typo can never read as a clean repository.
taskRunner:
type: io.kestra.plugin.scripts.runner.docker.Docker
containerImage: python:3.12-slim
env:
SCAN_PATH: "{{ inputs.scan_path }}"
script: |
import json
import os
import re
import sys
scan_path = (os.environ.get("SCAN_PATH") or ".github").strip()
if not os.path.isdir(scan_path):
sys.exit("scan_path '{}' does not exist in the checkout.".format(scan_path))
USES = re.compile(r"""^\s*-?\s*uses:\s*["']?([^\s"'#]+)["']?\s*(?:#\s*(.*?))?\s*$""")
REF = re.compile(r"^([\w.-]+)/([\w.-]+)(/[^@]*)?@(\S+)$")
FULL_SHA = re.compile(r"^[0-9a-f]{40}$")
EXACT_TAG = re.compile(r"^v?\d+\.\d+\.\d+(?:[-+][\w.]+)?$")
COMMENT_TAG = re.compile(r"v?\d+(?:\.\d+){0,2}(?:-[\w.]+)?")
found = {}
files_scanned = 0
for folder, _dirs, files in os.walk(scan_path):
for name in sorted(files):
if not name.endswith((".yml", ".yaml")):
continue
files_scanned += 1
path = os.path.join(folder, name)
with open(path, encoding="utf-8", errors="ignore") as handle:
for line in handle:
match = USES.match(line.rstrip("\n"))
target = REF.match(match.group(1)) if match else None
if not target:
continue
repo = "{}/{}".format(target.group(1), target.group(2))
ref = target.group(4)
if FULL_SHA.match(ref):
kind = "sha"
hint = COMMENT_TAG.search((match.group(2) or "").strip())
comment_tag = hint.group(0) if hint else ""
else:
kind = "exact" if EXACT_TAG.match(ref) else "floating"
comment_tag = ""
entry = found.setdefault((repo, ref, comment_tag), {
"repo": repo, "ref": ref, "kind": kind,
"comment_tag": comment_tag, "files": set()})
entry["files"].add(path)
refs = [dict(e, files=sorted(e["files"])[:5]) for e in found.values()]
refs.sort(key=lambda e: (e["repo"], e["ref"]))
with open("refs.json", "w", encoding="utf-8") as handle:
json.dump(refs, handle)
counts = {k: sum(1 for e in refs if e["kind"] == k) for k in ("sha", "exact", "floating")}
print("scanned {} YAML file(s) under {}: {} distinct external reference(s) ({} SHA-pinned, {} exact tag, {} floating)".format(
files_scanned, scan_path, len(refs), counts["sha"], counts["exact"], counts["floating"]))
- id: check_refs
type: io.kestra.plugin.scripts.python.Script
description: >
Resolves refs against the GitHub commits API, which peels annotated
tags to the commit they point at. Only the refs that can be judged are
resolved: exact tags, compared with the baseline, and SHA pins whose
comment names an exact version, compared with the pin itself. A rate
limit or a missing tag leaves a ref unresolved and keeps its previous
baseline entry. If nothing that needed resolving could be resolved,
the task fails instead of reporting a clean check.
taskRunner:
type: io.kestra.plugin.scripts.runner.docker.Docker
containerImage: python:3.12-slim
env:
REPOSITORY: "{{ inputs.repository }}"
GITHUB_TOKEN: "{{ inputs.use_github_token ? secret('GITHUB_TOKEN') : '' }}"
inputFiles:
baseline.json: "{{ (outputs.read_baseline.value ?? '') | toJson }}"
script: |
import json
import os
import re
import sys
import urllib.error
import urllib.parse
import urllib.request
REPOSITORY = os.environ.get("REPOSITORY", "")
TOKEN = os.environ.get("GITHUB_TOKEN", "").strip()
EXACT_TAG = re.compile(r"^v?\d+\.\d+\.\d+(?:[-+][\w.]+)?$")
class RateLimited(Exception):
pass
def read_baseline():
try:
text = open("baseline.json", encoding="utf-8").read().strip()
data = json.loads(text) if text else {}
if isinstance(data, str):
data = json.loads(data)
except (OSError, ValueError):
data = {}
return data if isinstance(data, dict) else {}
def resolve(repo, ref):
url = "https://api.github.com/repos/{}/commits/{}".format(repo, urllib.parse.quote(ref, safe="/"))
headers = {"User-Agent": "kestra-gha-moved-tag-sentinel",
"Accept": "application/vnd.github+json",
"X-GitHub-Api-Version": "2022-11-28"}
if TOKEN:
headers["Authorization"] = "Bearer " + TOKEN
try:
with urllib.request.urlopen(urllib.request.Request(url, headers=headers), timeout=20) as response:
return json.load(response)["sha"]
except urllib.error.HTTPError as error:
if error.code in (404, 422):
return None
if error.code in (403, 429):
raise RateLimited("HTTP {} from GitHub".format(error.code))
raise
cache = {}
limited = []
def lookup(repo, ref):
key = (repo, ref)
if key not in cache:
if limited:
cache[key] = "unavailable"
else:
try:
cache[key] = resolve(repo, ref)
except RateLimited as error:
limited.append(str(error))
cache[key] = "unavailable"
return cache[key]
baseline = read_baseline()
previous = baseline.get("refs") if isinstance(baseline.get("refs"), dict) else {}
first_run = not previous
refs = json.load(open("refs.json", encoding="utf-8"))
rows, alerts = [], []
counts = {"tag_moved": 0, "pin_mismatch": 0, "unpinned_exact": 0, "unpinned_floating": 0,
"pinned_ok": 0, "unresolved": 0}
next_refs = {}
attempted = resolved = 0
def short(sha):
return (sha or "unknown")[:7]
for item in refs:
repo, ref, kind, tag = item["repo"], item["ref"], item["kind"], item["comment_tag"]
where = item["files"][0] + (" (+{} more)".format(len(item["files"]) - 1) if len(item["files"]) > 1 else "")
label = "{}@{}".format(repo, ref if kind != "sha" else short(ref))
if kind == "floating":
counts["unpinned_floating"] += 1
rows.append("| {} | UNPINNED_FLOATING | advisory: moves by design | {} |".format(label, where))
elif kind == "exact":
attempted += 1
now = lookup(repo, ref)
key = "{}@{}".format(repo, ref)
if now in (None, "unavailable"):
counts["unresolved"] += 1
if key in previous:
next_refs[key] = previous[key]
rows.append("| {} | UNRESOLVED | {} | {} |".format(
label, "tag not found" if now is None else "API unavailable", where))
continue
resolved += 1
next_refs[key] = now
was = previous.get(key)
if was and was != now:
counts["tag_moved"] += 1
alerts.append("TAG_MOVED `{}` was {} and now resolves to {} ({})".format(label, short(was), short(now), where))
rows.append("| {} | TAG_MOVED | {} -> {} | {} |".format(label, short(was), short(now), where))
else:
counts["unpinned_exact"] += 1
rows.append("| {} | UNPINNED_EXACT | resolves to {}, not moved | {} |".format(label, short(now), where))
else:
if not tag or not EXACT_TAG.match(tag):
counts["pinned_ok"] += 1
rows.append("| {} | PINNED | no exact version comment to verify | {} |".format(label, where))
continue
attempted += 1
names = [tag] if tag.startswith("v") else ["v" + tag, tag]
now = None
for name in names:
now = lookup(repo, name)
if now not in (None, "unavailable"):
break
if now in (None, "unavailable"):
counts["unresolved"] += 1
rows.append("| {} | UNRESOLVED | comment names {}, {} | {} |".format(
label, tag, "tag not found" if now is None else "API unavailable", where))
continue
resolved += 1
if now != ref:
counts["pin_mismatch"] += 1
alerts.append("PIN_MISMATCH `{}` is pinned to {} but its comment says {}, which now resolves to {} ({})".format(
repo, short(ref), tag, short(now), where))
rows.append("| {} | PIN_MISMATCH | tag {} now at {} | {} |".format(label, tag, short(now), where))
else:
counts["pinned_ok"] += 1
rows.append("| {} | PINNED_VERIFIED | {} matches | {} |".format(label, tag, where))
if attempted and not resolved:
sys.exit("None of the {} reference(s) that needed resolving could be resolved ({}). Not reporting a clean check.".format(
attempted, limited[0] if limited else "tags not found"))
shown = alerts[:20] + (["...and {} more".format(len(alerts) - 20)] if len(alerts) > 20 else [])
alert_text = ""
if alerts:
alert_text = ":rotating_light: *{} GitHub Actions reference(s) need attention in `{}`*\n{}".format(
len(alerts), REPOSITORY, "\n".join("• " + line for line in shown))
summary = "\n".join([
"{} external reference(s) in {}: {} tag moved, {} pin mismatch, {} exact tag unpinned, {} floating, {} pinned and fine, {} unresolved. First run: {}.".format(
len(refs), REPOSITORY, counts["tag_moved"], counts["pin_mismatch"], counts["unpinned_exact"],
counts["unpinned_floating"], counts["pinned_ok"], counts["unresolved"], first_run),
"| reference | status | detail | first file |",
"| --- | --- | --- | --- |",
] + rows)
print(summary)
print("::" + json.dumps({"outputs": {
"ref_count": len(refs),
"tag_moved_count": counts["tag_moved"],
"pin_mismatch_count": counts["pin_mismatch"],
"unpinned_count": counts["unpinned_exact"] + counts["unpinned_floating"],
"has_alerts": len(alerts) > 0,
"first_run": first_run,
"alert_text": alert_text,
"summary": summary,
"baseline_json": json.dumps({"refs": next_refs}, sort_keys=True),
}}) + "::")
- id: report
type: io.kestra.plugin.core.log.Log
description: The full status table, so a run with no alerts still shows what was
checked.
message: "{{ outputs.check_refs.vars.summary }}"
- id: alert
type: io.kestra.plugin.core.flow.If
description: Only moved exact tags and mismatched pins page anyone. Advisory
findings stay in the log.
condition: "{{ outputs.check_refs.vars.has_alerts }}"
then:
- id: delivery_mode
type: io.kestra.plugin.core.flow.If
condition: "{{ inputs.dry_run }}"
then:
- id: would_send
type: io.kestra.plugin.core.log.Log
message: |
DRY RUN would post this to Slack:
{{ outputs.check_refs.vars.alert_text }}
else:
- id: notify_slack
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
description: One message for the whole run, not one per finding.
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
payload: |
{{ {'text': outputs.check_refs.vars.alert_text} | toJson }}
- id: advance_baseline
type: io.kestra.plugin.core.kv.Set
description: Last task on purpose. In a live run the baseline only advances
after the alert was delivered, so a failed Slack call repeats the alert
next run instead of swallowing it. A dry run advances it only on the very
first run, so repeated dry runs keep reporting the same findings.
runIf: "{{ (not inputs.dry_run) or outputs.check_refs.vars.first_run }}"
key: "{{ render(vars.baseline_key) }}"
kvType: JSON
overwrite: true
value: "{{ outputs.check_refs.vars.baseline_json }}"
errors:
- id: baseline_untouched
type: io.kestra.plugin.core.log.Log
level: ERROR
message: "Moved-tag check failed for {{ inputs.repository }} in execution {{
execution.id }}. The baseline under {{ render(vars.baseline_key) }} was
not advanced, so the next run compares against the same state. Do not read
this run as a clean check."
outputs:
- id: ref_count
type: INT
description: Distinct external action references found, e.g. 24.
value: "{{ outputs.check_refs.vars.ref_count }}"
- id: tag_moved_count
type: INT
description: Exact-version tags that now point at a different commit, e.g. 0.
value: "{{ outputs.check_refs.vars.tag_moved_count }}"
- id: pin_mismatch_count
type: INT
description: SHA pins whose version comment resolves to a different commit, e.g. 0.
value: "{{ outputs.check_refs.vars.pin_mismatch_count }}"
- id: unpinned_count
type: INT
description: References not pinned to a full SHA, exact or floating, e.g. 18.
value: "{{ outputs.check_refs.vars.unpinned_count }}"