Skip to content
Open
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
10 changes: 10 additions & 0 deletions .github/dependabot.yml
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,13 @@ updates:
directory: "/" # Location of package manifests
schedule:
interval: "daily"
groups:
codeql:
applies-to: version-updates
patterns:
- "github/codeql-action"
- "github/codeql-action/*"
- package-ecosystem: "uv"
directory: "/.github/format-tools"
schedule:
interval: "weekly"
8 changes: 8 additions & 0 deletions .github/format-tools/pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
[project]
name = "action-workflow-setup-format-tools"
version = "0.0.0"
requires-python = "==3.12.*"
dependencies = ["uv==0.12.1", "yamllint==1.38.0", "pyyaml==6.0.3"]

[tool.uv]
package = false
86 changes: 86 additions & 0 deletions .github/format-tools/uv.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

43 changes: 37 additions & 6 deletions .github/workflows/ci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ on:
permissions:
contents: read
pull-requests: read
security-events: write

jobs:
setup:
Expand Down Expand Up @@ -61,6 +60,7 @@ jobs:
persist-credentials: false
- uses: raven-actions/actionlint@3d39aea434753780c3b3d4a1a31c854b4dbf49d7 # v2
with:
version: "1.7.12"
# Pass explicit file globs so actionlint does not need to discover
# the project root from GITHUB_WORKSPACE (which doesn't contain
# .github/workflows/ when checkout used a path: subdirectory).
Expand All @@ -82,13 +82,24 @@ jobs:
path: ${{ needs.setup.outputs.checkout_path }}
repository: ${{ needs.setup.outputs.repo }}
persist-credentials: false
- name: Checkout trusted format tools
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
repository: ${{ github.repository }}
ref: ${{ github.workflow_sha }}
path: workflow-tools
sparse-checkout: .github/format-tools
persist-credentials: false
- name: Install uv
uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3
- name: Install yamllint
run: uv tool install yamllint
with:
python-version: "3.12"
version-file: workflow-tools/.github/format-tools/pyproject.toml
- name: Run yamllint
working-directory: ${{ needs.setup.outputs.checkout_path }}
run: yamllint .
run: >-
uv run --project "$GITHUB_WORKSPACE/workflow-tools/.github/format-tools"
--locked --no-build yamllint .

guardrail-test:
needs: setup
Expand All @@ -101,9 +112,24 @@ jobs:
path: ${{ needs.setup.outputs.checkout_path }}
repository: ${{ needs.setup.outputs.repo }}
persist-credentials: false
- name: Test guardrail alert logic
- name: Checkout trusted test tools
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
repository: ${{ github.repository }}
ref: ${{ github.workflow_sha }}
path: workflow-tools
sparse-checkout: .github/format-tools
persist-credentials: false
- name: Install uv
uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3
with:
python-version: "3.12"
version-file: workflow-tools/.github/format-tools/pyproject.toml
- name: Test action logic
working-directory: ${{ needs.setup.outputs.checkout_path }}
run: python3 -m unittest discover -s tests -p 'test_guardrail_audit_alert.py' -v
run: >-
uv run --project "$GITHUB_WORKSPACE/workflow-tools/.github/format-tools"
--locked --no-build python3 -m unittest discover -s tests -v

markdown-check:
needs: setup
Expand All @@ -128,6 +154,11 @@ jobs:

codeql:
needs: setup
permissions:
actions: read
contents: read
pull-requests: read
security-events: write
if: >
always() && needs.setup.result == 'success' && (
github.event_name != 'pull_request' ||
Expand Down
6 changes: 6 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -47,3 +47,9 @@ repos:
hooks:
- id: markdownlint-cli2
args: [--fix]
- repo: https://github.com/rhysd/actionlint
rev: v1.7.12
hooks:
- id: actionlint
entry: bash scripts/pre-commit/actionlint.sh
verbose: true
9 changes: 9 additions & 0 deletions scripts/pre-commit/actionlint.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
#!/usr/bin/env bash
set -euo pipefail

if [[ "$(uname -s)" == Darwin ]]; then
printf '%s\n' "actionlint: ShellCheck skipped on Darwin due to actionlint's pipe deadlock; CI runs it on Linux." >&2
exec actionlint -shellcheck= "$@"
fi

exec actionlint "$@"
105 changes: 105 additions & 0 deletions tests/test_codeql_pins.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
"""Verify that coupled CodeQL actions stay on one immutable release."""

from __future__ import annotations

import re
import unittest
from pathlib import Path

import yaml
from yaml.constructor import ConstructorError
from yaml.nodes import MappingNode


class UniqueKeyLoader(yaml.SafeLoader):
"""Reject duplicate explicit keys while retaining YAML merge semantics."""


def construct_unique_mapping(
loader: UniqueKeyLoader, node: MappingNode, deep: bool = False
) -> dict[object, object]:
"""Reject repeated explicit keys before constructing a mapping."""
keys: set[object] = set()
for key_node, _ in node.value:
if key_node.tag == "tag:yaml.org,2002:merge":
continue
key = loader.construct_object(key_node, deep=deep)
if key in keys:
raise ConstructorError(
"while constructing a mapping",
node.start_mark,
f"duplicate key {key!r}",
key_node.start_mark,
)
keys.add(key)
return yaml.SafeLoader.construct_mapping(loader, node, deep=deep)


UniqueKeyLoader.add_constructor(
yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, construct_unique_mapping
)


def codeql_references(content: str) -> list[str]:
"""Collect CodeQL action references from parsed workflow step mappings."""
workflow = yaml.load(content, Loader=UniqueKeyLoader)
jobs = workflow.get("jobs", {}) if isinstance(workflow, dict) else {}
return [
step["uses"]
for job in jobs.values()
if isinstance(job, dict)
for step in job.get("steps", [])
if isinstance(step, dict)
and isinstance(step.get("uses"), str)
and step["uses"].startswith("github/codeql-action/")
]


def has_one_immutable_release(references: list[str]) -> bool:
"""Require init, analyze, and every CodeQL reference to share one full SHA."""
parsed = [
reference.removeprefix("github/codeql-action/").partition("@") for reference in references
]
return (
{name for name, separator, _ in parsed if separator} >= {"init", "analyze"}
and all(separator and re.fullmatch(r"[0-9a-f]{40}", sha) for _, separator, sha in parsed)
and len({sha for _, _, sha in parsed}) == 1
)


class CodeQLPinTests(unittest.TestCase):
"""Reject independent component updates and mutable CodeQL references."""

def test_one_immutable_release(self) -> None:
"""Require init, analyze, and any other CodeQL actions to share a commit."""
directory = Path(__file__).resolve().parents[1] / ".github/workflows"
files = [*directory.glob("*.yaml"), *directory.glob("*.yml")]
references = [
reference for path in files for reference in codeql_references(path.read_text())
]
self.assertTrue(has_one_immutable_release(references))

def test_flow_mappings_are_checked_and_run_text_is_ignored(self) -> None:
"""Parse real step values regardless of YAML layout."""
sha = "a" * 40
content = f"""jobs:
scan:
steps:
- {{uses: github/codeql-action/init@{sha}}}
- "uses": github/codeql-action/analyze@{sha}
- {{uses: github/codeql-action/upload-sarif@v4}}
- run: |
uses: github/codeql-action/ignored@v4
"""
references = codeql_references(content)
self.assertEqual(len(references), 3)
self.assertFalse(has_one_immutable_release(references))

def test_duplicate_mapping_keys_are_rejected(self) -> None:
"""Duplicate YAML keys cannot hide a mutable action reference."""
with self.assertRaises(ConstructorError):
codeql_references(
"jobs:\n scan:\n steps:\n"
" - uses: github/codeql-action/init@v4\n"
" uses: github/codeql-action/init@" + "a" * 40 + "\n"
)
Loading