ci(security): add container validation checks

This commit is contained in:
Daniel Radl 2026-08-20 15:24:18 +02:00
parent 4b9d35666a
commit e97eb0a8ca
14 changed files with 525 additions and 8 deletions

View File

@ -17,6 +17,21 @@ updates:
schedule: schedule:
interval: weekly interval: weekly
- package-ecosystem: docker-compose
directory: /overrides
schedule:
interval: weekly
allow:
- dependency-name: nginxproxy/acme-companion
- dependency-name: nginxproxy/nginx-proxy
- dependency-name: traefik
groups:
proxy-images:
patterns:
- nginxproxy/acme-companion
- nginxproxy/nginx-proxy
- traefik
- package-ecosystem: pip - package-ecosystem: pip
directory: / directory: /
schedule: schedule:

150
.github/scripts/validate_compose.py vendored Normal file
View File

@ -0,0 +1,150 @@
"""Validate every supported Docker Compose override combination."""
import json
import os
import subprocess
import sys
from pathlib import Path
from typing import Dict, List
ROOT = Path(__file__).resolve().parents[2]
MATRIX_PATH = ROOT / "tests" / "compose-configs.json"
OVERRIDES_PATH = ROOT / "overrides"
def fail(message: str) -> None:
print(f"Compose validation configuration error: {message}", file=sys.stderr)
raise SystemExit(1)
def load_matrix() -> Dict[str, object]:
try:
matrix = json.loads(MATRIX_PATH.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError) as exc:
fail(f"cannot read {MATRIX_PATH.relative_to(ROOT)}: {exc}")
if not isinstance(matrix, dict):
fail("the matrix root must be a JSON object")
environment = matrix.get("environment")
configurations = matrix.get("configurations")
if not isinstance(environment, dict):
fail("'environment' must be a JSON object")
if not isinstance(configurations, list) or not configurations:
fail("'configurations' must be a non-empty JSON array")
return matrix
def validate_matrix(configurations: List[object]) -> None:
names = set()
covered_overrides = set()
for index, configuration in enumerate(configurations, start=1):
if not isinstance(configuration, dict):
fail(f"configuration #{index} must be a JSON object")
name = configuration.get("name")
files = configuration.get("files")
if not isinstance(name, str) or not name:
fail(f"configuration #{index} needs a non-empty 'name'")
if name in names:
fail(f"configuration name '{name}' is duplicated")
names.add(name)
if not isinstance(files, list) or not files:
fail(f"configuration '{name}' needs a non-empty 'files' array")
if len(files) != len(set(files)):
fail(f"configuration '{name}' references a file more than once")
for filename in files:
if not isinstance(filename, str):
fail(f"configuration '{name}' contains a non-string file name")
path = ROOT / filename
if not path.is_file():
fail(f"configuration '{name}' references missing file '{filename}'")
if path.parent == OVERRIDES_PATH:
covered_overrides.add(path.relative_to(ROOT).as_posix())
existing_overrides = {
path.relative_to(ROOT).as_posix()
for path in OVERRIDES_PATH.glob("compose.*.yaml")
}
uncovered_overrides = sorted(existing_overrides - covered_overrides)
if uncovered_overrides:
formatted = "\n - ".join(uncovered_overrides)
fail(
"every override must be covered by at least one configuration in "
f"{MATRIX_PATH.relative_to(ROOT)}. Add:\n - {formatted}"
)
def validate_compose(
configurations: List[object], environment: Dict[str, object]
) -> int:
compose_environment = os.environ.copy()
for key, value in environment.items():
if not isinstance(key, str) or not isinstance(value, str):
fail("all 'environment' keys and values must be strings")
compose_environment[key] = value
failures = 0
total = len(configurations)
for index, configuration in enumerate(configurations, start=1):
name = configuration["name"]
files = configuration["files"]
command = [
"docker",
"compose",
"--project-directory",
str(ROOT),
"--env-file",
str(ROOT / "example.env"),
]
for filename in files:
command.extend(("-f", str(ROOT / filename)))
command.extend(("config", "--quiet"))
print(f"[{index}/{total}] Validating {name}")
try:
result = subprocess.run(
command,
cwd=ROOT,
env=compose_environment,
text=True,
capture_output=True,
check=False,
)
except FileNotFoundError:
fail("Docker Compose is required, but the 'docker' command was not found")
if result.returncode:
failures += 1
print(f"FAILED: {name}", file=sys.stderr)
if result.stdout:
print(result.stdout.rstrip(), file=sys.stderr)
if result.stderr:
print(result.stderr.rstrip(), file=sys.stderr)
if failures:
print(
f"{failures} of {total} Compose configurations failed validation.",
file=sys.stderr,
)
return 1
print(f"Validated {total} Compose configurations.")
return 0
def main() -> int:
matrix = load_matrix()
configurations = matrix["configurations"]
environment = matrix["environment"]
validate_matrix(configurations)
return validate_compose(configurations, environment)
if __name__ == "__main__":
raise SystemExit(main())

View File

@ -9,4 +9,5 @@ jobs:
permissions: permissions:
contents: read contents: read
packages: write packages: write
security-events: write
secrets: inherit secrets: inherit

View File

@ -9,4 +9,5 @@ jobs:
permissions: permissions:
contents: write contents: write
packages: write packages: write
security-events: write
secrets: inherit secrets: inherit

View File

@ -3,6 +3,7 @@ name: Core / Build Develop
permissions: permissions:
contents: read contents: read
packages: write packages: write
security-events: write
on: on:
workflow_call: workflow_call:

View File

@ -3,6 +3,7 @@ name: Core / Build Stable
permissions: permissions:
contents: read contents: read
packages: write packages: write
security-events: write
on: on:
workflow_call: workflow_call:

View File

@ -29,6 +29,7 @@ on:
permissions: permissions:
contents: read contents: read
security-events: write
jobs: jobs:
resolve: resolve:
@ -94,6 +95,80 @@ jobs:
env: env:
REGISTRY_USER: localhost:5000/frappe REGISTRY_USER: localhost:5000/frappe
- name: Create Trivy report directory
run: mkdir -p trivy-results
- name: Scan base image
id: trivy_base
continue-on-error: true
uses: aquasecurity/trivy-action@v0.36.0
with:
image-ref: localhost:5000/frappe/base:${{ env.FRAPPE_VERSION }}
scanners: vuln
format: sarif
output: trivy-results/base.sarif
severity: HIGH,CRITICAL
ignore-unfixed: true
limit-severities-for-sarif: true
exit-code: 0
- name: Scan build image
if: ${{ env.ERPNEXT_VERSION != '' }}
id: trivy_build
continue-on-error: true
uses: aquasecurity/trivy-action@v0.36.0
with:
image-ref: localhost:5000/frappe/build:${{ env.ERPNEXT_VERSION }}
scanners: vuln
format: sarif
output: trivy-results/build.sarif
severity: HIGH,CRITICAL
ignore-unfixed: true
limit-severities-for-sarif: true
exit-code: 0
skip-setup-trivy: true
- name: Scan ERPNext image
if: ${{ env.ERPNEXT_VERSION != '' }}
id: trivy_erpnext
continue-on-error: true
uses: aquasecurity/trivy-action@v0.36.0
with:
image-ref: localhost:5000/frappe/erpnext:${{ env.ERPNEXT_VERSION }}
scanners: vuln
format: sarif
output: trivy-results/erpnext.sarif
severity: HIGH,CRITICAL
ignore-unfixed: true
limit-severities-for-sarif: true
exit-code: 0
skip-setup-trivy: true
- name: Upload Trivy report artifact
if: ${{ always() && hashFiles('trivy-results/*.sarif') != '' }}
continue-on-error: true
uses: actions/upload-artifact@v4
with:
name: trivy-${{ inputs.version }}-${{ matrix.arch }}
path: trivy-results/*.sarif
retention-days: 30
- name: Upload Trivy results to code scanning
if: >-
${{
always() &&
hashFiles('trivy-results/*.sarif') != '' &&
(
github.event_name != 'pull_request' ||
github.event.pull_request.head.repo.full_name == github.repository
)
}}
continue-on-error: true
uses: github/codeql-action/upload-sarif@v4
with:
sarif_file: trivy-results
category: trivy-${{ inputs.version }}-${{ matrix.arch }}
- name: Setup Python - name: Setup Python
uses: actions/setup-python@v7 uses: actions/setup-python@v7
with: with:

8
.hadolint.yaml Normal file
View File

@ -0,0 +1,8 @@
# Keep existing warnings visible without making all current pull requests fail.
# Raise high-confidence container safety rules to errors so they remain blocking.
failure-threshold: error
override:
error:
- DL3002
- DL3006
- DL3007

View File

@ -55,3 +55,27 @@ repos:
hooks: hooks:
- id: shellcheck - id: shellcheck
args: [-x] args: [-x]
- repo: local
hooks:
- id: hadolint
name: hadolint
description: Lint Dockerfiles and Containerfiles with Hadolint
language: docker_image
entry: ghcr.io/hadolint/hadolint:v2.15.1 hadolint
types: [dockerfile]
- id: validate-compose
name: validate compose configurations
description: Validate every supported Docker Compose override combination
language: system
entry: python .github/scripts/validate_compose.py
pass_filenames: false
files: >-
(?x)^(
compose\.yaml|
example\.env|
overrides/compose\..*\.yaml|
tests/compose-configs\.json|
\.github/scripts/validate_compose\.py
)$

View File

@ -21,6 +21,7 @@ They decide when the core image pipeline runs.
- resolves the image versions for the requested release line - resolves the image versions for the requested release line
- builds the shared core images into a local registry - builds the shared core images into a local registry
- scans the locally built images with Trivy
- runs the test suite against those images - runs the test suite against those images
`core-publish-images.yml` is the reusable workflow that: `core-publish-images.yml` is the reusable workflow that:
@ -60,10 +61,11 @@ flowchart TD
B[core-build-test-images.yml] B[core-build-test-images.yml]
C[Resolve versions] C[Resolve versions]
D[Build local test images] D[Build local test images]
E[Run pytest] E[Scan images with Trivy]
F[core-publish-images.yml] F[Run pytest]
G[Push Docker Hub: erpnext, base, build] G[core-publish-images.yml]
H[Push GHCR: base, build] H[Push Docker Hub: erpnext, base, build]
O[Push GHCR: base, build]
A --> B A --> B
B --> C B --> C
@ -71,7 +73,8 @@ flowchart TD
D --> E D --> E
E --> F E --> F
F --> G F --> G
F --> H G --> H
G --> O
end end
subgraph App["Downstream app flow"] subgraph App["Downstream app flow"]
@ -89,8 +92,8 @@ flowchart TD
M --> N M --> N
end end
G --> J
H --> J H --> J
O --> J
``` ```
More concretely: More concretely:
@ -99,6 +102,7 @@ More concretely:
core-build-test-images.yml core-build-test-images.yml
-> resolves frappe and erpnext tags -> resolves frappe and erpnext tags
-> builds images into a local CI registry -> builds images into a local CI registry
-> scans the locally built images with Trivy
-> runs tests -> runs tests
core-publish-images.yml core-publish-images.yml

View File

@ -0,0 +1,95 @@
---
title: Container Validation
---
This repository validates its Dockerfiles, supported Compose configurations, and
built container images at different stages of development.
# Local checks
The lint workflow runs the repository's pre-commit hooks on every pull request.
Run the same checks locally before committing:
```shell
pre-commit run --all-files
```
To run only the container-related checks:
```shell
pre-commit run hadolint --all-files
pre-commit run validate-compose --all-files
```
The Hadolint hook uses a pinned container image, so it requires a working Docker
daemon. The Compose validator requires Docker Compose, but it only renders the
configuration and does not start containers.
# Dockerfile linting
Hadolint checks every Dockerfile and Containerfile through pre-commit and the
existing lint workflow. The policy is defined in `.hadolint.yaml`.
The initial policy keeps existing warnings visible while only errors fail the
check. It also promotes these high-confidence rules to errors:
- `DL3002`: the final container user must not be root
- `DL3006`: base images must have an explicit tag
- `DL3007`: base images must not use the `latest` tag
This allows warnings to be fixed incrementally without making unrelated pull
requests fail immediately. The failure threshold can be tightened after the
existing findings have been addressed.
# Compose configuration registry
`tests/compose-configs.json` is the registry of supported Compose combinations.
`.github/scripts/validate_compose.py` renders every entry with `docker compose
config --quiet` and fails if Docker Compose cannot merge the files.
The validator also checks that every `overrides/compose.*.yaml` file is included
in at least one registered configuration. This keeps adding a new override
simple and makes it difficult to forget its validation case.
When adding an override:
1. Add `overrides/compose.<name>.yaml`.
2. Add the override to at least one realistic entry in
`tests/compose-configs.json`.
3. Add harmless placeholder values to the entry's `environment` object if the
override introduces required variables that are not in `example.env`.
4. Run `python .github/scripts/validate_compose.py`.
Configurations are kept in one declarative registry and are evaluated in a
single lint job. This avoids creating a separate GitHub Actions matrix job for
every small Compose combination while preserving matrix-like coverage.
# Container image scanning
The core build workflow scans the locally built `base`, `build`, and `erpnext`
images with Trivy for each supported architecture. Reports contain fixed
`HIGH` and `CRITICAL` operating-system and application dependency
vulnerabilities.
During the initial rollout, Trivy is report-only:
- findings do not fail the build
- SARIF reports are retained as workflow artifacts for 30 days
- results are uploaded to GitHub Code Scanning for trusted workflow runs
- fork pull requests retain artifacts but skip the Code Scanning upload because
their workflow tokens cannot write security events
This provides visibility before deciding which vulnerability classes should
become blocking.
# Proxy image updates
Dependabot checks the Compose files in `overrides` each week and groups updates
for these externally managed proxy images:
- `nginxproxy/nginx-proxy`
- `nginxproxy/acme-companion`
- `traefik`
Database and Redis image versions are intentionally excluded because their
supported versions are defined by the Frappe framework.

View File

@ -11,7 +11,7 @@ services:
- ${HTTPS_PUBLISH_PORT:-443}:443 - ${HTTPS_PUBLISH_PORT:-443}:443
acme-companion: acme-companion:
image: nginxproxy/acme-companion:latest image: nginxproxy/acme-companion:2.8.2
restart: unless-stopped restart: unless-stopped
environment: environment:
DEFAULT_EMAIL: ${LETSENCRYPT_EMAIL:?No LETSENCRYPT_EMAIL set} DEFAULT_EMAIL: ${LETSENCRYPT_EMAIL:?No LETSENCRYPT_EMAIL set}

View File

@ -5,7 +5,7 @@ services:
VIRTUAL_PORT: 8080 VIRTUAL_PORT: 8080
nginx-proxy: nginx-proxy:
image: nginxproxy/nginx-proxy:alpine image: nginxproxy/nginx-proxy:1.11.6-alpine
restart: unless-stopped restart: unless-stopped
ports: ports:
- ${HTTP_PUBLISH_PORT:-80}:80 - ${HTTP_PUBLISH_PORT:-80}:80

142
tests/compose-configs.json Normal file
View File

@ -0,0 +1,142 @@
{
"environment": {
"BASE_SITE": "site-one.localhost",
"BENCH_NETWORK": "bench-network",
"DB_PASSWORD_SECRETS_FILE": "./test-db-password.txt",
"EMAIL": "admin@example.com",
"HASHED_PASSWORD": "not-a-real-password-hash",
"ROUTER": "site-one",
"TRAEFIK_DOMAIN": "traefik.example.com"
},
"configurations": [
{
"name": "mariadb-no-proxy",
"files": [
"compose.yaml",
"overrides/compose.mariadb.yaml",
"overrides/compose.redis.yaml",
"overrides/compose.noproxy.yaml"
]
},
{
"name": "mariadb-secrets",
"files": [
"compose.yaml",
"overrides/compose.mariadb.yaml",
"overrides/compose.mariadb-secrets.yaml",
"overrides/compose.redis.yaml",
"overrides/compose.noproxy.yaml"
]
},
{
"name": "postgres-no-proxy",
"files": [
"compose.yaml",
"overrides/compose.postgres.yaml",
"overrides/compose.redis.yaml",
"overrides/compose.noproxy.yaml"
]
},
{
"name": "traefik-http",
"files": [
"compose.yaml",
"overrides/compose.mariadb.yaml",
"overrides/compose.redis.yaml",
"overrides/compose.proxy.yaml"
]
},
{
"name": "traefik-https",
"files": [
"compose.yaml",
"overrides/compose.mariadb.yaml",
"overrides/compose.redis.yaml",
"overrides/compose.https.yaml"
]
},
{
"name": "nginx-proxy-http",
"files": [
"compose.yaml",
"overrides/compose.mariadb.yaml",
"overrides/compose.redis.yaml",
"overrides/compose.nginxproxy.yaml"
]
},
{
"name": "nginx-proxy-https",
"files": [
"compose.yaml",
"overrides/compose.mariadb.yaml",
"overrides/compose.redis.yaml",
"overrides/compose.nginxproxy.yaml",
"overrides/compose.nginxproxy-ssl.yaml"
]
},
{
"name": "migrator",
"files": [
"compose.yaml",
"overrides/compose.mariadb.yaml",
"overrides/compose.redis.yaml",
"overrides/compose.proxy.yaml",
"overrides/compose.migrator.yaml"
]
},
{
"name": "backup-cron",
"files": [
"compose.yaml",
"overrides/compose.mariadb.yaml",
"overrides/compose.redis.yaml",
"overrides/compose.proxy.yaml",
"overrides/compose.backup-cron.yaml"
]
},
{
"name": "shared-mariadb",
"files": ["overrides/compose.mariadb-shared.yaml"]
},
{
"name": "standalone-traefik-http",
"files": ["overrides/compose.traefik.yaml"]
},
{
"name": "standalone-traefik-https",
"files": [
"overrides/compose.traefik.yaml",
"overrides/compose.traefik-ssl.yaml"
]
},
{
"name": "multi-bench-http",
"files": [
"compose.yaml",
"overrides/compose.redis.yaml",
"overrides/compose.multi-bench.yaml"
]
},
{
"name": "multi-bench-https",
"files": [
"compose.yaml",
"overrides/compose.redis.yaml",
"overrides/compose.multi-bench.yaml",
"overrides/compose.multi-bench-ssl.yaml"
]
},
{
"name": "custom-domain-http",
"files": ["compose.yaml", "overrides/compose.custom-domain.yaml"]
},
{
"name": "custom-domain-https",
"files": [
"compose.yaml",
"overrides/compose.custom-domain.yaml",
"overrides/compose.custom-domain-ssl.yaml"
]
}
]
}