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/cli/meta/env/__main__.py b/cli/meta/env/__main__.py index d1abfe9c6f..dfba6f91fe 100644 --- a/cli/meta/env/__main__.py +++ b/cli/meta/env/__main__.py @@ -13,7 +13,7 @@ from utils.env.writer import write_dotenv from . import PROJECT_ROOT as REPO_ROOT -HOST_OWNED_KEY = "INFINITO_DOTENV_HOST_OWNED" # nocheck: dotenv-host-owned-marker Reason: set only by compose.yml inside the runner container; not a configuration key, a .env entry could freeze the host .env +HOST_OWNED_KEY = "INFINITO_DOTENV_HOST_OWNED" # nocheck: dotenv-host-owned-marker Reason: set only by compose.yml inside the runner container and by the act wrapper when it binds the checkout; not a configuration key, a .env entry could freeze the host .env def main(argv: list[str] | None = None) -> int: 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/group_vars/all/04_webserver.yml b/group_vars/all/04_webserver.yml index a5e31a48d9..c31c81bec9 100644 --- a/group_vars/all/04_webserver.yml +++ b/group_vars/all/04_webserver.yml @@ -24,6 +24,9 @@ WEBSERVER_PROXY_WORKER_CONNECTIONS: "{{ lookup('config', 'svc-prx-openresty', 's WEBSERVER_PROXY_WORKER_RLIMIT_NOFILE: "{{ (WEBSERVER_PROXY_WORKER_CONNECTIONS | int) * 2 }}" +# HTTP/2 on every TLS vhost. Off because OpenResty 1.31.8.x bundles nginx 1.31.8, which CVE-2026-123007 and CVE-2026-123633 hit only with HTTP/2 on; set true once OpenResty ships nginx >= 1.31.9. +WEBSERVER_HTTP2_ENABLED: false + # Response security headers of every vhost; an app overrides any key under `security_headers` in its meta/server.yml. WEBSERVER_SECURITY_HEADERS: nosniff: false # X-Content-Type-Options: nosniff diff --git a/roles/dsk-gnt-claude/meta/services.yml b/roles/dsk-gnt-claude/meta/services.yml index d4e02dfc4a..4b1a036aae 100644 --- a/roles/dsk-gnt-claude/meta/services.yml +++ b/roles/dsk-gnt-claude/meta/services.yml @@ -9,7 +9,7 @@ claude: host: enabled: true lifecycle: alpha - npm_version: 2.1.328 + npm_version: 2.1.329 update: key: npm_version type: npm diff --git a/roles/dsk-gnt-codex/meta/services.yml b/roles/dsk-gnt-codex/meta/services.yml index 4badeb9453..ccefe60850 100644 --- a/roles/dsk-gnt-codex/meta/services.yml +++ b/roles/dsk-gnt-codex/meta/services.yml @@ -9,7 +9,7 @@ codex: host: enabled: true lifecycle: alpha - npm_version: 0.170.0 + npm_version: 0.171.0 update: key: npm_version type: npm diff --git a/roles/svc-cache-package/meta/services.yml b/roles/svc-cache-package/meta/services.yml index a0dc4ed913..ea71b5814f 100644 --- a/roles/svc-cache-package/meta/services.yml +++ b/roles/svc-cache-package/meta/services.yml @@ -20,7 +20,7 @@ package: shared: true bond: 1 image: sonatype/nexus3 - version: 3.98.2-ubi + version: 3.98.3-ubi name: package-cache # nocheck: min-storage-headroom Reason: the image transfers 0.373 GiB, but the service is the blobstore itself and fills up to blobstore_max (40g); sizing the host to the image alone would let the deploy prune a cache it has no room to refill min_storage: 4GB diff --git a/roles/svc-cache-package/templates/upstreams.conf.j2 b/roles/svc-cache-package/templates/upstreams.conf.j2 index 1e8127131a..0328b9045e 100644 --- a/roles/svc-cache-package/templates/upstreams.conf.j2 +++ b/roles/svc-cache-package/templates/upstreams.conf.j2 @@ -27,6 +27,9 @@ server { listen {{ listener.port }}{{ ' ssl' if listener.tls else '' }}; server_name {{ host.host }}; {% if listener.tls %} +{% if WEBSERVER_HTTP2_ENABLED | string | lower in ['true', 'yes', 'on', '1'] %} + http2 on; +{% endif %} ssl_certificate {{ CACHE_PACKAGE_CERTS_DIR }}/{{ host.host }}.crt; ssl_certificate_key {{ CACHE_PACKAGE_CERTS_DIR }}/{{ host.host }}.key; {% set repo = CACHE_PACKAGE_REPOS[host.repo] %} diff --git a/roles/svc-runner/meta/services.yml b/roles/svc-runner/meta/services.yml index 8fd11aec9d..43330b4c93 100644 --- a/roles/svc-runner/meta/services.yml +++ b/roles/svc-runner/meta/services.yml @@ -29,7 +29,7 @@ buildkit: enabled: false shared: false image: moby/buildkit - version: "v0.35.0" + version: "v0.35.1" # nocheck: dynamic-flag act-runner: enabled: false 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 27761cdd63..0be60119ab 100755 --- a/roles/sys-ctl-hlth-runtime/files/python/script.py +++ b/roles/sys-ctl-hlth-runtime/files/python/script.py @@ -1255,6 +1255,8 @@ ENGINE_ENV = { TRIVY_COMMON = ( "--cache-dir", CACHE, + "--timeout", + f"{JOB_TIMEOUT_SECONDS}s", "--disable-telemetry", "--skip-version-check", "--quiet", diff --git a/roles/sys-front-tls/templates/nginx_ssl_header.j2 b/roles/sys-front-tls/templates/nginx_ssl_header.j2 index 54c1c8079d..4d70c4970e 100644 --- a/roles/sys-front-tls/templates/nginx_ssl_header.j2 +++ b/roles/sys-front-tls/templates/nginx_ssl_header.j2 @@ -1,7 +1,9 @@ {% if lookup('tls', domain, 'enabled') | bool %} listen {{ lookup('tls', domain, 'ports.web') }} ssl; listen [::]:{{ lookup('tls', domain, 'ports.web') }} ssl; +{% if WEBSERVER_HTTP2_ENABLED | bool %} http2 on; +{% endif %} ssl_protocols TLSv1.2 TLSv1.3; ssl_ecdh_curve X25519:P-256; diff --git a/roles/web-app-discourse/meta/services.yml b/roles/web-app-discourse/meta/services.yml index 761c475c6d..2841f67f2f 100644 --- a/roles/web-app-discourse/meta/services.yml +++ b/roles/web-app-discourse/meta/services.yml @@ -66,12 +66,12 @@ discourse: shared: true enabled: true # nocheck: dynamic-flag name: discourse - ref: 59dacaecae5797991783ab357a86a573bb82a222 + ref: 93c8e629ea2b0960a4261b69a405e7d10f61a1ea min_storage: 15GB repository: https://github.com/discourse/discourse_docker.git application: repository: https://github.com/discourse/discourse.git - ref: v2026.10.1 + ref: v2026.10.2 ports: local: http: 8020 diff --git a/roles/web-app-erpnext/files/playwright/test-design.js b/roles/web-app-erpnext/files/playwright/test-design.js index 118746f294..2c6ff66efb 100644 --- a/roles/web-app-erpnext/files/playwright/test-design.js +++ b/roles/web-app-erpnext/files/playwright/test-design.js @@ -33,7 +33,7 @@ const LOGIN_ERROR = `${LOGIN_SECTION} .login-error-banner`; const LOGIN_ERROR_ICON = `${LOGIN_ERROR} > svg`; const LOGIN_ERROR_TITLE = `${LOGIN_ERROR} .es-alert__title`; const FOLDER_TILE = ".desktop-container .folder-icon"; -const ACTIVE_FILTER = ".btn.filter-button.btn-primary-light"; +const ACTIVE_FILTER = ".es-button.filter-button:has(> .filter-label:not(.hidden))"; const PAGE_HEAD = ".page-head"; const PAGE_TITLE = ".page-head .es-breadcrumbs li:last-child .es-breadcrumbs__item"; const SIDEBAR = ".body-sidebar"; 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/files/theme.css b/roles/web-app-erpnext/files/theme.css index be7d96e37d..0b63eb04c2 100644 --- a/roles/web-app-erpnext/files/theme.css +++ b/roles/web-app-erpnext/files/theme.css @@ -265,6 +265,22 @@ html .es-button[data-theme="red"] { --bt-disabled-border: var(--design-border); } +html .es-alert[data-theme="red"]:not([data-variant="outline"]) { + background: var(--design-danger-subtle); +} + +html .es-alert[data-theme="yellow"]:not([data-variant="outline"]) { + background: var(--design-warning-subtle); +} + +html .es-alert[data-theme="blue"]:not([data-variant="outline"]) { + background: var(--design-info-subtle); +} + +html .es-alert[data-theme="green"]:not([data-variant="outline"]) { + background: var(--design-success-subtle); +} + html .body-sidebar .standard-sidebar-item:not(.active-sidebar):has(a:not(.section-break)):hover { background-color: var(--design-surface-hover); } @@ -287,6 +303,10 @@ html .btn.btn-primary-light:hover { color: var(--design-text); } +html .es-button.filter-button:has(> .filter-label:not(.hidden)) { + --bt-fill-bg: var(--design-surface-active); +} + html .btn.btn-danger { background-color: var(--design-danger); color: var(--design-on-danger); 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 f567d0da3a..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.5.6 + 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.5.6 + 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.5.6 + version: v19.6.1 name: gitlab-workhorse healthcheck: test: ["CMD", "/scripts/healthcheck"] @@ -128,7 +128,7 @@ gitaly: # nocheck: default-placement-manager the repositories live on a node-local volume (meta/volumes.yml nfs: false, gitaly does not support NFS), which a reschedule leaves behind on the old node placement: manager image: registry.gitlab.com/gitlab-org/build/cng/gitaly - version: v19.5.6 + version: v19.6.1 healthcheck: test: ["CMD", "/scripts/healthcheck"] name: gitlab-gitaly @@ -143,7 +143,7 @@ shell: backup: stop_required: false image: registry.gitlab.com/gitlab-org/build/cng/gitlab-shell - version: v19.5.6 + 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.5.6 + 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-meta/meta/services.yml b/roles/web-app-meta/meta/services.yml index 398fca83e1..58a824671b 100644 --- a/roles/web-app-meta/meta/services.yml +++ b/roles/web-app-meta/meta/services.yml @@ -36,7 +36,7 @@ meta: swarm: enabled: true image: ghcr.io/infinito-nexus/meta - version: v2.0.4 + version: 2.1.0 name: meta min_storage: 1040MB ports: 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-openbao/meta/services.yml b/roles/web-app-openbao/meta/services.yml index 2835707517..f6bee3d856 100644 --- a/roles/web-app-openbao/meta/services.yml +++ b/roles/web-app-openbao/meta/services.yml @@ -60,7 +60,7 @@ openbao: pids_limit: 512 min_storage: 60MB image: openbao/openbao - version: "2.7.2" + version: "2.7.3" custom: true backup: stop_required: true diff --git a/roles/web-app-opencloud/files/playwright/test-design.js b/roles/web-app-opencloud/files/playwright/test-design.js index f7f877a754..8d99e4915f 100644 --- a/roles/web-app-opencloud/files/playwright/test-design.js +++ b/roles/web-app-opencloud/files/playwright/test-design.js @@ -17,6 +17,7 @@ const { adminPassword, adminUsername, baseUrl, ssoLoginAndAssertUsername } = req const SHOWCASE_FOLDER = "design-showcase"; const SHOWCASE_SPACE = "Design Showcase"; const SHOWCASE_GROUP = "design-showcase"; +const ACCESS_DENIED_TEXTS = ["#exitAnchor", "#opencloud .oc-card h2"]; const base = baseUrl.replace(/\/$/, ""); const idmUsername = decodeDotenvQuotedValue(process.env.IDM_ADMIN_USERNAME); @@ -449,7 +450,7 @@ test("design: a primary-filled control takes the primary color and its on-color" await assertToken(page, "#exitAnchor", "background-color", "--design-primary", `opencloud ${mode}`); await assertToken(page, "#exitAnchor", "color", "--design-on-primary", `opencloud ${mode}`); }); - await assertReadable(page, ["#exitAnchor", ".oc-login .oc-card h2"], "opencloud access denied"); + await assertReadable(page, ACCESS_DENIED_TEXTS, "opencloud access denied"); await expect( page.locator('img[alt="OpenCloud emblem"]'), "the upstream emblem must not show on the corporate frame", diff --git a/roles/web-app-opencloud/meta/services.yml b/roles/web-app-opencloud/meta/services.yml index 991d2e03a4..04d5cefbd1 100644 --- a/roles/web-app-opencloud/meta/services.yml +++ b/roles/web-app-opencloud/meta/services.yml @@ -38,7 +38,7 @@ opencloud: replicas: 1 name: opencloud image: opencloudeu/opencloud - version: 7.2.5 + version: 9.1.1 min_storage: 276MB # nocheck: default-placement-manager opencloud_data holds NFS-hostile engine state: NATS JetStream store (events, micro registry, posixfs id cache), bleve search index, idm.boltdb, posixfs xattr metadata; upstream says search cannot scale, so the volume must stay node-local placement: manager diff --git a/roles/web-app-opencloud/templates/style.css.j2 b/roles/web-app-opencloud/templates/style.css.j2 index c1c3ff354e..0c5dbc575c 100644 --- a/roles/web-app-opencloud/templates/style.css.j2 +++ b/roles/web-app-opencloud/templates/style.css.j2 @@ -28,14 +28,26 @@ background-color: var(--design-surface-active); } -.oc-button-primary-filled:hover:not([disabled], .no-hover) { +#exitAnchor { + --oc-button-color: var(--design-primary); + --oc-button-on-color: var(--design-on-primary); +} +:is(.oc-button-primary-filled, #exitAnchor):hover:not([disabled], .no-hover) { filter: none; background-color: var(--design-primary-hover); } -.oc-button-primary-filled:active:not([disabled]) { +:is(.oc-button-primary-filled, #exitAnchor):active:not([disabled]) { background-color: var(--design-primary-active); } +.oc-checkbox:checked:not(:disabled) { + border-color: var(--design-primary); + background-color: var(--design-primary); +} +.oc-checkbox[type="checkbox"]:is(:checked, :indeterminate):not(:disabled)::before { + background-color: var(--design-on-primary); +} + #oc-topbar { --design-focus: var(--design-on-frame); } 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-prometheus/meta/services.yml b/roles/web-app-prometheus/meta/services.yml index 344d2ca04b..b48d9e58b1 100644 --- a/roles/web-app-prometheus/meta/services.yml +++ b/roles/web-app-prometheus/meta/services.yml @@ -136,7 +136,7 @@ node-exporter: flavor: wget path: metrics image: prom/node-exporter - version: v1.12.1 + version: v1.13.1 name: prometheus-node-exporter cpus: "0.1" mem_reservation: 32m @@ -146,11 +146,6 @@ node-exporter: ports: internal: http: 9100 - security: - suppressions: - # nocheck: cve upstream tag ships fixable CRITICAL CVEs; lift it once a rebuilt tag lands - - image_tag: "v1.12.1" - until: 2026-11-30 # nocheck: playwright-service-flag # nocheck: variants-coverage — sso-variant-tor requires the onion on in every variant, so the false polarity has no variant left to live in 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-app-socialhome/meta/services.yml b/roles/web-app-socialhome/meta/services.yml index ecf1917f2b..8c994315b3 100644 --- a/roles/web-app-socialhome/meta/services.yml +++ b/roles/web-app-socialhome/meta/services.yml @@ -16,7 +16,7 @@ socialhome: placement: manager name: socialhome image: ghcr.io/social-home-io/socialhome - version: "2026.11.7" + version: "2026.11.19" ports: local: http: 8089 diff --git a/roles/web-app-stalwart/meta/services.yml b/roles/web-app-stalwart/meta/services.yml index d71345c571..61b9b64764 100644 --- a/roles/web-app-stalwart/meta/services.yml +++ b/roles/web-app-stalwart/meta/services.yml @@ -140,7 +140,7 @@ clamav: enabled: true shared: false image: clamav/clamav-debian - version: "1.5.4" + version: "1.5.5" ports: internal: milter: 7357 diff --git a/roles/web-app-weblate/README.md b/roles/web-app-weblate/README.md index 37d4d8a16e..aff89d0995 100644 --- a/roles/web-app-weblate/README.md +++ b/roles/web-app-weblate/README.md @@ -17,7 +17,7 @@ In this deployment Weblate is the memory behind the translation gateway. [`web-s ## Administration -The container's entrypoint provisions the administrator as the Weblate user `admin`; `WEBLATE_ADMIN_NAME` is its display name only. The role reads that account's API token out of Weblate's own database after the deploy and writes it to `sys-token-store` under `administrator` / `web-app-weblate`. +The container's entrypoint provisions the administrator as the Weblate user `admin`; `WEBLATE_ADMIN_NAME` is its display name only. The role reads that account's API token out of Weblate's own database after the deploy and writes it to `sys-token-store` under `administrator` / `web-app-weblate`. With SSO on, [`files/python/adopt_admin.py`](files/python/adopt_admin.py) binds that account to the administrator's Keycloak user id, the `sub` claim, because Weblate 2026.11 refuses to link a signed-out OIDC sign-in to an existing account by e-mail unless `REGISTRATION_REBIND` is on. ## Networks diff --git a/roles/web-app-weblate/files/python/adopt_admin.py b/roles/web-app-weblate/files/python/adopt_admin.py index 42e94e825b..317f84fad3 100644 --- a/roles/web-app-weblate/files/python/adopt_admin.py +++ b/roles/web-app-weblate/files/python/adopt_admin.py @@ -1,32 +1,45 @@ -# nocheck: mirrored-unit-test - imports weblate.auth.models at module level and runs -# inside `weblate shell`; the models are not importable outside the Weblate image -"""Give the superuser Weblate bootstrapped the platform administrator's name. +"""Give the superuser Weblate bootstrapped the platform administrator's name and SSO identity. Upstream's entrypoint calls ``createadmin`` without ``--username``, so the superuser is always named ``admin`` while carrying the platform -administrator's e-mail. That is one human with two accounts, and it breaks -the OIDC login: ``associate_by_email`` matches the local account, then -``reauthenticate`` sees a usable password and parks an ``@partial`` on -``/accounts/confirm/`` asking for it. The partial is sticky, so every retry -returns to the same page. +administrator's e-mail. Renaming keeps the account, and with it the API +token the deploy reads back; creating a second superuser would leave that +token behind. -Renaming keeps the account, and with it the API token the deploy reads back; -creating a second superuser would leave that token behind. +Since Weblate 2026.11 ``weblate.accounts.pipeline.associate_by_email`` +refuses a signed-out OIDC sign-in whose e-mail already belongs to a local +account (``email_in_use``) unless ``REGISTRATION_REBIND`` is on, and that +setting would let every Keycloak user take over any account by e-mail. So +the administrator is bound to exactly its own Keycloak user instead: a +``social_django`` association for provider ``oidc`` whose ``uid`` is the +Keycloak user id, which Keycloak sends as the ``sub`` claim. +``social_user`` then finds the administrator before any e-mail check runs. +An association with that id held by another account is moved to the +administrator. An administrator already bound to another subject stops the +run, so a foreign identity is never overwritten silently. The password is only dropped while SSO is on. Without SSO it is the only way -in, and ``playwright.env.j2`` hands it to the native-login round. +in, and ``playwright.env.j2`` hands it to the native-login round. With SSO it +also keeps ``reauthenticate`` from parking a sticky ``@partial`` on +``/accounts/confirm/`` should the association ever be missing. Fed to ``weblate shell`` on stdin. Every value arrives in the environment and none has a default: a missing one is a deploy bug and must stop the run. +``WEBLATE_ADMIN_OIDC_SUBJECT`` is empty while SSO is off. """ import os +from social_django.models import UserSocialAuth from weblate.auth.models import User +OIDC_PROVIDER = "oidc" +OIDC_ID_KEY = "sub" + bootstrap = os.environ["WEBLATE_ADMIN_BOOTSTRAP_USERNAME"] target = os.environ["WEBLATE_ADMIN_USERNAME"] sso_enabled = os.environ["WEBLATE_OIDC_ENABLED"] == "true" +subject = os.environ["WEBLATE_ADMIN_OIDC_SUBJECT"] changed = False @@ -39,6 +52,32 @@ if bootstrap != target: admin = User.objects.get(username=target) +if sso_enabled: + if not subject: + raise SystemExit( + f"ADOPT_REFUSED: SSO is on but no Keycloak subject arrived for '{target}'" + ) + foreign = UserSocialAuth.objects.filter(user=admin, provider=OIDC_PROVIDER).exclude( + uid=subject + ) + if foreign.exists(): + raise SystemExit( + f"ADOPT_REFUSED: '{target}' is already bound to another OIDC subject; check " + "which Keycloak user it belongs to and delete that row from " + "social_auth_usersocialauth before deploying again" + ) + binding = UserSocialAuth.objects.filter(provider=OIDC_PROVIDER, uid=subject).first() + if binding is None: + UserSocialAuth.objects.create( + user=admin, provider=OIDC_PROVIDER, uid=subject, id_key=OIDC_ID_KEY + ) + changed = True + elif binding.user_id != admin.pk or binding.id_key != OIDC_ID_KEY: + binding.user = admin + binding.id_key = OIDC_ID_KEY + binding.save(update_fields=["user", "id_key"]) + changed = True + if sso_enabled and admin.has_usable_password(): admin.set_unusable_password() admin.save(update_fields=["password"]) diff --git a/roles/web-app-weblate/meta/services.yml b/roles/web-app-weblate/meta/services.yml index 7cea6c5629..a672dbabd9 100644 --- a/roles/web-app-weblate/meta/services.yml +++ b/roles/web-app-weblate/meta/services.yml @@ -58,7 +58,7 @@ weblate: host: enabled: false image: weblate/weblate - version: "2026.9" + version: "2026.11" min_storage: 1GB ports: local: @@ -86,7 +86,7 @@ beat: host: enabled: false image: weblate/weblate - version: "2026.9" + version: "2026.11" min_storage: 1GB lifecycle: beta # nocheck: single-replica weblate-beat. It is the only task upstream lets run Django's migrate, and the beat scheduler itself must stay singular or every periodic task fires once per replica. @@ -109,7 +109,7 @@ worker: host: enabled: false image: weblate/weblate - version: "2026.9" + version: "2026.11" min_storage: 1GB lifecycle: beta cpus: "1.0" diff --git a/roles/web-app-weblate/tasks/utils/admin_oidc_subject.yml b/roles/web-app-weblate/tasks/utils/admin_oidc_subject.yml new file mode 100644 index 0000000000..448ea6e9a1 --- /dev/null +++ b/roles/web-app-weblate/tasks/utils/admin_oidc_subject.yml @@ -0,0 +1,57 @@ +--- +# include-gated: when: WEBLATE_OIDC_ENABLED | bool +- name: "🛡️ Assert Weblate signs in against the local Keycloak the bind reads" + ansible.builtin.assert: + that: + - OIDC.CLIENT.ISSUER_URL == weblate_oidc_local_issuer + fail_msg: >- + Weblate signs in against {{ OIDC.CLIENT.ISSUER_URL }}, not the local + Keycloak {{ weblate_oidc_local_issuer }}. The administrator bind reads its + user id from the local Keycloak, so another issuer sends a different sub and + locks the administrator out. Drop OIDC_OVERRIDE.URL and the OIDC_OVERRIDE.CLIENT + issuer override, or disable SSO for Weblate. + quiet: true + vars: + weblate_oidc_local_issuer: "{{ lookup('tls', 'web-app-keycloak', 'url.origin') ~ '/realms/' ~ OIDC.CLIENT.REALM }}" + +- name: "🔍 Resolve the Keycloak hosting node and container id" + ansible.builtin.include_tasks: "{{ lookup('path_absolute', 'roles/sys-svc-compose/tasks/utils/swarm/resolve_host_cid.yml') }}" + vars: + resolve_service_key: keycloak + resolve_service_name: "{{ lookup('container_service', 'web-app-keycloak', 'keycloak') }}" + resolve_output_prefix: WEBLATE_KEYCLOAK + resolve_compose_cid: "{{ WEBLATE_KEYCLOAK_CONTAINER_ADDRESS }}" + resolve_converge_retries: 60 + resolve_converge_delay: 5 + resolve_cid_filters: "--filter health=healthy" + +- name: "🔍 Read the Keycloak user of the administrator" + ansible.builtin.shell: >- # nocheck: container-exec-resolver WEBLATE_KEYCLOAK_LOCAL_CID resolved at delegate_to runtime; container_address would return a manager-only subshell + container exec -i {{ WEBLATE_KEYCLOAK_LOCAL_CID | quote }} sh -c ' + /opt/keycloak/bin/kcadm.sh config credentials --server http://127.0.0.1:8080 --realm master + --user "$KEYCLOAK_PERMANENT_ADMIN_USERNAME" --password "$KEYCLOAK_PERMANENT_ADMIN_PASSWORD" >&2 + && exec /opt/keycloak/bin/kcadm.sh get users -r "$1" -q username="$2" -q exact=true + --fields id,username --format csv --noquotes' _ + {{ OIDC.CLIENT.REALM | quote }} {{ WEBLATE_ADMIN_USERNAME | quote }} + register: weblate_keycloak_admin_users + changed_when: false + retries: 6 + delay: 10 + until: weblate_keycloak_admin_users.rc == 0 + delegate_to: "{{ WEBLATE_KEYCLOAK_HOST_NODE }}" + run_once: true + +- name: "🔗 Pick the Keycloak user id of the administrator" + ansible.builtin.set_fact: + weblate_admin_oidc_subjects: "{{ weblate_keycloak_admin_users.stdout_lines | map('trim') | select('match', '[^,]+,' ~ (WEBLATE_ADMIN_USERNAME | lower | regex_escape) + ~ '$') | map('regex_replace', ',.*$', '') | list }}" + +- name: "🛑 Refuse anything but exactly one Keycloak user for the administrator" + ansible.builtin.assert: + that: + - weblate_admin_oidc_subjects | length == 1 + fail_msg: >- + Keycloak realm {{ OIDC.CLIENT.REALM }} returned {{ weblate_admin_oidc_subjects | length }} + users named '{{ WEBLATE_ADMIN_USERNAME }}', so the administrator cannot be bound + to its single sign-on identity and Weblate would refuse its login as email_in_use. + quiet: true diff --git a/roles/web-app-weblate/tasks/utils/token.yml b/roles/web-app-weblate/tasks/utils/token.yml index ff9b00edf8..3b5b7e0d7d 100644 --- a/roles/web-app-weblate/tasks/utils/token.yml +++ b/roles/web-app-weblate/tasks/utils/token.yml @@ -6,11 +6,16 @@ resolve_output_prefix: WEBLATE resolve_compose_cid: "{{ WEBLATE_CONTAINER }}" +- name: "🔗 Look up the Keycloak user the administrator signs in as" + when: WEBLATE_OIDC_ENABLED | bool + ansible.builtin.include_tasks: utils/admin_oidc_subject.yml + - name: "👤 Let the platform administrator own the superuser Weblate bootstrapped" ansible.builtin.shell: # nocheck: container-exec-resolver only Weblate's own management shell can reach its user table cmd: > container exec -i -e WEBLATE_ADMIN_BOOTSTRAP_USERNAME -e WEBLATE_ADMIN_USERNAME -e WEBLATE_OIDC_ENABLED + -e WEBLATE_ADMIN_OIDC_SUBJECT {{ WEBLATE_LOCAL_CID | quote }} weblate shell stdin: "{{ lookup('file', 'python/adopt_admin.py') }}" @@ -18,10 +23,11 @@ WEBLATE_ADMIN_BOOTSTRAP_USERNAME: "{{ WEBLATE_ADMIN_BOOTSTRAP_USERNAME }}" WEBLATE_ADMIN_USERNAME: "{{ WEBLATE_ADMIN_USERNAME }}" WEBLATE_OIDC_ENABLED: "{{ WEBLATE_OIDC_ENABLED | bool | lower }}" + WEBLATE_ADMIN_OIDC_SUBJECT: "{{ (weblate_admin_oidc_subjects | first) if (WEBLATE_OIDC_ENABLED | bool) else '' }}" register: weblate_admin_adopt retries: 30 delay: 10 - until: weblate_admin_adopt.rc == 0 + until: weblate_admin_adopt.rc == 0 or 'ADOPT_REFUSED' in weblate_admin_adopt.stderr changed_when: "'ADOPTED=1' in weblate_admin_adopt.stdout" no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" delegate_to: "{{ WEBLATE_HOST_NODE }}" diff --git a/roles/web-app-weblate/vars/main.yml b/roles/web-app-weblate/vars/main.yml index 5bf31b1aa2..7acffe1303 100644 --- a/roles/web-app-weblate/vars/main.yml +++ b/roles/web-app-weblate/vars/main.yml @@ -18,6 +18,7 @@ WEBLATE_ADMIN_PASSWORD: "{{ lookup('users', 'platform_administrator').password } WEBLATE_ADMIN_BOOTSTRAP_USERNAME: admin WEBLATE_ADMIN_USERNAME: "{{ lookup('users', 'platform_administrator').username }}" +WEBLATE_KEYCLOAK_CONTAINER_ADDRESS: "{{ lookup('container_address', 'web-app-keycloak', 'keycloak') }}" WEBLATE_TOKEN_MIN_LENGTH: 40 WEBLATE_DATABASE_NAME: "{{ lookup('database', application_id, 'name') }}" diff --git a/roles/web-app-wordpress/meta/addons/mcp-adapter.yml b/roles/web-app-wordpress/meta/addons/mcp-adapter.yml index 3116fb74d6..e41612358a 100644 --- a/roles/web-app-wordpress/meta/addons/mcp-adapter.yml +++ b/roles/web-app-wordpress/meta/addons/mcp-adapter.yml @@ -3,7 +3,7 @@ enabled: "{{ lookup('config', 'web-app-wordpress', 'mcp.enabled') | bool }}" required: true mechanism: plugin source: upstream -version: v0.7.1 +version: v0.7.2 update: monitored: true catalog: github-releases 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/roles/web-svc-coturn/meta/services.yml b/roles/web-svc-coturn/meta/services.yml index 85cb8b539e..402ae2227b 100644 --- a/roles/web-svc-coturn/meta/services.yml +++ b/roles/web-svc-coturn/meta/services.yml @@ -11,7 +11,7 @@ coturn: enabled: true shared: true image: coturn/coturn - version: 4.19.1 + version: 4.19.2 min_storage: 246MB user_auth_enabled: false total_quota: 2000 diff --git a/roles/web-svc-translate/files/requirements.txt b/roles/web-svc-translate/files/requirements.txt index 10d8ffa36a..8633c9f554 100644 --- a/roles/web-svc-translate/files/requirements.txt +++ b/roles/web-svc-translate/files/requirements.txt @@ -1,4 +1,4 @@ fastapi==0.163.1 -python-multipart==0.0.33 +python-multipart==0.0.34 uvicorn[standard]==0.54.0 asyncpg==0.32.0 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/scripts/tests/deploy/act/README.md b/scripts/tests/deploy/act/README.md index ee3794a2ed..09524ef219 100644 --- a/scripts/tests/deploy/act/README.md +++ b/scripts/tests/deploy/act/README.md @@ -9,4 +9,4 @@ For the canonical Make target index that invokes these helpers, see [make.md](.. | Command | What it does | Notes | |---|---|---| -| `workflow.sh` | Runs any workflow file through `act`. | Supports custom job, matrix, container, network, and image settings. Binds `INFINITO_VULNERABILITY_DB_HOST_PATH` into the job container at the same path. Invoked via `make act-workflow ACT_WORKFLOW=`. | +| `workflow.sh` | Runs any workflow file through `act`. | Supports custom job, matrix, container, network, and image settings. Binds `INFINITO_VULNERABILITY_DB_HOST_PATH` into the job container at the same path. A bound checkout (`ACT_BIND=true`, or pulled `roles/web-app-cst-*`) passes `INFINITO_DOTENV_HOST_OWNED=true`, so the job's `make dotenv` keeps the host `.env`. Invoked via `make act-workflow ACT_WORKFLOW=`. | diff --git a/scripts/tests/deploy/act/workflow.sh b/scripts/tests/deploy/act/workflow.sh index 93d09a2e33..762974734f 100755 --- a/scripts/tests/deploy/act/workflow.sh +++ b/scripts/tests/deploy/act/workflow.sh @@ -105,6 +105,7 @@ if [[ "${ACT_BIND}" != "true" ]] && compgen -G "${_act_repo_root}/roles/web-app- fi if [[ "${ACT_BIND}" == "true" ]]; then cmd+=(--bind) + cmd+=(--env "INFINITO_DOTENV_HOST_OWNED=true") fi "${cmd[@]}" 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/javascript/roles/web-app-opencloud/files/playwright/test-design.test.js b/tests/unit/javascript/roles/web-app-opencloud/files/playwright/test-design.test.js new file mode 100644 index 0000000000..4606ba6255 --- /dev/null +++ b/tests/unit/javascript/roles/web-app-opencloud/files/playwright/test-design.test.js @@ -0,0 +1,82 @@ +const test = require("node:test"); +const assert = require("node:assert/strict"); +const fs = require("node:fs"); +const path = require("node:path"); + +const PROJECT_ROOT = path.resolve(__dirname, "../../../../../../.."); +const { loadInternals } = require(path.join(PROJECT_ROOT, "tests/unit/javascript/utils/internals.js")); + +const STYLESHEET = fs.readFileSync(path.join(PROJECT_ROOT, "roles/web-app-opencloud/templates/style.css.j2"), "utf8"); +const FILLED_CONTROLS = ":is(.oc-button-primary-filled, #exitAnchor)"; + +const noop = () => undefined; +const { ACCESS_DENIED_TEXTS } = loadInternals( + path.join(PROJECT_ROOT, "roles/web-app-opencloud/files/playwright/test-design.js"), + ["ACCESS_DENIED_TEXTS"], + { + "./onion-test": { test: Object.assign(noop, { use: noop, skip: noop }), expect: noop }, + "./_shared": { baseUrl: "https://opencloud.example.test/" }, + }, + {}, +); + +/** + * Args: + * css: role stylesheet template. + * selector: selector list of a rule that starts a line of the stylesheet. + * + * Returns: + * The declarations of that rule as a property to value map, or null when no rule has exactly this selector list. + */ +function declarations(css, selector) { + const escaped = selector.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + const rule = new RegExp(`(?:^|\\n)${escaped} \\{([^}]*)\\}`).exec(css); + if (!rule) return null; + return Object.fromEntries( + rule[1] + .split(";") + .map((declaration) => declaration.trim()) + .filter(Boolean) + .map((declaration) => declaration.split(/:\s*/, 2)), + ); +} + +test("the sign-in call to action of the access-denied page, secondary-filled since OpenCloud Web 8, takes the primary color and its on-color", () => { + assert.deepEqual(declarations(STYLESHEET, "#exitAnchor"), { + "--oc-button-color": "var(--design-primary)", + "--oc-button-on-color": "var(--design-on-primary)", + }); +}); + +test("the hovered or pressed call to action takes the hover and active shade of the primary color", () => { + assert.equal( + declarations(STYLESHEET, `${FILLED_CONTROLS}:hover:not([disabled], .no-hover)`)?.["background-color"], + "var(--design-primary-hover)", + ); + assert.equal( + declarations(STYLESHEET, `${FILLED_CONTROLS}:active:not([disabled])`)?.["background-color"], + "var(--design-primary-active)", + ); +}); + +test("a checked checkbox, which OpenCloud Web 8 fills with the secondary role, takes the primary color", () => { + assert.deepEqual(declarations(STYLESHEET, ".oc-checkbox:checked:not(:disabled)"), { + "border-color": "var(--design-primary)", + "background-color": "var(--design-primary)", + }); +}); + +test("the check and dash marks of a checkbox take the on-primary color without touching its focus outline", () => { + assert.equal( + declarations(STYLESHEET, '.oc-checkbox[type="checkbox"]:is(:checked, :indeterminate):not(:disabled)::before')?.[ + "background-color" + ], + "var(--design-on-primary)", + ); + assert.ok(!/--oc-role-on-secondary\s*:/.test(STYLESHEET)); +}); + +test("the access-denied readability check reads the card title inside the app, past the hidden browser-support card", () => { + assert.deepEqual([...ACCESS_DENIED_TEXTS], ["#exitAnchor", "#opencloud .oc-card h2"]); + assert.ok(ACCESS_DENIED_TEXTS.every((selector) => !selector.includes(".oc-login"))); +}); 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 3d9ffff556..1c6c0d4605 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/sys-front-tls/templates/test_nginx_ssl_header.py b/tests/unit/python/roles/sys-front-tls/templates/test_nginx_ssl_header.py index e0b710bfe1..16bf355c39 100644 --- a/tests/unit/python/roles/sys-front-tls/templates/test_nginx_ssl_header.py +++ b/tests/unit/python/roles/sys-front-tls/templates/test_nginx_ssl_header.py @@ -6,6 +6,7 @@ import unittest from jinja2 import Environment, FileSystemLoader, StrictUndefined, select_autoescape from plugins.filter.security_headers import FilterModule +from utils.cache.yaml import load_yaml from utils.tls_common import resolve_enabled from . import PROJECT_ROOT @@ -26,12 +27,13 @@ PRIMARY_DOMAINS = { } -def render(application_id: str, override: dict) -> str: +def render(application_id: str, override: dict, http2: bool = False) -> str: """Return the TLS server header of one vhost. Args: application_id: the app the vhost belongs to, or a redirect domain. override: the app's ``server.security_headers`` block. + http2: the value of ``WEBSERVER_HTTP2_ENABLED``. """ applications = { app: {"server": {"security_headers": override}} @@ -65,6 +67,7 @@ def render(application_id: str, override: dict) -> str: domain=PRIMARY_DOMAINS[application_id], lookup=lookup, WEBSERVER_SECURITY_HEADERS=PLATFORM, + WEBSERVER_HTTP2_ENABLED=http2, ) @@ -110,5 +113,17 @@ class TestCookieFlags(unittest.TestCase): self.assertNotIn("proxy_cookie_flags", render("web-app-x", {})) +class TestHttp2(unittest.TestCase): + def test_a_tls_vhost_serves_no_http2_while_the_switch_is_off(self): + self.assertNotIn("http2", render("web-app-x", {})) + + def test_a_tls_vhost_serves_http2_once_the_switch_is_on(self): + self.assertIn("\nhttp2 on;\n", render("web-app-x", {}, http2=True)) + + def test_the_platform_default_keeps_http2_off(self): + defaults = load_yaml(PROJECT_ROOT / "group_vars/all/04_webserver.yml") + self.assertIs(defaults["WEBSERVER_HTTP2_ENABLED"], False) + + if __name__ == "__main__": unittest.main() 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() diff --git a/tests/unit/python/roles/web-app-weblate/files/test_adopt_admin.py b/tests/unit/python/roles/web-app-weblate/files/test_adopt_admin.py new file mode 100644 index 0000000000..25dc820c64 --- /dev/null +++ b/tests/unit/python/roles/web-app-weblate/files/test_adopt_admin.py @@ -0,0 +1,370 @@ +from __future__ import annotations + +import contextlib +import io +import os +import runpy +import sys +import unittest +import unittest.mock +from types import ModuleType + +from ansible.parsing.dataloader import DataLoader +from ansible.template import Templar + +from utils.cache.files import PROJECT_ROOT +from utils.cache.yaml import load_yaml_any +from utils.templating.ansible import _trust_as_template + +SCRIPT = PROJECT_ROOT / "roles/web-app-weblate/files/python/adopt_admin.py" +TOKEN_TASKS = PROJECT_ROOT / "roles/web-app-weblate/tasks/utils/token.yml" +SUBJECT_INCLUDE = "utils/admin_oidc_subject.yml" +SUBJECT_TASKS = PROJECT_ROOT / "roles/web-app-weblate/tasks" / SUBJECT_INCLUDE +SUBJECT_FACT = "weblate_admin_oidc_subjects" +STOP_MARKER = "ADOPT_REFUSED" +ADMIN = "platformadmin" +SUBJECT = "4f1c2b8e-9d3a-4e57-8a61-0c2d5e7f9b10" +OTHER_SUBJECT = "a0b1c2d3-e4f5-4a6b-8c7d-9e0f1a2b3c4d" +JVM_NOISE = ( + "[0.001s][warning][os,container] Cgroup memory controller path at " + "'/sys/fs/cgroup' seems to have moved, detected limits won't be accurate" +) + + +def _matches(row, lookups: dict) -> bool: + return all(getattr(row, key) == value for key, value in lookups.items()) + + +class FakeQuerySet: + """The QuerySet calls ``adopt_admin.py`` makes. + + Args: + rows: the model instances the queryset holds. + """ + + def __init__(self, rows): + self._rows = list(rows) + + def filter(self, **lookups) -> FakeQuerySet: + return FakeQuerySet(row for row in self._rows if _matches(row, lookups)) + + def exclude(self, **lookups) -> FakeQuerySet: + return FakeQuerySet(row for row in self._rows if not _matches(row, lookups)) + + def first(self): + return self._rows[0] if self._rows else None + + def exists(self) -> bool: + return bool(self._rows) + + def get(self, **lookups): + found = self.filter(**lookups)._rows + if len(found) != 1: + raise LookupError(f"{len(found)} rows match {lookups}") + return found[0] + + +class FakeManager: + """A model manager over an in-memory table. + + Args: + model: the class ``create`` instantiates. + unique: field names that must be unique together, as ``unique_together``. + """ + + def __init__(self, model, unique: tuple[str, ...] = ()): + self.model = model + self.unique = unique + self.rows: list = [] + + def filter(self, **lookups) -> FakeQuerySet: + return FakeQuerySet(self.rows).filter(**lookups) + + def get(self, **lookups): + return FakeQuerySet(self.rows).get(**lookups) + + def create(self, **fields): + key = {name: fields[name] for name in self.unique} + if self.unique and FakeQuerySet(self.rows).filter(**key).exists(): + raise ValueError(f"unique constraint violated for {key}") + row = self.model(**fields) + self.rows.append(row) + return row + + +class FakeUser: + """``weblate.auth.models.User`` reduced to what the adoption touches. + + Args: + pk: primary key. + username: login name. + usable_password: whether ``has_usable_password`` answers True. + """ + + objects: FakeManager + + def __init__(self, pk: int, username: str, *, usable_password: bool = True): + self.pk = pk + self.username = username + self.usable_password = usable_password + + def save(self, update_fields) -> None: + self.saved = tuple(update_fields) + + def has_usable_password(self) -> bool: + return self.usable_password + + def set_unusable_password(self) -> None: + self.usable_password = False + + +class FakeSocial: + """``social_django.models.UserSocialAuth`` of social-auth-app-django 7.2. + + Args: + user: the owning account. + provider: backend name. + uid: the identifier the backend reports. + id_key: the claim ``uid`` was read from; ``social_user`` filters on it. + """ + + objects: FakeManager + + def __init__(self, user, provider: str, uid: str, id_key: str = ""): + self.user = user + self.provider = provider + self.uid = uid + self.id_key = id_key + + @property + def user_id(self) -> int: + return self.user.pk + + def save(self, update_fields) -> None: + self.saved = tuple(update_fields) + + +class Database: + """Fresh model classes and tables, one per test.""" + + def __init__(self): + self.User = type("User", (FakeUser,), {}) + self.User.objects = FakeManager(self.User) + self.UserSocialAuth = type("UserSocialAuth", (FakeSocial,), {}) + self.UserSocialAuth.objects = FakeManager( + self.UserSocialAuth, unique=("provider", "uid") + ) + + def user(self, pk: int, username: str, **kwargs): + return self.User.objects.create(pk=pk, username=username, **kwargs) + + def social(self, user, uid: str, id_key: str = "sub", provider: str = "oidc"): + return self.UserSocialAuth.objects.create( + user=user, provider=provider, uid=uid, id_key=id_key + ) + + def modules(self) -> dict[str, ModuleType]: + auth_models = ModuleType("weblate.auth.models") + auth_models.User = self.User + social_models = ModuleType("social_django.models") + social_models.UserSocialAuth = self.UserSocialAuth + return { + "weblate": ModuleType("weblate"), + "weblate.auth": ModuleType("weblate.auth"), + "weblate.auth.models": auth_models, + "social_django": ModuleType("social_django"), + "social_django.models": social_models, + } + + +def adopt(db: Database, *, sso: bool = True, subject: str = SUBJECT) -> str: + """Run the shipped script the way ``weblate shell`` does and return its stdout. + + Args: + db: the tables the script reads and writes. + sso: the value of ``WEBLATE_OIDC_ENABLED``. + subject: the value of ``WEBLATE_ADMIN_OIDC_SUBJECT``. + """ + env = { + "WEBLATE_ADMIN_BOOTSTRAP_USERNAME": "admin", + "WEBLATE_ADMIN_USERNAME": ADMIN, + "WEBLATE_OIDC_ENABLED": "true" if sso else "false", + "WEBLATE_ADMIN_OIDC_SUBJECT": subject, + } + out = io.StringIO() + with ( + unittest.mock.patch.dict(sys.modules, db.modules()), + unittest.mock.patch.dict(os.environ, env), + contextlib.redirect_stdout(out), + ): + runpy.run_path(str(SCRIPT), run_name="__weblate_shell__") + return out.getvalue() + + +def bindings(db: Database) -> list[tuple[str, str, str, str]]: + return [ + (row.user.username, row.provider, row.uid, row.id_key) + for row in db.UserSocialAuth.objects.rows + ] + + +class TestAdministratorSubjectBinding(unittest.TestCase): + def test_the_bootstrapped_superuser_is_bound_to_the_keycloak_subject(self): + db = Database() + admin = db.user(1, "admin") + self.assertIn("ADOPTED=1", adopt(db)) + self.assertEqual(admin.username, ADMIN) + self.assertEqual( + bindings(db), + [(ADMIN, "oidc", SUBJECT, "sub")], + "Weblate 2026.11 refuses to link the OIDC sign-in to the local " + "administrator by e-mail (email_in_use); social_user must find it " + "through an oidc association on the Keycloak sub instead", + ) + self.assertFalse(admin.usable_password) + + def test_a_second_run_changes_nothing(self): + db = Database() + db.user(1, ADMIN, usable_password=False) + adopt(db) + self.assertIn("ADOPTED=0", adopt(db)) + self.assertEqual(bindings(db), [(ADMIN, "oidc", SUBJECT, "sub")]) + + def test_an_unkeyed_legacy_row_for_the_subject_is_keyed_in_place(self): + db = Database() + admin = db.user(1, ADMIN, usable_password=False) + db.social(admin, SUBJECT, id_key="") + self.assertIn("ADOPTED=1", adopt(db)) + self.assertEqual(bindings(db), [(ADMIN, "oidc", SUBJECT, "sub")]) + + def test_another_account_holding_the_subject_loses_it(self): + db = Database() + db.user(1, ADMIN, usable_password=False) + stray = db.user(2, "platformadmin-old") + db.social(stray, SUBJECT) + self.assertIn("ADOPTED=1", adopt(db)) + self.assertEqual(bindings(db), [(ADMIN, "oidc", SUBJECT, "sub")]) + + def test_a_foreign_subject_on_the_administrator_stops_the_run(self): + db = Database() + admin = db.user(1, ADMIN, usable_password=False) + db.social(admin, OTHER_SUBJECT) + with self.assertRaises(SystemExit) as stop: + adopt(db) + self.assertTrue(str(stop.exception.code).startswith(f"{STOP_MARKER}:")) + self.assertEqual(bindings(db), [(ADMIN, "oidc", OTHER_SUBJECT, "sub")]) + + def test_other_providers_on_the_administrator_are_left_alone(self): + db = Database() + admin = db.user(1, ADMIN, usable_password=False) + db.social(admin, "admin@example.com", id_key="", provider="email") + adopt(db) + self.assertEqual( + sorted(bindings(db)), + [ + (ADMIN, "email", "admin@example.com", ""), + (ADMIN, "oidc", SUBJECT, "sub"), + ], + ) + + def test_sso_without_a_subject_stops_the_run(self): + db = Database() + db.user(1, ADMIN) + with self.assertRaises(SystemExit) as stop: + adopt(db, subject="") + self.assertTrue(str(stop.exception.code).startswith(f"{STOP_MARKER}:")) + self.assertEqual(bindings(db), []) + + def test_without_sso_nothing_is_bound_and_the_password_stays(self): + db = Database() + admin = db.user(1, "admin") + self.assertIn("ADOPTED=1", adopt(db, sso=False, subject="")) + self.assertEqual(bindings(db), []) + self.assertTrue(admin.usable_password) + + +def _tasks(path) -> list[dict]: + return load_yaml_any(str(path), default_if_missing=[]) + + +def _subject_expression() -> str: + for task in _tasks(SUBJECT_TASKS): + if SUBJECT_FACT in task.get("ansible.builtin.set_fact", {}): + return task["ansible.builtin.set_fact"][SUBJECT_FACT] + raise AssertionError(f"no task sets {SUBJECT_FACT}") + + +def pick_subjects(stdout_lines: list[str], username: str = ADMIN) -> list[str]: + templar = Templar( + loader=DataLoader(), + variables={ + "weblate_keycloak_admin_users": {"stdout_lines": stdout_lines}, + "WEBLATE_ADMIN_USERNAME": username, + }, + ) + return templar.template(_trust_as_template(_subject_expression())) + + +class TestKeycloakSubjectSelection(unittest.TestCase): + def test_jvm_warnings_before_the_csv_are_skipped(self): + self.assertEqual( + pick_subjects([JVM_NOISE, f"{SUBJECT},{ADMIN}"]), + [SUBJECT], + ) + + def test_the_administrator_name_is_matched_case_insensitively(self): + self.assertEqual( + pick_subjects([f"{SUBJECT},{ADMIN}"], "PlatformAdmin"), [SUBJECT] + ) + + def test_only_the_exact_username_matches(self): + self.assertEqual( + pick_subjects( + [ + f"{OTHER_SUBJECT},{ADMIN}2", + f"{OTHER_SUBJECT},x{ADMIN}", + f"{OTHER_SUBJECT},other,{ADMIN}", + ] + ), + [], + ) + + def test_the_username_is_not_read_as_a_pattern(self): + self.assertEqual( + pick_subjects([f"{OTHER_SUBJECT},platformXadmin"], "platform.admin"), [] + ) + + def test_two_matches_are_both_reported_for_the_assert(self): + self.assertEqual( + pick_subjects([f"{SUBJECT},{ADMIN}", f"{OTHER_SUBJECT},{ADMIN}"]), + [SUBJECT, OTHER_SUBJECT], + ) + + +class TestSubjectReachesTheShell(unittest.TestCase): + def test_the_keycloak_lookup_is_included_only_with_sso(self): + include = next( + task + for task in _tasks(TOKEN_TASKS) + if task.get("ansible.builtin.include_tasks") == SUBJECT_INCLUDE + ) + self.assertEqual(include["when"], "WEBLATE_OIDC_ENABLED | bool") + self.assertTrue(SUBJECT_TASKS.is_file()) + + def test_the_adopt_task_forwards_the_subject_into_the_container(self): + adopt_task = next( + task + for task in _tasks(TOKEN_TASKS) + if "adopt_admin.py" in str(task.get("ansible.builtin.shell", {})) + ) + self.assertIn( + "-e WEBLATE_ADMIN_OIDC_SUBJECT", adopt_task["ansible.builtin.shell"]["cmd"] + ) + self.assertIn("WEBLATE_ADMIN_OIDC_SUBJECT", adopt_task["environment"]) + self.assertIn( + f"'{STOP_MARKER}' in weblate_admin_adopt.stderr", adopt_task["until"] + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/scripts/tests/deploy/act/test_workflow.py b/tests/unit/python/scripts/tests/deploy/act/test_workflow.py index e5e6c86555..d433a565dc 100644 --- a/tests/unit/python/scripts/tests/deploy/act/test_workflow.py +++ b/tests/unit/python/scripts/tests/deploy/act/test_workflow.py @@ -7,11 +7,13 @@ import tempfile import unittest from pathlib import Path +from cli.meta.env.__main__ import HOST_OWNED_KEY from utils.cache.files import PROJECT_ROOT SCRIPT = PROJECT_ROOT / "scripts" / "tests" / "deploy" / "act" / "workflow.sh" ACT_STUB = '#!/usr/bin/env bash\nprintf \'%s\\0\' "$@" >"${STUB_LOG}"\n' DB_ENV = "INFINITO_VULNERABILITY_DB_HOST_PATH" +HOST_OWNED = f"{HOST_OWNED_KEY}=true" EXTRA_VARS = json.dumps( { "applications": { @@ -23,7 +25,11 @@ EXTRA_VARS = json.dumps( def run_act( - db_host_path: str | None, act_env: str = "" + db_host_path: str | None, + act_env: str = "", + *, + act_bind: str | None = None, + custom_role: bool = False, ) -> tuple[subprocess.CompletedProcess, list[str], Path, bool]: """Run the wrapper against an ``act`` stub that records its argv. @@ -31,6 +37,9 @@ def run_act( db_host_path: value of ``INFINITO_VULNERABILITY_DB_HOST_PATH`` below a scratch directory, or None to leave it unset. act_env: value of ``ACT_ENV``. + act_bind: value of ``ACT_BIND``, or None to leave it unset. + custom_role: run the wrapper from a scratch checkout that holds a + pulled ``roles/web-app-cst-*`` role instead of this repository. Returns: The finished process, the argv act received (one list item per @@ -38,6 +47,14 @@ def run_act( whether it existed afterwards. """ with tempfile.TemporaryDirectory() as tmp: + script = SCRIPT + if custom_role: + root = Path(tmp) / "repo" + (root / "roles" / "web-app-cst-demo").mkdir(parents=True) + (root / ".github" / "workflows").mkdir(parents=True) + script = root / "scripts" / "tests" / "deploy" / "act" / "workflow.sh" + script.parent.mkdir(parents=True) + script.symlink_to(SCRIPT) stub = Path(tmp) / "act" stub.write_text(ACT_STUB) stub.chmod(0o755) @@ -48,8 +65,10 @@ def run_act( env = { k: v for k, v in os.environ.items() - if k not in ("BASH_ENV", DB_ENV, "ACT_CONTAINER_OPTIONS") + if k not in ("BASH_ENV", DB_ENV, "ACT_CONTAINER_OPTIONS", "ACT_BIND") } + if act_bind is not None: + env["ACT_BIND"] = act_bind env.update( PATH=f"{tmp}{os.pathsep}{os.environ['PATH']}", STUB_LOG=str(log), @@ -63,7 +82,7 @@ def run_act( if db_host_path is not None: env[DB_ENV] = str(shared) done = subprocess.run( - ["bash", str(SCRIPT)], + ["bash", str(script)], env=env, capture_output=True, text=True, @@ -99,10 +118,12 @@ def env_items(argv: list[str]) -> list[str]: Returns: Every ``--env`` value in order, without the wrapper's own - ``INFINITO_VULNERABILITY_DB_HOST_PATH`` pin. + ``INFINITO_VULNERABILITY_DB_HOST_PATH`` and host-owned ``.env`` pins. """ return [ - value for value in option(argv, "--env") if not value.startswith(f"{DB_ENV}=") + value + for value in option(argv, "--env") + if not value.startswith(f"{DB_ENV}=") and value != HOST_OWNED ] @@ -165,5 +186,24 @@ class TestActWorkflowEnv(unittest.TestCase): self.assertEqual(items, ["INFINITO_INVENTORY_EXTRA_VARS=", "disable=css"]) +class TestBoundCheckoutKeepsTheHostDotenv(unittest.TestCase): + def test_an_explicit_bind_keeps_the_host_dotenv(self) -> None: + done, argv, _shared, _created = run_act("vulnerability-db", act_bind="true") + self.assertEqual(done.returncode, 0, done.stderr) + self.assertIn("--bind", argv) + self.assertIn(HOST_OWNED, option(argv, "--env")) + + def test_a_bind_for_pulled_custom_roles_keeps_the_host_dotenv(self) -> None: + done, argv, _shared, _created = run_act("vulnerability-db", custom_role=True) + self.assertEqual(done.returncode, 0, done.stderr) + self.assertIn("--bind", argv) + self.assertIn(HOST_OWNED, option(argv, "--env")) + + def test_the_marker_travels_only_with_the_bind(self) -> None: + done, argv, _shared, _created = run_act("vulnerability-db", act_bind="false") + self.assertEqual(done.returncode, 0, done.stderr) + self.assertEqual("--bind" in argv, HOST_OWNED in option(argv, "--env")) + + if __name__ == "__main__": unittest.main() diff --git a/tests/unit/python/utils/cache/test_render.py b/tests/unit/python/utils/cache/test_render.py index 559c25f7f0..58290c3ec0 100644 --- a/tests/unit/python/utils/cache/test_render.py +++ b/tests/unit/python/utils/cache/test_render.py @@ -10,6 +10,7 @@ from __future__ import annotations import stat import tempfile import unittest +import unittest.mock as mock from pathlib import Path from utils.cache.hosts import host_records @@ -88,5 +89,42 @@ class TestOllamaRegistry(unittest.TestCase): self.assertNotIn("location /v2/", block) +def _servers(http2: bool | str) -> tuple[list[str], list[str]]: + """Return the TLS and the plain server blocks of the rendered frontend. + + Args: + http2: the value ``WEBSERVER_HTTP2_ENABLED`` is rendered with. + """ + with mock.patch("utils.cache.render._webserver_http2", return_value=http2): + blocks = upstreams_conf().split("server {")[1:] + tls = [block for block in blocks if " ssl;" in block] + return tls, [block for block in blocks if " ssl;" not in block] + + +class TestHttp2(unittest.TestCase): + def test_no_listener_serves_http2_while_the_switch_is_off(self) -> None: + tls, plain = _servers(False) + + self.assertTrue(tls) + self.assertFalse([block for block in tls + plain if "http2" in block]) + + def test_every_tls_listener_serves_http2_once_the_switch_is_on(self) -> None: + tls, _plain = _servers(True) + + self.assertTrue(tls) + self.assertEqual([block for block in tls if "\n\thttp2 on;\n" not in block], []) + + def test_a_string_false_from_extra_vars_keeps_http2_off(self) -> None: + tls, _plain = _servers("false") + + self.assertFalse([block for block in tls if "http2" in block]) + + def test_a_plain_listener_never_serves_http2(self) -> None: + _tls, plain = _servers(True) + + self.assertTrue(plain) + self.assertFalse([block for block in plain if "http2" in block]) + + if __name__ == "__main__": unittest.main() diff --git a/tests/unit/python/utils/env/handlers/test_nix_config.py b/tests/unit/python/utils/env/handlers/test_nix_config.py new file mode 100644 index 0000000000..2ea254aee7 --- /dev/null +++ b/tests/unit/python/utils/env/handlers/test_nix_config.py @@ -0,0 +1,46 @@ +from __future__ import annotations + +import os +import unittest +from pathlib import Path +from unittest.mock import patch + +from utils.env.context import BuildContext, EnvBuilder +from utils.env.handlers import nix_config as handler + +_TOKENS_LINE = "access-tokens = github.com=placeholder-not-a-token" +_CALLER = {handler.KEY: f"{_TOKENS_LINE}\naccept-flake-config = true\n"} + + +def _ctx(*, on_gha: bool = False, on_act: bool = False) -> BuildContext: + return BuildContext( + static={}, + static_comments={}, + repo_root=Path("/repo"), + on_gha=on_gha, + on_act=on_act, + ) + + +def _apply(ctx: BuildContext) -> dict[str, str]: + eb = EnvBuilder() + handler.apply(eb, ctx) + return eb.values + + +class TestNixConfigTokenStaysOffTheHost(unittest.TestCase): + @patch.dict(os.environ, _CALLER, clear=False) + def test_a_github_runner_keeps_only_the_access_tokens_line(self) -> None: + self.assertEqual(_apply(_ctx(on_gha=True)), {handler.KEY: _TOKENS_LINE}) + + @patch.dict(os.environ, _CALLER, clear=False) + def test_act_never_writes_the_token(self) -> None: + self.assertNotIn(handler.KEY, _apply(_ctx(on_act=True))) + + @patch.dict(os.environ, _CALLER, clear=False) + def test_a_developer_machine_never_writes_the_token(self) -> None: + self.assertNotIn(handler.KEY, _apply(_ctx())) + + +if __name__ == "__main__": # pragma: no cover + unittest.main() diff --git a/utils/cache/render.py b/utils/cache/render.py index 8e041f6737..e8e888f917 100644 --- a/utils/cache/render.py +++ b/utils/cache/render.py @@ -33,6 +33,7 @@ if TYPE_CHECKING: ROLE = "svc-cache-package" ROLE_DIR = PROJECT_ROOT / "roles" / ROLE ROLE_VARS = ROLE_DIR / ROLE_FILE_VARS_MAIN +WEBSERVER_VARS = PROJECT_ROOT / "group_vars" / "all" / "04_webserver.yml" TEMPLATE_DIRS = (ROLE_DIR / "templates", PROJECT_ROOT / "compose" / "templates") UPSTREAMS_TEMPLATE = "upstreams.conf.j2" CONSUMER_TEMPLATE = "cache-consumer.yml.jinja" @@ -92,10 +93,15 @@ def _render(template: str, **context) -> str: return env.get_template(template).render(**context) +def _webserver_http2() -> bool: + return load_yaml_any(str(WEBSERVER_VARS))["WEBSERVER_HTTP2_ENABLED"] + + def upstreams_conf() -> str: """Return the nginx frontend configuration the declarations produce.""" return _render( UPSTREAMS_TEMPLATE, + WEBSERVER_HTTP2_ENABLED=_webserver_http2(), CACHE_PACKAGE_UPSTREAMS=list(host_records().values()), CACHE_PACKAGE_REPOS=repo_records(), CACHE_PACKAGE_BACKEND=BACKEND, diff --git a/utils/env/handlers/nix_config.py b/utils/env/handlers/nix_config.py index a56d12f4c7..07df642a86 100644 --- a/utils/env/handlers/nix_config.py +++ b/utils/env/handlers/nix_config.py @@ -1,10 +1,15 @@ -"""NIX_CONFIG: pass-through of the caller's access-tokens line, when present. +"""NIX_CONFIG: pass-through of the caller's access-tokens line on a GitHub runner. `.env` is consumed by bash `source` and docker-compose `--env-file`, neither of which round-trips multi-line values; the writer therefore rejects them. Other NIX_CONFIG settings (`accept-flake-config`, `experimental-features`, …) belong in `/etc/nix/nix.conf` (Dockerfile injects them inside the dev container; host operators set them once in `~/.config/nix/nix.conf`). + +Only a GitHub Actions runner gets the line: there the token is the job's +short-lived GITHUB_TOKEN. Under act or on a developer machine it is the +operator's own long-lived token, and `.env` would keep it in plaintext in the +host checkout. """ from __future__ import annotations @@ -16,10 +21,12 @@ if TYPE_CHECKING: from utils.env.context import BuildContext, EnvBuilder KEY = "NIX_CONFIG" -COMMENT = "Pass-through of the caller's NIX_CONFIG access-tokens line, when present." +COMMENT = "The caller's NIX_CONFIG access-tokens line, on a GitHub runner only." def apply(eb: EnvBuilder, ctx: BuildContext) -> None: + if not ctx.on_gha: + return nix_config = os.environ.get("NIX_CONFIG", "") access_tokens_line = next( (