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
4 changes: 2 additions & 2 deletions .github/actionlint.yaml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
paths:
.github/workflows/shared-checks.yml:
.github/workflows/shared-*.yml:
ignore:
# Callers in other repositories must reach this repository's action at the commit they pinned, which only the $/ self-repository syntax does; actionlint predates it.
# Callers in other repositories must reach this repository's actions at the commit they pinned, which only the $/ self-repository syntax does; actionlint predates it.
- specifying action "\$/
100 changes: 100 additions & 0 deletions .github/actions/docker-build/action.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
name: Docker build

description: Checks out the repository and builds one image for ghcr.io with the studio's tags, labels and build arguments, pushing it when asked.

inputs:
repository:
description: The <owner>/<repo> the image is named after; a repository whose name starts with a dot, like .github, needs another.
default: ${{ github.repository }}

component:
description: Name appended to the image, as in ghcr.io/<owner>/<repo>/<component>; empty for ghcr.io/<owner>/<repo>.
default: ""

context:
description: Build context.
default: .

file:
description: Dockerfile path; empty for the context's Dockerfile.
default: ""

push:
description: Push the image, "true" or "false".
required: true

version:
description: Passed to the build as VERSION.
required: true

revision:
description: Passed to the build as REVISION.
required: true

build-args:
description: Extra build arguments, one KEY=value per line.
default: ""

sentry-auth-token:
description: Exposed to the build as the BuildKit secret SENTRY_AUTH_TOKEN when not empty.
default: ""

outputs:
image:
description: The image name, lowercased.
value: ${{ steps.image.outputs.name }}

digest:
description: The image digest.
value: ${{ steps.build.outputs.digest }}

runs:
using: composite
steps:
- name: Check out
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false

# metadata-action lowercases the name itself, actions/attest does not.
- name: Name the image
id: image
shell: bash
env:
REPOSITORY: ${{ inputs.repository }}
COMPONENT: ${{ inputs.component }}
run: echo "name=ghcr.io/${REPOSITORY,,}${COMPONENT:+/${COMPONENT,,}}" >> "$GITHUB_OUTPUT"

- name: Set up Docker Buildx
uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1

- name: Extract Docker metadata
id: meta
uses: docker/metadata-action@dc802804100637a589fabce1cb79ff13a1411302 # v6.2.0
with:
images: ${{ steps.image.outputs.name }}
tags: |
type=ref,event=branch
type=ref,event=pr
type=semver,pattern={{version}}
type=semver,pattern={{major}}.{{minor}}

- name: Build the image
id: build
uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0
with:
context: ${{ inputs.context }}
file: ${{ inputs.file }}
push: ${{ inputs.push }}
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
build-args: |
VERSION=${{ inputs.version }}
REVISION=${{ inputs.revision }}
${{ inputs.build-args }}
secrets: ${{ inputs.sentry-auth-token && format('SENTRY_AUTH_TOKEN={0}', inputs.sentry-auth-token) || '' }}
cache-from: type=gha,scope=${{ steps.image.outputs.name }}
cache-to: type=gha,mode=max,scope=${{ steps.image.outputs.name }}
# BuildKit's own attestations would push untagged "unknown/unknown" manifests to ghcr; the caller attests instead.
provenance: false
sbom: false
118 changes: 118 additions & 0 deletions .github/workflows/shared-publish.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
name: Shared publish

on:
workflow_call:
inputs:
images:
description: JSON list of the images to build, each with a component (empty for the repository's own name), a context and an optional file.
type: string
default: |
[{"component": "", "context": "."}]

build-args:
description: Extra build arguments, one KEY=value per line, after the standard VERSION and REVISION.
type: string
default: ""

secrets:
sentry-auth-token:
description: Exposed to tag builds as the BuildKit secret SENTRY_AUTH_TOKEN.
required: false

outputs:
version:
description: The version the images were built with.
value: ${{ jobs.version.outputs.version }}

permissions:
contents: read

defaults:
run:
shell: bash

jobs:
version:
name: Version
runs-on: ubuntu-latest
timeout-minutes: 5
outputs:
version: ${{ steps.version.outputs.version }}
revision: ${{ steps.version.outputs.revision }}
steps:
# Sentry parses the version as semver, which has no leading v.
- name: Resolve the version
id: version
env:
SHA: ${{ github.event.pull_request.head.sha || github.sha }}
run: |
revision=${SHA:0:7}
if [ "$GITHUB_REF_TYPE" = tag ]; then version=${GITHUB_REF_NAME#v}; else version=0.0.0+$revision; fi
printf 'version=%s\nrevision=%s\n' "$version" "$revision" >> "$GITHUB_OUTPUT"

build:
name: ${{ matrix.component && format('Build ({0})', matrix.component) || 'Build' }}
needs: version
if: github.event_name == 'pull_request'
runs-on: ubuntu-latest
timeout-minutes: 30
strategy:
fail-fast: false
matrix:
include: ${{ fromJSON(inputs.images) }}
steps:
- name: Build the image
uses: $/.github/actions/docker-build
with:
component: ${{ matrix.component }}
context: ${{ matrix.context }}
file: ${{ matrix.file }}
push: "false"
version: ${{ needs.version.outputs.version }}
revision: ${{ needs.version.outputs.revision }}
build-args: ${{ inputs.build-args }}

publish:
name: ${{ matrix.component && format('Publish ({0})', matrix.component) || 'Publish' }}
needs: version
if: github.event_name != 'pull_request'
runs-on: ubuntu-latest
timeout-minutes: 30
permissions:
contents: read
packages: write
# Mint the OIDC token and write the build provenance attestation.
id-token: write
attestations: write
strategy:
fail-fast: false
matrix:
include: ${{ fromJSON(inputs.images) }}
steps:
- name: Log in to ghcr.io
uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}

- name: Build and push the image
id: build
uses: $/.github/actions/docker-build
with:
component: ${{ matrix.component }}
context: ${{ matrix.context }}
file: ${{ matrix.file }}
push: "true"
version: ${{ needs.version.outputs.version }}
revision: ${{ needs.version.outputs.revision }}
build-args: ${{ inputs.build-args }}
sentry-auth-token: ${{ github.ref_type == 'tag' && secrets.sentry-auth-token || '' }}

- name: Attest build provenance
uses: actions/attest@1e69f48acb82d1966a394da916b4c1698aa569d6 # v4.2.2
with:
subject-name: ${{ steps.build.outputs.image }}
subject-digest: ${{ steps.build.outputs.digest }}
# Pushing to ghcr would add an untagged referrer artifact.
push-to-registry: false
25 changes: 25 additions & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,31 @@ jobs:
- name: Run tests
run: node --test "scripts/*.test.mjs"

docker-build:
name: Docker build
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- name: Check out
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false

- name: Build the test image
id: build
uses: ./.github/actions/docker-build
with:
repository: BSStudio/Docker-Build-Test
context: test/docker-build
push: "false"
version: 0.0.0+test
revision: test

- name: Check the image name
env:
IMAGE: ${{ steps.build.outputs.image }}
run: test "$IMAGE" = ghcr.io/bsstudio/docker-build-test

licence-policy:
name: Licence policy
if: github.event_name == 'pull_request'
Expand Down
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,4 +41,6 @@ Security features (secret scanning, push protection, Dependabot alerts, CodeQL d

Every workflow follows one convention, written down in [`docs/workflows.md`](docs/workflows.md). Each repo enforces it with a `.github/workflows/checks.yml` that calls `.github/workflows/shared-checks.yml` here (the copyable caller is in the convention): `Checks / Workflows` runs actionlint, zizmor and `scripts/check-workflows.mjs` over the repo's workflows and composite actions, and `Checks / Dependencies` reviews new dependencies for vulnerabilities and licences in repos that turn it on. Wherever a ruleset exists it requires `Checks / Workflows`, plus `Checks / Dependencies` where the review is on.

Callers pin a tagged release of this repo; Renovate proposes each new release. The licence policy in `.github/dependency-review.yml` is the exception: `Checks / Dependencies` reads it from `main`, so allowing a licence or exempting a package needs no release. The `Licence policy` check runs each PR's version of the file here first. The checks run from the same commit as the workflow that calls them: `shared-checks.yml` reaches its composite action through the `$/` self-repository syntax.
Repos that publish Docker images call `.github/workflows/shared-publish.yml` from their `docker-publish.yml` (caller in the convention). Pull requests only build; every other event pushes to ghcr.io with a provenance attestation. The image version comes from the tag, or is `0.0.0+<commit>` without one, and source maps go to Sentry on tag builds only. The `Docker build` job in `test.yml` builds a throwaway image through its composite action, `.github/actions/docker-build`.

Callers pin a tagged release of this repo; Renovate proposes each new release. The licence policy in `.github/dependency-review.yml` is the exception: `Checks / Dependencies` reads it from `main`, so allowing a licence or exempting a package needs no release. The `Licence policy` check runs each PR's version of the file here first. Each shared workflow runs its composite action from its own commit, which it reaches through the `$/` self-repository syntax.
57 changes: 56 additions & 1 deletion docs/workflows.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ Every GitHub Actions workflow and composite action in the studio's repositories

- A workflow grants no more than reading by default: `permissions` is always set at the top, normally to `contents: read`.
- Write scopes go on the one job that needs them (review).
- No code from a pull request runs with a write scope (review). A job that runs on pull requests holds one only if every step that uses it is skipped on pull requests, or if the job checks nothing out and its steps are pinned actions that act on the pull request itself. The first case covers today's single build-and-push jobs of the publish workflows, until they move to a shared publish workflow that splits building from pushing; the second covers labeling pull requests.
- No code from a pull request runs with a write scope (review). A job that runs on pull requests holds one only if it checks nothing out and its steps are pinned actions that act on the pull request itself, such as labeling it. A job that calls a reusable workflow sets the most the called jobs may hold, and the rule applies to those jobs.
- Secrets are passed only on events other than `pull_request`, except upload tokens that can only add reports, such as Codecov's (review).
- Checkouts set `persist-credentials: false`; a job that pushes keeps the credentials and says why in a comment (the comment: review).
- Every action is pinned by its full commit SHA with the release in a comment, `@<sha> # vX.Y.Z` (the comment: review). Renovate keeps the pins current.
Expand Down Expand Up @@ -47,6 +47,8 @@ Every GitHub Actions workflow and composite action in the studio's repositories

The same rules apply to `action.yml` files, except that GitHub requires `shell` on every `run` step there. actionlint does not read `action.yml` files, so scripts in composite actions get no shellcheck: they stay at one command or move into a script file (review).

A reusable workflow reaches its own actions with `$/`, not `./`: in a called workflow a `./` action resolves against the caller's checkout.

## Calling the shared checks

Every repository runs the checks through the reusable workflow in this repository, from a `.github/workflows/checks.yml` like this:
Expand Down Expand Up @@ -78,6 +80,59 @@ jobs:
- `dependency-review: true` adds the dependency review for repositories with package manifests. It works on public repositories only and checks every new or changed dependency for known vulnerabilities and for a licence outside the licence policy in `.github/dependency-review.yml`. Without the input the `Dependencies` job is skipped, which still satisfies a required check.
- The pin follows this repository's releases: Renovate proposes each new release in every caller, and that pull request runs the new checks against the repository before anything merges. The licence policy is the exception: every caller reads it from this repository's `main`, so a change to it applies on the next run, and re-running a failed `Checks / Dependencies` picks it up.

## Calling the shared publish workflow

Every repository that publishes Docker images to ghcr.io builds them through `.github/workflows/shared-publish.yml` in this repository, from a `.github/workflows/docker-publish.yml` like this:

```yaml
name: Docker

on:
push:
branches: [main]
tags: ["v*.*.*"]
pull_request:
branches: [main]
workflow_dispatch:

permissions:
contents: read

concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}

jobs:
docker:
name: Docker
uses: BSStudio/.github/.github/workflows/shared-publish.yml@<release commit SHA> # vX.Y.Z
permissions:
contents: read
packages: write
id-token: write
attestations: write
secrets:
sentry-auth-token: ${{ github.ref_type == 'tag' && secrets.SENTRY_AUTH_TOKEN || '' }}
```

- On pull requests a `Build` job builds every image with `contents: read` and no secrets, and pushes nothing. On every other event a `Publish` job builds, pushes and attests; it needs the write scopes the caller grants.
- The image is `ghcr.io/<owner>/<repository>`, lowercased. A repository with several images lists them in `images`, each named `ghcr.io/<owner>/<repository>/<component>`; an entry takes `file` for a Dockerfile other than the context's own. The list is a block scalar, since the convention has no flow maps:

```yaml
with:
images: |
[
{"component": "backend", "context": "backend"},
{"component": "frontend", "context": "frontend"}
]
```

- Tags are the branch name, `pr-<number>` (never pushed), and `X.Y.Z` and `X.Y` for a `vX.Y.Z` tag.
- Every build gets the build arguments `VERSION` and `REVISION`, and the Dockerfile declares the ones it uses. `REVISION` is the commit's first seven characters (the pull request's head commit on pull requests); `VERSION` is the tag without its `v` on a tag, otherwise `0.0.0+<REVISION>`. A local build gets neither, so the `ARG` default applies. `build-args` adds more, one `KEY=value` per line. The `version` output passes the version to the caller's later jobs.
- Only tag builds get the Sentry token, as the BuildKit secret `SENTRY_AUTH_TOKEN`. Other builds run without it, so the Dockerfile's secret mount must not be `required`. The caller passes the token on tags only as well, which keeps it off pull request runs.
- Each pushed image gets a build provenance attestation, kept in GitHub's attestation store and signed by this repository's workflow. Verify it with `gh attestation verify oci://<image> --owner <owner>`, adding `--signer-repo BSStudio/.github` when the owner is not BSStudio.
- The pin follows this repository's releases, as for the shared checks.

## Running the checks locally

From a repository's root, with actionlint and zizmor installed and this repository cloned next to it:
Expand Down
6 changes: 6 additions & 0 deletions scripts/workflow-style.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,12 @@ function checkWorkflowRules(root, kinds, report) {
if (!child(job, "timeout-minutes") && !child(job, "uses")) report(job.line, `job "${job.key}" has no timeout-minutes`);
checkSteps(child(job, "steps"), kinds, report, { allowShell: false, afterServices: checkServices(job, kinds, report) });
});

// In a called workflow a ./ action resolves against the caller's checkout; a ./ workflow resolves against the called workflow's commit.
if (child(on, "workflow_call")) {
const uses = jobs.flatMap((job) => (child(job, "steps")?.children ?? []).map((step) => child(step, "uses")));
for (const node of uses) if (unquoted(node?.value)?.startsWith("./")) report(node.line, "a reusable workflow reaches its own actions with $/, not ./");
}
}

export function checkWorkflow(text, path) {
Expand Down
15 changes: 15 additions & 0 deletions scripts/workflow-style.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -342,6 +342,21 @@ test("comments do not affect spacing or order", () => {
assert.deepEqual(check(text), []);
});

// Lines 1–9; the first job starts on line 10.
const reusable = (...jobLines) =>
doc("name: Shared", "", "on:", " workflow_call:", "", "permissions:", " contents: read", "", "jobs:", ...jobLines);

test("reusable workflow reaches its own actions with $/", () => {
const stepUses = reusable(job, " - name: Build", " uses: ./.github/actions/x");
assert.deepEqual(check(stepUses), [{ line: 16, message: "a reusable workflow reaches its own actions with $/, not ./" }]);
});

test("./ actions stay allowed outside reusable workflows, $/ inside them, and ./ for nested workflows", () => {
assert.deepEqual(check(doc(header, job, " - name: Build", " uses: ./.github/actions/x")), []);
assert.deepEqual(check(reusable(job, " - name: Build", ' uses: "$/.github/actions/x"')), []);
assert.deepEqual(check(reusable(" call:", " name: Call", " uses: ./.github/workflows/y.yml")), []);
});

test("reusable-workflow jobs and composite actions are exempt where GitHub requires it", () => {
const caller = doc(header, " checks:", " name: Checks", " uses: BSStudio/.github/.github/workflows/shared-checks.yml@3d3c42e5aac5ba805825da76410c181273ba90b1 # v1.0.0", " with:", " dependency-review: true");
assert.deepEqual(check(caller), []);
Expand Down
3 changes: 3 additions & 0 deletions test/docker-build/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
FROM scratch
ARG VERSION
LABEL test.version=$VERSION