diff --git a/CHANGELOG.fr.md b/CHANGELOG.fr.md index 3bea143..8f814c6 100644 --- a/CHANGELOG.fr.md +++ b/CHANGELOG.fr.md @@ -7,6 +7,59 @@ Toutes les modifications notables du projet sont documentées dans ce fichier. Le format s'appuie sur [Keep a Changelog](https://keepachangelog.com/fr/1.1.0/), et le projet suit le [versionnage sémantique](https://semver.org/lang/fr/). +## [0.9.4] - 2026-11-15 + +### Ajouté + +- **`dsoxlab new catalog` écrit les cinq badges du README de la collection.** + Juste sous la ligne de langue de `README.md` et `README.fr.md` : CI, OpenSSF + Scorecard, conformité Plumber, SLSA 3 et licence, dans la forme qu'emploient + déjà les catalogues, avec les libellés Plumber et licence traduits en + français. Le badge de licence suit la licence que pose le squelette + (CC BY 4.0). +- **`new catalog --github `** : le compte ou l'organisation GitHub + du dépôt `/`. Il entre dans les badges et dans les commandes + de vérification de `RELEASING.md`, `RELEASING.fr.md` et `attester.yml`. Sans + lui, elles portent ``, et la commande dit de le remplacer. Un nom qui ne + peut pas être un nom GitHub est refusé avant toute écriture. +- **Deux workflows de plus dans le squelette : `scorecard.yml` et + `plumber.yml`**, repris du catalogue cloud avec leurs épinglages par SHA et + leurs permissions minimales, plus le `.plumber.yaml` sans lequel l'action + Plumber refuse de tourner. Sans eux, les badges Scorecard et Plumber restaient + vides. Les deux se sautent tant que le dépôt est privé. `RELEASING` les décrit. + +### Corrigé + +- **Le `RELEASING` du squelette ne nomme plus un propriétaire GitHub réel.** Ses + commandes `gh attestation verify`, `cosign verify-blob` et de ruleset visaient + un compte fixe : un catalogue créé par quelqu'un d'autre aurait vérifié ses + releases contre le dépôt d'un tiers. Elles prennent désormais le propriétaire + de `--github`, ou ``. +- **Le ruleset proposé par le `RELEASING` du squelette exige exactement les + contrôles que le squelette lance.** Repris d'un catalogue frère, il exigeait + Zizmor, Actionlint, Poutine, CodeQL et d'autres, que le `ci.yml` du squelette + ne lançait pas : appliqué tel quel, il bloquait toutes les pull requests. Le + squelette lance désormais ces jobs (voir Ajouté), et un test confronte les + contrôles exigés aux noms des jobs de `ci.yml`, dans les deux sens. +- **Une seule version de `harden-runner` dans le squelette** : `ci.yml`, + `release.yml` et `attester.yml` passent en v2.22.3, l'épinglage des deux + nouveaux workflows. Un test refuse une action épinglée sur deux versions. +- **Le squelette porte la chaîne de sécurité des catalogues frères**, reprise + de `applications-ia-dsoxlab-training` (e7db2da), où tous les jobs sont verts. + `ci.yml` gagne les jobs Zizmor, Actionlint, Poutine, Pre-commit parity et + CodeQL (python et actions) à côté de `Contract, guardrails and lint`, et le + ruleset de `RELEASING` exige ces sept contrôles sous leurs noms exacts. Un + test développe la matrice CodeQL et vérifie l'accord dans les deux sens. Le + squelette reçoit aussi `.github/dependabot.yml` (le modèle commun, `uv` et + `github-actions`), `.github/codeql/config.yml` (fixtures et solutions + exclues), `.github/CODEOWNERS` (le propriétaire de `--github`, ou ``), + deux gabarits d'issue et `.poutine.yml`. `SECURITY.md` et `SECURITY.fr.md` + suivent la référence : versions supportées, signalement privé par un avis de + sécurité GitHub de `/`, délais de divulgation, un périmètre écrit + pour tout catalogue de labs, et ce que le dépôt ne demandera jamais. + `setup-uv` passe en v10.3.3 dans tous les workflows : chaque action garde une + seule version. + ## [0.9.3] - 2026-11-14 ### Ajouté diff --git a/CHANGELOG.md b/CHANGELOG.md index 74813e9..223a6af 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,57 @@ All notable changes to this project are documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [0.9.4] - 2026-11-15 + +### Added + +- **`dsoxlab new catalog` writes the five README badges of the collection.** + Right under the language line of `README.md` and `README.fr.md`: CI, OpenSSF + Scorecard, Plumber compliance, SLSA 3 and licence, in the form the catalogs + already use, with the Plumber and licence labels translated in French. The + licence badge follows the licence the skeleton writes (CC BY 4.0). +- **`new catalog --github `**: the GitHub account or organization of the + repository `/`. It goes into the badges and into the verification + commands of `RELEASING.md`, `RELEASING.fr.md` and `attester.yml`. Without it, + they read ``, and the command says to replace it. An owner that cannot + be a GitHub name is refused before anything is written. +- **Two more workflows in the skeleton: `scorecard.yml` and `plumber.yml`**, + taken from the cloud catalog with their SHA pins and minimal permissions, plus + the `.plumber.yaml` the Plumber action refuses to run without. Without them the + Scorecard and Plumber badges stayed empty. Both skip while the repository is + private. `RELEASING` describes them. + +### Fixed + +- **The skeleton's `RELEASING` no longer names a real GitHub owner.** Its + `gh attestation verify`, `cosign verify-blob` and ruleset commands pointed at + a fixed account: a catalog created by anyone else would have checked its + releases against someone else's repository. They now use the `--github` + owner, or ``. +- **The ruleset proposed by the skeleton's `RELEASING` requires exactly the + checks the skeleton runs.** It was copied from a sibling catalog and required + Zizmor, Actionlint, Poutine, CodeQL and others that the skeleton's `ci.yml` + did not run: applied as is, it blocked every pull request. The skeleton now + runs those jobs (see Added), and a test checks the required checks against + the job names of `ci.yml`, both ways. +- **One version of `harden-runner` in the skeleton**: `ci.yml`, `release.yml` + and `attester.yml` move to v2.22.3, the pin of the two new workflows. A test + refuses an action pinned to two versions. +- **The skeleton carries the security chain of its sibling catalogs**, taken + from `applications-ia-dsoxlab-training` (e7db2da), where every job is green. + `ci.yml` gains the Zizmor, Actionlint, Poutine, Pre-commit parity and CodeQL + (python and actions) jobs next to `Contract, guardrails and lint`, and the + ruleset of `RELEASING` requires those seven checks by their exact names. A + test expands the CodeQL matrix and checks the agreement both ways. The + skeleton also gets `.github/dependabot.yml` (the common model, `uv` and + `github-actions`), `.github/codeql/config.yml` (fixtures and solutions left + out), `.github/CODEOWNERS` (the `--github` owner, or ``), two issue + templates and `.poutine.yml`. `SECURITY.md` and `SECURITY.fr.md` follow the + reference: supported versions, private report through a GitHub advisory of + `/`, disclosure timelines, a scope written for any lab catalog, + and what the repository will never ask. `setup-uv` moves to v10.3.3 in every + workflow, so each action keeps a single version. + ## [0.9.3] - 2026-11-14 ### Added diff --git a/README.fr.md b/README.fr.md index 8fbb940..c19ec8f 100644 --- a/README.fr.md +++ b/README.fr.md @@ -124,8 +124,8 @@ leurs sujets : chacun déclare tout dans son propre `meta.yml` et ses | Catalogue | Labs | Ce qu'il enseigne | |---|---:|---| +| [`kubernetes-dsoxlab-training`](https://github.com/stephrobert/kubernetes-dsoxlab-training) | 131 | Kubernetes sur cluster kubeadm, pour CKA, CKAD et CKS | | [`ansible-training`](https://github.com/stephrobert/ansible-training) | 113 | Ansible, du premier playbook aux collections | -| [`kubernetes-dsoxlab-training`](https://github.com/stephrobert/kubernetes-dsoxlab-training) | 111 | Kubernetes sur cluster kubeadm, pour CKA, CKAD et CKS | | [`containers-dsoxlab-training`](https://github.com/stephrobert/containers-dsoxlab-training) | 93 | Les conteneurs, Docker, Compose et Swarm | | [`terraform-dsoxlab-training`](https://github.com/stephrobert/terraform-dsoxlab-training) | 91 | Terraform et l'infrastructure as code | | [`linux-dsoxlab-training`](https://github.com/stephrobert/linux-dsoxlab-training) | 89 | Administration Linux, RHCSA et LFCS | @@ -141,9 +141,10 @@ leurs sujets : chacun déclare tout dans son propre `meta.yml` et ses | [`python-dsoxlab-training`](https://github.com/stephrobert/python-dsoxlab-training) | 7 | Python, la construction pas à pas d'un outil de sécurité | | [`proxmox-dsoxlab-training`](https://github.com/stephrobert/proxmox-dsoxlab-training) | 6 | Proxmox VE : installer, exploiter, sécuriser et automatiser un hyperviseur | | [`cicd-dsoxlab-training`](https://github.com/stephrobert/cicd-dsoxlab-training) | 5 | Les pipelines CI/CD, sur une forge locale et sans compte en ligne | +| [`applications-ia-dsoxlab-training`](https://github.com/stephrobert/applications-ia-dsoxlab-training) | 3 | Sécuriser et gouverner les applications générées par IA : classer, cadrer, vibe coder avec méthode | | [`github-actions-training`](https://github.com/stephrobert/github-actions-training) | 1 | GitHub Actions, des workflows rejoués en local | -_699 labs dans 18 catalogues, comptés sur les dépôts publiés (`labs/**/lab.yaml` de leur branche par défaut). Cette table est générée par `scripts/gen-catalogues.py` depuis `src/dsoxlab/templates/catalogues.yml`, le manifeste que lit `dsoxlab catalog list` ; aucun chiffre n'y est écrit à la main._ +_722 labs dans 19 catalogues, comptés sur les dépôts publiés (`labs/**/lab.yaml` de leur branche par défaut). Cette table est générée par `scripts/gen-catalogues.py` depuis `src/dsoxlab/templates/catalogues.yml`, le manifeste que lit `dsoxlab catalog list` ; aucun chiffre n'y est écrit à la main._ diff --git a/README.md b/README.md index 2ba3a3a..008371b 100644 --- a/README.md +++ b/README.md @@ -124,8 +124,8 @@ hand, because a written list of six once hid six others. | Catalog | Labs | What it teaches | |---|---:|---| +| [`kubernetes-dsoxlab-training`](https://github.com/stephrobert/kubernetes-dsoxlab-training) | 131 | Kubernetes on a kubeadm cluster, for CKA, CKAD and CKS | | [`ansible-training`](https://github.com/stephrobert/ansible-training) | 113 | Ansible, from first playbook to collections | -| [`kubernetes-dsoxlab-training`](https://github.com/stephrobert/kubernetes-dsoxlab-training) | 111 | Kubernetes on a kubeadm cluster, for CKA, CKAD and CKS | | [`containers-dsoxlab-training`](https://github.com/stephrobert/containers-dsoxlab-training) | 93 | Containers, Docker, Compose and Swarm | | [`terraform-dsoxlab-training`](https://github.com/stephrobert/terraform-dsoxlab-training) | 91 | Terraform and infrastructure as code | | [`linux-dsoxlab-training`](https://github.com/stephrobert/linux-dsoxlab-training) | 89 | Linux administration, RHCSA and LFCS | @@ -141,9 +141,10 @@ hand, because a written list of six once hid six others. | [`python-dsoxlab-training`](https://github.com/stephrobert/python-dsoxlab-training) | 7 | Python, building a security tool step by step | | [`proxmox-dsoxlab-training`](https://github.com/stephrobert/proxmox-dsoxlab-training) | 6 | Proxmox VE: install, operate, secure and automate a hypervisor | | [`cicd-dsoxlab-training`](https://github.com/stephrobert/cicd-dsoxlab-training) | 5 | CI/CD pipelines, on a local forge and no online account | +| [`applications-ia-dsoxlab-training`](https://github.com/stephrobert/applications-ia-dsoxlab-training) | 3 | Governing and securing AI-generated applications: classify, frame, vibe code with a method | | [`github-actions-training`](https://github.com/stephrobert/github-actions-training) | 1 | GitHub Actions, workflows replayed locally | -_699 labs across 18 catalogs, counted on the published repositories (`labs/**/lab.yaml` on their default branch). This table is generated by `scripts/gen-catalogues.py` from `src/dsoxlab/templates/catalogues.yml`, the manifest `dsoxlab catalog list` reads; no figure in it is written by hand._ +_722 labs across 19 catalogs, counted on the published repositories (`labs/**/lab.yaml` on their default branch). This table is generated by `scripts/gen-catalogues.py` from `src/dsoxlab/templates/catalogues.yml`, the manifest `dsoxlab catalog list` reads; no figure in it is written by hand._ diff --git a/pyproject.toml b/pyproject.toml index db6686e..1564aec 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "hatchling.build" [project] name = "dsoxlab" -version = "0.9.3" +version = "0.9.4" description = "Turn declarative exercises into reproducible, runnable and verifiable lab environments" readme = "README.md" requires-python = ">=3.11" diff --git a/src/dsoxlab/cli/auteur.py b/src/dsoxlab/cli/auteur.py index 2abd546..318109c 100644 --- a/src/dsoxlab/cli/auteur.py +++ b/src/dsoxlab/cli/auteur.py @@ -136,12 +136,15 @@ def new_catalog( dans: Annotated[ Path | None, typer.Option("--in", help=_("opt_new_dans")) ] = None, + github: Annotated[ + str | None, typer.Option("--github", help=_("opt_new_github")) + ] = None, ) -> None: """Crée un catalogue vide mais conforme.""" from ..services.scaffold import ScaffoldError, creer_catalogue try: - creation = creer_catalogue(identifiant, dans or Path.cwd()) + creation = creer_catalogue(identifiant, dans or Path.cwd(), proprietaire=github) except ScaffoldError as exc: error(str(exc)) raise typer.Exit(1) from None @@ -155,6 +158,11 @@ def new_catalog( # qu'un catalogue public sans licence n'est pas réutilisable, mais il le # dit pour que l'auteur la remplace si la sienne diffère. info(_("scaffold_licence_posee")) + if github is None: + # Les badges sont écrits quand même, sur un emplacement : un README + # sans badges serait à compléter de mémoire, un emplacement se + # remplace d'un rechercher-remplacer. Encore faut-il le dire. + warn(_("scaffold_github_a_remplacer", name=identifiant)) info(_("scaffold_catalogue_suite", path=str(creation.racine))) diff --git a/src/dsoxlab/i18n/strings/en.py b/src/dsoxlab/i18n/strings/en.py index e0950fa..8ae735b 100644 --- a/src/dsoxlab/i18n/strings/en.py +++ b/src/dsoxlab/i18n/strings/en.py @@ -421,13 +421,19 @@ "Scaffold a lab, discovered by the next list-labs.", "arg_new_id": "Id, lowercase, no spaces.", "opt_new_dans": "Directory to create the catalog in. Defaults to the current one.", + "opt_new_github": + "GitHub owner (account or organization) of the repository /. " + "Used by the README badges and the RELEASING commands.", "opt_new_runtime": "Lab runtime: shell (local workshop) or vm (dedicated machine).", "scaffold_catalogue_cree": "Catalog '{name}' created in {path}", "scaffold_socle_pose": "{count} files written: the reference README in both languages, the " "governance documents, a conftest.py with the bilingual message() " - "helper, a CI workflow and the repository guardrails.", + "helper, the CI with the security chain (zizmor, actionlint, poutine, " + "pre-commit parity, CodeQL), the release, Scorecard and Plumber " + "workflows behind the README badges, Dependabot, CODEOWNERS, issue " + "templates and the repository guardrails.", "scaffold_licence_posee": "LICENSE is CC BY 4.0, the licence of the collection. Replace the file " "if your catalog uses another one: GitHub only recognises a licence " @@ -455,6 +461,14 @@ "scaffold_id_invalide": "'{name}' cannot be used as an id: lowercase letters, digits, dot, " "dash and underscore only.", + "scaffold_github_invalide": + "'{name}' cannot be a GitHub owner: letters, digits and single dashes " + "only, 39 characters at most, no dash at either end.", + "scaffold_github_a_remplacer": + "No --github given: the README badges and the RELEASING commands use " + "the placeholder . Replace it with the GitHub account or " + "organization that will host {name}, or create the catalog again with " + "--github .", "scaffold_existe_deja": "{path} already exists. Pick another id, or remove that directory: " "a skeleton never overwrites work.", @@ -957,6 +971,10 @@ pre-commit, governance files and its own tests. It passes [cyan]validate-structure[/cyan] with no edit. [dim]--in [/dim] Where to create it. Defaults to the current directory. + [dim]--github [/dim] GitHub owner of the repository /, written + in the five README badges (CI, Scorecard, Plumber, + SLSA 3, licence) and the RELEASING commands. Without + it, they read [bold][/bold], to replace. [cyan]new lab [/cyan] Scaffolds a compliant lab, discovered by the next [cyan]list-labs[/cyan]. Its test [bold]fails[/bold] until it is written: a skeleton green from the start would teach grading diff --git a/src/dsoxlab/i18n/strings/fr.py b/src/dsoxlab/i18n/strings/fr.py index 820acaf..9a73737 100644 --- a/src/dsoxlab/i18n/strings/fr.py +++ b/src/dsoxlab/i18n/strings/fr.py @@ -427,13 +427,19 @@ "Crée un lab conforme, découvert dès le prochain list-labs.", "arg_new_id": "Identifiant, en minuscules, sans espace.", "opt_new_dans": "Répertoire où créer le catalogue. Défaut : le répertoire courant.", + "opt_new_github": + "Propriétaire GitHub (compte ou organisation) du dépôt /. " + "Sert aux badges du README et aux commandes de RELEASING.", "opt_new_runtime": "Runtime du lab : shell (atelier local) ou vm (machine dédiée).", "scaffold_catalogue_cree": "Catalogue « {name} » créé dans {path}", "scaffold_socle_pose": "{count} fichiers écrits : le README de référence dans les deux " "langues, les documents de gouvernance, un conftest.py avec le helper " - "bilingue message(), un workflow de CI et les garde-fous du dépôt.", + "bilingue message(), la CI avec la chaîne de sécurité (zizmor, " + "actionlint, poutine, parité pre-commit, CodeQL), les workflows de " + "release, Scorecard et Plumber qui alimentent les badges du README, " + "Dependabot, CODEOWNERS, les gabarits d'issue et les garde-fous du dépôt.", "scaffold_licence_posee": "LICENSE porte CC BY 4.0, la licence de la collection. Remplace le " "fichier si ton catalogue en emploie une autre : GitHub ne reconnaît " @@ -461,6 +467,15 @@ "scaffold_id_invalide": "« {name} » ne peut pas servir d'identifiant : minuscules, chiffres, " "point, tiret et souligné seulement.", + "scaffold_github_invalide": + "« {name} » ne peut pas être un propriétaire GitHub : lettres, " + "chiffres et tirets isolés seulement, 39 caractères au plus, sans " + "tiret en tête ni en queue.", + "scaffold_github_a_remplacer": + "Pas de --github : les badges du README et les commandes de RELEASING " + "portent l'emplacement . Remplace-le par le compte ou " + "l'organisation GitHub qui hébergera {name}, ou recrée le catalogue " + "avec --github .", "scaffold_existe_deja": "{path} existe déjà. Choisis un autre identifiant, ou retire ce " "répertoire : un squelette n'écrase jamais du travail.", @@ -975,6 +990,10 @@ pre-commit, gouvernance et ses propres tests. Il passe [cyan]validate-structure[/cyan] sans retouche. [dim]--in [/dim] Où le créer. Défaut : le répertoire courant. + [dim]--github [/dim] Propriétaire GitHub du dépôt /, écrit dans + les cinq badges du README (CI, Scorecard, Plumber, + SLSA 3, licence) et les commandes de RELEASING. Sans + elle, ils portent [bold][/bold], à remplacer. [cyan]new lab [/cyan] Crée un lab conforme, découvert dès le prochain [cyan]list-labs[/cyan]. Son test [bold]échoue[/bold] tant qu'il n'est pas écrit : un squelette vert d'emblée apprendrait à noter diff --git a/src/dsoxlab/services/scaffold.py b/src/dsoxlab/services/scaffold.py index 50174d5..dd8f6c7 100644 --- a/src/dsoxlab/services/scaffold.py +++ b/src/dsoxlab/services/scaffold.py @@ -26,7 +26,11 @@ from pathlib import Path from ..i18n import _ -from .scaffold_socle import fichiers_du_socle +from .scaffold_socle import ( + PROPRIETAIRE_PAR_DEFAUT, + fichiers_du_socle, + proprietaire_valide, +) #: Un identifiant sert de nom de répertoire et de clé CLI : on le borne pour #: qu'il ne puisse ni remonter l'arborescence, ni porter d'espace. @@ -286,9 +290,21 @@ def _ecrire(chemin: Path, contenu: str) -> Path: return chemin -def creer_catalogue(identifiant: str, destination: Path) -> Creation: - """Écrit un catalogue vide mais conforme, prêt à recevoir des labs.""" +def creer_catalogue( + identifiant: str, destination: Path, *, proprietaire: str | None = None +) -> Creation: + """Écrit un catalogue vide mais conforme, prêt à recevoir des labs. + + `proprietaire` est le compte ou l'organisation GitHub qui portera le dépôt. + Absent, les badges et les commandes de RELEASING portent l'emplacement + ``, et c'est à l'appelant de dire qu'il reste à remplacer. + """ _valider_identifiant(identifiant) + if proprietaire is not None and not proprietaire_valide(proprietaire): + # Refusé AVANT d'écrire quoi que ce soit : le nom entre dans des URL, + # du Markdown et des commandes, et un squelette à moitié écrit + # bloquerait la relance (« le répertoire existe déjà »). + raise ScaffoldError(_("scaffold_github_invalide", name=proprietaire)) racine = destination / identifiant if racine.exists(): # Ne jamais écrire par-dessus : ce répertoire porte peut-être déjà du @@ -306,7 +322,9 @@ def creer_catalogue(identifiant: str, destination: Path) -> Creation: # et tous les nouveaux catalogues l'ont. fichiers += [ _ecrire(racine / relatif, contenu) - for relatif, contenu in fichiers_du_socle(identifiant).items() + for relatif, contenu in fichiers_du_socle( + identifiant, proprietaire or PROPRIETAIRE_PAR_DEFAUT + ).items() ] (racine / "labs").mkdir(parents=True, exist_ok=True) # `ssh/` ne sert qu'aux labs `vm`, mais le créer vide ne coûte rien et diff --git a/src/dsoxlab/services/scaffold_socle.py b/src/dsoxlab/services/scaffold_socle.py index 7398de2..80a1a35 100644 --- a/src/dsoxlab/services/scaffold_socle.py +++ b/src/dsoxlab/services/scaffold_socle.py @@ -33,6 +33,9 @@ from __future__ import annotations +import re +from urllib.parse import quote + #: Le plancher commun aux douze catalogues établis, posé le 2026-10-17. Il ne #: sert que de repli quand la version du moteur est introuvable. from dsoxlab import __version__ @@ -40,12 +43,13 @@ _PLANCHER_COMMUN = "0.5.0" # Les actions sont épinglées par SHA de 40 caractères, avec la version en -# commentaire : un tag est déplaçable, un SHA non. Ces quatre-là sont celles -# qui passent aujourd'hui dans la CI des douze catalogues, relevées plutôt -# qu'inventées. -_SHA_HARDEN = "351661ca32ac09a36dc5ee2d536e3128f2a3c8ed" # v2.22.0 +# commentaire : un tag est déplaçable, un SHA non. Ces trois-là sont celles de +# la chaîne de sécurité éprouvée sur applications-ia-dsoxlab-training +# (e7db2da), relevées plutôt qu'inventées, et chaque workflow du socle emploie +# les mêmes : un catalogue neuf n'a qu'une version de chaque action. +_SHA_HARDEN = "46b06cea07f9e64621fdf066ba77ac6915163d43" # v2.22.3 _SHA_CHECKOUT = "3d3c42e5aac5ba805825da76410c181273ba90b1" # v7.0.1 -_SHA_SETUP_UV = "c18668ad3cf93ea998bef934396af7bb5c839dc7" # v10.2.0 +_SHA_SETUP_UV = "68559e99cc807c1eb7e9238fd43a15bba460eec2" # v10.3.3 # ── README : quatorze sections, dont sept génériques ───────────────────────── @@ -60,6 +64,8 @@ **Language:** [English](./README.md) · [Français](./README.fr.md) +{badges} + TO FILL IN: one paragraph. What this catalog teaches, and to whom. ## What it is @@ -199,6 +205,8 @@ **Langue :** [English](./README.md) · [Français](./README.fr.md) +{badges} + À REMPLIR : un paragraphe. Ce que ce catalogue apprend, et à qui. ## Ce que c'est @@ -650,72 +658,187 @@ def exiger_workdir(workdir: Path, lab_id: str) -> None: SECURITY_EN = """\ # Security policy -## What this repository contains +**Language:** [English](./SECURITY.md) · [Français](./SECURITY.fr.md) + +## Supported versions -A catalog of training labs: declarative files (`meta.yml`, `lab.yaml`), -statements in Markdown, Ansible playbooks, and `pytest` tests. **It executes -nothing by itself**: labs are played by the `dsoxlab` CLI, which lives in its -own repository. +`{id}` is under active development. Security fixes are applied to the latest +version of the `main` branch. + +| Version | Supported | +| --- | --- | +| latest (`main`) | yes | +| older | no | ## Reporting a vulnerability -Do **not** open a public issue. Use GitHub's private vulnerability reporting on -this repository, or write to the maintainers. +**Do not open a public issue for a security vulnerability.** + +If you believe you have found one, report it privately: -Please include what you found, how to reproduce it, and what you think the -impact is. You will get an acknowledgement, and a fix or an explanation of why -it is not one. +- Preferred: open a + [private security advisory](https://github.com/{proprietaire}/{id}/security/advisories/new) + on GitHub. +- Otherwise: TO FILL IN, a contact address of the maintainers. -## What counts as a vulnerability here +Please include: -- **A secret committed by mistake**: a token, a private key, a vault password. - Report it even if it looks revoked: it stays in git history. -- **A lab that runs something unexpected on the learner's machine**, beyond - what its statement announces. -- **A reference solution readable in clear text** where it is meant to be - encrypted: it is not a system flaw, but it destroys the exercise. +- a description of the vulnerability and its impact, +- the steps to reproduce it (command, environment, `dsoxlab --version`), +- any relevant logs or proof of concept. -## What does not +We will keep you posted on the fix and credit you in the release notes if you +wish. -A lab that deliberately sets up a vulnerable system is the subject being -taught, not a defect. A lab that asks the learner to weaken a configuration -does so inside its own machine, which `dsoxlab destroy` gives back. +## Disclosure policy + +We practise coordinated disclosure and commit to the following timelines, +counted from the moment we receive your report: + +| Step | Target | +| --- | --- | +| Acknowledging your report | within **48 hours** | +| Initial assessment and severity triage | within **5 days** | +| Fix released, or a written remediation plan | within **30 days** | +| Public disclosure of the vulnerability | within **90 days** | + +We publish the advisory as soon as a fix is available, or at the **90-day** mark +at the latest, whichever comes first. If a vulnerability is being actively +exploited, we may disclose sooner to protect users. If a complex fix needs more +time, we tell you before the deadline and agree a new date with you, rather than +letting it lapse in silence. + +## Scope + +This repository ships **lab content**: declarative files (`meta.yml`, +`lab.yaml`), briefs in Markdown, fixtures, Ansible playbooks, `pytest` tests and +encrypted reference solutions. **It executes nothing by itself**: the labs are +played by the external `dsoxlab` CLI, which lives in its own repository. + +CodeQL analyses neither `labs/**/fixtures/**` nor `labs/**/solution/**` (see +[`.github/codeql/config.yml`](.github/codeql/config.yml)). What the repository +ships as **its own** tooling (workflows, validation scripts, pytest tests) stays +fully analysed. + +In scope: + +- dangerous or malicious lab material, notably a test, a fixture or a playbook + that runs something on the learner's machine beyond what its brief announces, + reaches the network without saying so, or exfiltrates data; +- a leak of a real secret, a private key, a vault password or an API token + committed by mistake, even if it looks revoked: it stays in the git history; +- a reference solution shipped in clear text, which spoils the lab and stays in + the history; +- an action referenced without pinning by SHA in what the repository ships. + +Out of scope: + +- a lab that deliberately sets up a vulnerable system: the flaw is the subject + being taught, and it lives inside the lab's own machine or working directory; +- vulnerabilities of the `dsoxlab` engine itself, which belong to + [its own repository](https://github.com/stephrobert/dsoxlab); +- those of any third-party dependency, to be reported to its project; +- a lab that fails or grades wrongly: that is a defect, open a public issue. + +## What this repository will never ask you + +No lab requires a real secret, a personal account or a payment method. If a +brief asks you for one, that is a defect of the catalog: report it. """ SECURITY_FR = """\ # Politique de sécurité -## Ce que contient ce dépôt +**Langue :** [English](./SECURITY.md) · [Français](./SECURITY.fr.md) + +## Versions supportées -Un catalogue de labs de formation : des fichiers déclaratifs (`meta.yml`, -`lab.yaml`), des énoncés en Markdown, des playbooks Ansible et des tests -`pytest`. **Il n'exécute rien par lui-même** : les labs sont joués par la CLI -`dsoxlab`, qui vit dans son propre dépôt. +`{id}` est en développement actif. Les correctifs de sécurité sont appliqués à +la dernière version de la branche `main`. + +| Version | Supportée | +| --- | --- | +| dernière (`main`) | oui | +| plus anciennes | non | ## Signaler une vulnérabilité -N'ouvre **pas** d'issue publique. Emploie le signalement privé de GitHub sur ce -dépôt, ou écris aux mainteneurs. +**N'ouvrez pas d'issue publique pour une vulnérabilité de sécurité.** + +Si vous pensez avoir trouvé une vulnérabilité, signalez-la en privé : -Indique ce que tu as trouvé, comment le reproduire, et l'impact que tu lui -prêtes. Tu recevras un accusé de réception, puis une correction ou l'explication -de pourquoi ce n'en est pas une. +- De préférence : ouvrez un + [avis de sécurité privé](https://github.com/{proprietaire}/{id}/security/advisories/new) + sur GitHub. +- Sinon : À REMPLIR, une adresse de contact des mainteneurs. -## Ce qui compte comme une vulnérabilité ici +Merci d'inclure : -- **Un secret commité par erreur** : un jeton, une clé privée, un mot de passe - de vault. Signale-le même s'il semble révoqué : il reste dans l'historique - git. -- **Un lab qui exécute sur le poste de l'apprenant autre chose** que ce que son - énoncé annonce. -- **Une solution de référence lisible en clair** là où elle est censée être - chiffrée : ce n'est pas une faille du système, mais cela détruit l'exercice. +- une description de la vulnérabilité et de son impact, +- les étapes pour la reproduire (commande, environnement, `dsoxlab --version`), +- tout journal ou preuve de concept pertinent. -## Ce qui n'en est pas +Nous vous tiendrons informé de l'avancement du correctif et vous créditerons +dans les notes de version si vous le souhaitez. -Un lab qui monte délibérément un système vulnérable enseigne précisément ce -sujet, ce n'est pas un défaut. Un lab qui demande d'affaiblir une configuration -le fait dans sa propre machine, que `dsoxlab destroy` rend. +## Politique de divulgation + +Nous pratiquons la divulgation coordonnée et nous engageons sur les délais +suivants, décomptés à partir de la réception de votre signalement : + +| Étape | Délai visé | +| --- | --- | +| Accusé de réception de votre signalement | sous **48 heures** | +| Évaluation initiale et qualification de la sévérité | sous **5 jours** | +| Correctif publié, ou plan de remédiation écrit | sous **30 jours** | +| Divulgation publique de la vulnérabilité | sous **90 jours** | + +Nous publions l'avis de sécurité dès qu'un correctif est disponible, ou au plus +tard à l'échéance des **90 jours**, selon ce qui arrive en premier. Si une +vulnérabilité est activement exploitée, nous pouvons la divulguer plus tôt pour +protéger les utilisateurs. Si un correctif complexe demande plus de temps, nous +vous prévenons avant l'échéance et convenons d'une nouvelle date avec vous, +plutôt que de la laisser expirer sans rien dire. + +## Périmètre + +Ce dépôt livre du **contenu de labs** : fichiers déclaratifs (`meta.yml`, +`lab.yaml`), énoncés en Markdown, fixtures, playbooks Ansible, tests `pytest` et +solutions de référence chiffrées. **Il n'exécute rien par lui-même** : les labs +sont joués par la CLI externe `dsoxlab`, qui vit dans son propre dépôt. + +CodeQL n'analyse ni `labs/**/fixtures/**` ni `labs/**/solution/**` (voir +[`.github/codeql/config.yml`](.github/codeql/config.yml)). Ce que le dépôt livre +comme outillage **propre** (workflows, scripts de validation, tests pytest) reste +entièrement analysé. + +Dans le périmètre : + +- un matériau de lab dangereux ou malveillant, notamment un test, une fixture ou + un playbook qui exécuterait sur le poste de l'apprenant autre chose que ce que + son énoncé annonce, accéderait au réseau sans le dire, ou exfiltrerait des + données ; +- la fuite d'un vrai secret, d'une clé privée, d'un mot de passe de coffre ou + d'un jeton d'API commité par erreur, même s'il semble révoqué : il reste dans + l'historique git ; +- une solution de référence livrée en clair, qui gâche le lab et reste dans + l'historique ; +- une action référencée sans épinglage par SHA dans ce que le dépôt livre. + +Hors périmètre : + +- un lab qui met en place un système volontairement vulnérable : la faille est + le sujet enseigné, et elle vit dans la machine ou le répertoire de travail du + lab ; +- les vulnérabilités du moteur `dsoxlab` lui-même, qui relèvent de + [son propre dépôt](https://github.com/stephrobert/dsoxlab) ; +- celles d'une dépendance tierce, à signaler à son projet ; +- un lab qui échoue ou note mal : c'est un défaut, ouvrez une issue publique. + +## Ce que ce dépôt ne vous demandera jamais + +Aucun lab n'exige de vrai secret, de compte personnel ni de moyen de paiement. +Si un énoncé vous en demande un, c'est un défaut du catalogue : signalez-le. """ CHANGELOG_EN = """\ @@ -760,13 +883,21 @@ def exiger_workdir(workdir: Path, lab_id: str) -> None: # ── Intégration continue : les trois contrôles qu'un catalogue doit jouer ─── CI = """\ -# La CI d'un catalogue de labs joue trois contrôles, et aucun ne demande +# La CI d'un catalogue de labs, et aucun de ses jobs ne demande # d'infrastructure : ils sont donc tous jouables sur un runner public. # +# Le job « Contract, guardrails and lint » vérifie le catalogue : +# # 1. le contrat est valide, hors ligne (`validate-structure`) ; # 2. les garde-fous propres au dépôt passent (`pytest tests/`) ; # 3. le python du catalogue est propre (`ruff`). # +# Les autres forment la chaîne de sécurité des catalogues de la collection : +# zizmor, actionlint et poutine sur les workflows, la parité pre-commit, et +# CodeQL sur le python et les workflows. Leurs noms (`name:`) sont les +# contrôles qu'exige le ruleset décrit dans RELEASING : un job renommé ici doit +# l'être là-bas, sinon le ruleset attend un contrôle qui ne viendra jamais. +# # Ce qu'elle NE fait PAS, et c'est délibéré : jouer les labs. Un lab `vm` # demande un hyperviseur, et un lab `shell` demande les outils de son domaine. # L'attestation se joue sur une machine de formateur, et son verdict est @@ -787,12 +918,224 @@ def exiger_workdir(workdir: Path, lab_id: str) -> None: contents: read jobs: + # Fast security gate - the other jobs depend on it. + zizmor: + name: Zizmor (workflow static analysis) + runs-on: ubuntu-24.04 + timeout-minutes: 10 + permissions: + contents: read + steps: + - name: Harden the runner + uses: step-security/harden-runner@{sha_harden} # v2.22.3 + with: + egress-policy: audit + + - name: Checkout + uses: actions/checkout@{sha_checkout} # v7.0.1 + with: + persist-credentials: false + + - name: Zizmor + uses: zizmorcore/zizmor-action@45d7276c9ca790aabd705e31ca99c6185c3e76dd # v0.8.1 + with: + # Dependabot met à jour le SHA de l'ACTION, jamais cet input, qui + # épingle le BINAIRE : il est donc le seul de la chaîne à vieillir en + # silence. Mesuré le 2026-09-15 : la 1.26.1 refuse de charger un + # workflow qui appelle `uses: $/...`, la forme « self-repository » + # que GitHub a publiée en juillet 2026, et échoue sur « malformed + # uses ref » sans auditer quoi que ce soit. La 1.30.1 la lit, et la + # recommande même contre la forme relative. + # + # Et 1.30.0, pas 1.30.1 : l'action embarque sa propre table de + # versions connues, avec le digest de chaque image. Elle s'arrête à + # la dernière publiée avant SA dernière release, et répond « Unknown + # version » pour tout ce qui vient après. La 1.30.1 est sortie le + # 2026-09-09, après la v0.6.3 de l'action : elle est donc refusée. + version: "1.30.0" + advanced-security: false + # Les workflows DU CATALOGUE, et eux seuls. La cible reste explicite, + # comme dans les catalogues voisins : un lab qui livrerait un workflow + # en fixture serait jugé par ses tests, pas par la CI du dépôt. + inputs: .github/workflows + + # Workflow syntax gate. actionlint is the only scanner that rejects an + # invalid permission scope (e.g. the tempting-but-nonexistent + # `administration: read`) and shellchecks every `run:` block. + # Installed from the pinned release tarball with a SHA-256 check - same + # pattern as trufflehog below, so no extra third-party action enters the + # trust boundary just to lint. + actionlint: + name: Actionlint (workflow syntax) + runs-on: ubuntu-24.04 + timeout-minutes: 10 + permissions: + contents: read + steps: + - name: Harden the runner + uses: step-security/harden-runner@{sha_harden} # v2.22.3 + with: + egress-policy: audit + + - name: Checkout + uses: actions/checkout@{sha_checkout} # v7.0.1 + with: + persist-credentials: false + + - name: Install actionlint (verified release binary) + env: + ACTIONLINT_VERSION: "1.7.12" + run: | + set -euo pipefail + workdir="$(mktemp -d)" + base="https://github.com/rhysd/actionlint/releases/download/v${{ACTIONLINT_VERSION}}" + asset="actionlint_${{ACTIONLINT_VERSION}}_linux_amd64.tar.gz" + curl -fsSL -o "${{workdir}}/${{asset}}" "${{base}}/${{asset}}" + curl -fsSL -o "${{workdir}}/checksums.txt" "${{base}}/actionlint_${{ACTIONLINT_VERSION}}_checksums.txt" + (cd "${{workdir}}" && grep " ${{asset}}$" checksums.txt | sha256sum -c -) + tar -xzf "${{workdir}}/${{asset}}" -C "${{workdir}}" actionlint + sudo install -m 0755 "${{workdir}}/actionlint" /usr/local/bin/actionlint + actionlint --version + + - name: Run actionlint + run: actionlint -color + + # CI/CD exploit-chain analysis: models triggers, permissions and data flow to + # surface full attack scenarios (untrusted checkout exec, injection, risky + # default permissions). Complements zizmor rather than duplicating it. + poutine: + name: Poutine (CI/CD exploit chains) + runs-on: ubuntu-24.04 + timeout-minutes: 10 + permissions: + contents: read + steps: + - name: Harden the runner + uses: step-security/harden-runner@{sha_harden} # v2.22.3 + with: + egress-policy: audit + + - name: Checkout + uses: actions/checkout@{sha_checkout} # v7.0.1 + with: + persist-credentials: false + + - name: Poutine + uses: boostsecurityio/poutine-action@e240ebd3eff8b2db5a8e5f6b28f58739d7db2247 # v1.1.4 + + # Parity gate - run EVERY pre-commit hook (commit AND push stages) exactly as + # a contributor's local pre-commit would. Nothing enforced locally (hygiene, + # validate-structure, the lock, the guardrails, the writing rules) can then be slipped + # past with `git commit --no-verify`: any failing hook refuses the PR. This is + # the single source of truth - the CI runs the .pre-commit-config.yaml, not a + # hand-maintained copy of its steps. + pre-commit: + name: Pre-commit parity (all hooks) + needs: zizmor + runs-on: ubuntu-24.04 + timeout-minutes: 15 + permissions: + contents: read + # Pas de `DSOXLAB_PROVIDER` ici : un provider non résolu n'est pas une + # erreur pour `validate-structure`, seules les commandes d'infrastructure + # en exigent un. Un catalogue dont `infra.provider` est une liste de + # candidats peut en poser un ici si un hook en a besoin. + steps: + - name: Harden the runner + uses: step-security/harden-runner@{sha_harden} # v2.22.3 + with: + egress-policy: audit + + - name: Checkout + uses: actions/checkout@{sha_checkout} # v7.0.1 + with: + persist-credentials: false + fetch-depth: 0 # trufflehog walks git history + + - name: Set up uv + uses: astral-sh/setup-uv@{sha_uv} # v10.3.3 + + - name: Install trufflehog (verified release binary; the hook runs with --no-update) + # Download the pinned release tarball and verify its SHA-256 against the + # published checksums before use - no piped remote script (Plumber + # ISSUE-411). The skeleton's .pre-commit-config.yaml has no trufflehog + # hook yet: the sibling catalogs add one + # (`trufflehog git file://. --since-commit HEAD --results=verified + # --fail --no-update`), and this step is what lets it run here. + env: + TRUFFLEHOG_VERSION: "3.95.2" + run: | + set -euo pipefail + workdir="$(mktemp -d)" + base="https://github.com/trufflesecurity/trufflehog/releases/download/v${{TRUFFLEHOG_VERSION}}" + asset="trufflehog_${{TRUFFLEHOG_VERSION}}_linux_amd64.tar.gz" + curl -fsSL -o "${{workdir}}/${{asset}}" "${{base}}/${{asset}}" + curl -fsSL -o "${{workdir}}/checksums.txt" "${{base}}/trufflehog_${{TRUFFLEHOG_VERSION}}_checksums.txt" + (cd "${{workdir}}" && grep " ${{asset}}$" checksums.txt | sha256sum -c -) + tar -xzf "${{workdir}}/${{asset}}" -C "${{workdir}}" trufflehog + sudo install -m 0755 "${{workdir}}/trufflehog" /usr/local/bin/trufflehog + trufflehog --version + + - name: Run every hook (commit stage) + run: uvx pre-commit@4.6.0 run --all-files --show-diff-on-failure --color always + + - name: Run every hook (push stage) + run: uvx pre-commit@4.6.0 run --all-files --hook-stage pre-push --show-diff-on-failure --color always + + # A lock file that has drifted from its pyproject locks nothing: the + # vulnerability scanners keep reading uv.lock, which no longer describes + # what gets installed. `--check` neither resolves nor writes; it fails if + # the lock is stale. This check only became possible once dsoxlab left + # the dev group: as a local path source, it made the lock unresolvable + # anywhere ../dsoxlab is absent, CI included. + - name: The lock still describes the pyproject + run: uv lock --check + + codeql: + name: CodeQL (${{{{ matrix.language }}}}) + needs: zizmor + runs-on: ubuntu-24.04 + timeout-minutes: 15 + permissions: + contents: read + security-events: write + strategy: + fail-fast: false + matrix: + language: [python, actions] + steps: + - name: Harden the runner + uses: step-security/harden-runner@{sha_harden} # v2.22.3 + with: + egress-policy: audit + + - name: Checkout + uses: actions/checkout@{sha_checkout} # v7.0.1 + with: + persist-credentials: false + + - name: Initialize CodeQL + uses: github/codeql-action/init@9b3254085494b55a0f7c4c2b3d2d52cc712ce370 # v4.39.1 + with: + languages: ${{{{ matrix.language }}}} + # Neither Python nor workflows compile: there is no build to observe, + # and saying so spares CodeQL the search for a build command that + # does not exist. + build-mode: none + queries: security-extended + # Le matériau pédagogique est volontairement vulnérable, et le fichier + # dit pourquoi l'exclure plutôt que de corriger ce qui est le sujet. + config-file: ./.github/codeql/config.yml + + - name: Analyze + uses: github/codeql-action/analyze@9b3254085494b55a0f7c4c2b3d2d52cc712ce370 # v4.39.1 + contrat: name: Contract, guardrails and lint runs-on: ubuntu-24.04 steps: - name: Harden the runner - uses: step-security/harden-runner@{sha_harden} # v2.22.0 + uses: step-security/harden-runner@{sha_harden} # v2.22.3 with: egress-policy: audit @@ -802,7 +1145,7 @@ def exiger_workdir(workdir: Path, lab_id: str) -> None: persist-credentials: false - name: Install uv - uses: astral-sh/setup-uv@{sha_uv} # v10.2.0 + uses: astral-sh/setup-uv@{sha_uv} # v10.3.3 - name: Install dsoxlab # La borne est DÉCLARÉE, et non supposée. `uv tool install dsoxlab` @@ -1132,7 +1475,7 @@ def main() -> int: digest: ${{{{ steps.bundle.outputs.digest }}}} steps: - name: Harden the runner - uses: step-security/harden-runner@351661ca32ac09a36dc5ee2d536e3128f2a3c8ed # v2.22.0 + uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 with: egress-policy: audit @@ -1270,7 +1613,7 @@ def main() -> int: id-token: write # OIDC keyless pour la signature cosign steps: - name: Harden the runner - uses: step-security/harden-runner@351661ca32ac09a36dc5ee2d536e3128f2a3c8ed # v2.22.0 + uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 with: egress-policy: audit @@ -1365,8 +1708,8 @@ def main() -> int: # contrôle avec : # # gh attestation verify \ -# --repo / \ -# --signer-workflow //.github/workflows/attester.yml +# --repo {proprietaire}/{id} \ +# --signer-workflow {proprietaire}/{id}/.github/workflows/attester.yml # # Une archive attestée depuis le job de build échouerait à ce contrôle. name: Attester la provenance @@ -1404,7 +1747,7 @@ def main() -> int: contents: read steps: - name: Harden the runner - uses: step-security/harden-runner@351661ca32ac09a36dc5ee2d536e3128f2a3c8ed # v2.22.0 + uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 with: egress-policy: audit @@ -1440,6 +1783,480 @@ def main() -> int: """ +#: Le workflow OpenSSF Scorecard : c'est lui qui remplit le badge Scorecard du +#: README. Sans lui, le badge reste vide, et rien ne le dit. +# +# Repris du catalogue cloud, le plus récent de la collection, avec ses SHA. Une +# seule différence : la condition `if` qui le saute tant que le dépôt est +# privé, reprise du catalogue python. Un catalogue neuf naît souvent privé, et +# Scorecard ne sait ni lire ni publier un dépôt privé : sans elle, le premier +# push sur `main` serait rouge pour une raison qui n'est pas une faute. +SCORECARD = """\ +# OpenSSF Scorecard: measures the repository's supply-chain security posture +# (branch protection, pinned dependencies, token permissions, code review, ...) +# and publishes the result to the public Scorecard viewer and the README badge. +name: OpenSSF Scorecard + +on: + push: + branches: [main] + + branch_protection_rule: + + schedule: + - cron: '31 5 * * 3' + + workflow_dispatch: + +permissions: {{}} + +concurrency: + group: ${{{{ github.workflow }}}}-${{{{ github.ref }}}} + cancel-in-progress: true + +jobs: + analysis: + name: Scorecard analysis + # Scorecard needs a public repository (commit-graph API + result + # publication). Skips while private; activates once public. + if: ${{{{ !github.event.repository.private }}}} + runs-on: ubuntu-24.04 + timeout-minutes: 15 + + permissions: + contents: read + security-events: write # upload SARIF to Code Scanning + id-token: write # publish results to the OpenSSF Scorecard API + actions: read + + steps: + - name: Harden runner + uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 + with: + egress-policy: audit + + - name: Checkout + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Run OpenSSF Scorecard + uses: ossf/scorecard-action@fa7117db83c52d787ae5a89f350999701505d78e # v2.5.0 + with: + results_file: results.sarif + results_format: sarif + publish_results: true # publish to the OpenSSF viewer (drives the README badge) + + - name: Upload SARIF to Code Scanning + uses: github/codeql-action/upload-sarif@9b3254085494b55a0f7c4c2b3d2d52cc712ce370 # v4.39.1 + with: + sarif_file: results.sarif +""" + + +#: Le workflow Plumber : c'est lui qui publie le score du badge Plumber. +# +# Repris tel quel du catalogue cloud. Il lit `.plumber.yaml`, que le socle pose +# aussi : l'action refuse de tourner sans ce fichier. +PLUMBER = """\ +# Validates this catalogue's own CI/CD with Plumber (getplumber.io): it analyzes the +# repo's GitHub Actions workflows and repository settings against .plumber.yaml, +# uploads findings to Code Scanning, publishes the compliance score to the +# README badge, and fails below the threshold. The action verifies the +# downloaded Plumber binary's SLSA build-provenance attestation before running. +# +# This workflow runs ONLY in trusted contexts (push to main, schedule, manual): +# it needs a privileged token (Administration:read) to verify branch protection, +# and that secret must never be exposed to pull_request runs - especially from +# forks. Pull requests run ci.yml, which uses no secrets. +name: Plumber compliance + +on: + push: + branches: [main] + schedule: + - cron: '30 2 * * 1' + workflow_dispatch: + +permissions: {{}} + +concurrency: + group: ${{{{ github.workflow }}}}-${{{{ github.ref }}}} + cancel-in-progress: true + +jobs: + plumber: + name: Plumber analyze + # Skips while private (SARIF upload needs Advanced Security, free on public + # repos); activates automatically once the repo is public. + if: ${{{{ !github.event.repository.private }}}} + runs-on: ubuntu-24.04 + timeout-minutes: 10 + # The privileged token lives in this protected environment, which is + # restricted to the main branch - it is unreachable from pull_request runs. + environment: security + permissions: + contents: read + security-events: write # upload SARIF to Code Scanning + actions: read # read the workflow run for Plumber status + id-token: write # OIDC to publish the score to score.getplumber.io + steps: + - name: Harden the runner + uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 + with: + egress-policy: audit + + - name: Checkout + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Plumber compliance scan + # No `version:` input: the action installs the binary of its own release + # (the default in its action.yml), so Dependabot moves both together. + uses: getplumber/plumber@ec8cb3a7edd6a324b33e85109b627b2df6023d94 # v0.7.23 + with: + verify-attestation: "true" # check the binary's SLSA provenance before running + # Gate on the Plumber Score itself. `threshold` is DEPRECATED and its + # value 100 is explicitly "treated as unset" by the action - it gated + # nothing. min-points + soft-fail:false is the real gate: the job only + # passes at a full 100/100, and any finding fails it. + min-points: "100" + soft-fail: "false" + upload-sarif: "true" # findings to the Security tab (internal) + upload-artifacts: "false" # no downloadable artifact published + score-push: "true" # publish the score (drives the README badge) + # Fine-grained PAT (Administration + Contents + Metadata = Read), + # stored as an environment secret in the protected `security` + # environment, so branchMustBeProtected is verified for real. + # + # The token does TWO things: besides the branch-protection check, the + # action uses it to verify the provenance attestation of the binary it + # has just downloaded, through `gh attestation verify`. An empty token + # fails that step with `exit 4` on "set the GH_TOKEN environment + # variable", and the whole job falls over before analysing anything. + # Hence the fallback to the job token: with no PAT, provenance is + # still verified and only the branch-protection check abstains. + github-token: ${{{{ secrets.PLUMBER_ADMIN_TOKEN || github.token }}}} +""" + + +# ── Les badges du README ──────────────────────────────────────────────────── +# +# Les catalogues de la collection portent cinq badges sous la ligne de langue : +# CI, OpenSSF Scorecard, Plumber, SLSA 3 et licence. Leur forme est reprise du +# catalogue cloud. Le badge SLSA 3 tient parce que le socle pose `attester.yml` +# (voir ATTESTER) ; Scorecard et Plumber parce qu'il pose leurs workflows. + +#: Le propriétaire GitHub écrit quand l'auteur n'en donne pas. C'est un +#: emplacement, pas un nom : aucun propriétaire réel n'est codé dans le moteur, +#: et la CLI dit de le remplacer. +PROPRIETAIRE_PAR_DEFAUT = "" + +#: Un nom de compte ou d'organisation GitHub : lettres, chiffres et tirets +#: isolés, 39 caractères au plus, sans tiret en tête ni en queue. Il entre dans +#: des URL, du Markdown et des commandes : on le borne avant de l'écrire. +_PROPRIETAIRE_VALIDE = re.compile(r"^[A-Za-z0-9](?:[A-Za-z0-9]|-(?=[A-Za-z0-9])){0,38}$") + +#: La licence posée par défaut, et son libellé sur le badge. +_LICENCE_PAR_DEFAUT = "cc-by-4.0" +_LIBELLES_LICENCE = {"cc-by-4.0": "CC BY 4.0"} + + +def proprietaire_valide(proprietaire: str) -> bool: + """Le nom donné à `--github` peut-il être celui d'un compte GitHub ?""" + return bool(_PROPRIETAIRE_VALIDE.match(proprietaire)) + + +def badges(identifiant: str, proprietaire: str, langue: str) -> str: + """Les cinq lignes de badges du README, dans la langue demandée. + + Seuls deux libellés se traduisent, comme dans les catalogues : celui de + Plumber et celui de la licence. Le badge de licence suit la licence que le + socle pose, pour ne jamais annoncer une licence que `LICENSE` ne porte pas. + """ + depot = f"{proprietaire}/{identifiant}" + licence = _LIBELLES_LICENCE[_LICENCE_PAR_DEFAUT] + francais = langue == "fr" + mot_licence = "Licence" if francais else "License" + sep_licence = " : " if francais else ": " + plumber = "Conformité Plumber" if francais else "Plumber compliance" + ci = ( + f"[![CI](https://github.com/{depot}/actions/workflows/ci.yml/badge.svg)]" + f"(https://github.com/{depot}/actions/workflows/ci.yml)" + ) + scorecard = ( + f"[![OpenSSF Scorecard](https://img.shields.io/ossf-scorecard/github.com/{depot}" + f"?label=OpenSSF%20Scorecard)](https://securityscorecards.dev/viewer/?uri=github.com/{depot})" + ) + conformite = ( + f"[![{plumber}](https://score.getplumber.io/github.com/{depot}.svg)]" + f"(https://score.getplumber.io/github.com/{depot})" + ) + slsa = "[![SLSA 3](https://slsa.dev/images/gh-badge-level3.svg)](https://slsa.dev)" + badge_licence = ( + f"[![{mot_licence}{sep_licence}{licence}](https://img.shields.io/badge/" + f"{mot_licence}-{quote(licence)}-lightgrey.svg)](./LICENSE)" + ) + return "\n".join((ci, scorecard, conformite, slsa, badge_licence)) + + +# ── La chaîne de sécurité des catalogues frères ────────────────────────────── +# +# Reprise de applications-ia-dsoxlab-training (e7db2da), le premier catalogue +# neuf où elle a été éprouvée de bout en bout : tous ses jobs verts, et un +# ruleset qui exige les sept contrôles. Les commentaires propres à ce catalogue +# ont été rendus génériques. + +#: Dependabot : le modèle commun, écosystèmes `uv` et `github-actions`. +DEPENDABOT = """\ +# Règles Dependabot communes aux catalogues de labs dsoxlab. +# +# Ce fichier est le MÊME modèle dans tous les catalogues de la collection : +# l'écosystème `uv` pour le verrou Python, `github-actions` pour les workflows. +# Une divergence se corrige en réalignant le dépôt sur ce modèle, pas en +# adaptant le modèle au dépôt. +# +# Ce que le modèle règle : le NOMBRE de pull requests. Sans bloc `groups`, +# Dependabot ouvre une branche, une PR et une CI complète PAR DÉPENDANCE. +# Mesuré le 2026-09-15 sur cinq dépôts de la collection : celui dont +# l'écosystème de paquets n'avait aucun groupe portait 6 PR ouvertes, dont 5 +# pour cinq paquets de la même famille qui sortent leurs versions le même jour +# et ne se fusionnent jamais séparément. +version: 2 +updates: + # --- Paquets Python ------------------------------------------------------ + # + # Le dépôt verrouille ses dépendances dans `uv.lock` : c'est le verrou que + # Dependabot fait avancer, et c'est lui que les scanners de vulnérabilités + # lisent. Sans verrou, une contrainte `>=` laisse chaque installation + # résoudre ce qu'elle veut et aucun outil ne peut affirmer ce qui tourne. + - package-ecosystem: "uv" + directory: "/" + schedule: + interval: "weekly" + open-pull-requests-limit: 5 + commit-message: + prefix: "chore(deps)" + # Laisser décanter une nouvelle release : un paquet compromis est + # généralement retiré en quelques jours, et le cooldown réduit d'autant la + # fenêtre pendant laquelle on l'aurait tiré. + # + # Les paliers semver sont supportés pour les écosystèmes de PAQUETS : une + # majeure attend deux semaines, un correctif trois jours. + cooldown: + default-days: 7 + semver-major-days: 14 + semver-minor-days: 7 + semver-patch-days: 3 + groups: + deps-minor-and-patch: + patterns: ["*"] + update-types: ["minor", "patch"] + + # --- Actions GitHub ------------------------------------------------------ + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "weekly" + open-pull-requests-limit: 5 + commit-message: + prefix: "chore(ci)" + # `default-days` SEUL ici : les paliers semver-{major,minor,patch}-days ne + # sont PAS supportés pour l'écosystème github-actions. Les déclarer fait + # échouer la validation du fichier côté GitHub, qui cesse alors d'ouvrir + # des PR - et cela ressemble exactement à « aucune mise à jour + # disponible ». + cooldown: + default-days: 7 + # Un lot par semaine plutôt qu'une branche par action. Des catalogues de + # la collection ont eu cinq PR ouvertes en même temps, dont trois pour les + # trois actions github/codeql-action/*, qui sortent toujours la même + # version le même jour. + # + # Les majeures restent seules : ce sont elles qui cassent, elles méritent + # d'être lues, et les grouper ferait qu'une action incompatible bloquerait + # toutes les autres du lot. + # + # Les alertes de sécurité restent hors groupe, ce qui est le défaut + # (`applies-to: version-updates`) : elles sont urgentes et méritent une PR + # ciblée plutôt que d'attendre le lot hebdomadaire. + groups: + actions-minor-and-patch: + patterns: ["*"] + update-types: ["minor", "patch"] +""" + +#: CodeQL : ce que la CI analyse, et ce qu'elle laisse de côté à dessein. +CODEQL_CONFIG = """\ +# Configuration CodeQL d'un catalogue de labs. +# +# Les fixtures sont le point de départ des labs. Certaines sont volontairement +# fautives, parce que la faute est le sujet du lab : les analyser ferait des +# alertes permanentes sans rien protéger. Les solutions sont chiffrées : CodeQL +# n'en lirait rien. +# +# Restent analysés, et ce sont eux qui peuvent nuire à quelqu'un : +# +# .github/workflows/ les workflows du catalogue lui-même +# scripts/ l'outillage de validation des labs +# labs/**/challenge/ les tests pytest joués sur la machine de l'apprenant +name: "Catalogue de labs, hors fixtures et solutions des labs" + +paths-ignore: + - "labs/**/fixtures/**" + - "labs/**/solution/**" +""" + +#: CODEOWNERS : le propriétaire de `--github`, ou l'emplacement ``. +CODEOWNERS = """\ +# Default owner for everything in the repository: GitHub requests their review +# on every pull request. The ruleset proposed in RELEASING does not REQUIRE a +# code-owner review (a single maintainer cannot approve their own pull +# request); turn `require_code_owner_review` on once the catalog has several. +* @{proprietaire} + +# The CI/CD chain is the most sensitive surface in the repo: any change here can +# exfiltrate secrets or weaken every other gate. Owned explicitly so a review is +# always requested, even if the default owner above is ever broadened. +/.github/workflows/ @{proprietaire} +/.github/dependabot.yml @{proprietaire} +/.plumber.yaml @{proprietaire} +/.poutine.yml @{proprietaire} +/.pre-commit-config.yaml @{proprietaire} + +# Encrypted trainer solutions (ansible-vault): a leak here defeats every lab. +/labs/*/solution/ @{proprietaire} +""" + +#: Les gabarits d'issue : le défaut d'un lab ici, celui du moteur chez lui, et +#: une vulnérabilité en privé, jamais dans une issue publique. +ISSUE_CONFIG = """\ +# `blank_issues_enabled: true` est délibéré : une version de dsoxlab +# antérieure à `support --issue` dépose un corps libre, et cette voie doit +# continuer de marcher. +blank_issues_enabled: true +contact_links: + - name: "Security vulnerability / Vulnérabilité de sécurité" + url: https://github.com/{proprietaire}/{id}/security/advisories/new + about: "Report it privately, never in a public issue. / Signalez-la en privé, jamais dans une issue publique." + - name: "dsoxlab tool defect / Défaut de l'outil dsoxlab" + url: https://github.com/stephrobert/dsoxlab/issues/new/choose + about: "The engine crashes or misbehaves, regardless of a lab. / Le moteur plante ou se comporte mal, indépendamment d'un lab." +""" + +ISSUE_LAB = """\ +name: "Lab problem / Problème sur un lab" +description: "Wrong statement, test failing wrongly, missing fixture or documentation / Énoncé faux, test qui échoue à tort, fixture ou documentation manquante" +labels: ["lab"] +body: + - type: markdown + attributes: + value: | + This repository, `{proprietaire}/{id}`, holds the **labs**. For a + defect of the tool itself (`dsoxlab` crashes, a command misbehaves), + open the issue on https://github.com/stephrobert/dsoxlab/issues instead. + + Ce dépôt, `{proprietaire}/{id}`, porte les **labs**. Pour un défaut + de l'outil lui-même (`dsoxlab` plante, une commande se comporte mal), + ouvrez plutôt l'issue sur https://github.com/stephrobert/dsoxlab/issues + - type: input + id: lab + attributes: + label: "Lab / Lab concerné" + description: "The id given by `dsoxlab list-labs`. / L'identifiant rendu par `dsoxlab list-labs`." + placeholder: "" + validations: + required: true + - type: textarea + id: what-happened + attributes: + label: "What happened / Ce qui s'est passé" + description: "What you expected, and what you got instead. / Ce que vous attendiez, et ce que vous avez obtenu à la place." + validations: + required: true + - type: textarea + id: reproduce + attributes: + label: "Steps to reproduce / Étapes pour reproduire" + description: "The exact commands, and from which directory. / Les commandes exactes, depuis quel répertoire." + placeholder: | + 1. dsoxlab run + 2. ... + validations: + required: false + - type: textarea + id: support + attributes: + label: "Diagnostic report / Rapport de diagnostic" + description: >- + Output of `dsoxlab support`, anonymised by default. / + Sortie de `dsoxlab support`, anonymisée par défaut : ni chemin + personnel, ni adresse publique, ni nom de machine. + render: markdown + validations: + required: false + - type: input + id: os + attributes: + label: "Operating system / Système d'exploitation" + placeholder: Ubuntu 24.04 / AlmaLinux 10 / ... + validations: + required: false + - type: dropdown + id: runtime + attributes: + label: "Lab runtime / Runtime du lab" + options: + - shell + - vm + - not applicable + validations: + required: false + - type: textarea + id: logs + attributes: + label: "Output / logs (Sortie / journaux)" + description: "Rendered as code, no backticks needed. / Rendu comme du code, pas besoin de backticks." + render: shell + validations: + required: false +""" + +#: Poutine : les acquittements ciblés, action par action. +POUTINE = """\ +# Poutine - CI/CD exploit-chain analysis. +# +# Targeted acknowledgements ONLY. The rule stays globally enabled so any OTHER +# third-party action keeps being flagged: each skip below names one exact purl. +# +# `github_action_from_unverified_creator_used` fires on any action whose owner +# is not a Marketplace "verified creator". That status is a Marketplace +# publishing formality, not a security verdict - several first-class security +# tools do not carry it. Each action below is pinned by commit SHA, listed in +# `.plumber.yaml: trustedGithubActions`, and vetted by hand. +skip: + - rule: github_action_from_unverified_creator_used + purl: + # Official action of the plumber scanner itself (getplumber.io), which + # gates this very repo's compliance. + - pkg:githubactions/getplumber/plumber + # Official action of the zizmor scanner (zizmorcore), the workflow static + # analysis gate in ci.yml. + - pkg:githubactions/zizmorcore/zizmor-action + # Official action of poutine itself (BoostSecurity), the scanner running + # this very configuration. + - pkg:githubactions/boostsecurityio/poutine-action + # Astral - maintainer of uv and ruff, the toolchain this repo builds on. + - pkg:githubactions/astral-sh/setup-uv + # StepSecurity - harden-runner, the egress-monitoring baseline required as + # the first step of every job. + - pkg:githubactions/step-security/harden-runner + # Sigstore - the upstream project behind cosign keyless signing. + - pkg:githubactions/sigstore/cosign-installer +""" + + #: La marche à suivre pour publier, en anglais. RELEASING_EN = r"""# Releasing {id} @@ -1576,7 +2393,7 @@ def main() -> int: ```bash gh attestation verify {id}-.tar.gz \ - --repo stephrobert/{id} + --repo {proprietaire}/{id} ``` **The check that establishes Build Level 3** names the signing workflow. It @@ -1586,8 +2403,8 @@ def main() -> int: ```bash gh attestation verify {id}-.tar.gz \ - --repo stephrobert/{id} \ - --signer-workflow stephrobert/{id}/.github/workflows/attester.yml + --repo {proprietaire}/{id} \ + --signer-workflow {proprietaire}/{id}/.github/workflows/attester.yml ``` Keyless Cosign signature. **Both** certificate flags are mandatory: without @@ -1597,7 +2414,7 @@ def main() -> int: ```bash cosign verify-blob \ --bundle {id}-.tar.gz.cosign.bundle \ - --certificate-identity-regexp "https://github.com/stephrobert/{id}/.github/workflows/release.yml@.*" \ + --certificate-identity-regexp "https://github.com/{proprietaire}/{id}/.github/workflows/release.yml@.*" \ --certificate-oidc-issuer "https://token.actions.githubusercontent.com" \ {id}-.tar.gz ``` @@ -1610,7 +2427,17 @@ def main() -> int: ## GitHub settings to do once -Two workflows need configuration that does not live in the repository: +Two workflows feed the README badges, and both skip while the repository is +private: Scorecard cannot read a private repository, and Plumber's SARIF upload +needs Advanced Security, free on public repositories. + +- **`scorecard.yml`** runs OpenSSF Scorecard on every push to `main`, weekly and + on branch protection changes, and publishes the result to the public viewer + that the Scorecard badge reads. It needs no secret. +- **`plumber.yml`** checks the CI against `.plumber.yaml` and publishes the score + that the Plumber badge reads. The action refuses to run without that file. + +Two settings do not live in the repository: - **`plumber.yml`** expects a `security` environment, restricted to the `main` branch, holding the `PLUMBER_ADMIN_TOKEN` secret: a fine-grained PAT with @@ -1628,15 +2455,18 @@ def main() -> int: with a `git push`. It is set **once**, after the repository is created and the CI has run for the first time (a required check must have run at least once for GitHub to offer it). The payload below takes over the rules of the sibling -catalogs; the contexts are the job names of `ci.yml`, the CodeQL matrix giving -two. +catalogs. Its required checks are the job names of **this** repository's +`ci.yml`, and only those: the seven jobs of the skeleton, the CodeQL matrix +giving two (`CodeQL (python)` and `CodeQL (actions)`). A check that no workflow +runs stays "expected" forever and blocks every pull request. When you rename or +add a job in `ci.yml`, change its `name:` here too, and not before. No approval is required (`required_approving_review_count: 0`): the repository has a single maintainer, who cannot approve their own pull request. Going through a pull request, resolving threads and a green CI stay mandatory. ```bash -gh api --method POST repos/stephrobert/{id}/rulesets \ +gh api --method POST repos/{proprietaire}/{id}/rulesets \ --input - <<'JSON' {{ "name": "Protection de main", @@ -1660,7 +2490,7 @@ def main() -> int: {{"context": "Actionlint (workflow syntax)"}}, {{"context": "Poutine (CI/CD exploit chains)"}}, {{"context": "Pre-commit parity (all hooks)"}}, - {{"context": "Contrat du catalogue (leçons jumelées comprises)"}}, + {{"context": "Contract, guardrails and lint"}}, {{"context": "CodeQL (python)"}}, {{"context": "CodeQL (actions)"}}]}}}} ] @@ -1811,7 +2641,7 @@ def main() -> int: ```bash gh attestation verify {id}-.tar.gz \ - --repo stephrobert/{id} + --repo {proprietaire}/{id} ``` **La vérification qui atteste le niveau 3** nomme le workflow signataire. Elle @@ -1821,8 +2651,8 @@ def main() -> int: ```bash gh attestation verify {id}-.tar.gz \ - --repo stephrobert/{id} \ - --signer-workflow stephrobert/{id}/.github/workflows/attester.yml + --repo {proprietaire}/{id} \ + --signer-workflow {proprietaire}/{id}/.github/workflows/attester.yml ``` Signature Cosign keyless. Les **deux** options de certificat sont obligatoires : @@ -1832,7 +2662,7 @@ def main() -> int: ```bash cosign verify-blob \ --bundle {id}-.tar.gz.cosign.bundle \ - --certificate-identity-regexp "https://github.com/stephrobert/{id}/.github/workflows/release.yml@.*" \ + --certificate-identity-regexp "https://github.com/{proprietaire}/{id}/.github/workflows/release.yml@.*" \ --certificate-oidc-issuer "https://token.actions.githubusercontent.com" \ {id}-.tar.gz ``` @@ -1845,7 +2675,18 @@ def main() -> int: ## Réglages GitHub à faire une fois -Deux workflows ont besoin d'une configuration qui ne vit pas dans le dépôt : +Deux workflows alimentent les badges du README, et tous deux se sautent tant +que le dépôt est privé : Scorecard ne sait pas lire un dépôt privé, et l'envoi +SARIF de Plumber demande Advanced Security, gratuit sur un dépôt public. + +- **`scorecard.yml`** joue OpenSSF Scorecard à chaque push sur `main`, chaque + semaine et à chaque changement de protection de branche, et publie le + résultat sur le site public que lit le badge Scorecard. Il ne demande aucun + secret. +- **`plumber.yml`** contrôle la CI d'après `.plumber.yaml` et publie le score que + lit le badge Plumber. L'action refuse de tourner sans ce fichier. + +Deux réglages ne vivent pas dans le dépôt : - **`plumber.yml`** attend un environnement `security`, restreint à la branche `main`, portant le secret `PLUMBER_ADMIN_TOKEN` : un PAT à portée fine avec @@ -1863,8 +2704,12 @@ def main() -> int: avec un `git push`. Il se pose **une fois**, après la création du dépôt et le premier passage de la CI (un contrôle obligatoire doit avoir tourné au moins une fois pour que GitHub le propose). La charge ci-dessous reprend les règles -des catalogues voisins ; les contextes sont les noms des jobs de `ci.yml`, la -matrice CodeQL en donnant deux. +des catalogues voisins. Ses contrôles obligatoires sont les noms des jobs du +`ci.yml` de **ce** dépôt, et eux seuls : les sept jobs du squelette, la matrice +CodeQL en donnant deux (`CodeQL (python)` et `CodeQL (actions)`). Un contrôle +qu'aucun workflow ne lance reste « attendu » pour toujours et bloque toutes les +pull requests. Quand tu renommes ou ajoutes un job dans `ci.yml`, change son +`name:` ici aussi, et pas avant. Aucune approbation n'est exigée (`required_approving_review_count: 0`) : le dépôt n'a qu'un mainteneur, qui ne peut pas approuver sa propre pull request. @@ -1872,7 +2717,7 @@ def main() -> int: obligatoires. ```bash -gh api --method POST repos/stephrobert/{id}/rulesets \ +gh api --method POST repos/{proprietaire}/{id}/rulesets \ --input - <<'JSON' {{ "name": "Protection de main", @@ -1896,7 +2741,7 @@ def main() -> int: {{"context": "Actionlint (workflow syntax)"}}, {{"context": "Poutine (CI/CD exploit chains)"}}, {{"context": "Pre-commit parity (all hooks)"}}, - {{"context": "Contrat du catalogue (leçons jumelées comprises)"}}, + {{"context": "Contract, guardrails and lint"}}, {{"context": "CodeQL (python)"}}, {{"context": "CodeQL (actions)"}}]}}}} ] @@ -1919,7 +2764,7 @@ def licence_par_defaut() -> str: """ from ..templates import licence - return licence().read_text(encoding="utf-8") + return licence(_LICENCE_PAR_DEFAUT).read_text(encoding="utf-8") def version_du_moteur() -> str: @@ -1944,17 +2789,35 @@ def version_du_moteur() -> str: return brute if brute and brute != "0.0.0" else _PLANCHER_COMMUN -def fichiers_du_socle(identifiant: str) -> dict[str, str]: +def config_plumber() -> str: + """Le `.plumber.yaml` du socle, lu dans les gabarits packagés.""" + from ..templates import plumber_config + + return plumber_config().read_text(encoding="utf-8") + + +def fichiers_du_socle( + identifiant: str, proprietaire: str = PROPRIETAIRE_PAR_DEFAUT +) -> dict[str, str]: """Les fichiers du socle, par chemin relatif à la racine du catalogue. Un seul endroit décide de ce qu'un catalogue porte : ce dictionnaire. Le jour où la collection en ajoute un, il s'ajoute ici et tous les nouveaux catalogues l'ont, sans qu'on ait à s'en souvenir. + + `proprietaire` est le compte ou l'organisation GitHub du dépôt + `/`. Il sert aux badges du README et aux + commandes de vérification de RELEASING. Absent, c'est l'emplacement + ``, que l'auteur remplace. """ return { "LICENSE": licence_par_defaut(), - "README.md": README_EN.format(id=identifiant), - "README.fr.md": README_FR.format(id=identifiant), + "README.md": README_EN.format( + id=identifiant, badges=badges(identifiant, proprietaire, "en") + ), + "README.fr.md": README_FR.format( + id=identifiant, badges=badges(identifiant, proprietaire, "fr") + ), "meta.fr.yml": META_FR.format(id=identifiant), "conftest.py": CONFTEST, "pyproject.toml": PYPROJECT.format(id=identifiant), @@ -1962,8 +2825,8 @@ def fichiers_du_socle(identifiant: str) -> dict[str, str]: "CONTRIBUTING.fr.md": CONTRIBUTING_FR, "CODE_OF_CONDUCT.md": CODE_OF_CONDUCT_EN, "CODE_OF_CONDUCT.fr.md": CODE_OF_CONDUCT_FR, - "SECURITY.md": SECURITY_EN, - "SECURITY.fr.md": SECURITY_FR, + "SECURITY.md": SECURITY_EN.format(id=identifiant, proprietaire=proprietaire), + "SECURITY.fr.md": SECURITY_FR.format(id=identifiant, proprietaire=proprietaire), "CHANGELOG.md": CHANGELOG_EN, "CHANGELOG.fr.md": CHANGELOG_FR, ".github/workflows/ci.yml": CI.format( @@ -1971,9 +2834,24 @@ def fichiers_du_socle(identifiant: str) -> dict[str, str]: moteur=version_du_moteur(), ), ".github/workflows/release.yml": RELEASE.format(id=identifiant), - ".github/workflows/attester.yml": ATTESTER.format(id=identifiant), - "RELEASING.md": RELEASING_EN.format(id=identifiant), - "RELEASING.fr.md": RELEASING_FR.format(id=identifiant), + ".github/workflows/attester.yml": ATTESTER.format( + id=identifiant, proprietaire=proprietaire + ), + ".github/workflows/scorecard.yml": SCORECARD.format(), + ".github/dependabot.yml": DEPENDABOT, + ".github/codeql/config.yml": CODEQL_CONFIG, + ".github/CODEOWNERS": CODEOWNERS.format(proprietaire=proprietaire), + ".github/ISSUE_TEMPLATE/config.yml": ISSUE_CONFIG.format( + id=identifiant, proprietaire=proprietaire + ), + ".github/ISSUE_TEMPLATE/lab_report.yml": ISSUE_LAB.format( + id=identifiant, proprietaire=proprietaire + ), + ".poutine.yml": POUTINE, + ".github/workflows/plumber.yml": PLUMBER.format(), + ".plumber.yaml": config_plumber(), + "RELEASING.md": RELEASING_EN.format(id=identifiant, proprietaire=proprietaire), + "RELEASING.fr.md": RELEASING_FR.format(id=identifiant, proprietaire=proprietaire), ".pre-commit-config.yaml": PRE_COMMIT.format(moteur=version_du_moteur()), "tests/test_contrat_du_catalogue.py": TEST_CONTRAT, "tests/outils/pas_de_tiret_cadratin.py": TEST_TIRET, diff --git a/src/dsoxlab/templates/__init__.py b/src/dsoxlab/templates/__init__.py index 3ee5335..953a7be 100644 --- a/src/dsoxlab/templates/__init__.py +++ b/src/dsoxlab/templates/__init__.py @@ -68,6 +68,17 @@ def licence(nom: str = "cc-by-4.0") -> Path: return template_root() / "licences" / f"{nom}.txt" +def plumber_config() -> Path: + """La configuration Plumber qu'un catalogue neuf reçoit en `.plumber.yaml`. + + L'action Plumber refuse de tourner sans ce fichier. Il est repris du + catalogue cloud, et ne porte rien de propre à un catalogue : les contrôles + portent sur la CI (actions épinglées, sources autorisées, images), pas sur + ce que les labs enseignent. C'est une donnée, comme la licence. + """ + return template_root() / "plumber" / "plumber.yaml" + + def catalogues_manifeste() -> Path: """Le manifeste des catalogues connus, packagé avec l'outil. diff --git a/src/dsoxlab/templates/catalogues.yml b/src/dsoxlab/templates/catalogues.yml index fb650f3..6b9f518 100644 --- a/src/dsoxlab/templates/catalogues.yml +++ b/src/dsoxlab/templates/catalogues.yml @@ -144,3 +144,8 @@ catalogues: depot: https://github.com/stephrobert/mlops-dsoxlab-training description_en: "MLOps: reproduce, ship and operate a model" description_fr: "MLOps : reproduire, livrer et exploiter un modèle" + + - id: applications-ia + depot: https://github.com/stephrobert/applications-ia-dsoxlab-training + description_en: "Governing and securing AI-generated applications: classify, frame, vibe code with a method" + description_fr: "Sécuriser et gouverner les applications générées par IA : classer, cadrer, vibe coder avec méthode" diff --git a/src/dsoxlab/templates/plumber/plumber.yaml b/src/dsoxlab/templates/plumber/plumber.yaml new file mode 100644 index 0000000..2045a98 --- /dev/null +++ b/src/dsoxlab/templates/plumber/plumber.yaml @@ -0,0 +1,996 @@ +# Plumber Configuration - Trust Policy Manager for GitLab CI/CD +# This file is required for 'plumber analyze' to work. +# Default file name: .plumber.yaml +# Reference: https://github.com/getplumber/plumber/blob/main/.plumber.yaml +# Can be generated with: plumber config generate + +version: "2.0" + +# Plumber Score publishing is controlled by your CI pipeline, not this file: +# set the `score-push` input on the Plumber GitHub Action / GitLab component +# (or pass --score-push / PLUMBER_ANALYZE_SCORE_PUSH). Publishing happens ONLY +# in CI (it needs a CI-native OIDC id-token, so a local run never publishes and +# can't spoof another repo's badge). Docs: https://getplumber.io/docs/plumber-score +# To target a self-hosted score service, uncomment and set the endpoint: +# score: +# endpoint: https://score.example.com + +gitlab: + controls: + # =========================================== + # Container images must not use forbidden tags + # =========================================== + # Detects CI/CD jobs using Docker images with forbidden tags. + # Forbidden tags (like 'latest') can point to different images over time, + # making builds non-reproducible and potentially introducing security risks. + # + # Best practice: Use immutable tags (e.g., specific versions or SHA digests) and not forbidden tags + containerImageMustNotUseForbiddenTags: + # Set to false to disable this control + enabled: true + # Tags considered "forbidden" - images using these will be flagged + tags: + - latest + - dev + - development + - staging + - main + - master + # v8.15.0 + # Add your organization's custom mutable tags below: + # - nightly + # - edge + # - canary + # - unstable + # When true, ALL images must be pinned by digest (e.g., alpine@sha256:...). + # This takes precedence over the forbidden tags list - any image not using + # an immutable digest reference will be flagged, including standard version + # tags like alpine:3.19 or node:20. + containerImagesMustBePinnedByDigest: true + # =========================================== + # Container images must come from authorized sources + # =========================================== + # Detects CI/CD jobs using Docker images from untrusted registries. + # Only images from explicitly trusted sources should be used in pipelines + # to prevent supply chain attacks. + # + # Best practice: Maintain a list of approved registries and image patterns + containerImageMustComeFromAuthorizedSources: + # Set to false to disable this control + enabled: true + # Trust official Docker Hub images (e.g., nginx, alpine, python) + # These are images without a username prefix on Docker Hub + trustDockerHubOfficialImages: true + # Trusted registry URLs and patterns (supports wildcards) + # Images matching these patterns will be considered trusted + trustedUrls: + # Docker Hub official images (if trustDockerHubOfficialImages is false) + # - docker.io/library/* + + # Common CI/CD tool images + - docker.io/docker:* + - docker.io/getplumber/plumber:* + - getplumber/plumber:* + - docker.io/getplumber/plumber@sha256:* + # GitLab registry patterns + - $CI_REGISTRY_IMAGE:* + - $CI_REGISTRY_IMAGE/* + - $CI_REGISTRY/* + - ${CI_REGISTRY}/* + - ${CI_REGISTRY_IMAGE}:* + - ${CI_REGISTRY_IMAGE}/* + # GitLab Dependency Proxy + - ${CI_DEPENDENCY_PROXY_DIRECT_GROUP_IMAGE_PREFIX}/* + # GitLab official registries + - registry.gitlab.com/security-products/* + - registry.gitlab.com/gitlab-org/* + - registry.gitlab.com/pipeline-components/* + # Do NOT use host-wide patterns such as ghcr.io/*, gcr.io/*, quay.io/*, mcr.microsoft.com/*, + # nvcr.io/* - anyone can publish images on those registries; wildcards would trust all of them. + # Prefer org-scoped patterns instead, e.g. ghcr.io/my-org/*, quay.io/prometheus/* + + # Docker Hub - well-known publishers (DevOps / CI tooling) + # Each entry below corresponds to a Docker Hub Verified Publisher, + # the upstream project's own namespace, or an officially recognised + # community publisher for that tool. See docs/trusted-registries.md + # for verification notes. + - docker.io/curlimages/* # curl docker team (curl/curl-container) + - docker.io/alpine/* # Alpine Linux maintainers (alpinelinux org) + - docker.io/golangci/* # golangci-lint upstream + - docker.io/koalaman/* # ShellCheck author (Vidar Holen) + - docker.io/hadolint/* # hadolint upstream + - docker.io/semgrep/* # Semgrep, Inc. + - docker.io/sonarsource/* # SonarSource verified publisher + - docker.io/cypress/* # Cypress.io verified publisher + - docker.io/gittools/* # GitTools (GitVersion) upstream + - docker.io/renovate/* # Renovate Bot (Mend.io) verified publisher + - docker.io/gitlab/* # GitLab verified publisher + - docker.io/lycheeverse/* # lychee link checker upstream + - docker.io/hugomods/* # HugoMods Hugo container project + - docker.io/fsfe/* # Free Software Foundation Europe (REUSE) + - docker.io/hashicorp/* # HashiCorp (IBM) verified publisher + - docker.io/cimg/* # CircleCI convenience images + - docker.io/circleci/* # CircleCI legacy convenience images + # Docker Hub - cloud vendor official images + - docker.io/amazon/* # Amazon Web Services + - docker.io/google/* # Google + - docker.io/nvidia/* # NVIDIA verified publisher + - docker.io/bitnami/* # Bitnami / VMware (Broadcom) verified publisher + # Docker Hub - OS / distro official images + - docker.io/redhat/* # Red Hat + - docker.io/opensuse/* # openSUSE Project + - docker.io/gentoo/* # Gentoo Linux maintainers + - docker.io/nixos/* # NixOS Foundation + - docker.io/rustlang/* # Rust Programming Language official + # Microsoft Container Registry - official Microsoft products + - mcr.microsoft.com/dotnet/* # .NET official images + - mcr.microsoft.com/playwright/* # Playwright (Microsoft) browser images + - mcr.microsoft.com/playwright # tag-only ref form (no path suffix) + # Quay.io - well-known projects with their own organisation + - quay.io/buildah/* # Containers project (Buildah) + - quay.io/podman/* # Containers project (Podman) + - quay.io/containers/* # Containers project umbrella org + - quay.io/centos/* # CentOS Project (CentOS Stream) + - quay.io/pypa/* # Python Packaging Authority (manylinux) + - quay.io/gnome_infrastructure/* # GNOME Infrastructure team + # GitHub Container Registry - well-known upstream organisations + # ghcr.io//* is scoped to a single GitHub organisation, so each + # entry must be the actual org that publishes the upstream tool. + - ghcr.io/astral-sh/* # Astral (uv, ruff) + - ghcr.io/renovatebot/* # Renovate Bot upstream + - ghcr.io/containerbase/* # containerbase (Renovate base images) + - ghcr.io/canonical/* # Canonical (snapcraft-rocks etc.) + - ghcr.io/graalvm/* # Oracle GraalVM team + - ghcr.io/terraform-linters/* # tflint upstream organisation + - ghcr.io/prefix-dev/* # prefix.dev (pixi) + # Google Container Registry - Google-owned projects + - gcr.io/kaniko-project/* # Kaniko (Google Cloud Build) + - gcr.io/go-containerregistry/* # google/go-containerregistry (crane, gcrane) + - gcr.io/google.com/cloudsdktool/* # Google Cloud SDK (gcloud) official + # =========================================== + # Branch must be protected + # =========================================== + # Checks that repository branches have proper protection settings. + # Ensures critical branches (like main/master) are protected + # from force pushes and require code reviews. + # + # Best practice: Protect default branch and release branches + branchMustBeProtected: + # Set to false to disable this control + enabled: true + # Require the default branch to be protected + defaultMustBeProtected: true + # Branch name patterns that must be protected (supports wildcards) + namePatterns: + - main + - master + - release/* + - production + - dev + # Add your organization's protected branch patterns below: + # - develop + # - staging + # When false, force push must be disabled on protected branches + allowForcePush: false + # Require code owner approval for changes + codeOwnerApprovalRequired: false + # Minimum access level required to merge (0=No one, 30=Developer, 40=Maintainer) + minMergeAccessLevel: 30 + # Minimum access level required to push (0=No one, 30=Developer, 40=Maintainer) + minPushAccessLevel: 40 + # =========================================== + # Pipeline must not include hardcoded jobs + # =========================================== + # Detects CI/CD jobs that are defined directly in the .gitlab-ci.yml file + # instead of being included from reusable components or templates. + # + # Hardcoded jobs make pipelines harder to maintain and don't benefit from + # centralized updates when best practices change. + # + # Best practice: Use CI/CD components, templates, or includes for job definitions + pipelineMustNotIncludeHardcodedJobs: + # Set to false to disable this control + enabled: true + # =========================================== + # Includes must not use ambiguous tag/branch refs + # =========================================== + # Flags `include:` references whose ref resolves upstream as BOTH a tag + # and a branch: an `include:project` with `ref: v1`, or a CI/CD component + # `@v1`, where the source project keeps both a `v1` tag and a `v1` branch. + # GitLab resolves the tag first, so the pipeline runs today - but a tag + # deletion, rename, or typo silently switches the include onto the mutable + # branch, and the reviewer cannot tell from the YAML which revision runs. + # + # API-backed: the collector probes the source project's tag and branch + # namespaces and flags only a confirmed double-hit. Requires a token; + # without one (or on a failed probe) the control abstains. Pin to a + # 40-char commit SHA to remove the ambiguity. + externalRefsMustNotCollide: + enabled: true + # =========================================== + # Includes must be up to date + # =========================================== + # Detects CI/CD includes (components, templates, project files) from the + # GitLab CI Catalog that are not using the latest available version. + # + # Outdated includes may miss important bug fixes, security patches, + # or new features. + # + # Best practice: Regularly update includes to their latest versions + includesMustBeUpToDate: + # Set to false to disable this control + enabled: true + # =========================================== + # Includes must not use forbidden versions + # =========================================== + # Detects CI/CD includes (components, templates, project files) using + # mutable/forbidden version references like 'latest', 'main', 'master', or 'HEAD'. + # + # Mutable versions can change unexpectedly, making builds non-reproducible + # and potentially introducing breaking changes without warning. + # + # Best practice: Use specific version tags (e.g., v1.2.3, ~1.0) for includes + includesMustNotUseForbiddenVersions: + # Set to false to disable this control + enabled: true + # Version patterns considered forbidden: includes using these will be flagged + forbiddenVersions: + - latest + - "~latest" + - main + - master + - HEAD + # Add your organization's custom forbidden versions below: + # - dev + # - develop + # - staging + # When true, adds the project's default branch to forbidden versions + defaultBranchIsForbiddenVersion: false + # ============================================================================ + # Pipeline must include component + # ============================================================================ + # Ensures pipelines include required GitLab CI/CD components. + # Useful for enforcing security scanning, compliance, or utility components. + # + # Override detection: components that are imported but have their jobs + # overridden with forbidden CI/CD keywords (script, image, rules, etc.) + # are flagged as overridden. They still count as imported but produce a + # separate ISSUE-409 finding. Per-control compliance is binary today + # (any finding → 0%); inspect "Satisfied Groups" in the stats block + # for the granular view. + # + # Two ways to define requirements (use one, not both): + # + # Option 1 - Expression syntax ('required'): + # A natural boolean expression using AND, OR, and parentheses. + # AND binds tighter than OR, so "a AND b OR c" means "(a AND b) OR c". + # + # required: components/sast/sast AND components/secret-detection/secret-detection + # required: (components/sast/sast AND components/secret-detection/secret-detection) OR your-org/full-security/full-security + # + # Option 2 - Array syntax ('requiredGroups'): + # A list of groups using "OR of ANDs" logic: + # - Each inner array = components that must ALL be present (AND) + # - Outer array = only ONE group needs to be satisfied (OR) + # + # requiredGroups: + # - ["components/sast/sast", "components/secret-detection/secret-detection"] + # - ["your-org/full-security-pipeline/full-security"] + # + # For more expression examples, see https://github.com/getplumber/plumber/blob/main/configuration/expression_test.go + # + pipelineMustIncludeComponent: + enabled: false + # required: components/sast/sast AND components/secret-detection/secret-detection AND getplumber/plumber/plumber + requiredGroups: [] + # ============================================================================ + # Pipeline must include template + # ============================================================================ + # Ensures pipelines include required templates (project file includes). + # Useful for enforcing organization-specific CI templates. + # + # Override detection: templates that are imported but have their jobs + # overridden with forbidden CI/CD keywords (script, image, rules, etc.) + # are flagged as overridden. They still count as imported but produce a + # separate ISSUE-406 finding. Per-control compliance is binary today + # (any finding → 0%); inspect "Satisfied Groups" in the stats block + # for the granular view. + # + # Two ways to define requirements (use one, not both): + # + # Option 1 - Expression syntax ('required'): + # required: templates/go/go AND templates/trivy/trivy + # required: (templates/go/go AND templates/trivy/trivy) OR templates/full-go-pipeline + # + # Option 2 - Array syntax ('requiredGroups'): + # requiredGroups: + # - ["templates/go/go", "templates/trivy/trivy"] + # - ["templates/full-go-pipeline"] + # + # For more expression examples, see https://github.com/getplumber/plumber/blob/main/configuration/expression_test.go + # + pipelineMustIncludeTemplate: + enabled: false + # required: templates/go/go AND templates/trivy/trivy AND templates/iso27001/iso27001 + requiredGroups: [] + # =========================================== + # Pipeline must not enable debug trace + # =========================================== + # Detects CI/CD pipelines that set CI_DEBUG_TRACE or CI_DEBUG_SERVICES + # to "true" in global or job-level variables. + # + # When CI_DEBUG_TRACE is enabled, GitLab prints ALL environment variables + # in the job logs, including masked secrets like CI_JOB_TOKEN and any + # custom CI/CD variables. This is a critical security risk. + # + # Best practice: Never enable CI_DEBUG_TRACE in committed CI configuration + pipelineMustNotEnableDebugTrace: + # Set to false to disable this control + enabled: true + # CI/CD variable names that must not be set to "true" + forbiddenVariables: + - CI_DEBUG_TRACE + - CI_DEBUG_SERVICES + # =========================================== + # Pipeline must not use unsafe variable expansion + # =========================================== + # Detects user-controlled CI variables passed to commands that + # re-interpret their input as shell code. This is OWASP CICD-SEC-1. + # + # GitLab sets CI variables as environment variables. The shell does + # NOT re-parse expanded values for command substitution, so normal + # usage is safe. Only commands that re-interpret arguments as code + # create an injection surface. + # + # Flagged (re-interpretation contexts): + # - eval "$CI_COMMIT_BRANCH" + # - sh -c "$CI_MERGE_REQUEST_TITLE" + # - bash -c "$CI_COMMIT_MESSAGE" + # - dash -c / zsh -c / ksh -c + # - source <(echo "$CI_COMMIT_REF_NAME") + # - envsubst '$CI_COMMIT_MESSAGE' < tpl.sh | sh + # - echo "$CI_COMMIT_BRANCH" | xargs sh + # + # Not flagged (safe - shell doesn't re-parse env var values): + # - echo $CI_COMMIT_BRANCH + # - echo "$CI_COMMIT_MESSAGE" + # - curl -d "$CI_MERGE_REQUEST_TITLE" https://... + # - git checkout $CI_COMMIT_REF_NAME + # - printf '%s' "$CI_COMMIT_MESSAGE" + # + # Not caught (known limitation): + # - sh -c $BRANCH (where BRANCH: $CI_COMMIT_BRANCH in variables:) + # Indirect aliasing is not tracked; only direct variable names. + pipelineMustNotUseUnsafeVariableExpansion: + # Set to false to disable this control + enabled: true + # CI/CD variables whose values come from user input and must not + # appear in shell re-interpretation contexts (eval, sh -c, bash -c, etc.) + dangerousVariables: + - CI_MERGE_REQUEST_TITLE + - CI_MERGE_REQUEST_DESCRIPTION + - CI_COMMIT_MESSAGE + - CI_COMMIT_TITLE + - CI_COMMIT_TAG_MESSAGE + - CI_COMMIT_REF_NAME + - CI_COMMIT_REF_SLUG + - CI_COMMIT_BRANCH + - CI_MERGE_REQUEST_SOURCE_BRANCH_NAME + - CI_EXTERNAL_PULL_REQUEST_SOURCE_BRANCH_NAME + # Script lines + # sh -c "terraform workspace select $CI_COMMIT_REF_SLUG" + # sh -c "docker build --build-arg BRANCH=$CI_COMMIT_BRANCH ." + # sh -c "aws s3 sync dist/ s3://my-bucket/$CI_COMMIT_REF_SLUG/" + # bash -c "make deploy BRANCH=$CI_COMMIT_BRANCH" + # + # Allow with patterns: + # (Escape $ as \\$, {} as \\{ \\} in patterns.) + # allowedPatterns: + # - "helm.*--set.*\\$CI_" + # - "terraform workspace select.*\\$CI_" + # - "docker build.*--build-arg.*\\$CI_" + # - "aws s3 sync.*\\$CI_" + # - "make deploy.*\\$CI_" + allowedPatterns: [] + # =========================================== + # Security jobs must not be weakened + # =========================================== + # Detects GitLab CI security scanning jobs (SAST, Secret Detection, + # Container Scanning, Dependency Scanning, DAST, License Scanning) + # that have been weakened through overrides in .gitlab-ci.yml. + # + # Even when security templates are properly included, a developer + # (or attacker) can silently neutralize them by: + # - Setting allow_failure: true (failures become invisible) + # - Overriding rules: with when: never or when: manual + # - Setting when: manual at job level (job never runs automatically) + # + # The pipeline still "includes" the security template, giving a false + # sense of compliance while the actual scanning is disabled. + # + # Maps to OWASP CICD-SEC-4 (Poisoned Pipeline Execution). + # + # Best practice: Security jobs should run automatically and block the + # pipeline on failure. + securityJobsMustNotBeWeakened: + # Set to false to disable this control + enabled: true + # Job name patterns considered "security jobs" (supports wildcards). + # or any other jobs you want to be considered security jobs. + securityJobPatterns: + - "*-sast" + - "secret_detection" + - "container_scanning" + - "*_dependency_scanning" + - "gemnasium-*" + - "dast" + - "dast_*" + - "license_scanning" + # Detects security jobs with allow_failure: true. + # Example: + # semgrep-sast: + # allow_failure: true + # Off by default because GitLab templates ship with allow_failure: true. + # Opt-in for orgs that want security checks to block the pipeline. + allowFailureMustBeFalse: + enabled: false + # Detects security jobs whose rules: block is overridden with + # when: never (job will never run) or when: manual (requires manual click). + # Example: + # semgrep-sast: + # rules: + # - when: never + # Example: + # secret_detection: + # rules: + # - when: manual + rulesMustNotBeRedefined: + enabled: false + # Detects security jobs with when: manual set at job level. + # Same effect as a rules override, but written differently. + # Example: + # semgrep-sast: + # when: manual + whenMustNotBeManual: + enabled: false + # =========================================== + # Pipeline must not override job variables + # =========================================== + # Detects CI/CD variables that are redefined in the pipeline configuration + # file (.gitlab-ci.yml) when they should only be set in GitLab CI/CD + # Settings > Variables. + # + # An attacker who can modify .gitlab-ci.yml could override variables like + # SECURE_ANALYZERS_PREFIX to point to a fake registry, or set + # SAST_DISABLED: "true" to silently disable security scanners. The pipeline + # still appears green, but no actual scanning occurs. + # + # This control is generic: add any variable name you want to protect, + # not just security-related ones. + # + # Best practice: Set controlled variables in GitLab CI/CD Settings as + # protected/masked variables, never in the YAML file. + pipelineMustNotOverrideJobVariables: + # Set to false to disable this control + enabled: true + # CI/CD variable names that must not be defined in the pipeline config. + # They should only be set in GitLab CI/CD Settings > Variables or defined in the imported templates or components. + variables: + - SECURE_ANALYZERS_PREFIX + - SAST_DISABLED + - SAST_EXCLUDED_PATHS + - SAST_EXCLUDED_ANALYZERS + - SECRET_DETECTION_DISABLED + - SECRET_DETECTION_EXCLUDED_PATHS + - CONTAINER_SCANNING_DISABLED + - DAST_DISABLED + - DEPENDENCY_SCANNING_DISABLED + - LICENSE_SCANNING_DISABLED + # Add your organization's controlled variables below: + # - MY_CUSTOM_PROTECTED_VAR + # ── Pipeline must not execute unverified scripts ───────────────── + # + # Detects jobs that download or inline-execute scripts without integrity + # verification (curl | bash, wget | sh, curl -o … && bash, echo … | + # base64 -d | bash, and any `| sh` / `| bash` pipe). + # + # This is a well-documented supply chain attack vector: an attacker who + # compromises the remote URL can serve a modified script that exfiltrates + # CI/CD secrets ($CI_JOB_TOKEN, deploy keys, custom variables). + # + # Maps to OWASP CICD-SEC-3 (Dependency Chain Abuse) and CICD-SEC-8 + # (Ungoverned Usage of 3rd Party Services). + # + # Best practice: download scripts to a file, verify a checksum against a + # known-good value, then execute. Or vendor the script into your repo. + pipelineMustNotExecuteUnverifiedScripts: + # Set to false to disable this control + enabled: true + # URLs that are trusted and should not trigger findings. + # Supports wildcards (e.g., https://internal-artifacts.example.com/*). + trustedUrls: [] + # ── Pipeline must not use Docker-in-Docker ────────────────────── + # + # Detects CI/CD jobs that use Docker-in-Docker (dind) services. + # Running a Docker daemon inside a CI container on shared runners + # in privileged mode enables container escape, lateral movement, + # and access to secrets from other jobs on the same runner. + # + # This is a well-known attack vector documented in GitLab CI + # security best practices. + # + # Best practice: Use Kaniko or Buildah for container image builds + # instead of Docker-in-Docker. + pipelineMustNotUseDockerInDocker: + # Set to false to disable this control + enabled: true + # When true, also flags insecure daemon configuration + # (DOCKER_TLS_CERTDIR="" or DOCKER_HOST tcp://...:2375) + # in jobs that use a DinD service. + detectInsecureDaemon: true + +# ============================================================================ +# GitHub Actions controls +# ============================================================================ +github: + controls: + # =========================================== + # Actions must be pinned by commit SHA + # =========================================== + # Flags workflow steps whose `uses:` reference is not a 40-character + # commit SHA. Tag/branch refs (v4, main) are mutable: if the action's + # maintainer is compromised or retags a release, the caller workflow + # silently runs new code with its secrets. This is the vector behind + # the March 2025 tj-actions/changed-files compromise (CVE-2025-30066). + # + # The default trustedOwners list exempts first-party (`actions/*`, + # `github/*`) actions so the initial signal on a fresh repo stays + # focused on the third-party surface. Pair with Dependabot + # (`version-update-strategy: sha-and-version`) to keep pins fresh. + actionsMustBePinnedByCommitSha: + enabled: true + # Action-owner prefixes exempt from the pin-by-SHA requirement. + # Only list owners already inside the workflow's trust boundary. + trustedOwners: + - actions + - github + + # =========================================== + # Actions must come from authorized sources + # =========================================== + # Restrict which `uses:` action sources are allowed. Every third- + # party action runs with the caller workflow's token and secrets, so + # limiting actions to vetted owners shrinks the supply-chain surface. + githubActionMustComeFromAuthorizedSources: + enabled: true + # Trust the first-party GitHub-owned actions (actions/*, github/*) + # that any workflow already executes implicitly. Defaults to true. + trustGithubOfficialActions: true + # Trust actions whose owner is the same org/user as the scanned + # repository - an org's own actions are inside its trust boundary. + # Defaults to true. + trustSameOrgActions: true + # When > 0, also trust any action whose upstream repository has at + # least this many GitHub stars. Catches rename/re-creation squats + # where a once-trusted name is re-registered with no history. + # Requires GitHub API access; 0 disables the star check. + minimumStars: 0 + # Allowlist of trusted action sources. Each entry is either an + # exact `owner/repo` or an `owner/*` wildcard for a whole org. + trustedGithubActions: + - getplumber/plumber # Plumber's own GitHub Action + - zizmorcore/zizmor-action # GitHub Actions static analysis (zizmor) + - boostsecurityio/poutine-action # CI/CD exploit-chain analysis (poutine) + - step-security/harden-runner # egress monitoring, first step of every job + - sigstore/cosign-installer # keyless signing of the release bundle + - astral-sh/setup-uv # uv installer (Astral, maintainer of ruff/uv) + - pypa/gh-action-pypi-publish # official PyPA publisher (Trusted Publishing) + - ossf/scorecard-action + - docker/setup-qemu-action + - docker/setup-buildx-action + - docker/login-action + - docker/metadata-action + - docker/build-push-action + - anchore/scan-action + + # =========================================== + # Container images must not use forbidden tags + # =========================================== + # Same control as GitLab; values are GitHub-side. Pinning by digest + # protects against tag-retag supply-chain attacks. The forbidden tag + # list catches the common cases of mutable references. + containerImageMustNotUseForbiddenTags: + enabled: true + tags: + - latest + - dev + - development + - staging + - main + - master + # When true, ALL images must be pinned by digest (e.g., + # alpine@sha256:...). Takes precedence over the forbidden tags + # list - any image not using an immutable digest reference is + # flagged. + containerImagesMustBePinnedByDigest: true + + # =========================================== + # Pipeline must not use Docker-in-Docker + # =========================================== + # Workflows on GitHub-hosted runners that spin up `docker:dind` + # services have the same privilege-escalation risk as on GitLab. + # detectInsecureDaemon also flags plaintext DOCKER_HOST and empty + # DOCKER_TLS_CERTDIR values. + pipelineMustNotUseDockerInDocker: + enabled: true + detectInsecureDaemon: true + + # =========================================== + # Pipeline must not execute unverified scripts + # =========================================== + # Same control as GitLab (ISSUE-411). Scans every workflow `run:` step + # for pipe-to-shell, download-then-exec, redirect-then-exec, and Megalodon- + # style base64 obfuscation. Maps to OWASP CICD-SEC-3 / CICD-SEC-8. + pipelineMustNotExecuteUnverifiedScripts: + enabled: true + trustedUrls: [] + # - https://internal-artifacts.example.com/* + + # =========================================== + # Reusable workflows must not inherit secrets + # =========================================== + # Detects `jobs..secrets: inherit` calls. Inherit forwards + # every secret visible to the caller - repo, organisation, + # environment - to the reusable workflow regardless of what it + # actually needs. Use an explicit secrets map instead. + reusableWorkflowsMustNotInheritSecrets: + enabled: true + + # =========================================== + # Security jobs must not be weakened + # =========================================== + # Jobs matching the security-scanner naming patterns must not be + # neutralised via `continue-on-error: true` (mapped to the same + # IR field as GitLab's allow_failure: true) or manual-dispatch-only + # triggers. The pattern set covers the GitHub-native scanners + # users actually run - `codeql`, `dependency-review`, `trufflehog`, + # `gitleaks`, `osv-scanner`, plus generic fallbacks like + # `*scan*`, `*audit*`, `*security*` so SAST jobs named with + # project-specific prefixes still match. + securityJobsMustNotBeWeakened: + enabled: true + # How patterns are matched + # ──────────────────────── + # Each pattern is a glob (`*` matches any substring) compared + # against the job name plumber builds for every job in your + # workflows. That name is: + # + # / + # + # Examples: + # .github/workflows/codeql-analysis.yml + jobs.analyze + # -> codeql-analysis/analyze + # .github/workflows/ci.yml + jobs.lint + # -> ci/lint + # .github/workflows/workflow.yml + jobs.my-sast + # -> workflow/my-sast + # + # The namespace exists so two workflow files defining a job + # with the same id do not collide. Patterns can target whichever + # part of that name is stable for your repo: + # "**" token anywhere in the name (resilient) + # "/*" every job in one workflow file + # "*/" specific job id, any workflow + # "/" exact match, no wildcard + # + # The defaults below ship wildcard-wrapped because plumber does + # not know your repo's workflow-file convention. If your jobs + # follow a known layout you can drop the wildcards for tighter + # matching. + securityJobPatterns: + - "*codeql*" + - "*dependency-review*" + - "*trufflehog*" + - "*gitleaks*" + - "*osv-scanner*" + - "*-sast" + - "*-sast-*" + - "*-scan" + - "*scan*" + - "*-security" + - "*-security-*" + - "*-audit" + - "*-audit-*" + # Real-world slash-form examples (commented; uncomment / adapt + # to your repo for a tighter match than the wildcards above). + # Format reminder: /. + # + # - codeql-analysis/analyze # GitHub's default CodeQL template + # - dependency-review/dependency-review # GitHub's default Dependency Review template + # - security/gitleaks # gitleaks job in security.yml + # - security/trufflehog # trufflehog job in security.yml + # - security/* # every job in security.yml + # - "*/sast" # any job named "sast", any workflow + # - ci/semgrep-sast # exact match, no wildcard + allowFailureMustBeFalse: + enabled: true + rulesMustNotBeRedefined: + enabled: true + whenMustNotBeManual: + enabled: true + + # =========================================== + # Workflow must not inject user input in scripts + # =========================================== + # Catches the canonical script-injection class: `${{ github.event.* }}` + # / `${{ github.head_ref }}` / `${{ github.actor }}` interpolated + # directly into a `run:` shell. Attacker-controlled values like PR + # title or branch name can break out of the intended string and + # execute arbitrary commands with the job's secrets. Bind through + # `env:` first, then reference the env var from the shell. + workflowMustNotInjectUserInputInScripts: + enabled: true + + # =========================================== + # Workflow must not write untrusted content to $GITHUB_ENV / $GITHUB_PATH + # =========================================== + # Flags a `run:` step that writes an attacker-controlled expression + # (${{ github.event.* }} / ${{ github.head_ref }}) into $GITHUB_ENV or + # $GITHUB_PATH. Both files are sticky: every later step inherits the + # variable or PATH entry, so an injected NODE_OPTIONS (or a front-loaded + # PATH directory) hijacks later steps. Critical under pull_request_target / + # workflow_run. Bind the value through `env:` and reference the shell + # variable on the redirect line. + workflowMustNotWriteUntrustedContentToGitHubEnv: + enabled: true + + # =========================================== + # Workflow must not use dangerous triggers + # =========================================== + # Flags `pull_request_target` and `workflow_run` triggers, which + # run with the base repository's secrets while being influenceable + # by an unprivileged caller. Combined with any user-content + # checkout this becomes a direct exfiltration path (CVE-2025-30066). + # Use the standard `pull_request` trigger unless secrets are + # required. + workflowMustNotUseDangerousTriggers: + enabled: true + + # =========================================== + # pull_request_target must not check out PR head + # =========================================== + # Flags a workflow triggered by `pull_request_target` that checks + # out the pull-request head (github.event.pull_request.head.sha or + # github.head_ref). Base-repo secrets and fork-controlled code then + # run together, which is the tj-actions / CVE-2025-30066 vector. + # Keep fork code under a plain `pull_request` trigger instead. + pullRequestTargetMustNotCheckoutHead: + enabled: true + + # =========================================== + # Workflows must declare permissions + # =========================================== + # Workflows without an explicit `permissions:` block fall back to + # the repo-wide GITHUB_TOKEN default - often `contents: write` or + # `read-all`. Declaring `permissions: { contents: read }` at the + # workflow level enforces least-privilege regardless of the repo + # default. + workflowsMustDeclarePermissions: + enabled: true + + # =========================================== + # Branch must be protected (project governance) + # =========================================== + # The first project-governance control on the GitHub path. Every + # other shipping rule is pipeline-governance (workflow content); + # this one inspects repository settings via the GitHub branch- + # protection API. Requires a token with `repo` scope (classic + # PAT) or "Administration: read" (fine-grained PAT) - content- + # only read access is NOT enough. Without scope the collector + # returns an empty branch list and the rule emits no findings, + # same degraded contract as missing API auth elsewhere. + branchMustBeProtected: + enabled: true + defaultMustBeProtected: true + namePatterns: + - main + - master + - release/* + - production + - dev + allowForcePush: false + codeOwnerApprovalRequired: false + + # ============================================================================ + # Workflows must include required actions + # ============================================================================ + # Asserts that every workflow file under .github/workflows/ + # collectively references a set of required actions or reusable + # workflows. The GitHub counterpart of + # pipelineMustIncludeComponent / pipelineMustIncludeTemplate on + # the GitLab side. + # + # GitHub has two ways to "include" something external; the + # control treats both the same so you do not have to declare + # which is which: + # + # Step-level action: + # steps: + # - uses: myorg/sast-scan@v2 + # + # Job-level reusable workflow call: + # jobs: + # security: + # uses: myorg/policy/.github/workflows/scan.yml@v2 + # + # Each required entry is an `owner/repo[/path]` string. Matching + # is ref-agnostic so bumping a pinned SHA does not invalidate + # the policy. A slash-guard prevents accidental prefix + # collisions: `myorg/sast-scan` matches + # `myorg/sast-scan@` and + # `myorg/sast-scan/sub@`, but NOT + # `myorg/sast-scan-fork@`. + # + # Two ways to define requirements (use one, not both): + # + # Option 1, Expression syntax ('required'): + # A natural boolean expression using AND, OR, and parentheses. + # AND binds tighter than OR, so "a AND b OR c" means + # "(a AND b) OR c". + # + # required: myorg/sast-scan AND myorg/dependency-review + # required: (myorg/sast-scan AND myorg/secret-scan) OR myorg/full-security-suite + # + # Option 2, Array syntax ('requiredGroups'): + # A list of groups using "OR of ANDs" logic: + # - Each inner array = items that must ALL be present (AND) + # - Outer array = only ONE group needs to be satisfied (OR) + # + # requiredGroups: + # - ["myorg/sast-scan", "myorg/dependency-review"] + # - ["myorg/full-security-suite"] + # + # Disabled by default; opt in once your organization has settled + # on the action set every repo is expected to wire up. + workflowMustIncludeRequiredActions: + enabled: false + # required: myorg/sast-scan AND myorg/policy/.github/workflows/scan.yml + requiredGroups: [] + + # =========================================== + # Workflow must not grant write-all permissions + # =========================================== + # Flags workflows and jobs whose effective `permissions:` block is the + # literal `write-all` shortcut. write-all gives GITHUB_TOKEN every + # scope (contents, packages, deployments, id-token, …) at the same + # time, so any compromise in the workflow - a malicious dependency, + # a script-injection bug, a third-party action turning evil - gets + # to do anything the repo allows: push to main, publish releases, + # mint OIDC tokens for cloud accounts, mark deployments succeeded. + # + # Workflow-level `permissions: write-all` is propagated to every + # job by the GitHub Actions runner; the rule reads the per-job + # effective permissions, so a workflow-level grant is caught the + # same way as a job-level one. + # + # Scope: static `permissions:` in committed workflow YAML only. + # Flags the literal string shortcut `write-all` on a job's effective + # permissions (workflow-level `write-all` is propagated to every job). + # + # Does not flag: `permissions: { contents: write, … }` maps, `read-all`, + # or missing `permissions:` (see `workflowsMustDeclarePermissions` / + # ISSUE-801). Does not evaluate `${{ }}` expressions or permissions + # inside callee reusable-workflow files Plumber did not fetch. + # + # Pair with `workflowsMustDeclarePermissions` for the full story. + workflowMustNotGrantPermissionsWriteAll: + enabled: true + + # =========================================== + # Actions must not use ambiguous tag/branch refs + # =========================================== + # Flags `uses: owner/repo@ref` references whose symbolic name resolves + # upstream as BOTH a tag and a branch (e.g. a tag `v1` kept alongside a + # long-lived `v1` branch). GitHub Actions resolves tags first, so the + # workflow runs the tagged commit today - but a tag deletion, rename, or + # a workflow typo silently switches which revision executes, and the + # reviewer cannot tell from the YAML alone. Pin to a 40-char commit SHA + # to remove the ambiguity. + # + # Scope: committed `.github/workflows/*.{yml,yaml}` only; step-level + # `uses: owner/repo@ref`. Requires GitHub API auth: the collector probes + # both the tag and branch namespaces, and without auth the rule abstains. + # + # Fail-safe: the finding fires only on a positive tag+branch double-hit; + # any probe failure leaves the ref unflagged (no false positive). + externalRefsMustNotCollide: + enabled: true + + # =========================================== + # Actions must not reference archived repositories + # =========================================== + # Flags `uses: owner/repo@ref` references whose upstream repository + # is archived on GitHub. Archived repos no longer receive + # maintenance: open vulnerabilities stay open, dependency bumps + # stop, runtime compatibility regressions accumulate. Pinning by + # SHA does not save the caller - the last maintainer (or someone + # who later acquires the namespace) can still push new code under + # the original repository name. + # + # Scope: committed `.github/workflows/*.{yml,yaml}` only; step-level + # `uses: owner/repo@ref` (not reusable-workflow `jobs.*.uses`, not + # local `./.github/actions/*`). Requires GitHub API auth; without it + # the rule abstains (no finding). + # + # How it works: `GET /repos/{owner}/{repo}` → `archived` flag, one + # cached lookup per `owner/repo` (all refs share the same result). + # + # Does not see: callee reusable-workflow files, deleted/private repos + # (lookup may fail silently → abstain). + actionsMustNotBeArchived: + enabled: true + + # =========================================== + # Actions must not carry known CVEs + # =========================================== + # Cross-references every `uses: owner/repo@ref` against the GitHub + # Advisory Database under the `actions` ecosystem. A positive hit + # means at least one published advisory targets the action's + # repository. This is the rule that catches the published-CVE + # supply-chain class - tj-actions/changed-files (CVE-2025-30066), + # reviewdog/action-setup (March 2025), unpatched versions of + # `actions/artifact`. + # + # Scope: committed `.github/workflows/*.{yml,yaml}` only; step-level + # `uses: owner/repo@ref` (not reusable-workflow `jobs.*.uses`, not + # `./.github/actions/*`, not `docker://`). Requires GitHub API auth + # (`gh` / GH_TOKEN); without it the rule abstains (no finding). + # + # How it works: one Advisory Database query per `owner/repo` + # (`ecosystem=actions`), cached. When the pinned ref resolves to a + # semver tag, Plumber filters advisories by `vulnerable_version_range`. + # A ref that cannot be resolved to a release version - a commit SHA + # with no matching release tag, or a mutable non-numeric tag such as + # `rc` / `main` / `latest` - abstains and surfaces a "could not verify" + # warning rather than matching every advisory for that repo. Upgrade + # past the fixed-in version and re-pin the SHA to clear the finding. + # + # Does not see: org/repo Variables, runtime `$GITHUB_ENV` writes, or + # actions nested inside composite actions you do not call directly. + actionsMustNotCarryKnownCVEs: + enabled: true + + # =========================================== + # Pipeline must not enable debug trace + # =========================================== + # GitHub-side parallel of the GitLab `pipelineMustNotEnableDebugTrace` + # control. Flags workflows or jobs that set the GitHub Actions + # debug-trace toggles to a truthy value (`true`, `1`, `yes`). + # + # When `ACTIONS_STEP_DEBUG=true` or `ACTIONS_RUNNER_DEBUG=true`, + # the runner prints every environment variable (including masked + # secrets) and every internal action SDK call into the job log. + # The masking layer is bypassed for the dump itself, so any + # secret consumed by the workflow lands in plaintext in the run + # log and is then visible to anyone with `actions: read` on the + # repository, plus indefinitely on log artefacts. + # + # Scope: static `env:` in committed `.github/workflows/*.{yml,yaml}`. + # The collector merges workflow-, job-, and step-level `env:` into + # each job (step > job > workflow precedence on name collisions). + # + # Truthy values: `true`, `1`, `yes` (case-insensitive, trimmed). + # Variable names: case-insensitive match against `forbiddenVariables`. + # + # Also flags: `${{ }}` values on forbidden names in static `env:` + # (cannot verify off statically), and `run:` lines that write a + # forbidden name to `$GITHUB_ENV`. All ISSUE-203 findings are critical. + # + # Does not see: org/repo/environment Variables with no YAML reference, + # env inside callee reusable workflows Plumber did not fetch, or GitHub + # UI "Re-run with debug logging" (not in YAML). + pipelineMustNotEnableDebugTrace: + enabled: true + forbiddenVariables: + - ACTIONS_STEP_DEBUG + - ACTIONS_RUNNER_DEBUG diff --git a/tests/test_socle_badges.py b/tests/test_socle_badges.py new file mode 100644 index 0000000..a468245 --- /dev/null +++ b/tests/test_socle_badges.py @@ -0,0 +1,211 @@ +"""Les badges du README d'un catalogue neuf, et les workflows qui les remplissent. + +Les catalogues de la collection portent cinq badges sous la ligne de langue : +CI, OpenSSF Scorecard, Plumber, SLSA 3 et licence. `new catalog` n'en écrivait +aucun, et ne posait pas les deux workflows sans lesquels les badges Scorecard +et Plumber restent vides. + +Ce que ces tests tiennent : + +- avec `--github`, les cinq badges visent `/` ; +- sans lui, ils visent l'emplacement ``, et la CLI dit de le remplacer ; +- aucun propriétaire réel n'est codé dans le moteur ; +- les workflows Scorecard et Plumber sont écrits, et leur YAML se charge. + +Aucun test ne lit le rendu Rich : on lit les fichiers produits, et l'appel au +message, intercepté avant d'être affiché. +""" + +from __future__ import annotations + +import re +from pathlib import Path + +import pytest +import yaml +from typer.testing import CliRunner + +from dsoxlab.cli import app +from dsoxlab.i18n import _ +from dsoxlab.services.scaffold import ScaffoldError, creer_catalogue +from dsoxlab.services.scaffold_socle import PROPRIETAIRE_PAR_DEFAUT + +runner = CliRunner() + +#: Le texte alternatif de chaque badge, par langue. Seuls Plumber et la licence +#: se traduisent. +ALT_EN = ("CI", "OpenSSF Scorecard", "Plumber compliance", "SLSA 3", + "License: CC BY 4.0") +ALT_FR = ("CI", "OpenSSF Scorecard", "Conformité Plumber", "SLSA 3", + "Licence : CC BY 4.0") + + +def _badges(readme: Path) -> list[str]: + """Les lignes de badges, juste sous la ligne de langue.""" + return [ligne for ligne in readme.read_text(encoding="utf-8").splitlines() + if ligne.startswith("[![")] + + +def _verifier_badges(racine: Path, depot: str) -> None: + for nom, alts in (("README.md", ALT_EN), ("README.fr.md", ALT_FR)): + lignes = _badges(racine / nom) + assert [re.match(r"\[!\[([^\]]+)\]", ligne).group(1) # type: ignore[union-attr] + for ligne in lignes] == list(alts), f"{nom} : badges {lignes}" + # CI, Scorecard et Plumber visent le dépôt ; SLSA et la licence non. + for ligne in lignes[:3]: + assert ligne.count(depot) == 2, ( + f"{nom} : l'image et le lien de {ligne} ne visent pas tous deux {depot}" + ) + assert lignes[4].endswith("(./LICENSE)") + + +def test_avec_github_les_cinq_badges_visent_le_depot(tmp_path: Path) -> None: + racine = creer_catalogue("demo", tmp_path, proprietaire="exemple").racine + + _verifier_badges(racine, "exemple/demo") + assert PROPRIETAIRE_PAR_DEFAUT not in (racine / "README.md").read_text( + encoding="utf-8") + + +def test_les_badges_sont_sous_la_ligne_de_langue(tmp_path: Path) -> None: + """La place est celle des catalogues : la ligne de langue, puis les badges.""" + racine = creer_catalogue("demo", tmp_path, proprietaire="exemple").racine + for nom, langue in (("README.md", "**Language:**"), ("README.fr.md", "**Langue :**")): + lignes = (racine / nom).read_text(encoding="utf-8").splitlines() + rang = next(i for i, ligne in enumerate(lignes) if ligne.startswith(langue)) + assert lignes[rang + 1] == "" + assert lignes[rang + 2].startswith("[![CI]"), f"{nom} : {lignes[rang + 2]}" + + +def test_sans_github_les_badges_portent_l_emplacement(tmp_path: Path) -> None: + racine = creer_catalogue("demo", tmp_path).racine + + _verifier_badges(racine, "/demo") + + +def test_le_proprietaire_sert_aussi_dans_releasing(tmp_path: Path) -> None: + """Les commandes de vérification visent le même dépôt que les badges.""" + racine = creer_catalogue("demo", tmp_path, proprietaire="exemple").racine + for nom in ("RELEASING.md", "RELEASING.fr.md", ".github/workflows/attester.yml"): + texte = (racine / nom).read_text(encoding="utf-8") + assert "--repo exemple/demo" in texte, f"{nom} ne vise pas exemple/demo" + assert "" not in texte, f"{nom} garde l'emplacement " + + +def test_aucun_proprietaire_reel_n_est_code_dans_le_socle(tmp_path: Path) -> None: + """Partout où le dépôt du catalogue est nommé, c'est sous le propriétaire donné. + + Avant ce test, RELEASING portait un propriétaire réel en dur : un catalogue + créé par quelqu'un d'autre aurait vérifié ses releases contre le dépôt d'un + tiers. + """ + racine = creer_catalogue("demo", tmp_path, proprietaire="exemple").racine + vus = 0 + for chemin in racine.rglob("*"): + if not chemin.is_file(): + continue + texte = chemin.read_text(encoding="utf-8") + for proprietaire in re.findall(r"([\w.<>-]+)/demo(?![\w-])", texte): + vus += 1 + assert proprietaire.endswith("exemple"), ( + f"{chemin.relative_to(racine)} nomme {proprietaire}/demo" + ) + assert vus > 10, "le dépôt du catalogue n'est presque nommé nulle part" + + +@pytest.mark.parametrize("mauvais", ["", "-exemple", "exemple-", "ex--emple", + "ex/emple", "a" * 40, "ex emple", ""]) +def test_un_proprietaire_invalide_est_refuse_avant_d_ecrire( + tmp_path: Path, mauvais: str +) -> None: + with pytest.raises(ScaffoldError): + creer_catalogue("demo", tmp_path, proprietaire=mauvais) + assert not (tmp_path / "demo").exists(), "un squelette à moitié écrit est resté" + + +def _messages_avertis(monkeypatch: pytest.MonkeyPatch) -> list[str]: + """Intercepte les avertissements de `new catalog` avant leur affichage.""" + from dsoxlab.cli import auteur + + recus: list[str] = [] + monkeypatch.setattr(auteur, "warn", lambda message, *a, **k: recus.append(message)) + return recus + + +def test_la_cli_sans_github_dit_de_remplacer_l_emplacement( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + recus = _messages_avertis(monkeypatch) + + resultat = runner.invoke(app, ["new", "catalog", "demo", "--in", str(tmp_path)]) + + assert resultat.exit_code == 0, resultat.output + assert _("scaffold_github_a_remplacer", name="demo") in recus + _verifier_badges(tmp_path / "demo", "/demo") + + +def test_la_cli_avec_github_ne_dit_rien( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + recus = _messages_avertis(monkeypatch) + + resultat = runner.invoke( + app, ["new", "catalog", "demo", "--in", str(tmp_path), "--github", "exemple"] + ) + + assert resultat.exit_code == 0, resultat.output + assert recus == [] + _verifier_badges(tmp_path / "demo", "exemple/demo") + + +def test_la_cli_refuse_un_proprietaire_invalide(tmp_path: Path) -> None: + resultat = runner.invoke( + app, ["new", "catalog", "demo", "--in", str(tmp_path), "--github", "a/b"] + ) + + assert resultat.exit_code == 1 + assert not (tmp_path / "demo").exists() + + +def test_l_option_github_existe() -> None: + """L'option est déclarée sur `new catalog`, avec une aide traduite.""" + import typer.main + + groupe = typer.main.get_command(app) + commande = groupe.commands["new"].commands["catalog"] # type: ignore[attr-defined] + options = {nom for param in commande.params for nom in param.opts} + assert "--github" in options + aide = next(p.help for p in commande.params if "--github" in p.opts) # type: ignore[attr-defined] + assert aide == _("opt_new_github") + + +# ── Les workflows qui remplissent les badges ──────────────────────────────── + + +def test_les_workflows_des_badges_sont_ecrits_et_se_chargent(tmp_path: Path) -> None: + racine = creer_catalogue("demo", tmp_path).racine + workflows = racine / ".github" / "workflows" + + scorecard = yaml.safe_load((workflows / "scorecard.yml").read_text(encoding="utf-8")) + plumber = yaml.safe_load((workflows / "plumber.yml").read_text(encoding="utf-8")) + + for nom, workflow in (("scorecard", scorecard), ("plumber", plumber)): + # Deny-by-default au niveau du workflow, permissions par job. + assert workflow["permissions"] == {}, f"{nom} : permissions globales" + for job in workflow["jobs"].values(): + assert job["permissions"]["contents"] == "read" + # Les accolades de str.format ont bien été dédoublées puis rendues. + assert job["if"] == "${{ !github.event.repository.private }}" + actions = [s.get("uses", "") for s in scorecard["jobs"]["analysis"]["steps"]] + assert any(a.startswith("ossf/scorecard-action@") for a in actions) + actions = [s.get("uses", "") for s in plumber["jobs"]["plumber"]["steps"]] + assert any(a.startswith("getplumber/plumber@") for a in actions) + + +def test_le_workflow_plumber_trouve_sa_configuration(tmp_path: Path) -> None: + """L'action Plumber refuse de tourner sans `.plumber.yaml`.""" + racine = creer_catalogue("demo", tmp_path).racine + + config = yaml.safe_load((racine / ".plumber.yaml").read_text(encoding="utf-8")) + assert config["version"] == "2.0" + assert "github" in config diff --git a/tests/test_socle_du_catalogue.py b/tests/test_socle_du_catalogue.py index a23ae0e..828ba77 100644 --- a/tests/test_socle_du_catalogue.py +++ b/tests/test_socle_du_catalogue.py @@ -19,6 +19,7 @@ from __future__ import annotations +import json import re from pathlib import Path @@ -167,24 +168,31 @@ def test_la_licence_est_le_texte_nu(catalogue: Path) -> None: def test_le_workflow_et_les_hooks_sont_bien_formes(catalogue: Path) -> None: """Un YAML produit cassé serait découvert au premier push, pas avant.""" - for relatif in (".github/workflows/ci.yml", ".pre-commit-config.yaml", - "meta.yml", "meta.fr.yml"): + for relatif in (".github/workflows/ci.yml", ".github/workflows/scorecard.yml", + ".github/workflows/plumber.yml", ".plumber.yaml", + ".pre-commit-config.yaml", "meta.yml", "meta.fr.yml"): chemin = catalogue / relatif assert chemin.is_file(), f"{relatif} manque" yaml.safe_load(chemin.read_text(encoding="utf-8")) +#: Une clé `uses:` de YAML, en début de ligne. Un commentaire qui CITE une forme +#: de `uses:` pour expliquer pourquoi on ne l'emploie pas n'en est pas une. +_USES = re.compile(r"^\s*(?:-\s+)?uses:\s+(\S+)", re.MULTILINE) + + def test_les_actions_du_workflow_sont_epinglees_par_sha(catalogue: Path) -> None: """Un tag est déplaçable, un SHA non. C'est la règle de ce projet, et un catalogue produit par l'outil ne doit pas démarrer en la violant. """ - source = (catalogue / ".github" / "workflows" / "ci.yml").read_text( - encoding="utf-8") - utilisations = re.findall(r"uses: +(\S+)", source) + utilisations = [] + for workflow in sorted((catalogue / ".github" / "workflows").glob("*.yml")): + trouvees = _USES.findall(workflow.read_text(encoding="utf-8")) + assert trouvees, f"{workflow.name} n'utilise aucune action" + utilisations += [a for a in trouvees if not a.startswith("./")] - assert utilisations, "le workflow produit n'utilise aucune action" for action in utilisations: reference = action.split("@", 1)[-1] assert re.fullmatch(r"[0-9a-f]{40}", reference), ( @@ -529,3 +537,83 @@ def test_le_verrou_est_controle_au_commit(catalogue: Path) -> None: "le hook ne dit pas quoi faire : un catalogue neuf n'a pas de `uv.lock`, " "et le hook échouera jusqu'à ce que son auteur le crée." ) + + +def _controles_du_ruleset(releasing: Path) -> list[str]: + """Les contrôles obligatoires du ruleset que RELEASING propose d'appliquer.""" + texte = releasing.read_text(encoding="utf-8") + trouve = re.search(r"<<'JSON'\n(.*?)\nJSON\n", texte, re.DOTALL) + assert trouve is not None, f"{releasing.name} ne porte plus la charge du ruleset" + charge = json.loads(trouve.group(1)) + return [ + controle["context"] + for regle in charge["rules"] + if regle["type"] == "required_status_checks" + for controle in regle["parameters"]["required_status_checks"] + ] + + +def _noms_des_controles(ci: dict) -> set[str]: + """Les noms que GitHub donne aux contrôles d'un workflow, matrices développées. + + Un job à matrice produit un contrôle par valeur : `CodeQL (${{ matrix.language }})` + sur `[python, actions]` donne `CodeQL (python)` et `CodeQL (actions)`, et + c'est sous ces noms-là que le ruleset doit les exiger. + """ + noms: set[str] = set() + for cle, job in ci["jobs"].items(): + nom = str(job.get("name", cle)) + matrice = (job.get("strategy") or {}).get("matrix") or {} + variables = re.findall(r"\$\{\{\s*matrix\.(\w+)\s*\}\}", nom) + if not variables: + noms.add(nom) + continue + assert len(variables) == 1, f"{nom} : une seule variable de matrice gérée" + variable = variables[0] + for valeur in matrice[variable]: + noms.add(re.sub(r"\$\{\{\s*matrix\.\w+\s*\}\}", str(valeur), nom)) + return noms + + +def test_le_ruleset_n_exige_que_les_jobs_que_la_ci_lance(catalogue: Path) -> None: + """Un contrôle exigé qu'aucun job ne lance bloque toutes les pull requests. + + Le ruleset de RELEASING avait été repris d'un catalogue frère : il exigeait + Zizmor, Actionlint, Poutine, CodeQL… que le `ci.yml` du squelette ne lançait + pas encore. Appliqué sur un catalogue neuf, il a bloqué toutes ses PR : + GitHub attend pour toujours un contrôle qui ne viendra jamais. Le squelette + lance désormais ces jobs ; le test tient l'accord dans les deux sens. + """ + ci = yaml.safe_load( + (catalogue / ".github" / "workflows" / "ci.yml").read_text(encoding="utf-8") + ) + jobs = _noms_des_controles(ci) + + for nom in ("RELEASING.md", "RELEASING.fr.md"): + controles = _controles_du_ruleset(catalogue / nom) + assert controles, f"{nom} : le ruleset n'exige aucun contrôle" + orphelins = sorted(set(controles) - jobs) + assert not orphelins, ( + f"{nom} exige {orphelins}, qu'aucun job de ci.yml ne lance " + f"(jobs : {sorted(jobs)})" + ) + # Et l'inverse : un job de la CI que le ruleset n'exige pas peut + # rougir sans bloquer la fusion. + oublies = sorted(jobs - set(controles)) + assert not oublies, f"{nom} n'exige pas {oublies}" + + +def test_une_action_n_a_qu_une_version_dans_le_socle(catalogue: Path) -> None: + """Deux SHA pour la même action, c'est deux versions à suivre et à auditer. + + Les workflows Scorecard et Plumber sont arrivés avec harden-runner v2.22.3 + quand ci.yml, release.yml et attester.yml portaient encore v2.22.0. + """ + versions: dict[str, set[str]] = {} + for workflow in (catalogue / ".github" / "workflows").glob("*.yml"): + for action in _USES.findall(workflow.read_text(encoding="utf-8")): + if "@" in action: + nom, reference = action.split("@", 1) + versions.setdefault(nom, set()).add(reference) + doublons = {nom: sorted(refs) for nom, refs in versions.items() if len(refs) > 1} + assert not doublons, f"actions épinglées sur plusieurs versions : {doublons}" diff --git a/tests/test_socle_securite.py b/tests/test_socle_securite.py new file mode 100644 index 0000000..261fb29 --- /dev/null +++ b/tests/test_socle_securite.py @@ -0,0 +1,152 @@ +"""La chaîne de sécurité des catalogues frères, posée par `new catalog`. + +Reprise de applications-ia-dsoxlab-training (e7db2da) : les jobs Zizmor, +Actionlint, Poutine, Pre-commit parity et CodeQL dans `ci.yml`, Dependabot, la +configuration CodeQL, CODEOWNERS, les gabarits d'issue, `.poutine.yml`, et une +politique de sécurité avec délais de divulgation. + +Ce que ces tests tiennent : chaque fichier est écrit et se charge ; les sept +contrôles portent les noms exacts que le ruleset exige ; le propriétaire est +celui de `--github`, ou l'emplacement ``, jamais un compte réel. +""" + +from __future__ import annotations + +import re +from pathlib import Path + +import pytest +import yaml + +from dsoxlab.services.scaffold import creer_catalogue +from tests.test_socle_du_catalogue import _noms_des_controles + +#: Les contrôles exigés par le ruleset des catalogues frères, au caractère près. +SEPT_CONTROLES = { + "Zizmor (workflow static analysis)", + "Actionlint (workflow syntax)", + "Poutine (CI/CD exploit chains)", + "Pre-commit parity (all hooks)", + "Contract, guardrails and lint", + "CodeQL (python)", + "CodeQL (actions)", +} + +_YAML = ( + ".github/dependabot.yml", + ".github/codeql/config.yml", + ".github/ISSUE_TEMPLATE/config.yml", + ".github/ISSUE_TEMPLATE/lab_report.yml", + ".poutine.yml", +) + + +@pytest.fixture +def avec(tmp_path: Path) -> Path: + return creer_catalogue("demo", tmp_path / "avec", proprietaire="exemple").racine + + +@pytest.fixture +def sans(tmp_path: Path) -> Path: + return creer_catalogue("demo", tmp_path / "sans").racine + + +def test_chaque_fichier_de_la_chaine_est_ecrit_et_se_charge(avec: Path) -> None: + for relatif in _YAML: + chemin = avec / relatif + assert chemin.is_file(), f"{relatif} manque au socle" + assert yaml.safe_load(chemin.read_text(encoding="utf-8")), f"{relatif} est vide" + for relatif in (".github/CODEOWNERS", "SECURITY.md", "SECURITY.fr.md"): + assert (avec / relatif).is_file(), f"{relatif} manque au socle" + + +def test_les_sept_controles_portent_leur_nom_exact(avec: Path) -> None: + """Le ruleset exige des NOMS : un job renommé est un contrôle jamais rendu.""" + ci = yaml.safe_load( + (avec / ".github" / "workflows" / "ci.yml").read_text(encoding="utf-8") + ) + assert _noms_des_controles(ci) == SEPT_CONTROLES + + +def test_dependabot_suit_le_verrou_et_les_actions(avec: Path) -> None: + config = yaml.safe_load((avec / ".github" / "dependabot.yml").read_text(encoding="utf-8")) + ecosystemes = {u["package-ecosystem"] for u in config["updates"]} + assert ecosystemes == {"uv", "github-actions"} + # Les paliers semver ne sont pas acceptés pour github-actions : les + # déclarer fait rejeter le fichier par GitHub, qui cesse d'ouvrir des PR. + actions = next(u for u in config["updates"] if u["package-ecosystem"] == "github-actions") + assert set(actions["cooldown"]) == {"default-days"} + + +def test_codeql_laisse_les_fixtures_et_les_solutions(avec: Path) -> None: + config = yaml.safe_load((avec / ".github" / "codeql" / "config.yml").read_text(encoding="utf-8")) + assert config["paths-ignore"] == ["labs/**/fixtures/**", "labs/**/solution/**"] + + +def _proprietaires_codeowners(racine: Path) -> set[str]: + texte = (racine / ".github" / "CODEOWNERS").read_text(encoding="utf-8") + return { + mot + for ligne in texte.splitlines() + if ligne.strip() and not ligne.lstrip().startswith("#") + for mot in ligne.split()[1:] + } + + +def test_codeowners_nomme_le_proprietaire_de_github(avec: Path, sans: Path) -> None: + assert _proprietaires_codeowners(avec) == {"@exemple"} + assert _proprietaires_codeowners(sans) == {"@"} + + +def test_security_suit_la_structure_de_reference(avec: Path) -> None: + for nom, titres in ( + ("SECURITY.md", ["Supported versions", "Reporting a vulnerability", + "Disclosure policy", "Scope", + "What this repository will never ask you"]), + ("SECURITY.fr.md", ["Versions supportées", "Signaler une vulnérabilité", + "Politique de divulgation", "Périmètre", + "Ce que ce dépôt ne vous demandera jamais"]), + ): + texte = (avec / nom).read_text(encoding="utf-8") + assert re.findall(r"^## (.+)$", texte, re.MULTILINE) == titres, nom + assert "https://github.com/exemple/demo/security/advisories/new" in texte + assert "90" in texte and "48" in texte, f"{nom} : délais de divulgation absents" + # Le périmètre est celui d'un catalogue de labs, pas d'un domaine. + for nom in ("SECURITY.md", "SECURITY.fr.md"): + texte = (avec / nom).read_text(encoding="utf-8").lower() + for mot in (" ia ", " ai ", "intelligence", "agent"): + assert mot not in texte, f"{nom} parle encore de {mot.strip()!r}" + + +def test_le_gabarit_d_issue_vise_le_depot_du_catalogue(avec: Path) -> None: + config = yaml.safe_load( + (avec / ".github" / "ISSUE_TEMPLATE" / "config.yml").read_text(encoding="utf-8") + ) + urls = [lien["url"] for lien in config["contact_links"]] + assert "https://github.com/exemple/demo/security/advisories/new" in urls + rapport = (avec / ".github" / "ISSUE_TEMPLATE" / "lab_report.yml").read_text(encoding="utf-8") + assert "exemple/demo" in rapport + + +#: Les seuls dépôts tiers qu'un catalogue neuf peut nommer : le moteur, et les +#: deux binaires que la CI télécharge avec vérification d'empreinte. +_DEPOTS_TIERS = {"dsoxlab", "actionlint", "trufflehog"} + + +def test_aucun_proprietaire_reel_sans_option_github(sans: Path) -> None: + """Sans `--github`, le catalogue n'est attribué à personne de réel. + + Toute URL GitHub d'un fichier `.github/` ou de SECURITY vise soit le dépôt + `/demo`, soit un dépôt tiers attendu (le moteur, un binaire vérifié). + """ + fichiers = [p for p in (sans / ".github").rglob("*") if p.is_file()] + fichiers += [sans / "SECURITY.md", sans / "SECURITY.fr.md", sans / ".poutine.yml"] + for chemin in fichiers: + texte = chemin.read_text(encoding="utf-8") + for proprietaire, depot in re.findall(r"github\.com/([\w.<>-]+)/([\w.<>-]+)", texte): + if proprietaire == "": + assert depot.startswith("demo"), f"{chemin.name} : /{depot}" + continue + assert depot in _DEPOTS_TIERS, ( + f"{chemin.relative_to(sans)} nomme {proprietaire}/{depot}" + ) diff --git a/uv.lock b/uv.lock index cde9bda..a6dfc35 100644 --- a/uv.lock +++ b/uv.lock @@ -331,7 +331,7 @@ wheels = [ [[package]] name = "dsoxlab" -version = "0.9.3" +version = "0.9.4" source = { editable = "." } dependencies = [ { name = "ansible-core" },