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
85 changes: 85 additions & 0 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
name: Publish release

on:
workflow_dispatch:
inputs:
version:
description: "Stable SemVer version without the v prefix (for example, 1.2.3)"
required: true
type: string

concurrency:
group: publish-release
cancel-in-progress: false

permissions: {}

jobs:
validate:
name: Validate release request
runs-on: ubuntu-latest
timeout-minutes: 5
permissions:
contents: read
env:
GH_TOKEN: ${{ github.token }}
RELEASE_VERSION: ${{ inputs.version }}
steps:
- name: Validate version and selected branch
shell: bash
run: |
set -euo pipefail

if [[ "$GITHUB_REF" != "refs/heads/main" ]]; then
echo "Error: run this workflow from the main branch only." >&2
exit 1
fi

if [[ ! "$RELEASE_VERSION" =~ ^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$ ]]; then
echo "Error: version must be stable SemVer without v (for example, 1.2.3)." >&2
exit 1
fi

main_sha="$(gh api "repos/${GITHUB_REPOSITORY}/git/ref/heads/main" --jq '.object.sha')"
if [[ "$GITHUB_SHA" != "$main_sha" ]]; then
echo "Error: the selected commit is no longer the current main HEAD." >&2
exit 1
fi

publish:
name: Create tag and release
needs: validate
runs-on: ubuntu-latest
timeout-minutes: 5
permissions:
contents: write
env:
GH_TOKEN: ${{ github.token }}
RELEASE_VERSION: ${{ inputs.version }}
steps:
- name: Create a new version tag and publish its release
shell: bash
run: |
set -euo pipefail

# Recheck immediately before writing, including after any queued run.
if [[ "$GITHUB_REF" != "refs/heads/main" ]]; then
echo "Error: releases must originate from main." >&2
exit 1
fi

main_sha="$(gh api "repos/${GITHUB_REPOSITORY}/git/ref/heads/main" --jq '.object.sha')"
if [[ "$GITHUB_SHA" != "$main_sha" ]]; then
echo "Error: main moved after this workflow was requested. Start a new run." >&2
exit 1
fi

tag="v${RELEASE_VERSION}"

# GitHub rejects an already existing ref, rather than reusing or moving a tag.
gh api --method POST "repos/${GITHUB_REPOSITORY}/git/refs" \
-f ref="refs/tags/${tag}" \
-f sha="$GITHUB_SHA" >/dev/null

# Do not allow gh to implicitly create a tag or attach to a different ref.
gh release create "$tag" --verify-tag --title "$tag" --generate-notes
3 changes: 3 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,9 @@ Do not add `Directory.Build.props`, `Directory.Packages.props`, project files, o
- Keep zizmor offline in CI and do not grant scanner-specific tokens or write permissions. Treat scanner exceptions as narrow, documented policy decisions rather than blanket suppressions.
- Preserve push path filters, concurrency cancellation, and bounded job timeouts unless a concrete requirement justifies changing them; pull requests targeting `main` must not use path filters because the stable required checks must always be reported.

- Keep manual release publishing restricted to the current `main` commit and new stable SemVer tags; never reuse, force-move, or delete an existing release tag. Only the release job may request `contents: write`.
- The immutable-tag ruleset is distributed separately as `immutable-tags.json` and is not stored in this repository; it requires a separate administrative action. Protect all tags from update/deletion without restricting first creation, and do not register bypass actors.

## Trust boundaries for repository-aware .NET commands

- Do not treat a checkout as trusted merely because it is a Git repository or because its files are readable.
Expand Down
3 changes: 3 additions & 0 deletions AGENTS.pt-BR.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,9 @@ Não adicione `Directory.Build.props`, `Directory.Packages.props`, arquivos de p
- Mantenha o zizmor offline no CI e não conceda tokens específicos ou permissões de escrita aos scanners. Trate exceções de scanner como decisões estreitas e documentadas, não como supressões amplas.
- Preserve filtros de paths no `push`, cancelamento por concurrency e timeouts limitados, salvo quando existir requisito concreto para alterá-los; pull requests voltados à `main` não devem usar filtros de paths, pois os checks obrigatórios estáveis precisam sempre ser reportados.

- Mantenha a publicação manual de releases restrita ao commit atual da `main` e a novas tags SemVer estáveis; nunca reutilize, mova à força ou exclua uma tag existente de release. Somente o job de publicação deve solicitar `contents: write`.
- O ruleset para tags imutáveis é distribuído separadamente como `immutable-tags.json` e não é versionado neste repositório; sua ativação exige ação administrativa separada. Proteja todas as tags contra alteração/exclusão sem restringir sua criação inicial e sem atores de bypass.

## Limites de confiança para comandos .NET orientados ao repositório

- Não trate um checkout como confiável apenas por ser um repositório Git ou por seus arquivos estarem legíveis.
Expand Down
18 changes: 18 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ dotfiles/
├── .github/
│ ├── dependabot.yml
│ └── workflows/
│ ├── release.yml
│ └── validate.yml
├── bin/
│ ├── dotfiles-doctor
Expand Down Expand Up @@ -512,6 +513,23 @@ For an occasional full-history secret audit, run Gitleaks explicitly against Git
gitleaks git --config .gitleaks.toml --no-banner --no-color --redact=100 .
```

## Manual releases and immutable tags

The `Publish release` workflow (`.github/workflows/release.yml`) is triggered **manually only**. After its pull request is merged, open **Actions → Publish release → Run workflow**, select `main`, and enter a stable SemVer version **without** the `v` prefix, for example `1.0.0`. The workflow creates a new lightweight tag `v1.0.0` at the current `main` commit and publishes a GitHub Release with automatically generated notes. It does not build or upload binaries.

The workflow rejects non-`main` runs, malformed versions (including prerelease/build metadata), stale selected commits, and previously created tag names. Publication runs are serialized and are not automatically canceled. Only the publishing job receives `contents: write`; no external action, PAT, or repository secret is needed. **Do not execute the first release until the tag ruleset below is active.**

The desired tag ruleset is supplied separately as a downloadable `immutable-tags.json` file; it is intentionally **not committed** to this repository. Download it before using the command below. Merely possessing this file does **not** install an administrative GitHub ruleset. An administrator must first check that `Immutable tags` is absent in **Settings → Rules → Rulesets**, then create a **new tag ruleset** with: name `Immutable tags`, enforcement `Active`, target **all tags**, **Restrict updates** and **Restrict deletions** enabled, **Restrict creations** disabled, and an empty bypass list. The equivalent one-time API operation (requires a GitHub CLI login with repository Administration: write) is:

```bash
gh api --method POST repos/rodri-oliveira-dev/dotfiles/rulesets \
--input immutable-tags.json
```

Verify the created ruleset in GitHub Settings before releasing. This protects all tags, including the first version, against subsequent moves and deletions while allowing the release workflow to create new version tags. Repository administrators can still change or disable the ruleset itself; this is not an absolute guarantee against an administrator changing repository policy. [GitHub tag rules documentation](https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/managing-rulesets/available-rules-for-rulesets).

If the tag is created but release publication fails, **do not delete or move the tag**. Verify that it points to the intended commit, then complete the release for that existing tag with `gh release create vX.Y.Z --verify-tag --title vX.Y.Z --generate-notes` using an appropriately authorized account. Rerunning the workflow for that version intentionally fails because the tag already exists. The tag ruleset protects Git tags; it does not, by itself, make release descriptions or assets immutable.

## Security

Never commit:
Expand Down
18 changes: 18 additions & 0 deletions README.pt-BR.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ dotfiles/
├── .github/
│ ├── dependabot.yml
│ └── workflows/
│ ├── release.yml
│ └── validate.yml
├── bin/
│ ├── dotfiles-doctor
Expand Down Expand Up @@ -512,6 +513,23 @@ Para uma auditoria ocasional do histórico completo, execute Gitleaks explicitam
gitleaks git --config .gitleaks.toml --no-banner --no-color --redact=100 .
```

## Releases manuais e tags imutáveis

O workflow `Publish release` (`.github/workflows/release.yml`) é acionado **somente de forma manual**. Depois do merge do PR, acesse **Actions → Publish release → Run workflow**, selecione `main` e informe a versão SemVer estável **sem** o prefixo `v`, por exemplo `1.0.0`. O workflow cria a nova tag leve `v1.0.0` apontando para o commit atual da `main` e publica uma GitHub Release com notas geradas automaticamente. Não compila nem envia binários.

O workflow recusa execução fora da `main`, versões inválidas (inclusive pré-release e metadados de build), commit selecionado desatualizado e nomes de tags já criados. As publicações são serializadas e não são canceladas automaticamente. Apenas o job de publicação recebe `contents: write`; não são necessários actions de terceiros, PAT ou secret adicional. **Não execute a primeira release antes da ativação do ruleset de tags abaixo.**

A configuração desejada do ruleset está disponível separadamente para download como `immutable-tags.json` e, intencionalmente, **não está versionada** neste repositório. Baixe o arquivo antes de executar o comando abaixo. Ter o arquivo localmente **não ativa** uma regra administrativa no GitHub. Um administrador precisa primeiro confirmar que `Immutable tags` ainda não existe em **Settings → Rules → Rulesets** e criar um **novo ruleset de tags** com: nome `Immutable tags`, enforcement `Active`, alvo **todas as tags**, **Restrict updates** e **Restrict deletions** habilitados, **Restrict creations** desabilitado e lista de bypass vazia. A operação equivalente via API, executada uma única vez com GitHub CLI autenticado e permissão Administration: write, é:

```bash
gh api --method POST repos/rodri-oliveira-dev/dotfiles/rulesets \
--input immutable-tags.json
```

Confira no GitHub que o ruleset foi criado e está ativo antes de publicar. Ele protege todas as tags contra alterações e exclusões, sem impedir a criação das novas versões pelo workflow. Administradores ainda podem modificar ou desativar o próprio ruleset; a proteção não é absoluta contra mudanças administrativas na política. [Documentação oficial de regras para tags](https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/managing-rulesets/available-rules-for-rulesets).

Se a tag for criada, mas a publicação da release falhar, **não exclua nem mova a tag**. Confirme o commit referenciado e conclua a publicação da release para a mesma tag com `gh release create vX.Y.Z --verify-tag --title vX.Y.Z --generate-notes`, usando uma conta autorizada. Reexecutar o workflow com a mesma versão falha intencionalmente, pois a tag já existe. O ruleset protege as tags Git, mas não torna, por si só, as descrições e os artefatos da release imutáveis.

## Segurança

Nunca versione:
Expand Down
14 changes: 14 additions & 0 deletions tests/ci-policy.bats
Original file line number Diff line number Diff line change
Expand Up @@ -35,3 +35,17 @@ setup() {
grep -Fxq " name: Shell validation" "$WORKFLOW"
grep -Fxq " name: Clean container lifecycle" "$WORKFLOW"
}

@test "manual release runs only from current main and never reuses a tag" {
local release_workflow="$REPO_ROOT/.github/workflows/release.yml"

grep -Fxq " workflow_dispatch:" "$release_workflow"
grep -Fxq " cancel-in-progress: false" "$release_workflow"
grep -Fxq "permissions: {}" "$release_workflow"
grep -Fxq " contents: write" "$release_workflow"
grep -Fq '[[ "$GITHUB_REF" != "refs/heads/main" ]]' "$release_workflow"
grep -Fq '[[ "$GITHUB_SHA" != "$main_sha" ]]' "$release_workflow"
grep -Fq 'gh api --method POST "repos/${GITHUB_REPOSITORY}/git/refs"' "$release_workflow"
grep -Fq 'gh release create "$tag" --verify-tag' "$release_workflow"
! grep -Fq -- '--force' "$release_workflow"
}
Loading