diff --git a/.github/workflows/call-images-build-ci.yml b/.github/workflows/call-images-build-ci.yml index e375c6af30..a445630d43 100644 --- a/.github/workflows/call-images-build-ci.yml +++ b/.github/workflows/call-images-build-ci.yml @@ -78,6 +78,8 @@ jobs: permissions: contents: read packages: write + env: + FORK_TARGET_BUILD: ${{ github.event_name == 'pull_request_target' && github.event.pull_request.head.repo.full_name != github.repository }} steps: - name: ⬇️ Checkout trusted workflow repo (helpers) @@ -158,7 +160,8 @@ jobs: INFINITO_DISTROS: ${{ join(fromJson(needs.pools.outputs.matrix), ' ') }} IMAGE_ARCH: ${{ matrix.architecture }} IMAGE_DIGEST_DIR: build/image-digests - USE_NIX_TOKEN: ${{ !(github.event_name == 'pull_request_target' && github.event.pull_request.head.repo.full_name != github.repository) }} + USE_NIX_TOKEN: ${{ env.FORK_TARGET_BUILD != 'true' }} + EXPORT_BUILD_CACHE: ${{ env.FORK_TARGET_BUILD != 'true' }} NIX_GITHUB_TOKEN: ${{ github.token }} MAX_ATTEMPTS: "7" RETRY_DELAY_SECONDS: "20" diff --git a/.github/workflows/call-images-mirror-missing.yml b/.github/workflows/call-images-mirror-missing.yml index 9d95329996..7f70bdec8a 100644 --- a/.github/workflows/call-images-mirror-missing.yml +++ b/.github/workflows/call-images-mirror-missing.yml @@ -91,6 +91,8 @@ jobs: steps: - name: ⬇️ Checkout uses: actions/checkout@v7.0.0 + with: + persist-credentials: false - name: 🔍 Resolve GHCR namespace and repository id: vars @@ -99,6 +101,10 @@ jobs: GHCR_NAMESPACE_INPUT: ${{ inputs.ghcr_namespace || '' }} run: bash scripts/meta/resolve/ghcr/namespace_and_repository.sh + - name: 🔗 Check symlinks out as plain files (optional) + if: ${{ inputs.source_repository != '' && inputs.source_ref != '' }} + run: git config --global core.symlinks false + - name: ⬇️ Checkout source repo for scan (optional) if: ${{ inputs.source_repository != '' && inputs.source_ref != '' }} uses: actions/checkout@v7.0.0 @@ -110,6 +116,12 @@ jobs: persist-credentials: false allow-unsafe-pr-checkout: ${{ inputs.allow_unsafe_checkout }} + - name: 🔗 Refuse symlinks in the scanned source (optional) + if: ${{ inputs.source_repository != '' && inputs.source_ref != '' }} + env: + SOURCE_PATH: ${{ inputs.source_path }} + run: bash scripts/github/gate/no_symlinks.sh "${SOURCE_PATH}" + - name: 🔧 Setup Python uses: actions/setup-python@v6 with: diff --git a/.github/workflows/call-orchestrator.yml b/.github/workflows/call-orchestrator.yml index 04da142767..cc1ac3fff9 100644 --- a/.github/workflows/call-orchestrator.yml +++ b/.github/workflows/call-orchestrator.yml @@ -398,7 +398,7 @@ jobs: if: ${{ !cancelled() }} run: grep '^INFINITO_GHCR_MIRROR_PREFIX=' default.env >> "$GITHUB_ENV" - name: 🛡️ Open, update and close the runtime vulnerability issues - if: ${{ !cancelled() }} + if: ${{ !cancelled() && (contains(needs.*.result, 'success') || contains(needs.*.result, 'failure') || contains(needs.*.result, 'cancelled')) }} env: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} run: python3 -m cli.meta.ci.runtime_vulnerabilities --run-id "${{ github.run_id }}" --repo "${{ github.repository }}" --ref "${GITHUB_REF}" --dir "${RUNNER_TEMP}/rescue-diagnostics" diff --git a/.github/workflows/entry-pr-change-orchestrate.yml b/.github/workflows/entry-pr-change-orchestrate.yml index 0a3c46f036..4f2921e911 100644 --- a/.github/workflows/entry-pr-change-orchestrate.yml +++ b/.github/workflows/entry-pr-change-orchestrate.yml @@ -140,8 +140,27 @@ jobs: PR_MERGE_SHA: ${{ github.event.pull_request.merge_commit_sha || '' }} run: ./scripts/meta/resolve/pr/merge_ref.sh - build-ci-images-fork: + fork-trust-gate: + name: 🛡️ Gate fork trust needs: prepare-fork-merge-ref + runs-on: ubuntu-26.04 + steps: + - name: ⬇️ Checkout + uses: actions/checkout@v7.0.0 + with: + persist-credentials: false + + - name: 🛡️ Require the maintainer Trusted label + shell: bash + env: + TRUSTED: ${{ needs.prepare-fork-merge-ref.outputs.trusted }} + PR_NUMBER: ${{ github.event.pull_request.number }} + run: bash scripts/github/gate/trusted_label.sh + + build-ci-images-fork: + needs: + - prepare-fork-merge-ref + - fork-trust-gate permissions: contents: read packages: write @@ -155,7 +174,9 @@ jobs: allow_unsafe_checkout: true images-mirror-missing-fork: - needs: prepare-fork-merge-ref + needs: + - prepare-fork-merge-ref + - fork-trust-gate permissions: contents: read packages: write diff --git a/docs/contributing/artefact/git/pipeline.md b/docs/contributing/artefact/git/pipeline.md index e69ee1385d..1bbe1b25a9 100644 --- a/docs/contributing/artefact/git/pipeline.md +++ b/docs/contributing/artefact/git/pipeline.md @@ -32,7 +32,7 @@ The orchestrator runs the following stages in order: ### 1. Fork Prerequisites ⏳ -For fork PRs, CI waits for privileged images built by the `pull_request_target` event before proceeding. For an untrusted fork that build runs from the safe base merge ref **without organization secrets** (only the per-job `GITHUB_TOKEN`); a maintainer-applied `🛡️ Trusted` label switches the build source to the PR head, unlocks the mirror credentials, and skips the wait — see [Trusted fork PRs](#trusted-fork-prs-). +For fork PRs, CI waits for privileged images built by the `pull_request_target` event before proceeding. That build and the mirror producer run only for a fork PR that carries the maintainer-applied `🛡️ Trusted` label; for an untrusted fork the `🛡️ Gate fork trust` job fails instead, and the waiting `pull_request` run fails fast with it. The label also switches the build source to the PR head and skips the wait — see [Trusted fork PRs](#trusted-fork-prs-). ### 2. Security 🛡️ @@ -62,7 +62,7 @@ The `code-quality-gate` requires linting, code tests, and security checks to all [call-images-mirror-missing.yml](../../../../.github/workflows/call-images-mirror-missing.yml) mirrors any missing upstream images in parallel with the DNS tests so later deploy jobs pull from GHCR instead of Docker Hub, MCR, or other external registries. This shields CI from upstream rate limits, geo-blocking, and transient registry outages. -Fork PRs cannot publish mirror packages directly, so their runs wait for the `pull_request_target` mirror producer before continuing. The producer mirrors with the Docker Hub credentials only for trusted PRs ([🛡️ Trusted](#trusted-fork-prs-)); untrusted forks mirror anonymously (no organization secrets). See [mirror.md](../image/mirror.md) for the mirroring architecture and naming convention. +Fork PRs cannot publish mirror packages directly, so their runs wait for the `pull_request_target` mirror producer before continuing. The producer runs only for trusted PRs ([🛡️ Trusted](#trusted-fork-prs-)) and is the only fork-facing job that receives the Docker Hub credentials. It checks the fork tree out with `core.symlinks=false` and refuses any symlink left in it, so the scan reads the tree's own files and nothing outside it. See [mirror.md](../image/mirror.md) for the mirroring architecture and naming convention. GHCR publication uses the workflow `GITHUB_TOKEN`; optional Docker Hub secrets are used only to reduce source-side Docker Hub rate limits while mirroring. See [authentication.md](../../tools/ghcr/authentication.md). @@ -139,7 +139,7 @@ See [configuration.md](../../tools/github/actions/configuration.md) for all repo Fork PRs run under the `pull_request` event without write permissions. Privileged steps (image builds, package writes) run via `pull_request_target`. The fork CI waits for those privileged images before proceeding. See [pull-request.md](pull-request.md) for the contributor-facing fork workflow. -By default — for an **untrusted** fork PR — the privileged `pull_request_target` build checks out the **base merge ref** (`refs/pull//merge`) from the base repository: the PR's changes merged onto base, with all workflow and build-orchestration scripts coming from base, never from the fork. Because `actions/checkout` otherwise refuses to fetch a PR ref under `pull_request_target`, the source checkout sets `allow-unsafe-pr-checkout: true`. The untrusted build runs **without organization secrets** — `secrets: inherit` is not passed and it authenticates to GHCR with the per-job `GITHUB_TOKEN` only, so a malicious fork cannot read repository/organization secrets. (The `pull_request_target` token still carries `packages: write`, so the `🛡️ Trusted` label remains the real trust boundary for anything beyond image publication.) +For an **untrusted** fork PR the privileged `pull_request_target` jobs stop at the `🛡️ Gate fork trust` job: it fails, so neither the image build nor the mirror producer runs fork content next to the `packages: write` token, and the fork's `pull_request` run fails its prerequisite wait as soon as that run ends. The merge-ref expressions in `build-ci-images-fork` stay as a fallback only. Because `actions/checkout` otherwise refuses to fetch a PR ref under `pull_request_target`, the source checkouts set `allow-unsafe-pr-checkout: true`; the lint `tests/lint/repository/test_workflow_fork_checkout_gated.py` fails any `pull_request_target` job with such a checkout that does not need the gate. ### Trusted fork PRs 🔓 @@ -147,12 +147,13 @@ When a maintainer applies the `🛡️ Trusted` label, the fork PR is treated as - The orchestrator's `wait-fork-prereq-run` job **skips the wait** for the privileged fork images. - The privileged `pull_request_target` build switches its **build source** from the base merge ref to the **raw PR head** (`head.repo.full_name` @ `head.sha`). -- The trusted build additionally receives the Docker Hub mirror credentials (passed only when the label is present); untrusted builds mirror anonymously. +- The trusted mirror producer receives the Docker Hub mirror credentials; untrusted fork PRs get no privileged job at all. +- A fork-sourced build imports the shared `buildcache-` registry cache but never exports to it, so only base-sourced builds write the cache every trusted build reads. - The built image **keeps the merge-SHA tag** (`ci-`) so the `pull_request` orchestrator finds it unchanged — no consumer workflow has to know about the label. Security gates: -- The `🛡️ Trusted` label flips the build source to the PR head and unlocks the Docker Hub credentials; without it the safe base merge ref is built with no organization secrets. Restrict who may set the label via repository label permissions / branch protection so only maintainers can grant it. +- The `🛡️ Trusted` label is the only way a fork PR reaches the privileged build and mirror. Restrict who may set the label via repository label permissions / branch protection so only maintainers can grant it. The label stays on the PR across later pushes, so review every new head before CI uses it, or remove the label first. - Build-orchestration scripts (`scripts/image/push.sh` and the helper checkout) always come from the base repo at `github.sha`; only the Docker build **context** (`_src`) is the fork head. `persist-credentials: false` keeps the token out of the source checkout, and `USE_NIX_TOKEN` stays disabled for fork-sourced builds. - Fork `pull_request` runs always receive a read-only token (GitHub-enforced); the label never grants write tokens or secrets to the untrusted event. diff --git a/roles/sys-ctl-hlth-runtime/README.md b/roles/sys-ctl-hlth-runtime/README.md index 6b8c6a393f..b8c0a520c8 100644 --- a/roles/sys-ctl-hlth-runtime/README.md +++ b/roles/sys-ctl-hlth-runtime/README.md @@ -39,6 +39,7 @@ Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional ( - **Metrics:** While `web-app-prometheus` is deployed, the check replaces `infinito_hlth_runtime.prom` in `DIR_METRICS_TEXTFILE` atomically with the gauges `infinito_hlth_runtime_findings{target,kind,image,severity,scanner,verdict}`, `infinito_hlth_runtime_last_run_timestamp_seconds`, `infinito_hlth_runtime_last_run_success` and `infinito_hlth_runtime_scanner_errors{scanner}`. No series carries a CVE id. - **Suppressions:** A role accepts findings for its own containers under `.security.suppressions` of its `meta/services.yml`, each entry `id` (one CVE) or `image_tag` (every finding of the image while it runs that tag, which MUST equal the service's `version`) plus `until` below a `# nocheck: cve ` marker, see [suppression.md](../../docs/contributing/actions/testing/suppression.md). Host suppressions are the `id` entries under the engine entries of this role and cover that engine's host findings; an `image_tag` entry there covers the engine's own image. - **Databases:** With `db_update` the engines refresh their databases under `database_dir` before each run, three attempts 30 s apart; without it the databases MUST already be there, and a missing one fails the run. SBOMs of running images are cached under `cache_dir` by image id. +- **Run bound:** Every engine run ends after `JOB_TIMEOUT_SECONDS` of [script.py](./files/python/script.py), 4 h, and then fails the check. Trivy gets the same bound as its `--timeout`, because its own default of 5 minutes failed the scan of the 4.5 GB `local_discourse/discourse` image on a busy swarm node with `context deadline exceeded`. - **Scratch:** Every engine run gets its own temporary directory in the run's work directory under `cache_dir`, removed as soon as the run ends, also when the engine fails, times out or crashes. Engine runs that export an image take turns, whatever `workers` is: each holds a lock on `database_dir` from creating its scratch directory until it has removed it, and on a timeout or crash also its container. The lock spans every scan that reads the same `database_dir`, so the swarm lab nodes and the local stacks of every worktree, which all share the host directory `INFINITO_VULNERABILITY_DB_HOST_PATH` of `default.env`, take turns on their one host disk. The other engine runs keep running in parallel. A run killed mid-scan leaves its work directory to the next run, which removes it first. - **Deploy-time run:** The deploy runs the check once at its end and fails on its first failure, without the retries `sys-service-terminator` gives other units. - **Development and CI deploys:** A CI row pins one engine and restores its databases; a local deploy draws one engine and refreshes the shared host directory `INFINITO_VULNERABILITY_DB_HOST_PATH`. Both run it behind Syft plus the Grype runtime pass and read the databases read-only at `INFINITO_VULNERABILITY_DB_DIR`. Production hosts run every engine. diff --git a/roles/sys-ctl-hlth-runtime/files/python/script.py b/roles/sys-ctl-hlth-runtime/files/python/script.py index bb6f05a8a9..87b1526518 100755 --- a/roles/sys-ctl-hlth-runtime/files/python/script.py +++ b/roles/sys-ctl-hlth-runtime/files/python/script.py @@ -1295,6 +1295,8 @@ ENGINE_ENV = { TRIVY_COMMON = ( "--cache-dir", CACHE, + "--timeout", + f"{JOB_TIMEOUT_SECONDS}s", "--disable-telemetry", "--skip-version-check", "--quiet", diff --git a/roles/web-app-erpnext/files/python/apply/email_account.py b/roles/web-app-erpnext/files/python/apply/email_account.py index f97769cb2d..846e62ee30 100644 --- a/roles/web-app-erpnext/files/python/apply/email_account.py +++ b/roles/web-app-erpnext/files/python/apply/email_account.py @@ -1,5 +1,3 @@ -# nocheck: mirrored-unit-test - imports frappe at module level and runs inside `bench -# execute`; the framework is not installable outside the ERPNext image import os import frappe @@ -9,6 +7,9 @@ MAIL_FROM_NAME = os.environ["MAIL_FROM_NAME"] MAIL_FROM_ADDRESS = os.environ["MAIL_FROM_ADDRESS"] SMTP_HOST = os.environ["SMTP_HOST"] SMTP_PORT = int(os.environ["SMTP_PORT"]) +SMTP_TLS = os.environ["SMTP_TLS"] == "true" +SMTP_START_TLS = os.environ["SMTP_START_TLS"] == "true" +SMTP_AUTH = os.environ["SMTP_AUTH"] == "true" SMTP_USER = os.environ["SMTP_USER"] SMTP_PASS = os.environ["SMTP_PASS"] @@ -27,7 +28,8 @@ def upsert_outbound_account(): ea.enable_incoming = 0 ea.smtp_server = SMTP_HOST ea.smtp_port = SMTP_PORT - ea.use_tls = 1 + ea.use_ssl_for_outgoing = int(SMTP_TLS and not SMTP_START_TLS) + ea.use_tls = int(SMTP_TLS and SMTP_START_TLS) ea.login_id_is_different = 1 ea.login_id = SMTP_USER ea.password = SMTP_PASS @@ -35,7 +37,7 @@ def upsert_outbound_account(): ea.flags.ignore_permissions = True ea.flags.ignore_validate = True ea.flags.no_check_in_db = True - ea.no_smtp_authentication = 0 + ea.no_smtp_authentication = int(not SMTP_AUTH) ea.flags.ignore_links = True ea.flags.ignore_mandatory = True try: diff --git a/roles/web-app-erpnext/tasks/addons/email_account.yml b/roles/web-app-erpnext/tasks/addons/email_account.yml index 5b7b64db86..91eb8cc1fe 100644 --- a/roles/web-app-erpnext/tasks/addons/email_account.yml +++ b/roles/web-app-erpnext/tasks/addons/email_account.yml @@ -5,7 +5,7 @@ cmd: > # nocheck: container-exec-resolver runtime-resolved CID, delegated to the hosting node container exec -i -e SITE_NAME -e MAIL_FROM_NAME -e MAIL_FROM_ADDRESS - -e SMTP_HOST -e SMTP_PORT -e SMTP_USER -e SMTP_PASS + -e SMTP_HOST -e SMTP_PORT -e SMTP_TLS -e SMTP_START_TLS -e SMTP_AUTH -e SMTP_USER -e SMTP_PASS {{ ERPNEXT_BACKEND_LOCAL_CID | quote }} {{ ERPNEXT_BENCH_PYTHON }} stdin: "{{ lookup('ansible.builtin.file', role_path ~ '/files/python/apply/email_account.py') }}" @@ -16,6 +16,9 @@ MAIL_FROM_ADDRESS: "{{ ERPNEXT_MAIL.username | default('') }}" SMTP_HOST: "{{ ERPNEXT_MAIL.host | default('') }}" SMTP_PORT: "{{ ERPNEXT_MAIL.port | default(587) }}" + SMTP_TLS: "{{ ERPNEXT_MAIL.tls | bool | string | lower }}" + SMTP_START_TLS: "{{ ERPNEXT_MAIL.start_tls | bool | string | lower }}" + SMTP_AUTH: "{{ ERPNEXT_MAIL.auth | bool | string | lower }}" SMTP_USER: "{{ ERPNEXT_MAIL.username | default('') }}" SMTP_PASS: "{{ ERPNEXT_MAIL.password | default('') }}" when: ERPNEXT_MAIL.host is defined and (ERPNEXT_MAIL.host | length > 0) diff --git a/roles/web-app-espocrm/meta/services.yml b/roles/web-app-espocrm/meta/services.yml index 60f35be54e..f8ee319dad 100644 --- a/roles/web-app-espocrm/meta/services.yml +++ b/roles/web-app-espocrm/meta/services.yml @@ -38,7 +38,7 @@ espocrm: swarm: enabled: true image: espocrm/espocrm - version: "10.1.3" + version: "10.1.4" custom: true name: espocrm min_storage: 470MB diff --git a/roles/web-app-gitlab/meta/services.yml b/roles/web-app-gitlab/meta/services.yml index f7990236af..cf4fc8fa72 100644 --- a/roles/web-app-gitlab/meta/services.yml +++ b/roles/web-app-gitlab/meta/services.yml @@ -78,7 +78,7 @@ webservice: backup: stop_required: false image: registry.gitlab.com/gitlab-org/build/cng/gitlab-webservice-ce - version: v19.6.0 + version: v19.6.1 name: gitlab-webservice healthcheck: test: ["CMD", "/scripts/healthcheck"] @@ -99,7 +99,7 @@ sidekiq: flavor: tcp path: liveness image: registry.gitlab.com/gitlab-org/build/cng/gitlab-sidekiq-ce - version: v19.6.0 + version: v19.6.1 name: gitlab-sidekiq cpus: "1.0" mem_reservation: 2g @@ -112,7 +112,7 @@ workhorse: backup: stop_required: false image: registry.gitlab.com/gitlab-org/build/cng/gitlab-workhorse-ce - version: v19.6.0 + version: v19.6.1 name: gitlab-workhorse healthcheck: test: ["CMD", "/scripts/healthcheck"] @@ -143,7 +143,7 @@ shell: backup: stop_required: false image: registry.gitlab.com/gitlab-org/build/cng/gitlab-shell - version: v19.6.0 + version: v19.6.1 name: gitlab-shell ports: internal: @@ -158,7 +158,7 @@ migrations: # nocheck: single-replica replicas: 1 image: registry.gitlab.com/gitlab-org/build/cng/gitlab-rails-ce - version: v19.6.0 + version: v19.6.1 name: gitlab-migrations cpus: "1.0" mem_reservation: 1g diff --git a/roles/web-app-joomla/files/Dockerfile b/roles/web-app-joomla/files/Dockerfile index 73e682fc6b..fb0c128619 100644 --- a/roles/web-app-joomla/files/Dockerfile +++ b/roles/web-app-joomla/files/Dockerfile @@ -16,5 +16,6 @@ COPY ${JOOMLA_ENTRYPOINT_SCRIPT_HOST_REL} ${JOOMLA_ENTRYPOINT_SCRIPT_DOCKER} RUN chmod +x "${JOOMLA_ENTRYPOINT_SCRIPT_DOCKER}" \ && ln -sf "${JOOMLA_ENTRYPOINT_SCRIPT_DOCKER}" /usr/local/bin/entrypoint-joomla +ENV JOOMLA_STOCK_ENTRYPOINT=/entrypoint.sh ENTRYPOINT ["/usr/local/bin/entrypoint-joomla"] CMD ["apache2-foreground"] diff --git a/roles/web-app-joomla/files/shell/docker-entrypoint-joomla.sh b/roles/web-app-joomla/files/shell/docker-entrypoint-joomla.sh index 49a9d03bbb..ed909dae1f 100644 --- a/roles/web-app-joomla/files/shell/docker-entrypoint-joomla.sh +++ b/roles/web-app-joomla/files/shell/docker-entrypoint-joomla.sh @@ -1,30 +1,124 @@ #!/bin/bash -# Serialize the stock image's first-boot copy+auto-install across replicas that -# share the /var/www/html NFS volume (mkdir is atomic on NFS: one leader runs it, -# the rest block on the ready marker). The setup only runs when $1 is apache2*/ -# php-fpm, so the leader must drive it with `apache2 -v` (returns after setup) — -# a plain `true` skips the whole setup block and copies nothing. - -target="/var/www/html" -lock="${target}/.infinito-init.lock" +webroot="${JOOMLA_WEBROOT:?JOOMLA_WEBROOT must be set}" +stock="${JOOMLA_STOCK_ENTRYPOINT:?JOOMLA_STOCK_ENTRYPOINT must be set}" ready="${JOOMLA_INIT_READY_FILE:?JOOMLA_INIT_READY_FILE must be set}" +stale_after="${JOOMLA_INIT_LOCK_STALE_SECONDS:?JOOMLA_INIT_LOCK_STALE_SECONDS must be set}" +lock="${webroot}/.infinito-init.lock" +owner="${lock}/owner" +marker="${webroot}/.joomla-initializing" +pending="${webroot}/.infinito-init.cleanup" +config="${webroot}/configuration.php" +token="${HOSTNAME}.$$.$(date +%s%N)" +beat=$((stale_after / 4 + 1)) +heartbeat_pid="" -if [ ! -e "${ready}" ] && [ ! -e "${target}/configuration.php" ]; then - if mkdir "${lock}" 2>/dev/null; then - /entrypoint.sh apache2 -v || true # nocheck: shell-or-true -- grandfathered: worked in practice; TODO: sharpen to catch only the exact tolerated error - if [ -e "${target}/configuration.php" ]; then - chown -R www-data:www-data \ - "${target}/administrator/cache" "${target}/administrator/logs" \ - "${target}/cache" "${target}/tmp" 2>/dev/null || true # nocheck: shell-or-true -- grandfathered: worked in practice; TODO: sharpen to catch only the exact tolerated error - touch "${ready}" - fi - else - tries=0 - while [ ! -e "${ready}" ] && [ ! -e "${target}/configuration.php" ] && [ "${tries}" -lt 300 ]; do - sleep 2 - tries=$((tries + 1)) - done +trap 'exit 143' TERM +trap 'exit 130' INT + +log_error() { + printf '[ERROR] %s\n' "$1" >&2 +} + +initialized() { + [ -e "${ready}" ] || { [ -s "${config}" ] && [ ! -e "${marker}" ]; } +} + +stale() { + local stamp + stamp="$(stat -c %Y "$1/owner" 2>/dev/null)" || + stamp="$(stat -c %Y "$1" 2>/dev/null)" || + return 1 + [ $(($(date +%s) - stamp)) -gt "${stale_after}" ] +} + +take_over_stale() { + local moved="${lock}.stale.${token}" + stale "${lock}" || return 1 + mv -T "${lock}" "${moved}" 2>/dev/null || return 1 + if stale "${moved}"; then + rm -rf "${moved}" + return 0 fi -fi + mv -T "${moved}" "${lock}" + return 1 +} -exec /entrypoint.sh "$@" +heartbeat() { + while sleep "${beat}"; do + touch "${owner}" + done +} + +release() { + if [ -n "${heartbeat_pid}" ]; then + kill "${heartbeat_pid}" 2>/dev/null + fi + heartbeat_pid="" + if [ "$(cat "${owner}" 2>/dev/null)" = "${token}" ]; then + rm -rf "${lock}" + fi +} + +run_setup() { + local log + log="$(mktemp)" + { "${stock}" apache2 -l 2>&1 | tee "${log}"; } & + wait "$!" + if [ -s "${config}" ] && [ -d "${marker}" ] && + grep -q 'Unable to delete installation folder' "${log}" && + ! grep -qE 'Failed to (correct ownership|restore configuration)|Refusing to change permissions' "${log}"; then + touch "${pending}" + fi + rm -f "${log}" +} + +finish_cleanup() { + rm -rf "${webroot}/installation" || return 1 + rm -f "${webroot}/joomla.xml" || return 1 + if [ ! -e "${webroot}/robots.txt" ] && [ -e "${webroot}/robots.txt.dist" ]; then + mv "${webroot}/robots.txt.dist" "${webroot}/robots.txt" || return 1 + fi + rmdir "${marker}" || return 1 + rm -f "${pending}" +} + +recover() { + if [ ! -e "${marker}" ]; then + run_setup + fi + if [ -e "${marker}" ] && [ -e "${pending}" ] && ! finish_cleanup; then + log_error "Finishing Joomla's installer cleanup in ${webroot} failed; ${pending} stays, so the next start retries it." + return 1 + fi + if initialized; then + touch "${ready}" + return 0 + fi + if [ -e "${marker}" ]; then + log_error "${marker} remains from an unfinished Joomla setup. If that setup stopped at 'Unable to delete installation folder!', run 'touch ${pending}' and restart; otherwise restore the site and database, then remove ${marker}." + fi + return 1 +} + +lead() { + local status + printf '%s\n' "${token}" > "${owner}" + trap release EXIT + heartbeat & + heartbeat_pid=$! + recover + status=$? + release + trap - EXIT + return "${status}" +} + +until initialized; do + if mkdir "${lock}" 2>/dev/null; then + lead || exit 1 + elif ! take_over_stale; then + sleep 2 + fi +done + +exec "${stock}" "$@" diff --git a/roles/web-app-joomla/templates/env.j2 b/roles/web-app-joomla/templates/env.j2 index 0fdedc5d0f..14dd382f92 100644 --- a/roles/web-app-joomla/templates/env.j2 +++ b/roles/web-app-joomla/templates/env.j2 @@ -1,6 +1,8 @@ {% include 'roles/sys-svc-container/templates/env.j2' %} +JOOMLA_INIT_LOCK_STALE_SECONDS={{ JOOMLA_INIT_LOCK_STALE_SECONDS }} JOOMLA_INIT_READY_FILE={{ JOOMLA_INIT_READY_FILE }} +JOOMLA_WEBROOT={{ JOOMLA_DOCROOT }} JOOMLA_SITE_NAME={{ JOOMLA_SITE_NAME }} JOOMLA_ADMIN_USER={{ JOOMLA_USER }} JOOMLA_ADMIN_USERNAME={{ JOOMLA_USER_NAME }} diff --git a/roles/web-app-joomla/vars/main.yml b/roles/web-app-joomla/vars/main.yml index fd24e7d44d..c4744ff5c5 100644 --- a/roles/web-app-joomla/vars/main.yml +++ b/roles/web-app-joomla/vars/main.yml @@ -13,6 +13,7 @@ JOOMLA_CONFIG_FILE: "/var/www/html/configuration.php" JOOMLA_INSTALLER_CLI_FILE: "/var/www/html/installation/joomla.php" JOOMLA_CLI_FILE: "/var/www/html/cli/joomla.php" JOOMLA_INIT_READY_FILE: "/var/www/html/.infinito-init.ready" +JOOMLA_INIT_LOCK_STALE_SECONDS: 180 JOOMLA_CLI_EXTENSION_ENABLE_SINCE: "6.1.0" JOOMLA_DOCROOT: "{{ lookup('volume', application_id, 'data').target }}" diff --git a/roles/web-app-mediawiki/templates/oidc.php.j2 b/roles/web-app-mediawiki/templates/oidc.php.j2 index 7ce2059aa1..c4904c4993 100644 --- a/roles/web-app-mediawiki/templates/oidc.php.j2 +++ b/roles/web-app-mediawiki/templates/oidc.php.j2 @@ -5,8 +5,9 @@ $pa = "$IP/extensions/PluggableAuth/extension.json"; $oidc = "$IP/extensions/OpenIDConnect/extension.json"; +$oidcVendor = "$IP/extensions/OpenIDConnect/vendor/autoload.php"; -if ( file_exists( $pa ) && file_exists( $oidc ) ) { +if ( file_exists( $pa ) && file_exists( $oidc ) && file_exists( $oidcVendor ) ) { {% if 'web-svc-logout' in CURRENT_PLAY_APPLICATIONS %} $wgPasswordAttemptThrottle = []; diff --git a/roles/web-app-moodle/files/build/config.php b/roles/web-app-moodle/files/build/config.php index 3ac7ee66a2..a2c2bb9305 100644 --- a/roles/web-app-moodle/files/build/config.php +++ b/roles/web-app-moodle/files/build/config.php @@ -1,5 +1,4 @@ admin = 'admin'; $CFG->directorypermissions = 02770; $CFG->routerconfigured = true; +$CFG->session_handler_class = '\core\session\database'; + $CFG->reverseproxy = moodle_env_bool('MOODLE_REVERSEPROXY'); $CFG->sslproxy = moodle_env_bool('MOODLE_SSLPROXY'); diff --git a/roles/web-app-pretix/meta/services.yml b/roles/web-app-pretix/meta/services.yml index 158ec18ba7..8986698c27 100644 --- a/roles/web-app-pretix/meta/services.yml +++ b/roles/web-app-pretix/meta/services.yml @@ -56,7 +56,7 @@ pretix: # nocheck: docker-version runtime base of the source build, not the served application version: "3.13" source_repository: https://github.com/pretix/pretix.git - source_version: v2026.9.2 + source_version: v2026.9.3 update: - key: source_version type: git_tags diff --git a/roles/web-app-shopware/files/Dockerfile b/roles/web-app-shopware/files/Dockerfile index 092232bc4f..55ccd9f9dc 100644 --- a/roles/web-app-shopware/files/Dockerfile +++ b/roles/web-app-shopware/files/Dockerfile @@ -26,6 +26,7 @@ RUN set -eux; \ --no-scripts \ --ignore-platform-req=ext-gd \ --ignore-platform-req=ext-intl \ + --ignore-platform-req=ext-mbstring \ --ignore-platform-req=ext-pdo_mysql; \ composer require symfony/redis-messenger:^7.4 league/flysystem-async-aws-s3:^3.0 \ heptacom/shopware-platform-admin-open-auth:^9.0 \ @@ -35,6 +36,7 @@ RUN set -eux; \ --update-no-dev \ --ignore-platform-req=ext-gd \ --ignore-platform-req=ext-intl \ + --ignore-platform-req=ext-mbstring \ --ignore-platform-req=ext-pdo_mysql \ --ignore-platform-req=ext-redis diff --git a/roles/web-app-snipe-it/meta/services.yml b/roles/web-app-snipe-it/meta/services.yml index 4ac02548e6..5f6908c819 100644 --- a/roles/web-app-snipe-it/meta/services.yml +++ b/roles/web-app-snipe-it/meta/services.yml @@ -61,7 +61,7 @@ snipe-it: enabled: true swarm: enabled: true - version: v8.8.3-alpine + version: v8.8.4-alpine custom: true name: snipe-it image: snipe/snipe-it @@ -85,11 +85,6 @@ snipe-it: - web-app-stalwart - web-app-mailu lifecycle: beta - security: - suppressions: - # nocheck: cve upstream tag ships fixable CRITICAL CVEs; lift it once a rebuilt tag lands - - image_tag: "v8.8.3-alpine" - until: 2026-11-30 sso: bond: 1 enabled: "{{ 'web-app-keycloak' in group_names }}" diff --git a/roles/web-svc-collabora/meta/services.yml b/roles/web-svc-collabora/meta/services.yml index 3867c2486e..b281a5812e 100644 --- a/roles/web-svc-collabora/meta/services.yml +++ b/roles/web-svc-collabora/meta/services.yml @@ -25,7 +25,7 @@ collabora: enabled: true shared: true image: collabora/code - version: "26.04.6.1.1" + version: "26.04.6.2.1" name: collabora min_storage: 734MB cpus: 2 @@ -40,11 +40,6 @@ collabora: proxy: service_key: collabora lifecycle: beta - security: - suppressions: - # nocheck: cve upstream tag ships fixable CRITICAL CVEs; lift it once a rebuilt tag lands - - image_tag: "26.04.6.1.1" - until: 2026-11-30 # nocheck: dynamic-flag # nocheck: design-off Reason: '/' answers a plain OK, the admin console is off and the editor opens only as a POST from the WOPI host (Nextcloud) design: diff --git a/scripts/github/cancel/pull_request_runs.sh b/scripts/github/cancel/pull_request_runs.sh index 8abc9d7cc2..35ca10bb86 100755 --- a/scripts/github/cancel/pull_request_runs.sh +++ b/scripts/github/cancel/pull_request_runs.sh @@ -24,7 +24,8 @@ validate_force_cancel_after # A fork PR's runs carry an empty `pull_requests` array, so the branch matcher # is all that is left — and it cannot tell two pull requests apart that share a # head repository and head branch. Rather than cancel the wrong one, drop the -# matcher for as long as the head is ambiguous. +# branch and head-sha matchers for as long as the head is ambiguous: anyone may +# open a pull request from another fork's branch and close it to cancel its runs. disable_ambiguous_branch_fallback() { local rivals local -a query @@ -55,6 +56,7 @@ disable_ambiguous_branch_fallback() { if [[ "${rivals}" != "0" ]]; then echo "Branch fallback disabled: ${rivals} other open pull request(s) share ${PR_HEAD_REPOSITORY%%/*}:${PR_HEAD_REF}" PR_HEAD_REF="" + PR_HEAD_SHA="" fi } @@ -88,7 +90,15 @@ run_ids="$( | select(.event == "pull_request" or .event == "pull_request_target") | select( any(.pull_requests[]?; (.number // -1) == $pr_number) - or ($pr_head_sha != "" and (.head_sha // "") == $pr_head_sha) + or ( + $pr_head_sha != "" + and (.head_sha // "") == $pr_head_sha + and all(.pull_requests[]?; (.number // $pr_number) == $pr_number) + and ( + (.head_repository.full_name // "") == $pr_head_repository + or ((.display_title // "") | test("PR #\($pr_number)( |$)")) + ) + ) or ( $pr_head_ref != "" and all(.pull_requests[]?; (.number // $pr_number) == $pr_number) diff --git a/scripts/github/gate/no_symlinks.sh b/scripts/github/gate/no_symlinks.sh new file mode 100755 index 0000000000..738e0aa091 --- /dev/null +++ b/scripts/github/gate/no_symlinks.sh @@ -0,0 +1,18 @@ +#!/usr/bin/env bash +# +# Usage: no_symlinks.sh +# a directory checked out from an untrusted ref; the script fails +# when it holds a symlink, which would let a later read leave it. + +set -euo pipefail + +tree="${1:?Usage: no_symlinks.sh }" + +mapfile -t links < <(find "${tree}" -type l -print) + +if ((${#links[@]} > 0)); then + echo "Refusing ${tree}: ${#links[@]} symlink(s) survived core.symlinks=false." >&2 + printf ' - %q\n' "${links[@]:0:20}" >&2 + exit 1 +fi +echo "No symlinks under ${tree}." diff --git a/scripts/github/gate/trusted_label.sh b/scripts/github/gate/trusted_label.sh new file mode 100755 index 0000000000..642025c24b --- /dev/null +++ b/scripts/github/gate/trusted_label.sh @@ -0,0 +1,16 @@ +#!/usr/bin/env bash +# +# Inputs via env: +# TRUSTED "true" when the fork PR carries the maintainer '🛡️ Trusted' label. +# PR_NUMBER the pull request number, named in the refusal. + +set -euo pipefail + +: "${TRUSTED:?}" +: "${PR_NUMBER:?}" + +if [[ "${TRUSTED}" != "true" ]]; then + echo "Fork PR #${PR_NUMBER} is not labelled '🛡️ Trusted'. The privileged image build and mirror run fork content with a packages:write token, so they start only after a maintainer reviewed the head and applied the label." >&2 + exit 1 +fi +echo "Fork PR #${PR_NUMBER} carries '🛡️ Trusted'; the privileged image build and mirror may run." diff --git a/scripts/image/push.sh b/scripts/image/push.sh index 4bb1299b7d..f2e54aa88e 100755 --- a/scripts/image/push.sh +++ b/scripts/image/push.sh @@ -17,6 +17,7 @@ export INFINITO_PARENT_IMAGE : "${IMAGE_DIGEST_DIR:?Missing IMAGE_DIGEST_DIR}" : "${GITHUB_REPOSITORY:?Missing GITHUB_REPOSITORY}" : "${USE_NIX_TOKEN:?Missing USE_NIX_TOKEN}" +: "${EXPORT_BUILD_CACHE:?Missing EXPORT_BUILD_CACHE}" : "${INFINITO_PARENT_IMAGE:?Missing INFINITO_PARENT_IMAGE; source scripts/meta/env/load.sh}" : "${INFINITO_SRC_DIR:?Missing INFINITO_SRC_DIR; source scripts/meta/env/load.sh}" : "${INFINITO_VENV_DIR:?Missing INFINITO_VENV_DIR; source scripts/meta/env/load.sh}" @@ -39,6 +40,13 @@ else echo "pull_request_target on fork detected: skipping NIX_CONFIG token build-arg." fi +cache_to_arg=() +if [[ "${EXPORT_BUILD_CACHE}" == "true" ]]; then + cache_to_arg=(--cache-to "type=registry,mode=max,ref=${cache_ref}") +else + echo "Fork-sourced build: importing ${cache_ref} without exporting to it." +fi + while true; do echo "=== Build & push attempt ${attempt}/${max_attempts} ===" @@ -56,7 +64,7 @@ while true; do --build-arg "INFINITO_DOCKER_CLI_INSTALL_SCRIPT=${INFINITO_DOCKER_CLI_INSTALL_SCRIPT:?source scripts/meta/env/load.sh}" \ "${nix_arg[@]}" \ --cache-from "type=registry,ref=${cache_ref}" \ - --cache-to "type=registry,mode=max,ref=${cache_ref}" \ + "${cache_to_arg[@]}" \ "${BUILD_CONTEXT_DIR}"; then echo "Build & push succeeded on attempt ${attempt}/${max_attempts}." break diff --git a/tests/integration/meta/workflows/test_cancel_runs.py b/tests/integration/meta/workflows/test_cancel_runs.py index 3e9f6a2d5f..d2ea4c875e 100644 --- a/tests/integration/meta/workflows/test_cancel_runs.py +++ b/tests/integration/meta/workflows/test_cancel_runs.py @@ -237,6 +237,7 @@ class TestCancelPullRequestRuns(CancelScriptMixin, unittest.TestCase): { "id": 299, "event": "pull_request_target", + "display_title": "pull_request_target / PR #106 / synchronize / AlejandroRomanIbanez:feature/makefile-wsl2", "head_sha": "deadbeef", "head_branch": "unexpected-branch-name", "head_repository": {"full_name": "base-repo/core"}, @@ -249,6 +250,71 @@ class TestCancelPullRequestRuns(CancelScriptMixin, unittest.TestCase): ) self.assertEqual(cancelled, ["299"]) + def test_head_sha_never_cancels_another_pull_requests_runs(self): + in_progress_runs = """\ +{"workflow_runs":[ + { + "id": 340, + "event": "pull_request", + "head_sha": "deadbeef", + "head_branch": "fix/victim", + "head_repository": {"full_name": "base-repo/core"}, + "pull_requests": [{"number": 107}] + }, + { + "id": 341, + "event": "pull_request_target", + "display_title": "pull_request_target / PR #1061 / synchronize / victim:fix/victim", + "head_sha": "deadbeef", + "head_branch": "main", + "head_repository": {"full_name": "base-repo/core"}, + "pull_requests": [] + }, + { + "id": 342, + "event": "pull_request", + "head_sha": "deadbeef", + "head_branch": "fix/victim", + "head_repository": {"full_name": "victim/core"}, + "pull_requests": [] + }, + { + "id": 343, + "event": "pull_request", + "head_sha": "deadbeef", + "head_branch": "other-branch", + "head_repository": {"full_name": "AlejandroRomanIbanez/core"}, + "pull_requests": [] + } +]} +""" + _, cancelled = self._run_script( + runs_by_status={"in_progress": in_progress_runs} + ) + self.assertEqual(cancelled, ["343"]) + + def test_head_sha_never_cancels_a_rival_pull_request_on_the_same_head(self): + in_progress_runs = """\ +{"workflow_runs":[ + { + "id": 344, + "event": "pull_request", + "head_sha": "deadbeef", + "head_branch": "feature/makefile-wsl2", + "head_repository": {"full_name": "AlejandroRomanIbanez/core"}, + "pull_requests": [] + } +]} +""" + result, cancelled = self._run_script( + runs_by_status={ + "in_progress": in_progress_runs, + "pulls": '[{"number": 107, "head": {"ref": "feature/makefile-wsl2"}}]\n', + }, + ) + self.assertEqual(cancelled, []) + self.assertIn("Branch fallback disabled", result.stdout) + NEWEST_PER_GROUP_RUNS = """\ {"workflow_runs":[ { diff --git a/tests/lint/repository/test_workflow_fork_checkout_gated.py b/tests/lint/repository/test_workflow_fork_checkout_gated.py new file mode 100644 index 0000000000..7e77cb1d7f --- /dev/null +++ b/tests/lint/repository/test_workflow_fork_checkout_gated.py @@ -0,0 +1,77 @@ +from __future__ import annotations + +import re +import unittest + +from utils.cache.yaml import load_yaml_any + +from . import PROJECT_ROOT + +_WORKFLOWS_DIR = PROJECT_ROOT / ".github" / "workflows" +_GATE_JOB = "fork-trust-gate" +_UNSAFE_CALL_INPUT = "allow_unsafe_checkout" +_UNSAFE_STEP_INPUT = "allow-unsafe-pr-checkout" +_GATE_BYPASS = re.compile(r"\b(?:always|cancelled|failure)\(\s*\)") + + +def _listens_to_pull_request_target(document) -> bool: + triggers = document.get("on") or document.get(True) or {} + if isinstance(triggers, str): + return triggers == "pull_request_target" + return "pull_request_target" in triggers + + +def _enabled(value) -> bool: + return value not in (None, False, "false") + + +def _checks_out_pull_request_code(job: dict) -> bool: + if _enabled((job.get("with") or {}).get(_UNSAFE_CALL_INPUT)): + return True + return any( + _enabled((step.get("with") or {}).get(_UNSAFE_STEP_INPUT)) + for step in job.get("steps") or [] + if isinstance(step, dict) + ) + + +def _needs(job: dict) -> list[str]: + needs = job.get("needs") or [] + return [needs] if isinstance(needs, str) else list(needs) + + +def _offenders(name: str, document) -> list[str]: + offenders: list[str] = [] + for job_id, job in (document.get("jobs") or {}).items(): + if not isinstance(job, dict) or not _checks_out_pull_request_code(job): + continue + if _GATE_JOB not in _needs(job): + offenders.append(f"{name}: {job_id}: does not need it") + elif _GATE_BYPASS.search(str(job.get("if", ""))): + offenders.append(f"{name}: {job_id}: runs past a failed gate") + return offenders + + +class TestWorkflowForkCheckoutGated(unittest.TestCase): + def test_pull_request_checkouts_under_pull_request_target_need_the_gate( + self, + ) -> None: + offenders: list[str] = [] + for path in sorted(_WORKFLOWS_DIR.glob("*.y*ml")): + document = load_yaml_any(str(path), default_if_missing={}) or {} + if _listens_to_pull_request_target(document): + offenders.extend(_offenders(path.name, document)) + + if offenders: + self.fail( + f"{len(offenders)} pull_request_target job(s) check out pull " + f"request code without depending on a green '{_GATE_JOB}'. Such " + "a job runs fork content next to a write-scoped token, so it " + "must wait for the gate that refuses fork PRs lacking the " + "maintainer '🛡️ Trusted' label, and its if: must not use " + "always(), cancelled() or failure().\n" + "\n".join(offenders) + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/php/roles/web-app-moodle/files/build/ConfigTest.php b/tests/unit/php/roles/web-app-moodle/files/build/ConfigTest.php new file mode 100644 index 0000000000..74c5fca9b8 --- /dev/null +++ b/tests/unit/php/roles/web-app-moodle/files/build/ConfigTest.php @@ -0,0 +1,61 @@ + 'mariadb', + 'MOODLE_DB_HOST' => 'mariadb', + 'MOODLE_DB_NAME' => 'moodle', + 'MOODLE_DB_USER' => 'moodle', + 'MOODLE_DB_PASS' => 'secret', + 'MOODLE_DB_PREFIX' => 'mdl_', + 'MOODLE_DB_PORT' => '3306', + 'MOODLE_WWWROOT' => 'https://academy.example.test', + 'MOODLE_DATAROOT' => '/var/www/moodledata', + 'MOODLE_LOCALCACHEDIR' => '/var/cache/moodle', + 'MOODLE_REVERSEPROXY' => 'false', + 'MOODLE_SSLPROXY' => 'true', + 'MOODLE_EGRESS_BLOCKED_HOSTS' => '10.0.0.0/8', + 'MOODLE_EGRESS_ALLOWED_PORTS' => '443', + 'MOODLE_INTERNAL_HOST' => 'moodle', + 'MOODLE_OBJECTFS_ENABLED' => 'false', + ]; + + private string $root; + + protected function setUp(): void + { + $this->root = sys_get_temp_dir() . '/mdlconfig' . bin2hex(random_bytes(6)); + mkdir($this->root . '/lib', 0700, true); + copy(dirname(__DIR__, 7) . '/roles/web-app-moodle/files/build/config.php', $this->root . '/config.php'); + file_put_contents($this->root . '/lib/setup.php', "root . '/lib/setup.php'); + unlink($this->root . '/config.php'); + rmdir($this->root . '/lib'); + rmdir($this->root); + } + + public function testEveryReplicaReadsSessionsFromTheSharedDatabase(): void + { + $process = proc_open( + [PHP_BINARY, '-r', 'require $argv[1]; echo $CFG->session_handler_class ?? "";', $this->root . '/config.php'], + [1 => ['pipe', 'w'], 2 => ['redirect', 1]], + $pipes, + null, + self::ENV + ['PATH' => (string) getenv('PATH')] + ); + $output = (string) stream_get_contents($pipes[1]); + fclose($pipes[1]); + + $this->assertSame(0, proc_close($process), $output); + $this->assertSame('\core\session\database', $output); + } +} diff --git a/tests/unit/python/cli/meta/ci/test_runtime_vulnerabilities.py b/tests/unit/python/cli/meta/ci/test_runtime_vulnerabilities.py index 7299a44aaf..fbb5d54ea4 100644 --- a/tests/unit/python/cli/meta/ci/test_runtime_vulnerabilities.py +++ b/tests/unit/python/cli/meta/ci/test_runtime_vulnerabilities.py @@ -2,6 +2,7 @@ from __future__ import annotations import datetime as dt import json +import re import tempfile import unittest from pathlib import Path @@ -370,23 +371,47 @@ class TestMainGuard(unittest.TestCase): self.assertEqual(gh.calls[0][:2], ["run", "download"]) self.assertIn(f"opened {NGINX_TITLE}", actions) - def guarded(self, job): - step = next( + @staticmethod + def report_job(): + workflow = PROJECT_ROOT / ".github" / "workflows" / "call-orchestrator.yml" + return load_yaml(str(workflow))["jobs"]["report-main-failures"] + + @staticmethod + def sync_step(job): + return next( step for step in job["steps"] if "runtime_vulnerabilities" in step.get("run", "") ) + + def guarded(self, job): return ( "github.ref == 'refs/heads/main'" in job["if"] - and '--ref "${GITHUB_REF}"' in step["run"] + and '--ref "${GITHUB_REF}"' in self.sync_step(job)["run"] ) def test_the_workflow_job_runs_only_on_main_and_hands_the_ref_on(self): - workflow = PROJECT_ROOT / ".github" / "workflows" / "call-orchestrator.yml" - job = load_yaml(str(workflow))["jobs"]["report-main-failures"] + job = self.report_job() self.assertTrue(self.guarded(job)) self.assertFalse(self.guarded({**job, "if": "${{ always() }}"})) + @staticmethod + def sync_runs(condition, results): + wanted = re.findall(r"contains\(needs\.\*\.result, '(\w+)'\)", condition) + return not wanted or any(result in wanted for result in results) + + def test_the_sync_runs_only_after_a_deploy_chunk_ran(self): + job = self.report_job() + condition = self.sync_step(job)["if"] + skipped = ["skipped"] * len(job["needs"]) + self.assertFalse(self.sync_runs(condition, skipped)) + for result in ("success", "failure", "cancelled"): + self.assertTrue(self.sync_runs(condition, [result, *skipped[1:]])) + + def test_negative_control_an_unguarded_sync_runs_without_any_deploy(self): + skipped = ["skipped"] * len(self.report_job()["needs"]) + self.assertTrue(self.sync_runs("${{ !cancelled() }}", skipped)) + if __name__ == "__main__": unittest.main() diff --git a/tests/unit/python/roles/sys-ctl-hlth-runtime/files/test_script.py b/tests/unit/python/roles/sys-ctl-hlth-runtime/files/test_script.py index d55f57a126..d67dd6450e 100644 --- a/tests/unit/python/roles/sys-ctl-hlth-runtime/files/test_script.py +++ b/tests/unit/python/roles/sys-ctl-hlth-runtime/files/test_script.py @@ -1944,6 +1944,20 @@ class TestCommands(TestCase): step = SCRIPT.trivy_step(self.layout, "trivy:1", self.container, _config(), []) self.assertIn("/var/run/docker.sock:/var/run/docker.sock:ro", step.argv) + def test_every_trivy_run_ends_only_at_the_job_bound(self): + steps = [ + SCRIPT.trivy_step(self.layout, "trivy:1", self.container, _config(), []), + SCRIPT.trivy_step(self.layout, "trivy:1", self.host, _config(), []), + *SCRIPT.db_steps("trivy", self.layout, "trivy:1"), + ] + for step in steps: + with self.subTest(step=step.label): + self.assertIn("--timeout", step.argv) + self.assertEqual( + step.argv[step.argv.index("--timeout") + 1], + f"{SCRIPT.JOB_TIMEOUT_SECONDS}s", + ) + def test_the_host_scan_skips_the_excluded_paths(self): step = SCRIPT.trivy_step(self.layout, "trivy:1", self.host, _config(), []) self.assertEqual( diff --git a/tests/unit/python/roles/web-app-erpnext/files/apply/_fake_frappe.py b/tests/unit/python/roles/web-app-erpnext/files/apply/_fake_frappe.py index e2f2b6bbde..5837207a3f 100644 --- a/tests/unit/python/roles/web-app-erpnext/files/apply/_fake_frappe.py +++ b/tests/unit/python/roles/web-app-erpnext/files/apply/_fake_frappe.py @@ -24,6 +24,7 @@ CHILD_TABLES = {"Fiscal Year": ("companies",), "User": ("roles",)} NAME_FIELDS = { "Company": "company_name", "Customer Group": "customer_group_name", + "Email Account": "email_account_name", "Fiscal Year": "year", "Item Group": "item_group_name", "Price List": "price_list_name", @@ -101,6 +102,17 @@ class FakeDoc: self._values["name"] = self._frappe.insert(self.doctype, self._values) return self + def is_new(self): + return not self._values.get("name") + + def db_insert(self): + return self.insert() + + def db_update(self): + self._frappe.records[self.doctype][self._values["name"]] = copy.deepcopy( + self._values + ) + def save(self, ignore_permissions=False): if self._single: self._frappe.singles[self.doctype] = copy.deepcopy(self._values) diff --git a/tests/unit/python/roles/web-app-erpnext/files/apply/test_email_account.py b/tests/unit/python/roles/web-app-erpnext/files/apply/test_email_account.py new file mode 100644 index 0000000000..ce1c1b8a11 --- /dev/null +++ b/tests/unit/python/roles/web-app-erpnext/files/apply/test_email_account.py @@ -0,0 +1,94 @@ +from __future__ import annotations + +import unittest + +from . import PROJECT_ROOT +from ._fake_frappe import FakeFrappe, run_script + +SCRIPT = PROJECT_ROOT / "roles/web-app-erpnext/files/python/apply/email_account.py" +ACCOUNT = "Email Account" +NAME = "ERPNext Outbound" + + +def _env(*, port, tls, start_tls, auth): + return { + "SITE_NAME": "next.erp.infinito.example", + "MAIL_FROM_NAME": "Infinito ERPNext", + "MAIL_FROM_ADDRESS": "no-reply@infinito.example", + "SMTP_HOST": "mail.infinito.example", + "SMTP_PORT": str(port), + "SMTP_TLS": str(tls).lower(), + "SMTP_START_TLS": str(start_tls).lower(), + "SMTP_AUTH": str(auth).lower(), + "SMTP_USER": "no-reply@infinito.example", + "SMTP_PASS": "submission-token", + } + + +class TestEmailAccount(unittest.TestCase): + def setUp(self) -> None: + self.frappe = FakeFrappe() + + def _account(self, **transport): + run_script(SCRIPT, self.frappe, _env(**transport)) + return self.frappe.records[ACCOUNT][NAME] + + def _run(self, **transport): + account = self._account(**transport) + return ( + account.get("smtp_port"), + account.get("use_ssl_for_outgoing"), + account.get("use_tls"), + ) + + def test_an_implicit_tls_relay_opens_the_session_inside_tls(self) -> None: + self.assertEqual( + (465, 1, 0), self._run(port=465, tls=True, start_tls=False, auth=True) + ) + + def test_a_starttls_relay_upgrades_a_plain_session(self) -> None: + self.assertEqual( + (587, 0, 1), self._run(port=587, tls=True, start_tls=True, auth=True) + ) + + def test_a_relay_without_tls_speaks_plain_smtp(self) -> None: + self.assertEqual( + (25, 0, 0), self._run(port=25, tls=False, start_tls=False, auth=False) + ) + + def test_a_relay_that_takes_no_login_is_sent_to_without_smtp_auth(self) -> None: + account = self._account(port=25, tls=False, start_tls=False, auth=False) + + self.assertEqual(1, account.get("no_smtp_authentication")) + + def test_a_relay_that_takes_a_login_is_sent_to_with_smtp_auth(self) -> None: + account = self._account(port=465, tls=True, start_tls=False, auth=True) + + self.assertEqual(0, account.get("no_smtp_authentication")) + + def test_an_account_left_on_starttls_converges_to_the_relay_transport( + self, + ) -> None: + self.frappe.seed( + ACCOUNT, + NAME, + email_account_name=NAME, + smtp_port=465, + use_ssl_for_outgoing=0, + use_tls=1, + ) + + transport = self._run(port=465, tls=True, start_tls=False, auth=True) + + self.assertEqual((465, 1, 0), transport) + self.assertEqual([NAME], list(self.frappe.records[ACCOUNT])) + + def test_the_account_is_committed_and_the_site_closed(self) -> None: + self._run(port=465, tls=True, start_tls=False, auth=True) + + self.assertTrue(self.frappe.db.committed) + self.assertEqual(("destroy",), self.frappe.calls[-1]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/web-app-joomla/files/__init__.py b/tests/unit/python/roles/web-app-joomla/files/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/roles/web-app-joomla/files/shell/__init__.py b/tests/unit/python/roles/web-app-joomla/files/shell/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/roles/web-app-joomla/files/shell/test_docker_entrypoint_joomla.py b/tests/unit/python/roles/web-app-joomla/files/shell/test_docker_entrypoint_joomla.py new file mode 100644 index 0000000000..411f8b2ee9 --- /dev/null +++ b/tests/unit/python/roles/web-app-joomla/files/shell/test_docker_entrypoint_joomla.py @@ -0,0 +1,255 @@ +import contextlib +import os +import signal +import subprocess +import tempfile +import time +import unittest +from pathlib import Path + +from utils import PROJECT_ROOT + +SHELL_DIR = PROJECT_ROOT / "roles/web-app-joomla/files/shell" +ENTRYPOINT = SHELL_DIR / "docker-entrypoint-joomla.sh" +SERVE = "serve apache2-foreground" + +STOCK_STUB = """#!/usr/bin/env bash +printf 'call %s\\n' "$*" >> "${STUB_CALLS}" +case "$1" in apache2*) ;; *) exit 0 ;; esac +case "${2-}" in -v | -V | -h | -t | -T) exit 0 ;; esac +cd "${JOOMLA_WEBROOT}" || exit 9 +if [ -e .joomla-initializing ]; then + echo '[ERROR] Initialization is incomplete or another initializer is active.' >&2 + exit 1 +fi +if [ ! -s configuration.php ]; then + if [ "${STUB_DB}" != up ]; then + echo '[ERROR] Database initialization failed (exit 1).' >&2 + exit 1 + fi + mkdir .joomla-initializing + printf 'init\\n' >> "${STUB_CALLS}" + mkdir -p installation + touch index.php installation/joomla.php joomla.xml robots.txt.dist + sleep "${STUB_SETUP_DELAY}" + if [ "${STUB_INSTALL}" = broken ]; then + echo '[ERROR] Automatic Joomla installation failed (exit 1).' >&2 + exit 1 + fi + echo ' configuration.php + sleep "${STUB_FINISH_DELAY}" + case "${STUB_INSTALL}" in + crash) + echo '[ERROR] Automatic Joomla installation failed (exit 255).' >&2 + exit 1 ;; + nfs) + echo ' [ERROR] Unable to delete installation folder!' + exit 1 ;; + nfs-unowned) + echo ' [ERROR] Unable to delete installation folder!' + echo '[ERROR] Failed to correct ownership after initialization.' >&2 + exit 1 ;; + esac + rm -rf installation joomla.xml + mv robots.txt.dist robots.txt + rmdir .joomla-initializing +fi +printf 'serve %s\\n' "$*" >> "${STUB_CALLS}" +""" + +RM_STUB = """#!/usr/bin/env bash +if [ "${STUB_RM_FAIL}" = 1 ]; then + case "$*" in *installation*) echo 'rm: Device or resource busy' >&2; exit 1 ;; esac +fi +PATH="${STUB_REAL_PATH}" exec rm "$@" +""" + + +class TestJoomlaEntrypoint(unittest.TestCase): + def setUp(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.root = Path(tmp.name) + self.webroot = self.root / "html" + self.webroot.mkdir() + bin_dir = self.root / "bin" + bin_dir.mkdir() + self.stock = self.root / "entrypoint.sh" + for path, body in {self.stock: STOCK_STUB, bin_dir / "rm": RM_STUB}.items(): + path.write_text(body) + path.chmod(0o755) + self.ready = self.webroot / ".infinito-init.ready" + self.marker = self.webroot / ".joomla-initializing" + self.lock = self.webroot / ".infinito-init.lock" + self.pending = self.webroot / ".infinito-init.cleanup" + self.env = { + **os.environ, + "PATH": f"{bin_dir}{os.pathsep}{os.environ['PATH']}", + "STUB_REAL_PATH": os.environ["PATH"], + "JOOMLA_WEBROOT": str(self.webroot), + "JOOMLA_STOCK_ENTRYPOINT": str(self.stock), + "JOOMLA_INIT_READY_FILE": str(self.ready), + "JOOMLA_INIT_LOCK_STALE_SECONDS": "60", + "STUB_DB": "up", + "STUB_INSTALL": "ok", + "STUB_SETUP_DELAY": "0", + "STUB_FINISH_DELAY": "0", + "STUB_RM_FAIL": "0", + } + + def spawn(self, name, **env): + log = self.root / f"{name}.log" + log.touch() + with (self.root / f"{name}.err").open("a") as err: + process = subprocess.Popen( + ["bash", str(ENTRYPOINT), "apache2-foreground"], + env={**self.env, "STUB_CALLS": str(log), **env}, + stdout=subprocess.DEVNULL, + stderr=err, + start_new_session=True, + ) + self.addCleanup(self.kill_group, process) + return process + + def kill_group(self, process): + with contextlib.suppress(ProcessLookupError, PermissionError): + os.killpg(process.pid, signal.SIGKILL) + process.wait() + + def run_entrypoint(self, **env): + return self.spawn("calls", **env).wait(timeout=60) + + def text(self, name): + path = self.root / name + return path.read_text(encoding="utf-8") # nocheck: cache-read tempdir + + def calls(self, name): + return self.text(f"{name}.log").splitlines() + + def wait_for(self, path): + deadline = time.monotonic() + 30 + while not path.exists() and time.monotonic() < deadline: + time.sleep(0.1) + self.assertTrue(path.exists()) + + def leave_stuck_volume(self): + for name in ("installation", ".joomla-initializing", ".infinito-init.lock"): + (self.webroot / name).mkdir() + (self.webroot / "configuration.php").write_text(" dict[str, str]: + """ + Args: + template: file name of a PHP template under the role's templates/. + + Returns: + every extension the template loads, mapped to the conditions of the + blocks around its wfLoadExtension call, with the template's string + variables written out. + """ + php = JINJA.sub("", read_text(str(ROLE / "templates" / template))) + variables = dict(ASSIGNMENT.findall(php)) + loads: dict[str, str] = {} + headers: list[str] = [] + start = 0 + for match in SYNTAX.finditer(php): + symbol = match.group(0) + if match.group(1): + loads[match.group(1)] = " ".join(headers) + continue + if symbol == "{": + headers.append(php[start : match.start()]) + elif symbol == "}": + headers.pop() + start = match.end() + for name, value in variables.items(): + pattern = re.compile(re.escape(name) + r"(?!\w)") + loads = { + ext: pattern.sub(lambda _match, value=value: f'"{value}"', guard) + for ext, guard in loads.items() + } + return loads + + +class TestComposerAutoloaderGate(unittest.TestCase): + def test_composer_autoloaded_extensions_wait_for_their_vendor_tree(self) -> None: + for extension, template in COMPOSER_AUTOLOADED.items(): + with self.subTest(extension=extension): + guard = _guards(template)[extension] + self.assertRegex( + guard, + rf'file_exists\(\s*"\$IP/extensions/{extension}/vendor/autoload\.php"\s*\)', + f"{extension} declares load_composer_autoloader, and MediaWiki's " + "ExtensionRegistry caches per replica for a day whether its " + "vendor/autoload.php existed when the extension was first queued, " + "so loading it before composer finished leaves that replica " + "without the extension's composer classes", + ) + + +if __name__ == "__main__": + unittest.main()