diff --git a/.gitattributes b/.gitattributes index f925aea7..87a805ee 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,2 +1,63 @@ -.github/workflows/ci.yml merge=ours -.github/workflows/promote.yml merge=ours \ No newline at end of file +# Fork-sync protection for OutSystems-owned files. +# +# This repo is a fork of jpillora/chisel and is synced from upstream regularly. +# `merge=ours` keeps OUR version of a path when an upstream merge touches it. +# +# ⚠ REQUIRED ONE-TIME SETUP IN EVERY CLONE ⚠ +# The `ours` merge driver is NOT built into git. Without this config these rules +# silently do nothing and upstream will overwrite the files below: +# +# git config merge.ours.driver true +# +# It is local config and cannot be committed, so each developer — and any CI +# job that merges from upstream — must run it once. Verify with: +# +# git config --get merge.ours.driver # must print: true +# +# Note: this protects MERGES. Cherry-picks of upstream commits that touch these +# paths still need manual review. + +# --- Paths that exist in BOTH our fork and upstream (real collisions) --- +.github/workflows/ci.yml merge=ours + +# promote.yml is NEUTERED, NOT DELETED, and must stay that way. +# +# Upstream ships a real 56-line workflow here: on `release: published` it +# retags the version manifest to latest//. on GHCR AND +# Docker Hub via `docker buildx imagetools create` -- no vulnerability gate +# anywhere in front of it. We do not want it. +# +# We keep the path occupied by an INERT PLACEHOLDER: a valid workflow whose +# only trigger is workflow_dispatch and whose only job explains itself and +# fails. That is load-bearing in two ways: +# 1. it can never fire on its own, and holds no permissions; +# 2. `merge=ours` binds to a PATH. With the path occupied, every upstream +# sync resolves in our favour and upstream's version stays out. +# +# Deleting the path instead would remove the shield silently -- nothing fails +# until the next sync, which then restores upstream's version. +# +# Production OutSystems/chisel currently truncates this file to 0 bytes +# instead. That works, but GitHub records a FAILED run for an unparseable +# workflow on every push, and a permanently red Actions tab trains people to +# ignore the red that matters. Fold this approach back at cutover. +# +# CI pins the file by SHA-256, so a cherry-pick or hand edit fails the build: +# see "Assert neutered workflows are still neutered" in ci.yml. +.github/workflows/promote.yml merge=ours + +# --- OutSystems-only files (RDODCP-1463). No upstream collision today; +# these entries are defensive in case upstream later adds the same paths. --- +.github/workflows/release.yml merge=ours +.github/workflows/rescan.yml merge=ours +.trivyignore merge=ours +.grype.yaml merge=ours +.gitattributes merge=ours +scripts/scan-report.sh merge=ours +scripts/setup-fork-sync.sh merge=ours + +# --- OutSystems-only, pre-existing. Upstream keeps its own copies under +# .github/ (goreleaser.yml, ko-base.Dockerfile), so these do not collide +# today, but they are ours and must survive any future upstream change. --- +goreleaser.yml merge=ours +Dockerfile merge=ours diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index cc6ad04d..927caa27 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -2,3 +2,15 @@ # Global reviewers * @OutSystems/cloud-enablement-services + +# The build and release pipeline, and everything the vulnerability gate depends +# on. A change here can publish an unscanned artifact or exfiltrate a token, so +# it must not ride along in an unrelated review. +/.github/workflows/ @OutSystems/cloud-enablement-services +/.github/dependabot.yml @OutSystems/cloud-enablement-services +/scripts/ @OutSystems/cloud-enablement-services +/goreleaser.yml @OutSystems/cloud-enablement-services +/Dockerfile @OutSystems/cloud-enablement-services +/.trivyignore @OutSystems/cloud-enablement-services +/.grype.yaml @OutSystems/cloud-enablement-services +/.gitattributes @OutSystems/cloud-enablement-services diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 6067b7de..dade381e 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -1,13 +1,22 @@ version: 2 updates: - # Maintain dependencies for GitHub Actions + # GitHub Actions. + # Weekly, not monthly: anchore/scan-action pins the Grype binary INSIDE the + # action (GrypeVersion.js), so bumping the action is the only way that pin + # moves. A month of drift here is a month of scanning with an old database. - package-ecosystem: "github-actions" directory: "/" schedule: - interval: "monthly" + interval: "weekly" + + # Base images. Proposes a PR when a newer base image is published. + - package-ecosystem: "docker" + directory: "/" + schedule: + interval: "weekly" -# Dependencies listed in go.mod + # Go modules. - package-ecosystem: "gomod" - directory: "/" # Location of package manifests + directory: "/" schedule: - interval: "monthly" \ No newline at end of file + interval: "monthly" diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e69de29b..02a0f9b0 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -0,0 +1,341 @@ +# Chisel CI — RDODCP-1463 +# +# Replaces the build-and-scan half of the private Azure DevOps pipeline +# (rd-PaaS/pipelines/cloud-connector/templates/publish_image.yaml). +# +# Phase 1 deliberately PUBLISHES NOTHING. GoReleaser runs with --snapshot, so +# the image is built into the runner's local Docker daemon and never pushed. +# No registry permission is required and no secret is referenced. +# +# Threat model (RDODCP-1462) controls implemented here: +# T1 pull_request trigger only; no secrets referenced anywhere in this file +# T2 untrusted values never interpolated into run:; actionlint + zizmor gate +# T3 every action pinned to a full commit SHA +# T5 no PAT — the default GITHUB_TOKEN is read-only here +# T7 GitHub-hosted ephemeral runners only +# T10 Trivy AND Grype both gate on CRITICAL,HIGH; govulncheck added +# T12 .trivyignore / .grype.yaml live in-repo, publicly auditable, and every +# suppression they apply is echoed in the job log (nothing hides silently) +# T13 findings are printed IN FULL in the job log — package, installed +# version and fixed version. No SARIF upload, no artifact upload. +# NOTE: on a public repo the job log is world-readable, so unfixed +# CRITICAL/HIGH CVEs in this image are disclosed the moment CI runs. +# Accepted deliberately: every finding here concerns a public base image +# or a public Go module, and the gate blocks the build until it is fixed. +# T17 no secret material is echoed (the ADO token-debug steps are NOT ported) +# +# GO TOOLCHAIN GATE (differs from ADO on purpose) +# Trivy and Grype both report Go standard-library CVEs with severity UNKNOWN, +# because the Go security team does not publish CVSS scores. A plain +# "severity: CRITICAL,HIGH" filter therefore drops them silently — which is +# what ADO does today. Remediating a stdlib CVE is a one-line bump of the "go" +# directive in go.mod, so this workflow scans every severity and gates on any +# stdlib finding regardless of score, printing the Go version that fixes it. +# +# Deferred: cosign signing, SLSA provenance, SBOM (separate story). + +name: CI + +on: + pull_request: + branches: + - master + - 'RDODCP-**' + push: + branches: + # master is built as-is after every squash-merge. Without this, the + # commit that actually lands on master has never been built in the + # shape it landed in -- only the PR head was. + - master + - 'RDODCP-**' + +# T5 — read-only. No job needs more: nothing is published and nothing is +# uploaded to the Security tab. +permissions: + contents: read + +concurrency: + group: ci-${{ github.ref }} + cancel-in-progress: true + +env: + # Local-only tag. --snapshot never pushes, so this is not a real package. + IMAGE_REF: ghcr.io/outsystems/chisel:latest + +jobs: + test: + name: Unit tests + govulncheck + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 + with: + persist-credentials: false + + # Installs exactly the version in the go.mod "go" directive, so bumping + # that line is what remediates a Go stdlib CVE. + - uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 # v6 + with: + go-version-file: go.mod + cache: true + + - name: go vet + run: go vet ./... + + - name: Unit tests + run: go test -race ./... + + # T14 — call-graph-aware Go vulnerability analysis. Not present in ADO. + # Unlike Trivy/Grype this reports whether the vulnerable symbol is + # actually reachable, and it always names the fixing Go version. + # Keep this version current: govulncheck fails with an internal error on + # a Go release newer than the one it was built against. + # if: always() — a failing unit test must not mask a vulnerability + # report. These are independent signals and we want both on every run. + - name: govulncheck + if: always() + run: | + set -euo pipefail + go install golang.org/x/vuln/cmd/govulncheck@v1.9.0 + + go_directive=$(awk '/^go /{print $2; exit}' go.mod) + echo "go.mod 'go' directive : ${go_directive}" + echo "toolchain used to build: $(go version | awk '{print $3}')" + echo + + # -format json always exits 0, so the gate below is ours to make. + govulncheck -format json ./... > govulncheck.json + + echo "--- Vulnerabilities this code CALLS (build-blocking) -------------------------" + jq -rs ' + def pad($s; $n): ($s | tostring)[0:$n] as $t + | $t + ((" " * ($n - ($t | length))) // ""); + def line($id; $mod; $cur; $fix): pad($id;16) + pad($mod;42) + pad($cur;16) + $fix; + + [ .[] | select(.finding).finding ] + | map(select(.trace[0].function != null)) + | group_by(.osv) | map(.[0]) + | if length == 0 then " None." + else + [ line("ID";"MODULE";"FOUND";"FIXED IN"), + line("--";"------";"-----";"--------") ] + + map(line(.osv; + (.trace[0].module // "-"); + (.trace[0].version // "-"); + (.fixed_version // "NO FIX AVAILABLE"))) + | join("\n") + end + ' govulncheck.json + + echo + echo "--- Present but NOT called (informational, not blocking) ---------------------" + jq -rs ' + [ .[] | select(.finding).finding ] as $f + | ( $f | map(select(.trace[0].function != null) | .osv) | unique ) as $called + | $f + | map(select(.trace[0].function == null)) + | map(select([.osv] | inside($called) | not)) + | group_by(.osv) | map(.[0]) + | if length == 0 then " None." + else map(" \(.osv) \(.trace[0].module) \(.trace[0].version // "-") -> fixed in \(.fixed_version // "no fix")") + | join("\n") + end + ' govulncheck.json + + called=$(jq -rs '[ .[] | select(.finding).finding ] + | map(select(.trace[0].function != null) | .osv) | unique | length' govulncheck.json) + + echo + if [ "${called}" -gt 0 ]; then + gofix=$(jq -rs '[ .[] | select(.finding).finding ] + | map(select(.trace[0].function != null and .trace[0].module == "stdlib") | .fixed_version) + | map(select(. != null) | ltrimstr("v")) | unique | join(", ")' govulncheck.json) + if [ -n "${gofix}" ]; then + echo "::error::Go toolchain is vulnerable. Set the 'go' directive in go.mod to ${gofix} (currently ${go_directive})." + fi + echo "::error::govulncheck: ${called} reachable vulnerability(ies). See the table above for the fixing version." + exit 1 + fi + echo "govulncheck: no reachable vulnerabilities." + + lint-workflows: + name: Workflow lint (actionlint + zizmor) + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 + with: + persist-credentials: false + + - uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 # v6 + with: + go-version-file: go.mod + + # T2 — catches ${{ }} interpolation of untrusted input into run: blocks. + # Every workflow is valid YAML, including the disabled promote.yml + # placeholder, so both linters run over the whole directory. + - name: actionlint + run: | + go install github.com/rhysd/actionlint/cmd/actionlint@v1.7.12 + actionlint -color + + # T3 — fails the build on any action referenced by a mutable tag. + - name: zizmor + run: | + python3 -m pip install --disable-pip-version-check --quiet zizmor==1.32.0 + zizmor --persona=regular .github/workflows/ + + # The real control. promote.yml exists UPSTREAM as a 56-line workflow + # that retags images to latest//. on GHCR and + # Docker Hub when a release is published -- with no vulnerability gate + # in front of it. We keep the path occupied by an inert placeholder so + # that `merge=ours` in .gitattributes has something to bind to and an + # upstream sync can never restore the real thing. + # + # Pinned by content, not just by existence: a checksum catches a + # cherry-pick or a hand edit that `merge=ours` would not see. If you + # are changing this file deliberately, update the hash here too -- the + # build failing is the point. + - name: Assert neutered workflows are still neutered + run: | + set -euo pipefail + expected='73019a0df58f83bc3319255a6784bce850aaab156d71a8da216060268f49ada0' + f=.github/workflows/promote.yml + if [ ! -e "${f}" ]; then + echo "::error file=${f}::${f} was DELETED. It must exist: .gitattributes relies on the path to keep upstream's version out." + exit 1 + fi + actual=$(sha256sum "${f}" | cut -d' ' -f1) + if [ "${actual}" != "${expected}" ]; then + echo "::error file=${f}::${f} changed. expected ${expected}, got ${actual}. Upstream's promote.yml publishes to GHCR and Docker Hub with no vulnerability gate -- confirm this edit is yours, then update the hash in ci.yml." + exit 1 + fi + echo "ok: ${f} is the known-inert placeholder (${actual})" + + build-scan: + name: Build image + Trivy/Grype gate + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 + with: + fetch-depth: 0 # goreleaser needs tag history to derive a version + persist-credentials: false + + - uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 # v6 + with: + go-version-file: go.mod + # cache: false — zizmor [cache-poisoning]. The Go build cache is + # writable from a PR branch, and this job's output is the artifact we + # scan and (in release.yml) publish. A poisoned cache entry could put + # code into the image that no scanner attributes to a source file. + # The cache saves ~30s; the job is not worth that risk. + cache: false + + # ADO: "Run GoReleaser Build (No Publish)". + # --snapshot builds the binary and the Docker image locally; it cannot push. + - name: GoReleaser build (snapshot, no publish) + uses: goreleaser/goreleaser-action@e435ccd777264be153ace6237001ef4d979d3a7a # v6 + with: + version: v2.20.2 + args: release --snapshot --clean --config goreleaser.yml + + - name: Confirm image was built locally + run: | + echo "Go toolchain: $(go version | awk '{print $3}') (from the go.mod 'go' directive)" + echo "Images built:" + docker images --format '{{.Repository}}:{{.Tag}} {{.ID}}' | grep chisel + docker image inspect "$IMAGE_REF" --format 'id={{.Id}} created={{.Created}}' + + # ADO: "Download and Run Trivy Scan" — scans the LOCAL image, never pulls. + # No severity filter here on purpose: Go stdlib CVEs carry severity + # UNKNOWN and would be dropped before we ever saw them. Filtering and + # gating are done by the steps below, from the full JSON. + - name: Trivy scan + uses: aquasecurity/trivy-action@ed142fd0673e97e23eac54620cfb913e5ce36c25 # v0.36.0 + env: + # T12 — keep ignored findings in the report so the log can show what + # .trivyignore suppressed instead of silently dropping it. + TRIVY_SHOW_SUPPRESSED: 'true' + with: + # 'latest' on purpose. Aqua DELETES old Trivy releases outright + # (everything below ~v0.70.0 now 404s), so ANY pin here is a dated + # time bomb: it works until the release is removed, then the + # installer exits 1 with no error message. trivy-action overrides + # setup-trivy's own 'latest' default with a lagging pin, so this + # restores it. Note the vulnerability DB is fetched fresh every run + # regardless -- floating the binary buys newer detection logic and + # parsers, not newer CVE data. + version: latest + image-ref: ${{ env.IMAGE_REF }} + scan-type: image + scanners: vuln + # NOTE: the input is vuln-type. trivy-action silently IGNORES an + # unknown input (it only warns), so 'pkg-types' was a no-op here. + vuln-type: os,library + trivyignores: .trivyignore + format: json + output: trivy.json + exit-code: '0' # the gate step below decides, not the scanner + timeout: 10m + + - name: Trivy findings + if: always() + run: ./scripts/scan-report.sh report trivy trivy.json "$IMAGE_REF" + + # ADO: "Setup Grype and Run Scan". .grype.yaml at repo root is picked up + # automatically by grype, so the suppression list applies without a flag. + # severity-cutoff only sets the scanner's own fail threshold; the JSON + # still contains every severity, so the report step filters it. + # if: always() — a Trivy crash must not rob us of Grype's findings. The + # two scanners disagree in both directions (Grype alone sees the zlib + # CRITICAL; Trivy alone sees the x/net HIGH), so one dying must never + # silently halve our coverage. + # Grype has no 'latest' equivalent: scan-action hard-pins a version in + # GrypeVersion.js (v6 pinned v0.97.1; v7.4.2 pins v0.118.0, while Grype + # itself is already past v0.122). The `grype-version` input takes a + # concrete tag, so resolve the newest release at run time and pass it. + # The ACTION stays SHA-pinned -- that is the supply-chain control, and it + # is unaffected by which scanner binary it then downloads. + - name: Resolve the latest Grype release + id: grype-version + if: always() + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + set -euo pipefail + v=$(gh api repos/anchore/grype/releases/latest --jq .tag_name) + case "${v}" in + v[0-9]*) ;; + *) echo "::error::refusing to install unexpected Grype tag '${v}'"; exit 1 ;; + esac + echo "version=${v}" >> "$GITHUB_OUTPUT" + echo "Grype ${v} (action pins v0.118.0; overriding to latest)" + + - name: Grype scan + if: always() + uses: anchore/scan-action@27805bf3b4e84b4a5c980df22ed233c00390a439 # v7.4.2 + with: + image: ${{ env.IMAGE_REF }} + grype-version: ${{ steps.grype-version.outputs.version }} + severity-cutoff: high + output-format: json + output-file: grype.json + fail-build: false # the gate step below decides, not the scanner + + - name: Grype findings + if: always() + run: ./scripts/scan-report.sh report grype grype.json "$IMAGE_REF" + + # ADO: "Check Trivy Vulnerabilities" / "Check Grype Vulnerabilities". + # In ADO these used continueOnError + ##vso[task.setvariable] flags, with + # the publish step gated on those variables. Here a failing step simply + # stops the job, so no flag plumbing is needed. + # + # This is the SAME script release.yml runs before it pushes, so the gate + # that blocks a PR is the gate that blocks a publish. + # if: always() — fails CLOSED. scan-report.sh exits 2 when a report file + # is missing, so a scanner that crashed is treated as a failed gate, not + # as a pass. Without this the gate is simply SKIPPED when a scan step + # fails, which is the one outcome we must never allow to look like "no + # findings". + - name: Gate on CRITICAL/HIGH and Go toolchain + if: always() + run: ./scripts/scan-report.sh gate trivy.json grype.json diff --git a/.github/workflows/promote.yml b/.github/workflows/promote.yml index e69de29b..0ede0ac2 100644 --- a/.github/workflows/promote.yml +++ b/.github/workflows/promote.yml @@ -0,0 +1,42 @@ +# DISABLED PLACEHOLDER — this workflow intentionally does nothing. +# +# Upstream jpillora/chisel ships a REAL workflow at this path. On +# `release: published` it retags the version manifest to latest, +# and . on GHCR *and Docker Hub*, via +# `docker buildx imagetools create`, with no vulnerability scan anywhere in +# front of it. OutSystems does not want that behaviour. +# +# WHY THE FILE IS KEPT RATHER THAN DELETED +# .gitattributes maps this PATH to `merge=ours`. With the path occupied, +# every upstream sync resolves in our favour and upstream's version can +# never land. Delete the path and that protection silently stops working — +# nothing fails until the next sync, which then restores upstream's version. +# +# WHY AN INERT STUB RATHER THAN A 0-BYTE FILE +# GitHub records a failed run for every unparseable workflow on every push. +# A permanently red Actions tab trains people to ignore the red that +# matters — such as the nightly rescan finding a CRITICAL CVE. A valid stub +# keeps the path occupied, lints cleanly, and never fires on its own. +# +# Image promotion of a SCANNED image happens in release.yml, after the gate. +# If you need tag promotion, add it there. Not here. +# +# CI asserts this file's exact SHA-256. Editing it fails the build on +# purpose — see "Assert neutered workflows" in ci.yml. + +name: promote (disabled placeholder) + +on: + workflow_dispatch: + +permissions: {} + +jobs: + disabled: + name: This workflow is intentionally disabled + runs-on: ubuntu-latest + steps: + - name: Explain and fail + run: | + echo "::error::promote.yml is a disabled placeholder. Image promotion happens in release.yml, behind the vulnerability gate. See the comment block at the top of this file." + exit 1 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 00000000..6dd0a1a2 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,445 @@ +# Chisel release — RDODCP-1463 +# +# Publishes to ghcr.io/outsystems/chisel on a tag push. Replaces the publish +# half of the private Azure DevOps pipeline +# (rd-PaaS/pipelines/cloud-connector/templates/publish_image.yaml). +# +# Trigger: a tag of the form v-os., e.g. v1.12.0-os.4 — the existing +# production convention, unchanged. GoReleaser derives the version from the +# tag and names the archives exactly as the ADO pipeline named them. +# +# Publishes TWO artifacts, both only after the vulnerability gate: +# 1. the container image, to ghcr.io/outsystems/chisel, tagged +# : AND :latest +# 2. a GitHub Release badged Latest, carrying the linux archives, +# checksums.txt and an SPDX SBOM: +# chisel__linux_386.tar.gz +# chisel__linux_amd64.tar.gz +# chisel__linux_arm64.tar.gz +# checksums.txt +# chisel__sbom.spdx.json +# +# Order of operations IMPROVES on the ADO pipeline it replaces. ADO builds what +# it scans with `goreleaser release --snapshot --clean`, then publishes with +# `goreleaser release --clean` -- and --clean wipes dist/ and rebuilds, so the +# image and the archives it uploads are NOT the ones it scanned. Here GoReleaser +# runs ONCE with --skip=publish; everything published afterwards comes out of +# that single dist/ directory, and the published digest is asserted equal to the +# digest that passed the gate. Nothing is rebuilt, and nothing is published that +# the gate would have rejected. +# +# SCOPE NOTE. GITHUB_TOKEN's `packages: write` is REPO-scoped, not +# package-scoped: any job in this repo holding it can write to every package +# this repo has write access to. The "Push images" step therefore refuses to +# push any ref outside ${PACKAGE} as a hard stop. + +name: Release + +on: + push: + tags: + - 'v*-os.*' + +permissions: + contents: read + +concurrency: + group: release-${{ github.ref }} + cancel-in-progress: false # never abandon a half-finished push + +env: + PACKAGE: ghcr.io/outsystems/chisel + +jobs: + release: + name: Build, scan, publish to chisel + runs-on: ubuntu-latest + # Phase 5 cutover control. The Environment carries the protection rules — + # required reviewers and a deployment-branch policy — so the approval is + # enforced by GitHub at the job boundary, BEFORE any step holding + # packages: write runs. A protection rule on the branch cannot do this: + # by the time a tag is pushed the decision to publish has already been + # made. This is the gate a human actually stands at. + environment: release + permissions: + # Two elevations over the workflow-level `contents: read`, both scoped to + # this single job and both sitting behind the release approval: + # contents: write -- create the GitHub Release and upload the archives + # packages: write -- push the image to GHCR + # security-events: write -- upload Trivy/Grype SARIF to code scanning + contents: write + packages: write + security-events: write + issues: write + steps: + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 + with: + fetch-depth: 0 # goreleaser needs the tag and its history + persist-credentials: false + + - uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 # v6 + with: + go-version-file: go.mod + # cache: false — zizmor [cache-poisoning]. The Go build cache is + # writable from a PR branch, and this job's output is the artifact we + # scan and (in release.yml) publish. A poisoned cache entry could put + # code into the image that no scanner attributes to a source file. + # The cache saves ~30s; the job is not worth that risk. + cache: false + + # --skip=publish builds the binary and the Docker images into the local + # daemon and pushes nothing. The push happens after the gate, below. + - name: GoReleaser build (local only) + uses: goreleaser/goreleaser-action@e435ccd777264be153ace6237001ef4d979d3a7a # v6 + with: + version: v2.20.2 + args: release --clean --skip=publish --config goreleaser.yml + + - name: Show what was built + run: | + set -euo pipefail + echo "Go toolchain: $(go version | awk '{print $3}') (from the go.mod 'go' directive)" + echo "GoReleaser version: $(jq -r .version dist/metadata.json)" + echo "Images built locally:" + jq -r '.[] | select(.type == "Docker Image") | " " + .name' dist/artifacts.json + echo "Archives built locally (uploaded to the Release after the gate):" + jq -r '.[] | select(.type == "Archive") | " " + .name' dist/artifacts.json | sort + + - name: Trivy scan + uses: aquasecurity/trivy-action@ed142fd0673e97e23eac54620cfb913e5ce36c25 # v0.36.0 + env: + TRIVY_SHOW_SUPPRESSED: 'true' + with: + # 'latest' on purpose. Aqua DELETES old Trivy releases outright + # (everything below ~v0.70.0 now 404s), so ANY pin here is a dated + # time bomb: it works until the release is removed, then the + # installer exits 1 with no error message. trivy-action overrides + # setup-trivy's own 'latest' default with a lagging pin, so this + # restores it. Note the vulnerability DB is fetched fresh every run + # regardless -- floating the binary buys newer detection logic and + # parsers, not newer CVE data. + version: latest + image-ref: ${{ env.PACKAGE }}:latest + scan-type: image + scanners: vuln + # NOTE: the input is vuln-type. trivy-action silently IGNORES an + # unknown input (it only warns), so 'pkg-types' was a no-op here. + vuln-type: os,library + trivyignores: .trivyignore + format: json + output: trivy.json + exit-code: '0' # the gate decides, not the scanner + timeout: 10m + + - name: Trivy findings + if: always() + run: ./scripts/scan-report.sh report trivy trivy.json "${PACKAGE}:latest" + + # Grype has no 'latest' equivalent: scan-action hard-pins a version in + # GrypeVersion.js (v6 pinned v0.97.1; v7.4.2 pins v0.118.0, while Grype + # itself is already past v0.122). The `grype-version` input takes a + # concrete tag, so resolve the newest release at run time and pass it. + # The ACTION stays SHA-pinned -- that is the supply-chain control, and it + # is unaffected by which scanner binary it then downloads. + - name: Resolve the latest Grype release + id: grype-version + if: always() + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + set -euo pipefail + v=$(gh api repos/anchore/grype/releases/latest --jq .tag_name) + case "${v}" in + v[0-9]*) ;; + *) echo "::error::refusing to install unexpected Grype tag '${v}'"; exit 1 ;; + esac + echo "version=${v}" >> "$GITHUB_OUTPUT" + echo "Grype ${v} (action pins v0.118.0; overriding to latest)" + + - name: Grype scan + uses: anchore/scan-action@27805bf3b4e84b4a5c980df22ed233c00390a439 # v7.4.2 + with: + image: ${{ env.PACKAGE }}:latest + grype-version: ${{ steps.grype-version.outputs.version }} + severity-cutoff: high + output-format: json + output-file: grype.json + fail-build: false # the gate decides, not the scanner + + - name: Grype findings + if: always() + run: ./scripts/scan-report.sh report grype grype.json "${PACKAGE}:latest" + + # Same script, same thresholds as ci.yml. Nothing is pushed past this. + - name: Gate on CRITICAL/HIGH and Go toolchain + run: ./scripts/scan-report.sh gate trivy.json grype.json + + # --------------------------------------------------------------------- + # Everything from here to "Log in to GHCR" is REPORTING, not gating. All + # of it runs with `if: always()` so that a FAILED gate still produces the + # alert and the SARIF -- a blocked release is exactly when the evidence + # matters most. None of it can turn a failed gate green: these steps do + # not run `gate`, and `continue-on-error` only suppresses their own + # failure, never an earlier step's. + # --------------------------------------------------------------------- + + + + + # T11 / Q6 — alerting with NO repository secret. Opens a GitHub Issue + # ONLY when a scanner found CRITICAL/HIGH; Slack's GitHub app carries it + # to the channel via its default-on `issues` feature. A clean scan opens + # nothing and the channel stays silent, which is ADO's behaviour. + # See alert() in scripts/scan-report.sh for the dedup and + # public-disclosure reasoning, and rescan.yml for the Slack setup. + - name: Alert on Trivy findings + if: always() + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + run: | + set -euo pipefail + version=$(jq -r .version dist/metadata.json 2>/dev/null || echo "${GITHUB_REF_NAME}") + ./scripts/scan-report.sh alert trivy trivy.json "${PACKAGE}:${version}" "Build-time" "${RUN_URL}" + + - name: Alert on Grype findings + if: always() + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + run: | + set -euo pipefail + version=$(jq -r .version dist/metadata.json 2>/dev/null || echo "${GITHUB_REF_NAME}") + ./scripts/scan-report.sh alert grype grype.json "${PACKAGE}:${version}" "Build-time" "${RUN_URL}" + + # T10 / T13. SARIF into GitHub code scanning is the finding HISTORY that + # partly replaces what Wiz provided centrally -- per-finding first-seen, + # fixed-at and dismissal, queryable per repo. Q2 asks security whether + # this plus SBOM ingestion is sufficient; shipping it makes that question + # concrete rather than hypothetical. + # + # `trivy convert` reuses the JSON report already on disk, so this costs + # no second scan and no second DB fetch. + - name: Convert the Trivy report to SARIF + if: always() + continue-on-error: true + run: | + set -euo pipefail + if ! command -v trivy >/dev/null 2>&1; then + echo "::warning::trivy is not on PATH — skipping SARIF conversion." + exit 0 + fi + if [ ! -f trivy.json ]; then + echo "::warning::trivy.json is missing — skipping SARIF conversion." + exit 0 + fi + trivy convert --format sarif --output trivy.sarif trivy.json + echo "wrote trivy.sarif ($(wc -c < trivy.sarif) bytes)" + + # Grype has no convert subcommand, so this is a second scan-action run. + # The Grype binary and its DB are both already cached from the first run, + # so it is seconds, not a full rescan. + - name: Grype scan (SARIF output) + if: always() + continue-on-error: true + uses: anchore/scan-action@27805bf3b4e84b4a5c980df22ed233c00390a439 # v7.4.2 + with: + image: ${{ env.PACKAGE }}:latest + grype-version: ${{ steps.grype-version.outputs.version }} + severity-cutoff: high + output-format: sarif + output-file: grype.sarif + fail-build: false + + # continue-on-error on both uploads is load-bearing, not defensive + # habit: code scanning on a PRIVATE repo requires GitHub Advanced + # Security, so this 403s in the chisel sandbox. On public + # OutSystems/chisel it is free and will succeed. Failing the release for + # a reporting upload would be the wrong trade in either case. + - name: Upload the Trivy SARIF to code scanning + if: always() + continue-on-error: true + uses: github/codeql-action/upload-sarif@33d7b85da1a04171e211befe2c739303b9a4c066 # v4 + with: + sarif_file: trivy.sarif + category: trivy + + - name: Upload the Grype SARIF to code scanning + if: always() + continue-on-error: true + uses: github/codeql-action/upload-sarif@33d7b85da1a04171e211befe2c739303b9a4c066 # v4 + with: + sarif_file: grype.sarif + category: grype + + # T13. An SPDX SBOM of the image that just passed the gate, attached to + # the Release below. This is the artifact the internal asset inventory + # ingests in place of a Wiz scan, so it must describe the PUBLISHED + # image, not a rebuild -- hence it is generated here, from the same local + # image the scanners read, before anything is pushed. + # + # UNSIGNED for now. Signing (cosign keyless) is a separate story and the + # threat model expects it; see T8/T9. An unsigned SBOM still answers + # "what is in this image", which is what Q2 is about. It does not yet + # answer "prove this SBOM came from us". + - name: Generate the SPDX SBOM + continue-on-error: true + uses: anchore/sbom-action@66cbf4bc1f1c0d2edc94016e65bc221b6bb0ad6c # v0.24.3 + with: + image: ${{ env.PACKAGE }}:latest + format: spdx-json + output-file: sbom.spdx.json + upload-artifact: false + upload-release-assets: false + + - name: Log in to GHCR + env: + GHCR_USER: ${{ github.actor }} + GHCR_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: echo "${GHCR_TOKEN}" | docker login ghcr.io -u "${GHCR_USER}" --password-stdin + + # ADO parity: its "Check if image with trimmed tag exists on GHCR" step set + # skipRelease=true so a published tag is never overwritten. ADO skipped + # silently; this fails loudly instead, because a silent skip reads like a + # successful publish. `latest` is excluded on purpose — it must move. + - name: Refuse to overwrite an existing version tag or Release + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + set -euo pipefail + version=$(jq -r .version dist/metadata.json) + + if docker manifest inspect "${PACKAGE}:${version}" >/dev/null 2>&1; then + echo "::error::${PACKAGE}:${version} already exists. Published tags are immutable — bump the tag instead of re-running." + exit 1 + fi + + # Same rule for the Release. gh would fail on a duplicate anyway, but + # it would fail AFTER the image push, leaving a half-published state. + if gh release view "${GITHUB_REF_NAME}" >/dev/null 2>&1; then + echo "::error::Release ${GITHUB_REF_NAME} already exists. Releases are immutable — bump the tag instead of re-running." + exit 1 + fi + + echo "${PACKAGE}:${version} and release ${GITHUB_REF_NAME} are both unpublished — proceeding." + + # Pushes exactly what GoReleaser built, read back from its own manifest. + # The allow-list is a hard stop: if goreleaser.yml is ever edited to + # point somewhere else, this fails instead of writing to that package. + - name: Push images to chisel + run: | + set -euo pipefail + mapfile -t images < <(jq -r '.[] | select(.type == "Docker Image") | .name' dist/artifacts.json) + [ "${#images[@]}" -gt 0 ] || { echo "::error::GoReleaser produced no images"; exit 1; } + + for img in "${images[@]}"; do + case "${img}" in + "${PACKAGE}:"*) ;; + *) echo "::error::refusing to push ${img} — this workflow may only write to ${PACKAGE}" + exit 1 ;; + esac + done + + for img in "${images[@]}"; do + echo "pushing ${img}" + docker push "${img}" + done + + # Asserts, rather than prints. RepoDigests is the manifest digest docker + # recorded when it pushed the image we scanned; imagetools asks the + # registry what the tag resolves to NOW. If they differ, something + # overwrote the tag between our push and this check, and the gate result + # no longer describes what is in the package. + # + # This is what makes "what we scanned is what we shipped" verifiable + # with a single registry — no candidate/released split needed. + - name: Verify the published image is the image that passed the gate + run: | + set -euo pipefail + version=$(jq -r .version dist/metadata.json) + + pushed=$(docker image inspect "${PACKAGE}:${version}" \ + --format '{{index .RepoDigests 0}}' | cut -d@ -f2) + registry=$(docker buildx imagetools inspect "${PACKAGE}:${version}" \ + --format '{{json .Manifest}}' | jq -r .digest) + + echo "scanned & pushed : ${pushed}" + echo "registry resolves: ${registry}" + if [ "${pushed}" != "${registry}" ]; then + echo "::error::Digest mismatch — ${PACKAGE}:${version} no longer resolves to the image that passed the gate." + exit 1 + fi + echo "Digest match confirmed." + + echo "chisel --version reports: $(docker run --rm "${PACKAGE}:${version}" --version)" + + # Creates the GitHub Release from the archives GoReleaser built and + # checksummed BEFORE the gate ran. Nothing is rebuilt: these are the same + # files that were on disk when the image built from the same compilation + # passed Trivy and Grype. `gh release create` is used here instead of a + # second GoReleaser run precisely so that a rebuild is not possible — + # that rebuild is the defect in the ADO pipeline this workflow replaces. + # + # --latest, never --prerelease. A pre-release CANNOT be marked latest + # (GitHub returns 422 "Latest release cannot be draft or prerelease"), + # and while every release is a pre-release the repository has no latest + # release at all: GET /releases/latest returns 404, so any consumer + # asking GitHub for the newest version gets nothing. The container image + # already carries both : and :latest via + # goreleaser.yml dockers.image_templates; this keeps the Release + # consistent with the image. + - name: Create the GitHub Release with the linux archives + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + set -euo pipefail + version=$(jq -r .version dist/metadata.json) + + mapfile -t archives < <(jq -r '.[] | select(.type == "Archive") | .path' dist/artifacts.json | sort) + [ "${#archives[@]}" -gt 0 ] || { echo "::error::GoReleaser produced no archives"; exit 1; } + [ -f dist/checksums.txt ] || { echo "::error::dist/checksums.txt is missing"; exit 1; } + + # The SBOM step is continue-on-error, so attach it only if it exists. + # A missing SBOM is a warning, not a failed release: the image and + # the binaries have both already passed the gate at this point. + extra=() + if [ -f sbom.spdx.json ]; then + cp sbom.spdx.json "dist/chisel_${version}_sbom.spdx.json" + extra+=("dist/chisel_${version}_sbom.spdx.json") + else + echo "::warning::sbom.spdx.json was not produced — publishing without an SBOM." + fi + + digest=$(docker image inspect "${PACKAGE}:${version}" --format '{{index .RepoDigests 0}}') + + { + echo "Built, scanned and published by \`release.yml\` (RDODCP-1463)." + echo + echo "Container image, scanned and gated before publish:" + echo + echo '```' + echo "${digest}" + echo '```' + if [ -f sbom.spdx.json ]; then + echo + echo "An unsigned SPDX SBOM of that image is attached (\`*_sbom.spdx.json\`)." + fi + } > release-notes.md + + echo "Attaching:" + printf ' %s\n' "${archives[@]}" dist/checksums.txt ${extra[@]+"${extra[@]}"} + + gh release create "${GITHUB_REF_NAME}" \ + --title "${GITHUB_REF_NAME}" \ + --notes-file release-notes.md \ + --latest \ + --verify-tag \ + "${archives[@]}" dist/checksums.txt ${extra[@]+"${extra[@]}"} + + echo "Release published:" + gh release view "${GITHUB_REF_NAME}" --json assets \ + --jq '.assets[] | " \(.name) \(.size) bytes"' + + - name: Log out of GHCR + if: always() + run: docker logout ghcr.io diff --git a/.github/workflows/rescan.yml b/.github/workflows/rescan.yml new file mode 100644 index 00000000..0a97d034 --- /dev/null +++ b/.github/workflows/rescan.yml @@ -0,0 +1,325 @@ +# Six-hourly rescan of the PUBLISHED image — RDODCP-1463 (Phase 3) +# +# Replaces the second half of the ADO nightly job. In ADO this is not a separate +# pipeline: daily_scan_published_images.yaml is appended as extra steps to +# publish_image.yaml, which runs on a 00:00 cron. After publishing, it pulls the +# already-published image back from GHCR and rescans it, because a CVE +# disclosed after release makes a previously clean image vulnerable without +# anything in the repo changing. +# +# Differences from ADO, deliberate: +# * No Wiz (threat model: wizcli needs a client id and secret). +# * Every SIX HOURS, not daily. P16 (added by the AppSec review) is the +# reconnaissance window on published SBOMs and provenance: an attacker +# reads the exact dependency versions we publish and targets a newly +# disclosed CVE before a rescan notices. The agreed mitigation raises the +# cadence from daily to 6-hourly, so that is what this runs at. +# * The run FAILS on a finding, where ADO's daily scan only alerted. Slack +# is kept as well, in ADO's format, but it is the SECOND signal: the first +# is a red Actions tab and GitHub's own watcher email, neither of which +# can be lost to a webhook outage or a rotated URL. +# * Reports are printed in the log, not saved as artifacts. SARIF goes to +# code scanning instead, which keeps per-finding history (T13). +# +# ⚠ TRIGGER LIMITS — read before expecting this to fire ⚠ +# `schedule`, `workflow_dispatch` and `repository_dispatch` ALL require the +# workflow file to be on the DEFAULT branch (master). While this lives only on +# RDODCP-1463 it can be exercised by the `push` trigger below and nothing +# else. The daily run starts only once this is merged to master. +# +# SLACK ALERTING (T11 / Q6) — NO REPOSITORY SECRET +# +# Requirement: match ADO. Alert ONLY when a scanner finds CRITICAL or HIGH, +# with the counts in the message. A clean scan says nothing. ADO does this +# with a SLACK_WEBHOOK_URL from its `slack-secrets` variable group; we do not +# want that secret in a public repo. +# +# HOW THIS WORKS WITHOUT ONE +# Slack's GitHub app notifies on ISSUES by default, and an issue only exists +# if we create one. So the workflow does not notify on the run -- it opens an +# issue when, and only when, a scanner finds CRITICAL/HIGH: +# +# no CRITICAL/HIGH -> no issue -> Slack silent (ADO parity) +# CRITICAL/HIGH -> an issue -> Slack gets the title +# +# We write the title, so the counts and the image name travel with it. Runs +# on GITHUB_TOKEN with `issues: write`. Nothing to rotate, nothing to leak, +# and forks inherit a workflow that needs no secret. +# +# Channel setup, once: +# +# /github subscribe OutSystems/chisel +# +# `issues` is on by default, so no filter is needed. Add +# `/github unsubscribe OutSystems/chisel pulls commits releases deployments` +# if only vulnerability alerts are wanted in that channel. +# +# ⚠ PREREQUISITE: ISSUES MUST BE ENABLED ON THE REPOSITORY ⚠ +# OutSystems/chisel is a fork, and GitHub disables Issues on forks by +# default -- it currently has has_issues=false, as does this sandbox. Two +# consequences: +# +# 1. Until Issues are enabled, alert() refuses and logs a warning. The gate +# still blocks; only the notification is lost. Nothing fails. +# 2. Enabling Issues on a PUBLIC repo opens an inbound channel from the +# internet. For a project being deliberately run as true open source +# that is arguably wanted anyway -- SECURITY.md and a disclosure route +# are already committed controls -- but it is a decision, not a +# side-effect of CI. +# +# WHY EVERY gh CALL IN alert() PASSES --repo +# Found the hard way. `gh issue create` with no --repo infers the repository +# from the checkout, and when that repository is a fork WITH ISSUES DISABLED +# it silently REDIRECTS to the upstream parent. A test run against the +# private sandbox opened an issue on the public jpillora/chisel. Every gh +# call is now pinned to $GITHUB_REPOSITORY and alert() refuses outright if +# Issues are off, rather than letting anything infer a target. +# +# PUBLIC-REPO DISCLOSURE +# The issue carries only what ADO's Slack message already carries -- severity +# COUNTS and the image reference -- and no CVE identifiers. Per-CVE detail +# stays in the run log, the job summary and the SARIF, which are public under +# this model anyway. +# +# IF THIS IS NOT ACCEPTABLE, Q6's fallback is a dedicated single-channel +# incoming webhook as a repo secret. That is exactly the decision Q6 puts to +# security. +# +# Two further caveats on master: +# 1. GitHub disables scheduled workflows in a public repository after 60 +# days with no repository activity. Chisel is quiet for long stretches, +# so confirm after the first 60-day gap that it is still enabled. +# 2. This repo is a fork. Confirm the first scheduled run actually fires; +# if it does not, drive it from an internal scheduler via +# repository_dispatch (type: rescan-published-image), which is why that +# trigger is wired up here. + +name: Rescan published image + +on: + schedule: + # Every 6 hours (02:17, 08:17, 14:17, 20:17 UTC) — P16. ADO ran once at + # 00:00. The :17 offset avoids GitHub's top-of-hour scheduling queue, where + # cron jobs are routinely delayed or dropped under load. + - cron: '17 */6 * * *' + workflow_dispatch: + inputs: + image: + description: 'Image to rescan (must be under ghcr.io/outsystems/)' + required: false + default: 'ghcr.io/outsystems/chisel:latest' + repository_dispatch: + types: [rescan-published-image] + +permissions: + contents: read + +concurrency: + group: rescan-${{ github.ref }} + cancel-in-progress: true + +env: + DEFAULT_IMAGE: ghcr.io/outsystems/chisel:latest + +jobs: + rescan: + name: Rescan published image + runs-on: ubuntu-latest + permissions: + contents: read + packages: read # harmless on a public package; required if it is ever private + security-events: write # upload Trivy/Grype SARIF to code scanning + issues: write # open the vulnerability alert issue (T11); no secret needed + steps: + # Checked out for .trivyignore, .grype.yaml, scripts/ and go.mod — the + # suppression lists must be the ones under review, not the ones baked + # into whatever commit produced the published image. + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 + with: + persist-credentials: false + + - name: Resolve image to rescan + env: + REQUESTED_IMAGE: ${{ github.event.inputs.image || github.event.client_payload.image || '' }} + run: | + set -euo pipefail + image="${REQUESTED_IMAGE:-${DEFAULT_IMAGE}}" + + # repository_dispatch payloads come from whoever holds a repo-write + # token. Pin the blast radius to our own namespace regardless. + case "${image}" in + ghcr.io/outsystems/*:*) ;; + *) echo "::error::refusing to scan '${image}' — only ghcr.io/outsystems/: is allowed" + exit 1 ;; + esac + + echo "IMAGE_REF=${image}" >> "${GITHUB_ENV}" + echo "Rescanning ${image}" + + - name: Log in to GHCR + env: + GHCR_USER: ${{ github.actor }} + GHCR_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: echo "${GHCR_TOKEN}" | docker login ghcr.io -u "${GHCR_USER}" --password-stdin + + # ADO: "Daily Scan - Pull Published Image". Scanning the pulled image + # rather than the registry reference is what makes this a check of what + # consumers actually run. + - name: Pull the published image + run: | + set -euo pipefail + docker pull "${IMAGE_REF}" + docker image inspect "${IMAGE_REF}" \ + --format 'digest={{index .RepoDigests 0}} created={{.Created}}' + + - name: Trivy scan + uses: aquasecurity/trivy-action@ed142fd0673e97e23eac54620cfb913e5ce36c25 # v0.36.0 + env: + TRIVY_SHOW_SUPPRESSED: 'true' + with: + # 'latest' on purpose. Aqua DELETES old Trivy releases outright + # (everything below ~v0.70.0 now 404s), so ANY pin here is a dated + # time bomb: it works until the release is removed, then the + # installer exits 1 with no error message. trivy-action overrides + # setup-trivy's own 'latest' default with a lagging pin, so this + # restores it. Note the vulnerability DB is fetched fresh every run + # regardless -- floating the binary buys newer detection logic and + # parsers, not newer CVE data. + version: latest + image-ref: ${{ env.IMAGE_REF }} + scan-type: image + scanners: vuln + # NOTE: the input is vuln-type. trivy-action silently IGNORES an + # unknown input (it only warns), so 'pkg-types' was a no-op here. + vuln-type: os,library + trivyignores: .trivyignore + format: json + output: trivy.json + exit-code: '0' + timeout: 10m + + - name: Trivy findings + if: always() + run: ./scripts/scan-report.sh report trivy trivy.json "$IMAGE_REF" + + # Grype has no 'latest' equivalent: scan-action hard-pins a version in + # GrypeVersion.js (v6 pinned v0.97.1; v7.4.2 pins v0.118.0, while Grype + # itself is already past v0.122). The `grype-version` input takes a + # concrete tag, so resolve the newest release at run time and pass it. + # The ACTION stays SHA-pinned -- that is the supply-chain control, and it + # is unaffected by which scanner binary it then downloads. + - name: Resolve the latest Grype release + id: grype-version + if: always() + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + set -euo pipefail + v=$(gh api repos/anchore/grype/releases/latest --jq .tag_name) + case "${v}" in + v[0-9]*) ;; + *) echo "::error::refusing to install unexpected Grype tag '${v}'"; exit 1 ;; + esac + echo "version=${v}" >> "$GITHUB_OUTPUT" + echo "Grype ${v} (action pins v0.118.0; overriding to latest)" + + - name: Grype scan + uses: anchore/scan-action@27805bf3b4e84b4a5c980df22ed233c00390a439 # v7.4.2 + with: + image: ${{ env.IMAGE_REF }} + grype-version: ${{ steps.grype-version.outputs.version }} + severity-cutoff: high + output-format: json + output-file: grype.json + fail-build: false + + - name: Grype findings + if: always() + run: ./scripts/scan-report.sh report grype grype.json "$IMAGE_REF" + + # Same script and thresholds as ci.yml and release.yml. A red run here + # means a published image needs rebuilding, not that a PR is bad. + # + # NOTE: the "bump go.mod" line in the GO TOOLCHAIN section refers to + # go.mod at HEAD, which may be newer than the commit that built the + # published image. Treat it as "what to build the next image with". + - name: Gate on CRITICAL/HIGH and Go toolchain + run: ./scripts/scan-report.sh gate trivy.json grype.json + + # --------------------------------------------------------------------- + # Reporting, not gating. `if: always()` so a FAILED gate still files its + # SARIF -- which is the whole point of a rescan: the finding arrived + # after the image shipped, and the evidence matters most exactly when + # the run is red. + # --------------------------------------------------------------------- + + + + + # T11 / Q6 — see release.yml and alert() in scripts/scan-report.sh. + # No context label: ADO's nightly messages say "Trivy Scan Failed" with + # no "(Build-time)" suffix, and this is the scan that corresponds to it. + - name: Alert on Trivy findings + if: always() + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + run: ./scripts/scan-report.sh alert trivy trivy.json "${IMAGE_REF}" "" "${RUN_URL}" + + - name: Alert on Grype findings + if: always() + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + run: ./scripts/scan-report.sh alert grype grype.json "${IMAGE_REF}" "" "${RUN_URL}" + + # T10 / T13 — see the matching block in release.yml for why these are + # continue-on-error (code scanning needs Advanced Security on a private + # repo; free on public OutSystems/chisel). + - name: Convert the Trivy report to SARIF + if: always() + continue-on-error: true + run: | + set -euo pipefail + if ! command -v trivy >/dev/null 2>&1; then + echo "::warning::trivy is not on PATH — skipping SARIF conversion." + exit 0 + fi + if [ ! -f trivy.json ]; then + echo "::warning::trivy.json is missing — skipping SARIF conversion." + exit 0 + fi + trivy convert --format sarif --output trivy.sarif trivy.json + echo "wrote trivy.sarif ($(wc -c < trivy.sarif) bytes)" + + - name: Grype scan (SARIF output) + if: always() + continue-on-error: true + uses: anchore/scan-action@27805bf3b4e84b4a5c980df22ed233c00390a439 # v7.4.2 + with: + image: ${{ env.IMAGE_REF }} + grype-version: ${{ steps.grype-version.outputs.version }} + severity-cutoff: high + output-format: sarif + output-file: grype.sarif + fail-build: false + + - name: Upload the Trivy SARIF to code scanning + if: always() + continue-on-error: true + uses: github/codeql-action/upload-sarif@33d7b85da1a04171e211befe2c739303b9a4c066 # v4 + with: + sarif_file: trivy.sarif + category: trivy-rescan + + - name: Upload the Grype SARIF to code scanning + if: always() + continue-on-error: true + uses: github/codeql-action/upload-sarif@33d7b85da1a04171e211befe2c739303b9a4c066 # v4 + with: + sarif_file: grype.sarif + category: grype-rescan + + - name: Log out of GHCR + if: always() + run: docker logout ghcr.io diff --git a/.grype.yaml b/.grype.yaml new file mode 100644 index 00000000..ddc6cf68 --- /dev/null +++ b/.grype.yaml @@ -0,0 +1,19 @@ +# Grype config — Chisel +# +# Moved from the private rd-PaaS pipeline repo as part of RDODCP-1463. +# Grype auto-discovers .grype.yaml in the working directory, so this applies to +# both local runs and the CI scan without needing a -c flag. +# +# Governance: every entry needs a Jira reference, a written justification and a +# review date. Reviewed quarterly and reported to security (threat model T12). +# +# CVE-2026-85091 — zlib heap buffer overflow in gz_vacate() (CWE-787). +# No fixed version exists upstream for the affected range (>= 1.3.1.2, +# <= 1.3.2); Grype itself reports fix.state as empty. Blocking every build on an +# unfixable CVE prevents shipping already-patched fixes for everything else +# (see RDODCP-1650: this CVE was the sole reason an openssl 3.3.7-r1 security +# fix for 6 Critical + 6 High CVEs never reached the published :latest image). +# Re-evaluate once Alpine ships a patched zlib for 3.21.x. +# Ref: RDODCP-1650 | Review by: 2027-03-31 +ignore: + - vulnerability: CVE-2026-85091 diff --git a/.trivyignore b/.trivyignore new file mode 100644 index 00000000..27dba2c7 --- /dev/null +++ b/.trivyignore @@ -0,0 +1,17 @@ +# Trivy ignore file — Chisel +# +# Moved from the private rd-PaaS pipeline repo as part of RDODCP-1463. +# Keeping it here makes every suppression publicly auditable (threat model T12). +# +# Governance: every entry needs a Jira reference, a written justification and a +# review date. The full list is reviewed quarterly and reported to security. +# +# CVE-2026-48113 — chisel "ACL Bypass via Post-Handshake SSH Channel ExtraData +# Injection". FALSE POSITIVE for this build: the fix is already present (PR #51, +# "Enforce auth ACL on tunnel channels", contained in tags v1.11.5-os.1/2/3). +# Trivy flags it only because the OutSystems fork tag `1.11.5-os.N` is a SemVer +# *pre-release* of `1.11.5`, so it sorts *below* the fixed `1.11.5`. +# Re-evaluate (and remove) when chisel rebases onto an upstream version above +# 1.11.5, at which point the tag sorts above the fix. +# Ref: RDODCP-917 | Review by: 2027-03-31 +CVE-2026-48113 diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 00000000..ba2ba9c9 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,57 @@ +# Security Policy + +## Reporting a vulnerability + +**Please do not open a public issue for security problems.** + +Report privately through GitHub's private vulnerability reporting: + +1. Go to the [Security tab](https://github.com/OutSystems/chisel/security) of this repository. +2. Select **Report a vulnerability**. +3. Describe the issue, the version affected, and how to reproduce it. + +The report is visible only to the maintainers of this repository until an +advisory is published. If you cannot use that form, contact OutSystems through +the channel listed at and reference this +repository. + + + +## What to expect + +| Stage | Target | +| --- | --- | +| Acknowledgement of your report | 3 working days | +| Initial assessment and severity | 10 working days | +| Fix or mitigation plan communicated | 30 days for High/Critical | + +We will keep you updated while we investigate, and will credit you in the +advisory unless you ask us not to. + +## Supported versions + +Only the most recent release is supported. It is published here as a GitHub +Release badged **Latest**, and as a container image at +`ghcr.io/outsystems/chisel`, tagged with the version and `latest`. + +## How releases are secured + +Every release is built by [`.github/workflows/release.yml`](.github/workflows/release.yml) +and must pass, before anything is published: + +- **Trivy** and **Grype** container scans, gating on CRITICAL and HIGH +- **govulncheck** against the Go standard library and module graph +- a **human approval** on a protected GitHub Environment + +The image is compiled **once**. The digest that is published is asserted equal +to the digest that passed the scan, so the artifact you pull is the artifact +that was scanned — not a rebuild of it. An SPDX SBOM is attached to every +release. + +The published image is **re-scanned every 6 hours** against newly disclosed +CVEs. A finding fails that run and opens a tracking issue. + +Build logs and scan results are public. You can verify any release yourself +from the Actions tab. diff --git a/go.mod b/go.mod index 74e580bf..e7f82a6e 100644 --- a/go.mod +++ b/go.mod @@ -1,17 +1,17 @@ module github.com/jpillora/chisel -go 1.26.10 +go 1.26.11 require ( github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5 github.com/fsnotify/fsnotify v1.10.1 - github.com/gorilla/websocket v1.5.3 + github.com/gorilla/websocket v1.5.4-0.20240701034025-d67f41855da4 github.com/jpillora/backoff v1.0.0 github.com/jpillora/opts v1.8.1 github.com/jpillora/requestlog v1.0.0 github.com/jpillora/sizestr v1.0.0 golang.org/x/crypto v0.58.0 - golang.org/x/net v0.60.0 + golang.org/x/net v0.62.0 golang.org/x/sync v0.24.0 ) diff --git a/go.sum b/go.sum index 7d1b6e20..5c95788c 100644 --- a/go.sum +++ b/go.sum @@ -8,6 +8,8 @@ github.com/fsnotify/fsnotify v1.10.1 h1:b0/UzAf9yR5rhf3RPm9gf3ehBPpf0oZKIjtpKrx5 github.com/fsnotify/fsnotify v1.10.1/go.mod h1:TLheqan6HD6GBK6PrDWyDPBaEV8LspOxvPSjC+bVfgo= github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg= github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= +github.com/gorilla/websocket v1.5.4-0.20240701034025-d67f41855da4 h1:PYKzliEgITjLJoJqbV90S0YRaG8LNAsICH6fp6MApC0= +github.com/gorilla/websocket v1.5.4-0.20240701034025-d67f41855da4/go.mod h1:r4w70xmWCQKmi1ONH4KIaBptdivuRPyosB9RmPlGEwA= github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= github.com/hashicorp/errwrap v1.1.0 h1:OxrOeh75EUXMY8TBjag2fzXGZ40LB6IKw45YeGUDY2I= github.com/hashicorp/errwrap v1.1.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= @@ -37,6 +39,8 @@ golang.org/x/crypto v0.58.0 h1:COkYLr4k7nDI4r6QtMML2AfzeIswWHAJthLS6K/M/54= golang.org/x/crypto v0.58.0/go.mod h1:Xh+kl5A+M0gMiWDytH2Hhr5Z7WbNCpv/eB/EFgfSk+w= golang.org/x/net v0.60.0 h1:79p50tfZlm0J9YfoDsSi639qSXNGVwEzOPLCxM2FsYU= golang.org/x/net v0.60.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg= +golang.org/x/net v0.62.0 h1:18ELalfM5+XNRwzM2nYqXsZQ9ByS1uhj2O/U7+5jqRY= +golang.org/x/net v0.62.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI= golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA= golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA= diff --git a/scripts/scan-report.sh b/scripts/scan-report.sh new file mode 100755 index 00000000..57f9401b --- /dev/null +++ b/scripts/scan-report.sh @@ -0,0 +1,523 @@ +#!/usr/bin/env bash +# +# Shared vulnerability report + gate for the RDODCP-1463 workflows. +# +# Both ci.yml (build only) and release.yml (build + publish) call this, so the +# gate that blocks a PR is byte-for-byte the gate that blocks a publish. Keeping +# it in one file is the point: a release path with its own copy of this logic +# will eventually drift from CI and ship an image CI would have rejected. +# +# Usage: +# scan-report.sh report trivy [go.mod] +# scan-report.sh report grype [go.mod] +# scan-report.sh gate +# scan-report.sh alert [context] [run-url] +# +# Gating policy: +# * any CRITICAL or HIGH finding, from either scanner +# * any Go stdlib finding at ANY severity. Go stdlib CVEs are published +# without a CVSS score, so both scanners label them UNKNOWN and a plain +# CRITICAL/HIGH filter drops them silently. Remediation is a one-line bump +# of the "go" directive in go.mod, so there is no reason to tolerate them. +# +# Run it locally against saved reports exactly as CI does — no runner needed. + +set -euo pipefail + +die() { echo "scan-report: $*" >&2; exit 2; } + +# Shared jq prelude: fixed-width column padding, so Trivy and Grype print in +# one identical format. +JQ_PAD=' + def pad($s; $n): ($s | tostring)[0:$n] as $t + | $t + ((" " * ($n - ($t | length))) // ""); + def line($sev; $id; $type; $pkg; $cur; $fix): + pad($sev;9) + pad($id;20) + pad($type;11) + pad($pkg;40) + pad($cur;22) + $fix; + def header: + [ line("SEVERITY";"CVE";"TYPE";"PACKAGE";"INSTALLED";"FIXED IN"), + line("--------";"---";"----";"-------";"---------";"--------") ]; +' + +go_directive() { + local gomod="${1:-go.mod}" + [ -f "${gomod}" ] && awk '/^go /{print $2; exit}' "${gomod}" || echo "unknown" +} + +# --------------------------------------------------------- step summary ------ +# +# T11 / Q6, the no-secret branch. We do NOT post to Slack from the workflow; +# the channel is subscribed through Slack's GitHub app instead, which holds no +# credential in this repository. The cost of that choice is that the Slack card +# carries no severity counts -- the app's message format is fixed and a +# workflow cannot add content to it. +# +# This recovers most of that. GitHub renders $GITHUB_STEP_SUMMARY at the top of +# the run page, which is exactly where the Slack card's link lands. So the +# counts are one click from the notification instead of inside it. +# +# Writes nothing outside Actions: GITHUB_STEP_SUMMARY is unset locally. +step_summary() { + local scanner="$1" file="$2" image="$3" + + [ -n "${GITHUB_STEP_SUMMARY:-}" ] || return 0 + [ -f "${file}" ] || return 0 + + local label jq_counts jq_rows + case "${scanner}" in + trivy) + label="Trivy" + # `. as $s` is required: inside the inner map(), `.` is rebound to the + # vulnerability object, so `== .` would compare a severity to itself and + # every count would come out 0. + jq_counts='[.Results[]?.Vulnerabilities[]?] as $v + | ["CRITICAL","HIGH","MEDIUM","LOW","UNKNOWN"] + | map(. as $s | "| \($s) | \($v | map(select((.Severity // "UNKNOWN") == $s)) | length) |") + | join("\n")' + jq_rows='[ .Results[]? as $r | ($r.Vulnerabilities // [])[] + | select(.Severity == "CRITICAL" or .Severity == "HIGH") + | "| \(.Severity) | \(.VulnerabilityID) | \(.PkgName) | \(.InstalledVersion // "-") | \(if (.FixedVersion // "") == "" then "_no fix_" else .FixedVersion end) |" ] + | sort | join("\n")' + ;; + grype) + label="Grype" + jq_counts='[.matches[]?] as $v + | ["Critical","High","Medium","Low","Negligible","Unknown"] + | map(. as $s | "| \($s | ascii_upcase) | \($v | map(select((.vulnerability.severity // "Unknown") == $s)) | length) |") + | join("\n")' + jq_rows='[ .matches[]? + | select(.vulnerability.severity == "Critical" or .vulnerability.severity == "High") + | "| \(.vulnerability.severity | ascii_upcase) | \(.vulnerability.id) | \(.artifact.name) | \(.artifact.version // "-") | \(if ((.vulnerability.fix.versions // []) | length) > 0 then (.vulnerability.fix.versions | join(", ")) else "_no fix_" end) |" ] + | sort | join("\n")' + ;; + *) return 0 ;; + esac + + local rows + rows=$(jq -r "${jq_rows}" "${file}" 2>/dev/null || echo "") + + { + if [ -n "${rows}" ]; then + echo "### ❌ ${label} — \`${image}\`" + else + echo "### ✅ ${label} — \`${image}\`" + fi + echo + echo "| Severity | Count |" + echo "| --- | ---: |" + jq -r "${jq_counts}" "${file}" 2>/dev/null || true + echo + if [ -n "${rows}" ]; then + echo "**Gated findings (CRITICAL/HIGH)**" + echo + echo "| Severity | ID | Package | Installed | Fixed in |" + echo "| --- | --- | --- | --- | --- |" + echo "${rows}" + else + echo "No CRITICAL/HIGH findings." + fi + echo + } >> "${GITHUB_STEP_SUMMARY}" +} + +report_trivy() { + local file="$1" image="$2" godir="$3" + + echo "==============================================================================" + echo " TRIVY — ${image}" + echo "==============================================================================" + + # ADO parity: its "Check Trivy Vulnerabilities" task printed the package count + # and a count per severity. Everything below CRITICAL/HIGH is informational; + # only CRITICAL/HIGH (and Go stdlib, any severity) gate the build. + jq -r "${JQ_PAD}"' + ([.Results[]?.Packages[]?] | length) as $pkgs + | [ .Results[]?.Vulnerabilities[]? ] as $v + | [ " Tested \($pkgs) packages", "", " Vulnerability breakdown:" ] + + ( ["CRITICAL","HIGH","MEDIUM","LOW","UNKNOWN"] + | map(. as $s + | " " + pad($s; 10) + + ($v | map(select((.Severity // "UNKNOWN") == $s)) | length | tostring)) ) + | join("\n") + ' "${file}" + + echo + echo "--- CRITICAL/HIGH detail (gated) ---------------------------------------------" + jq -r "${JQ_PAD}"' + [ .Results[]? as $r + | ($r.Vulnerabilities // [])[] + | select(.Severity == "CRITICAL" or .Severity == "HIGH") + | { sev: .Severity, + id: .VulnerabilityID, + typ: ($r.Type // "-"), + pkg: .PkgName, + cur: (.InstalledVersion // "-"), + fix: (if (.FixedVersion // "") == "" then "NO FIX AVAILABLE" else .FixedVersion end) } ] + | if length == 0 then " No CRITICAL/HIGH vulnerabilities." + else header + + ( sort_by(.sev, .typ, .pkg) | map(line(.sev; .id; .typ; .pkg; .cur; .fix)) ) + + [ "", "Total CRITICAL/HIGH: \(length)" ] + | join("\n") + end + ' "${file}" + + echo + echo "--- GO TOOLCHAIN (stdlib, any severity — gated) ------------------------------" + jq -r --arg godir "${godir}" ' + [ .Results[]?.Vulnerabilities[]? + | select(.PkgName == "stdlib") + | { sev: .Severity, + id: .VulnerabilityID, + cur: ((.InstalledVersion // "-") | ltrimstr("v")), + fix: (if (.FixedVersion // "") == "" then "NO FIX AVAILABLE" else .FixedVersion end) } ] + | if length == 0 then " Clean. go.mod requests go \($godir)." + else ( map(" \(.sev) \(.id) stdlib \(.cur) -> FIXED IN GO: \(.fix)") + + [ "", " ACTION: go.mod requests go \($godir). Set its \"go\" directive to: " + + ( map(.fix) | join(" / ") ) ] ) + | join("\n") + end + ' "${file}" + + echo + echo "--- Suppressed by .trivyignore (NOT gated) -----------------------------------" + jq -r ' + [ .Results[]?.ExperimentalModifiedFindings[]? + | select(.Status == "ignored") + | (.Finding // .) as $f + | " \($f.Severity) \($f.VulnerabilityID) \($f.PkgName) \($f.InstalledVersion) (fix: \($f.FixedVersion // "none"))" ] + | if length == 0 then " (none)" else join("\n") end + ' "${file}" +} + +report_grype() { + local file="$1" image="$2" godir="$3" + + echo "==============================================================================" + echo " GRYPE — ${image}" + echo "==============================================================================" + + # Grype's JSON lists only matched packages, not the whole SBOM, so there is no + # honest "tested N packages" figure here — only the per-severity counts. + jq -r "${JQ_PAD}"' + [ .matches[]? ] as $v + | [ " Vulnerability breakdown:" ] + + ( ["Critical","High","Medium","Low","Negligible","Unknown"] + | map(. as $s + | " " + pad(($s | ascii_upcase); 12) + + ($v | map(select((.vulnerability.severity // "Unknown") == $s)) | length | tostring)) ) + | join("\n") + ' "${file}" + + echo + echo "--- CRITICAL/HIGH detail (gated) ---------------------------------------------" + jq -r "${JQ_PAD}"' + [ .matches[]? + | select(.vulnerability.severity == "Critical" or .vulnerability.severity == "High") + | { sev: (.vulnerability.severity | ascii_upcase), + id: .vulnerability.id, + typ: (.artifact.type // "-"), + pkg: .artifact.name, + cur: (.artifact.version // "-"), + fix: (if ((.vulnerability.fix.versions // []) | length) > 0 + then (.vulnerability.fix.versions | join(", ")) + elif (.vulnerability.fix.state // "") == "wont-fix" + then "WONT FIX (upstream)" + else "NO FIX AVAILABLE" end) } ] + | if length == 0 then " No CRITICAL/HIGH vulnerabilities." + else header + + ( sort_by(.sev, .typ, .pkg) | map(line(.sev; .id; .typ; .pkg; .cur; .fix)) ) + + [ "", "Total CRITICAL/HIGH: \(length)" ] + | join("\n") + end + ' "${file}" + + echo + echo "--- GO TOOLCHAIN (stdlib, any severity — gated) ------------------------------" + jq -r --arg godir "${godir}" ' + [ .matches[]? + | select(.artifact.name == "stdlib") + | { sev: (.vulnerability.severity | ascii_upcase), + id: .vulnerability.id, + cur: ((.artifact.version // "-") | ltrimstr("go")), + fix: (if ((.vulnerability.fix.versions // []) | length) > 0 + then (.vulnerability.fix.versions | join(" / ")) + else "NO FIX AVAILABLE" end) } ] + | if length == 0 then " Clean. go.mod requests go \($godir)." + else ( map(" \(.sev) \(.id) stdlib \(.cur) -> FIXED IN GO: \(.fix)") + + [ "", " ACTION: go.mod requests go \($godir). Set its \"go\" directive to: " + + ( map(.fix) | join(" / ") ) ] ) + | join("\n") + end + ' "${file}" + + echo + echo "--- Suppressed by .grype.yaml (NOT gated) ------------------------------------" + jq -r ' + [ .ignoredMatches[]? + | select(.vulnerability.severity == "Critical" or .vulnerability.severity == "High") + | " \(.vulnerability.severity | ascii_upcase) \(.vulnerability.id) \(.artifact.name) \(.artifact.version)" ] + | if length == 0 then " (none)" else join("\n") end + ' "${file}" +} + +gate() { + local trivy="$1" grype="$2" + + local trivy_ch grype_ch trivy_go grype_go failed=0 + trivy_ch=$(jq '[.Results[]?.Vulnerabilities[]? + | select(.Severity == "CRITICAL" or .Severity == "HIGH")] | length' "${trivy}") + grype_ch=$(jq '[.matches[]? + | select(.vulnerability.severity == "Critical" or .vulnerability.severity == "High")] | length' "${grype}") + trivy_go=$(jq '[.Results[]?.Vulnerabilities[]? | select(.PkgName == "stdlib")] | length' "${trivy}") + grype_go=$(jq '[.matches[]? | select(.artifact.name == "stdlib")] | length' "${grype}") + + echo "Trivy CRITICAL/HIGH : ${trivy_ch}" + echo "Grype CRITICAL/HIGH : ${grype_ch}" + echo "Trivy Go stdlib : ${trivy_go}" + echo "Grype Go stdlib : ${grype_go}" + + if [ "${trivy_ch}" -gt 0 ] || [ "${grype_ch}" -gt 0 ]; then + echo "::error::Vulnerability gate failed — Trivy ${trivy_ch}, Grype ${grype_ch} CRITICAL/HIGH. Fixed versions are in the findings steps above." + failed=1 + fi + if [ "${trivy_go}" -gt 0 ] || [ "${grype_go}" -gt 0 ]; then + echo "::error::Go toolchain gate failed — bump the 'go' directive in go.mod. The fixing Go version is in the GO TOOLCHAIN section above." + failed=1 + fi + + [ "${failed}" -eq 0 ] || exit 1 + echo "Gate passed: no CRITICAL/HIGH findings and no Go stdlib findings." +} + +# ------------------------------------------------------------------ alert ---- +# +# T11 / Q6 — alerting with NO REPOSITORY SECRET. +# +# ADO posts to Slack from a SLACK_WEBHOOK_URL in its `slack-secrets` variable +# group, ONLY when a scanner found CRITICAL/HIGH, with the counts inline. We +# want that behaviour on a PUBLIC repo without carrying the webhook. +# +# Slack's GitHub app is the no-secret channel, but subscribing to `workflows` +# does not reproduce ADO: it has no documented failure-only filter, so it posts +# a card on every run (ADO posts on none), and its message format is fixed so +# it cannot carry counts or the image name. +# +# So we do not notify on the RUN. We open an ISSUE, and let the app's `issues` +# feature — which is on by DEFAULT — carry it to Slack. An issue only exists if +# we create one, so: +# +# no CRITICAL/HIGH -> no issue -> Slack is silent (ADO parity) +# CRITICAL/HIGH -> an issue -> Slack gets the title +# +# and because WE write the title, the counts and the image name travel with it. +# All of that runs on GITHUB_TOKEN with `issues: write`. Nothing to rotate, +# nothing to leak, and forks inherit a workflow that needs no secret. +# +# PUBLIC-REPO DISCLOSURE. The issue is public. It deliberately carries only +# what ADO's Slack message already carries -- severity COUNTS and the image +# reference -- and no CVE identifiers. The per-CVE detail stays in the run log, +# the job summary and the SARIF, all of which are already public under this +# model (the threat model's whole premise is that a customer can read the build +# and the scan). This keeps the alert from being a more discoverable, indexable +# restatement of which unpatched CVEs are in the shipped image. +# +# RE-ALERT POLICY. One open issue per scanner per image, identified by a marker +# in the body. While it is open, later findings COMMENT on it instead of +# opening another, so a CVE that stays unfixed does not produce four issues a +# day from the rescan. When a later scan comes back clean, the issue is closed +# with a comment -- which the app also reports, so the channel sees the +# resolution as well as the alarm. ADO re-posted every night and never said +# when it stopped. +# +# This function NEVER fails the caller. Alerting is not a gate: `gate` has +# already decided by the time this runs. A GitHub API hiccup must not turn a +# passing build red, nor a failing build green. +alert() { + local scanner="$1" file="$2" image="$3" context="${4:-}" url="${5:-}" + + if [ ! -f "${file}" ]; then + echo "alert: ${file} missing — skipping." >&2 + return 0 + fi + if ! command -v gh >/dev/null 2>&1; then + echo "alert: gh is not available — skipping." >&2 + return 0 + fi + if [ -z "${GH_TOKEN:-}${GITHUB_TOKEN:-}" ]; then + echo "alert: no GitHub token in the environment — skipping." >&2 + return 0 + fi + + # --------------------------------------------------------------------- + # PIN THE REPOSITORY. This is not belt-and-braces, it is the fix for a + # real incident found while testing this function. + # + # `gh issue create` with no --repo infers the repo from the checkout, and + # when the inferred repo is a FORK WITH ISSUES DISABLED it silently + # REDIRECTS to the upstream parent and files the issue there. Testing this + # against the private chisel sandbox opened an issue on the public + # jpillora/chisel. Both OutSystems/chisel and the sandbox are forks with + # has_issues=false, so without this every vulnerability alert would have + # been published to a third party's public tracker. + # + # So: every gh call below passes --repo explicitly, and we refuse outright + # rather than let anything infer a target. + # --------------------------------------------------------------------- + local repo="${GH_REPO:-${GITHUB_REPOSITORY:-}}" + if [ -z "${repo}" ]; then + echo "alert: GITHUB_REPOSITORY is not set — refusing to let gh infer a repository. Skipping." >&2 + return 0 + fi + + local has_issues + has_issues=$(gh api "repos/${repo}" --jq '.has_issues' 2>/dev/null || echo "") + if [ "${has_issues}" != "true" ]; then + echo "::warning::Issues are disabled on ${repo}, so the vulnerability alert cannot be filed and Slack will not be notified. Enable Issues on the repository, or switch T11 to the webhook option. The gate result itself is unaffected." + return 0 + fi + + local critical high label + case "${scanner}" in + trivy) + label="Trivy" + critical=$(jq '[.Results[]?.Vulnerabilities[]? | select(.Severity == "CRITICAL")] | length' "${file}" 2>/dev/null || echo 0) + high=$(jq '[.Results[]?.Vulnerabilities[]? | select(.Severity == "HIGH")] | length' "${file}" 2>/dev/null || echo 0) + ;; + grype) + label="Grype" + critical=$(jq '[.matches[]? | select(.vulnerability.severity == "Critical")] | length' "${file}" 2>/dev/null || echo 0) + high=$(jq '[.matches[]? | select(.vulnerability.severity == "High")] | length' "${file}" 2>/dev/null || echo 0) + ;; + *) echo "alert: unknown scanner '${scanner}' — skipping." >&2; return 0 ;; + esac + + case "${critical}" in ''|*[!0-9]*) critical=0 ;; esac + case "${high}" in ''|*[!0-9]*) high=0 ;; esac + + # The dedup key. Kept out of the title so that changing counts does not open + # a second issue for the same scanner and image. + local marker="" + + # The label must exist before it can be filtered on OR attached, so create + # it first and idempotently. + gh label create vulnerability-alert --repo "${repo}" \ + --color B60205 --description "Opened automatically by a Trivy/Grype gate failure" \ + >/dev/null 2>&1 || true + + # Collect EVERY open issue carrying this marker, not just one. + # + # Two things learned by testing, both encoded here: + # + # 1. No `| head -1`. With `set -o pipefail`, head closing the pipe sends + # SIGPIPE to gh, the pipeline exits non-zero, and the `|| existing=""` + # fallback discards a result that WAS found -- so every run opened a + # duplicate. jq does the limiting instead. + # 2. GitHub's issue list is eventually consistent: an issue created + # seconds earlier may not appear yet, which can still produce a + # duplicate. At this workflow's real cadence (6h) that cannot happen, + # but the close path below handles ALL matches rather than one, so any + # duplicate that does appear is cleaned up on the next clean scan + # instead of lingering. + local existing="" + existing=$(gh issue list --repo "${repo}" --state open --label vulnerability-alert \ + --limit 100 --json number,body \ + --jq "[.[] | select(.body | contains(\"${marker}\")) | .number] | sort | .[]" \ + 2>/dev/null) || existing="" + + # ---- clean scan: close anything still open, then stop -------------------- + if [ "${critical}" -eq 0 ] && [ "${high}" -eq 0 ]; then + echo "alert: ${label} found no CRITICAL/HIGH on ${image} — nothing to alert." + local n state + for n in ${existing}; do + # Re-read the issue itself rather than trusting the list, which lags by + # a few seconds. Without this a back-to-back clean scan "closes" an + # already-closed issue and posts a second resolution comment to Slack. + state=$(gh issue view "${n}" --repo "${repo}" --json state --jq .state 2>/dev/null || echo "") + [ "${state}" = "OPEN" ] || continue + echo "alert: closing #${n} — the finding is gone." + gh issue comment "${n}" --repo "${repo}" \ + --body "✅ ${label} now reports no CRITICAL/HIGH on \`${image}\`. Closing. ([run](${url}))" \ + >/dev/null 2>&1 || echo "::warning::could not comment on #${n}" + gh issue close "${n}" --repo "${repo}" >/dev/null 2>&1 \ + || echo "::warning::could not close #${n}" + done + return 0 + fi + + # ---- ADO's exact phrasing: "*N* Critical, *M* High", zero counts omitted -- + local summary="" + [ "${critical}" -gt 0 ] && summary="${critical} Critical" + if [ "${high}" -gt 0 ]; then + [ -n "${summary}" ] && summary="${summary}, " + summary="${summary}${high} High" + fi + + local heading suffix="" + if [ -n "${context}" ]; then + heading="${label} Scan Failed (${context})" + [ "${context}" = "Build-time" ] && suffix=" (newly built)" + else + heading="${label} Scan Failed" + fi + + local title="🚨 ${heading} — ${summary} in ${image}" + local body + body=$(printf '%s\n\n**%s**\n\n* Image: `%s`%s\n* Found **%s** vulnerabilities\n\nPer-CVE detail, fixed versions and the suppression list are in the workflow run — deliberately not repeated here, see the note in `scripts/scan-report.sh`.\n\n📎 [View the %s report](%s)\n\nThis issue closes itself when a later scan of the same image comes back clean.\n' \ + "${marker}" "${heading}" "${image}" "${suffix}" "${summary}" "${label}" "${url}") + + if [ -n "${existing}" ]; then + # Comment on the oldest; any duplicate gets closed by the next clean scan. + local oldest + oldest=$(printf '%s\n' ${existing} | sed -n '1p') + echo "alert: #${oldest} is already open for ${label}/${image} — commenting instead of opening another." + gh issue comment "${oldest}" --repo "${repo}" \ + --body "🚨 Still failing: **${summary}** in \`${image}\`. ([run](${url}))" \ + >/dev/null 2>&1 || echo "::warning::could not comment on #${oldest}" + return 0 + fi + + echo "alert: opening an issue — ${title}" + if gh issue create --repo "${repo}" --title "${title}" --body "${body}" \ + --label vulnerability-alert >/dev/null 2>&1 + then + echo "alert: issue opened." + else + echo "::warning::Could not open the alert issue for ${label}. The scan result itself is unaffected — see the gate step." + fi + return 0 +} + +command -v jq >/dev/null || die "jq is required" + +case "${1:-}" in + report) + scanner="${2:-}"; file="${3:-}"; image="${4:-unknown image}"; gomod="${5:-go.mod}" + [ -n "${file}" ] || die "usage: $0 report [go.mod]" + [ -f "${file}" ] || die "${file} missing — the scan step did not produce a report" + godir=$(go_directive "${gomod}") + case "${scanner}" in + trivy) report_trivy "${file}" "${image}" "${godir}" ;; + grype) report_grype "${file}" "${image}" "${godir}" ;; + *) die "unknown scanner '${scanner}' (expected trivy or grype)" ;; + esac + # Same data, rendered into the run page. No-op outside Actions. + step_summary "${scanner}" "${file}" "${image}" + ;; + gate) + [ -f "${2:-}" ] || die "usage: $0 gate " + [ -f "${3:-}" ] || die "usage: $0 gate " + gate "$2" "$3" + ;; + alert) + # Deliberately tolerant: a bad invocation warns and exits 0. See alert(). + scanner="${2:-}"; file="${3:-}"; image="${4:-unknown image}" + context="${5:-}"; url="${6:-}" + if [ -z "${scanner}" ] || [ -z "${file}" ]; then + echo "alert: usage: $0 alert [context] [run-url]" >&2 + exit 0 + fi + alert "${scanner}" "${file}" "${image}" "${context}" "${url}" + ;; + *) + die "usage: $0 {report [go.mod] | gate | alert [context] [run-url]}" + ;; +esac diff --git a/scripts/setup-fork-sync.sh b/scripts/setup-fork-sync.sh new file mode 100755 index 00000000..2491d3c3 --- /dev/null +++ b/scripts/setup-fork-sync.sh @@ -0,0 +1,17 @@ +#!/usr/bin/env bash +# One-time per-clone setup so .gitattributes `merge=ours` rules work. +# +# The `ours` merge driver is not built into git and git config cannot be +# committed, so every clone needs this. Without it, syncing from upstream +# silently overwrites OutSystems-owned files such as .github/workflows/ci.yml. +set -euo pipefail + +git config merge.ours.driver true +echo "✅ merge.ours.driver = $(git config --get merge.ours.driver)" + +if ! git remote get-url upstream >/dev/null 2>&1; then + echo "ℹ️ No 'upstream' remote. Add it with:" + echo " git remote add upstream https://github.com/jpillora/chisel.git" +else + echo "✅ upstream = $(git remote get-url upstream)" +fi